diff options
| author | Armand Philippot <git@armandphilippot.com> | 2021-12-27 11:12:47 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2021-12-27 11:12:47 +0100 |
| commit | 7deed83dbb8835727c743662bee776794d460e74 (patch) | |
| tree | db66e3840c42c9c9a6964041d862a9d784ec4410 /src/utils | |
| parent | ef7912256cb4765d553b002c24b9752c2d5096ac (diff) | |
chore: display comments as a tree
I was displaying comments without the parent/children link. Now, each
child is displayed under its parent. I also remove the reply button for
children to avoid too many child depth.
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/helpers/format.ts | 31 |
1 files changed, 30 insertions, 1 deletions
diff --git a/src/utils/helpers/format.ts b/src/utils/helpers/format.ts index fc7f1c2..81bae9c 100644 --- a/src/utils/helpers/format.ts +++ b/src/utils/helpers/format.ts @@ -158,6 +158,34 @@ export const getFormattedComments = (rawComments: RawComment[]): Comment[] => { }; /** + * Create a comments tree with replies. + * @param comments - A flatten comments list. + * @returns An array of comments with replies. + */ +export const buildCommentsTree = (comments: Comment[]) => { + type CommentsHashTable = { + [key: string]: Comment; + }; + + const hashTable: CommentsHashTable = Object.create(null); + const commentsTree: Comment[] = []; + + comments.forEach( + (comment) => (hashTable[comment.id] = { ...comment, replies: [] }) + ); + + comments.forEach((comment) => { + if (!comment.parentId) { + commentsTree.push(hashTable[comment.id]); + } else { + hashTable[comment.parentId].replies.push(hashTable[comment.id]); + } + }); + + return commentsTree; +}; + +/** * Format an article from RawArticle to Article type. * @param rawPost - An article coming from WP GraphQL. * @returns A formatted article. @@ -183,11 +211,12 @@ export const getFormattedPost = (rawPost: RawArticle): Article => { }; const formattedComments = getFormattedComments(comments.nodes); + const commentsTree = buildCommentsTree(formattedComments); const formattedPost: Article = { author: author.node, commentCount, - comments: formattedComments, + comments: commentsTree, content: contentParts.afterMore, databaseId, dates, |
