Files
5chan/src/hooks/use-replies.ts
T

45 lines
2.0 KiB
TypeScript
Raw Normal View History

import { useMemo, useCallback } from 'react';
import { Comment, useAccountComments } from '@plebbit/plebbit-react-hooks';
2024-04-02 16:42:36 +02:00
import { flattenCommentsPages } from '@plebbit/plebbit-react-hooks/dist/lib/utils';
const useRepliesAndAccountReplies = (comment: Comment) => {
// flatten all replies including nested ones from the original comment
2024-04-02 16:42:36 +02:00
const flattenedReplies = useMemo(() => flattenCommentsPages(comment.replies), [comment.replies]);
2024-04-29 22:37:08 +02:00
// generate a Set of CIDs from flattened replies for quick lookup
const replyCids = useMemo(() => new Set(flattenedReplies.map((reply) => reply.cid)), [flattenedReplies]);
2024-04-29 22:37:08 +02:00
// filter against the original comment's CID and all CIDs in flattened replies
const filter = useCallback(
(accountComment: Comment) => {
2024-04-29 22:37:08 +02:00
return accountComment.parentCid === comment.cid || replyCids.has(accountComment.parentCid);
},
2024-04-29 22:37:08 +02:00
[comment.cid, replyCids],
);
const { accountComments } = useAccountComments({ filter });
// the account's replies have a delay before getting published, so get them locally from accountComments instead
const accountRepliesNotYetPublished = useMemo(() => {
2024-04-02 16:42:36 +02:00
const replies = flattenedReplies || [];
const replyCids = new Set(replies.map((reply: Comment) => reply?.cid));
// filter out the account comments already in comment.replies, so they don't appear twice
return accountComments.filter((accountReply) => !replyCids.has(accountReply?.cid));
2024-04-02 16:42:36 +02:00
}, [flattenedReplies, accountComments]);
const repliesAndNotYetPublishedReplies = useMemo(() => {
2024-04-23 16:10:44 +02:00
const repliesSortedByVotes = [
// put the author's unpublished replies at the top, latest first (reverse)
...accountRepliesNotYetPublished.reverse(),
// put the published replies after,
2024-04-02 16:42:36 +02:00
...(flattenedReplies || []),
];
2024-04-23 16:10:44 +02:00
// sort by timestamp
return repliesSortedByVotes.sort((a: Comment, b: Comment) => a.timestamp - b.timestamp);
2024-04-02 16:42:36 +02:00
}, [flattenedReplies, accountRepliesNotYetPublished]);
return repliesAndNotYetPublishedReplies;
};
export default useRepliesAndAccountReplies;