snort/src/Feed/ThreadFeed.ts

60 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-01-17 13:03:15 +00:00
import { useEffect, useMemo, useState } from "react";
2023-01-20 11:11:50 +00:00
import { u256 } from "Nostr";
import EventKind from "Nostr/EventKind";
import { Subscriptions } from "Nostr/Subscriptions";
import useSubscription from "Feed/Subscription";
2023-01-20 17:07:14 +00:00
import { useSelector } from "react-redux";
import { RootState } from "State/Store";
import { UserPreferences } from "State/Login";
2023-01-24 14:09:56 +00:00
import { debounce } from "Util";
2022-12-18 14:51:47 +00:00
2023-01-15 19:40:47 +00:00
export default function useThreadFeed(id: u256) {
2023-01-17 13:03:15 +00:00
const [trackingEvents, setTrackingEvent] = useState<u256[]>([id]);
2023-01-20 17:07:14 +00:00
const pref = useSelector<RootState, UserPreferences>(s => s.login.preferences);
2023-01-17 13:03:15 +00:00
function addId(id: u256[]) {
setTrackingEvent((s) => {
2023-01-21 16:18:44 +00:00
let orig = new Set(s);
2023-01-24 14:09:56 +00:00
if (id.some(a => !orig.has(a))) {
let tmp = new Set([...s, ...id]);
2023-01-21 16:18:44 +00:00
return Array.from(tmp);
} else {
return s;
}
2023-01-17 13:03:15 +00:00
})
}
2022-12-30 23:35:02 +00:00
const sub = useMemo(() => {
const thisSub = new Subscriptions();
2023-01-02 11:15:13 +00:00
thisSub.Id = `thread:${id.substring(0, 8)}`;
2023-01-17 13:03:15 +00:00
thisSub.Ids = new Set(trackingEvents);
2022-12-30 23:35:02 +00:00
// get replies to this event
const subRelated = new Subscriptions();
2023-02-03 21:38:14 +00:00
subRelated.Kinds = new Set(pref.enableReactions ? [EventKind.Reaction, EventKind.TextNote, EventKind.Deletion, EventKind.Repost, EventKind.ZapReceipt] : [EventKind.TextNote]);
2022-12-30 23:35:02 +00:00
subRelated.ETags = thisSub.Ids;
thisSub.AddSubscription(subRelated);
return thisSub;
2023-01-25 13:54:45 +00:00
}, [trackingEvents, pref, id]);
2022-12-30 23:35:02 +00:00
2023-02-01 13:22:11 +00:00
const main = useSubscription(sub, { leaveOpen: true, cache: true });
2022-12-30 23:35:02 +00:00
2023-01-17 13:03:15 +00:00
useEffect(() => {
2023-01-24 14:09:56 +00:00
if (main.store) {
return debounce(200, () => {
let mainNotes = main.store.notes.filter(a => a.kind === EventKind.TextNote);
let eTags = mainNotes
.filter(a => a.kind === EventKind.TextNote)
.map(a => a.tags.filter(b => b[0] === "e").map(b => b[1])).flat();
let ids = mainNotes.map(a => a.id);
let allEvents = new Set([...eTags, ...ids]);
addId(Array.from(allEvents));
})
}
2023-01-21 16:09:35 +00:00
}, [main.store]);
2023-01-17 13:03:15 +00:00
2023-01-21 16:18:44 +00:00
return main.store;
2023-02-03 21:38:14 +00:00
}