]> Untitled Git - lemmy-ui.git/blob - src/shared/utils/app/build-comments-tree.ts
fix: Fix badge alignment and break out into component
[lemmy-ui.git] / src / shared / utils / app / build-comments-tree.ts
1 import { getCommentParentId, getDepthFromComment } from "@utils/app";
2 import { CommentView } from "lemmy-js-client";
3 import { CommentNodeI } from "../../interfaces";
4
5 export default function buildCommentsTree(
6   comments: CommentView[],
7   parentComment: boolean
8 ): CommentNodeI[] {
9   const map = new Map<number, CommentNodeI>();
10   const depthOffset = !parentComment
11     ? 0
12     : getDepthFromComment(comments[0].comment) ?? 0;
13
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 = {
18       comment_view,
19       children: [],
20       depth,
21     };
22     map.set(comment_view.comment.id, { ...node });
23   }
24
25   const tree: CommentNodeI[] = [];
26
27   // if its a parent comment fetch, then push the first comment to the top node.
28   if (parentComment) {
29     const cNode = map.get(comments[0].comment.id);
30     if (cNode) {
31       tree.push(cNode);
32     }
33   }
34
35   for (const comment_view of comments) {
36     const child = map.get(comment_view.comment.id);
37     if (child) {
38       const parent_id = getCommentParentId(comment_view.comment);
39       if (parent_id) {
40         const parent = map.get(parent_id);
41         // Necessary because blocked comment might not exist
42         if (parent) {
43           parent.children.push(child);
44         }
45       } else {
46         if (!parentComment) {
47           tree.push(child);
48         }
49       }
50     }
51   }
52
53   return tree;
54 }