snort/src/pages/feed/ThreadFeed.js

77 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-12-18 14:51:47 +00:00
import { useContext, useEffect, useState } from "react";
2022-12-18 22:23:52 +00:00
import { useDispatch, useSelector } from "react-redux";
2022-12-18 14:51:47 +00:00
import { NostrContext } from "../..";
2022-12-18 22:23:52 +00:00
import Event from "../../nostr/Event";
2022-12-18 14:51:47 +00:00
import { Subscriptions } from "../../nostr/Subscriptions";
2022-12-18 22:23:52 +00:00
import { addNote, reset } from "../../state/Thread";
2022-12-18 14:51:47 +00:00
import { addPubKey } from "../../state/Users";
export default function useThreadFeed(id) {
const dispatch = useDispatch();
const system = useContext(NostrContext);
2022-12-18 22:23:52 +00:00
const notes = useSelector(s => s.thread.notes);
2022-12-20 23:14:13 +00:00
const [thisLoaded, setThisLoaded] = useState(false);
2022-12-18 14:51:47 +00:00
2022-12-18 22:23:52 +00:00
// track profiles
2022-12-18 14:51:47 +00:00
useEffect(() => {
2022-12-20 23:14:13 +00:00
let keys = [];
2022-12-18 22:23:52 +00:00
for (let n of notes) {
if (n.pubkey) {
2022-12-20 23:14:13 +00:00
keys.push(n.pubkey);
2022-12-18 22:23:52 +00:00
}
2022-12-20 23:14:13 +00:00
for (let t of n.tags) {
if (t[0] === "p" && t[1]) {
keys.push(t[1]);
2022-12-18 14:51:47 +00:00
}
}
}
2022-12-20 23:14:13 +00:00
dispatch(addPubKey(keys));
2022-12-18 22:23:52 +00:00
}, [notes]);
2022-12-18 14:51:47 +00:00
useEffect(() => {
if (system) {
let sub = new Subscriptions();
2022-12-20 23:14:13 +00:00
let thisNote = notes.find(a => a.id === id);
if (thisNote && !thisLoaded) {
console.debug(notes);
setThisLoaded(true);
2022-12-18 22:23:52 +00:00
let thisNote = Event.FromObject(notes[0]);
let thread = thisNote.GetThread();
if (thread !== null) {
if (thread.ReplyTo) {
sub.Ids.add(thread.ReplyTo.Event);
}
if (thread.Root) {
sub.Ids.add(thread.Root.Event);
}
for (let m of thread.Mentions) {
sub.Ids.add(m.Event);
}
2022-12-18 14:51:47 +00:00
}
2022-12-18 22:23:52 +00:00
} else if (notes.length === 0) {
sub.Ids.add(id);
} else {
return;
}
2022-12-20 23:14:13 +00:00
// get replies to this event
let subRelated = new Subscriptions();
subRelated.ETags = sub.Ids;
sub.AddSubscription(subRelated);
2022-12-18 14:51:47 +00:00
sub.OnEvent = (e) => {
2022-12-18 22:23:52 +00:00
dispatch(addNote(e));
};
2022-12-18 14:51:47 +00:00
system.AddSubscription(sub);
}
2022-12-18 22:23:52 +00:00
}, [system, notes]);
2022-12-18 14:51:47 +00:00
2022-12-18 22:23:52 +00:00
useEffect(() => {
2022-12-20 23:14:13 +00:00
console.debug("use thread stream")
2022-12-18 22:23:52 +00:00
dispatch(reset());
}, []);
2022-12-18 14:51:47 +00:00
2022-12-18 22:23:52 +00:00
return { notes };
2022-12-18 14:51:47 +00:00
}