]> Untitled Git - lemmy-ui.git/blob - src/shared/utils/app/build-comments-tree.ts
fix submodule error
[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   // 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);
41     if (child) {
42       const parent_id = getCommentParentId(comment_view.comment);
43       if (parent_id) {
44         const parent = map.get(parent_id);
45         // Necessary because blocked comment might not exist
46         if (parent) {
47           parent.children.push(child);
48         }
49       } else {
50         if (!parentComment) {
51           tree.push(child);
52         }
53       }
54     }
55   }
56
57   return tree;
58 }