snort/src/Feed/ThreadFeed.ts

49 lines
1.7 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";
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) => {
let tmp = new Set([...s, ...id]);
return Array.from(tmp);
})
}
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-01-20 17:07:14 +00:00
subRelated.Kinds = new Set(pref.enableReactions ? [EventKind.Reaction, EventKind.TextNote, EventKind.Deletion, EventKind.Repost] : [EventKind.TextNote]);
2022-12-30 23:35:02 +00:00
subRelated.ETags = thisSub.Ids;
thisSub.AddSubscription(subRelated);
return thisSub;
2023-01-17 13:03:15 +00:00
}, [trackingEvents]);
2022-12-30 23:35:02 +00:00
const main = useSubscription(sub, { leaveOpen: true });
2023-01-17 13:03:15 +00:00
useEffect(() => {
// debounce
let t = setTimeout(() => {
2023-01-21 16:09:35 +00:00
let eTags = main.store.notes.map(a => a.tags.filter(b => b[0] === "e").map(b => b[1])).flat();
let ids = main.store.notes.map(a => a.id);
2023-01-17 13:03:15 +00:00
let allEvents = new Set([...eTags, ...ids]);
addId(Array.from(allEvents));
}, 200);
return () => clearTimeout(t);
2023-01-21 16:09:35 +00:00
}, [main.store]);
2023-01-17 13:03:15 +00:00
return main;
2022-12-18 14:51:47 +00:00
}