From 9eb3665fa7b92715bd74ff3fe40d3849acbfd231 Mon Sep 17 00:00:00 2001 From: Peter Bui Date: Fri, 28 Jul 2023 23:37:44 -0400 Subject: [PATCH] fix: improve building comment tree (#40) As we build the map of nodes, keep track of the minimum depth level. Afterwards, nodes at the minimum depth level go into the tree as the roots. We no longer need to check if the tree belongs to a parent comment or not. Fixes #36 more. --- .../components/lemmy/comment/Comments.svelte | 2 +- src/lib/components/lemmy/comment/comments.ts | 25 +++++++------------ 2 files changed, 10 insertions(+), 17 deletions(-) diff --git a/src/lib/components/lemmy/comment/Comments.svelte b/src/lib/components/lemmy/comment/Comments.svelte index a4f934c5..3fe22e03 100644 --- a/src/lib/components/lemmy/comment/Comments.svelte +++ b/src/lib/components/lemmy/comment/Comments.svelte @@ -59,7 +59,7 @@ return } - const tree = buildCommentsTree(newComments.comments, false) + const tree = buildCommentsTree(newComments.comments, parent.depth) // 0.18.2 -> 0.18.3 broke this // so i'm adding this check diff --git a/src/lib/components/lemmy/comment/comments.ts b/src/lib/components/lemmy/comment/comments.ts index a3f64275..5a4ce728 100644 --- a/src/lib/components/lemmy/comment/comments.ts +++ b/src/lib/components/lemmy/comment/comments.ts @@ -24,31 +24,29 @@ function getDepthFromComment(comment?: Comment): number | undefined { export function buildCommentsTree( comments: CommentView[], - parentComment: boolean, baseDepth: number = 0 ): CommentNodeI[] { const map = new Map() - const depthOffset = !parentComment - ? 0 - : getDepthFromComment(comments[0].comment) ?? 0 + let min_depth = Number.MAX_VALUE for (const comment_view of comments) { const depthI = getDepthFromComment(comment_view.comment) ?? 0 - const depth = depthI ? depthI - depthOffset : 0 + const depth = depthI + baseDepth const node: CommentNodeI = { comment_view, children: [], - depth: depth + baseDepth, + depth: depth, } + min_depth = Math.min(min_depth, depth) map.set(comment_view.comment.id, { ...node }) } const tree: CommentNodeI[] = [] - // if its a parent comment fetch, then push the first comment to the top node. - if (parentComment) { - const cNode = map.get(comments[0].comment.id) - if (cNode) { + // push all nodes at the minimum depth to the top of the tree + for (const comment_view of comments) { + const cNode = map.get(comment_view.comment.id) + if (cNode && cNode.depth == min_depth) { tree.push(cNode) } } @@ -63,10 +61,6 @@ export function buildCommentsTree( if (parent) { parent.children.push(child) } - } else { - if (!parentComment) { - tree.push(child) - } } } } @@ -120,9 +114,8 @@ export function insertCommentIntoTree( export async function buildCommentsTreeAsync( comments: CommentView[], - parentComment: boolean ) { - const result = buildCommentsTree(comments, parentComment) + const result = buildCommentsTree(comments) return result }