snort/packages/app/src/Hooks/useFollowControls.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-04-15 21:31:51 +00:00
import { DiffSyncTags, EventKind, NostrLink, NostrPrefix } from "@snort/system";
2024-01-30 22:38:23 +00:00
import { useMemo } from "react";
import useEventPublisher from "./useEventPublisher";
import useLogin from "./useLogin";
/**
* Simple hook for adding / removing follows
*/
export default function useFollowsControls() {
const { publisher, system } = useEventPublisher();
2024-04-15 21:31:51 +00:00
const { pubkey, contacts, relays } = useLogin(s => ({
pubkey: s.publicKey,
contacts: s.contacts,
readonly: s.readonly,
relays: s.relays.item,
}));
2024-01-30 22:38:23 +00:00
return useMemo(() => {
2024-04-15 21:31:51 +00:00
const link = new NostrLink(NostrPrefix.Event, "", EventKind.ContactList, pubkey);
const sync = new DiffSyncTags(link);
const content = JSON.stringify(relays);
2024-01-30 22:38:23 +00:00
return {
isFollowing: (pk: string) => {
2024-04-15 21:31:51 +00:00
return contacts.some(a => a[0] === "p" && a[1] === pk);
2024-01-30 22:38:23 +00:00
},
addFollow: async (pk: Array<string>) => {
2024-04-15 21:31:51 +00:00
sync.add(pk.map(a => ["p", a]));
if (publisher) {
await sync.persist(publisher.signer, system, content);
}
2024-01-30 22:38:23 +00:00
},
removeFollow: async (pk: Array<string>) => {
2024-04-15 21:31:51 +00:00
sync.remove(pk.map(a => ["p", a]));
if (publisher) {
await sync.persist(publisher.signer, system, content);
}
2024-01-30 22:38:23 +00:00
},
setFollows: async (pk: Array<string>) => {
2024-04-15 21:31:51 +00:00
sync.replace(pk.map(a => ["p", a]));
if (publisher) {
await sync.persist(publisher.signer, system, content);
}
2024-01-30 22:38:23 +00:00
},
2024-04-15 21:31:51 +00:00
followList: contacts.filter(a => a[0] === "p").map(a => a[1]),
2024-01-30 22:38:23 +00:00
};
2024-04-15 21:31:51 +00:00
}, [contacts, relays, publisher, system]);
2024-01-30 22:38:23 +00:00
}