1 import { getCommentParentId, getDepthFromComment } from "@utils/app";
2 import { CommentView } from "lemmy-js-client";
3 import { CommentNodeI } from "../../interfaces";
5 export default function buildCommentsTree(
6 comments: CommentView[],
7 parentComment: boolean,
9 const map = new Map<number, CommentNodeI>();
10 const depthOffset = !parentComment
12 : getDepthFromComment(comments[0].comment) ?? 0;
14 for (const comment_view of comments) {
15 const depthI = getDepthFromComment(comment_view.comment) ?? 0;
16 const depth = depthI ? depthI - depthOffset : 0;
17 const node: CommentNodeI = {
22 map.set(comment_view.comment.id, { ...node });
25 const tree: CommentNodeI[] = [];
27 // if its a parent comment fetch, then push the first comment to the top node.
29 const cNode = map.get(comments[0].comment.id);
35 // This should not be sorted on the front end, in order to preserve the
36 // back end sorts. However, the parent ids must be sorted, so make sure
37 // When adding new comments to trees, that they're inserted right after
38 // their parent index. This is done in post.tsx
39 for (const comment_view of comments) {
40 const child = map.get(comment_view.comment.id);
42 const parent_id = getCommentParentId(comment_view.comment);
44 const parent = map.get(parent_id);
45 // Necessary because blocked comment might not exist
47 parent.children.push(child);