Browse Source

Properly sort by newest reply

The previous algorithm would fail with this order of comments:
- Comment 1
  - Comment 2
    - Comment 4
- Comment 3
merge-requests/150/head
blankie 1 year ago
parent
commit
ad00abe067
No known key found for this signature in database GPG Key ID: CC15FC822C7F61F5
  1. 16
      tildes/tildes/models/comment/comment_tree.py

16
tildes/tildes/models/comment/comment_tree.py

@ -92,6 +92,13 @@ class CommentTree:
comment.depth = 0
self.tree.append(comment)
@staticmethod
def _first_bottommost_reply(comment: Comment) -> Comment:
"""Continuously gets the first reply from a comment until there is no more."""
while comment.replies:
comment = comment.replies[0]
return comment
@staticmethod
def _sort_tree(tree: list[Comment], sort: CommentTreeSortOption) -> list[Comment]:
"""Sort the tree by the desired ordering (recursively).
@ -118,12 +125,13 @@ class CommentTree:
elif sort == CommentTreeSortOption.RELEVANCE:
tree = sorted(tree, key=lambda c: c.relevance_sorting_value, reverse=True)
elif sort == CommentTreeSortOption.NEWEST_REPLY:
# sort by the creation time of the most recent reply in the entire tree, or
# the comment itself if it has no children. the comment's first reply is
# the newest reply since it has been sorted above
# sort by the creation time of the first bottom-most reply in the
# entire tree, or the comment itself if there are no replies.
# the comment's first bottom-most reply is the newest reply since
# it has been sorted above
tree = sorted(
tree,
key=lambda c: (c.replies[0] if c.replies else c).created_time,
key=lambda c: CommentTree._first_bottommost_reply(c).created_time,
reverse=True,
)

Loading…
Cancel
Save