From 30e14e5d31e56ae3631defdd46d46f5fe515b978 Mon Sep 17 00:00:00 2001 From: Deimos Date: Thu, 12 Sep 2019 17:19:16 -0600 Subject: [PATCH] Calculate comment depths when building CommentTree Previously I was just using Jinja's built-in loop.depth0 to output comment depth in HTML, but actually attaching a depth attribute to the comments will allow it to be used elsewhere as well. It's possible this should even be on the Comment model itself, since it never changes and might be useful in other ways. --- tildes/tests/test_comment.py | 5 +++++ tildes/tildes/models/comment/comment_tree.py | 4 ++++ tildes/tildes/templates/macros/comments.jinja2 | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tildes/tests/test_comment.py b/tildes/tests/test_comment.py index 7115a4b..92a56f2 100644 --- a/tildes/tests/test_comment.py +++ b/tildes/tests/test_comment.py @@ -189,6 +189,11 @@ def test_comment_tree(db, topic, session_user): assert child.replies == [] assert child2.replies == [subchild, subchild2] + # check depth values are as expected + assert root.depth == 0 + assert child.depth == 1 + assert subchild.depth == 2 + # delete child2 (which has replies) and ensure it stays in the tree child2.is_deleted = True db.commit() diff --git a/tildes/tildes/models/comment/comment_tree.py b/tildes/tildes/models/comment/comment_tree.py index abf65ee..5ba3386 100644 --- a/tildes/tildes/models/comment/comment_tree.py +++ b/tildes/tildes/models/comment/comment_tree.py @@ -69,6 +69,8 @@ class CommentTree: for comment in self.comments: if comment.parent_comment_id: parent_comment = self.comments_by_id[comment.parent_comment_id] + + comment.depth = parent_comment.depth + 1 parent_comment.replies.append(comment) # if this comment isn't deleted, work back up towards the root, @@ -83,6 +85,7 @@ class CommentTree: next_parent_id = parent_comment.parent_comment_id parent_comment = self.comments_by_id[next_parent_id] else: + comment.depth = 0 self.tree.append(comment) @staticmethod @@ -235,6 +238,7 @@ class CommentInTree(ObjectProxy): self.replies: List[CommentInTree] = [] self.has_visible_descendant = False self.num_children = 0 + self.depth: Optional[int] = None @property def has_uncollapsed_descendant(self) -> bool: diff --git a/tildes/tildes/templates/macros/comments.jinja2 b/tildes/tildes/templates/macros/comments.jinja2 index 95b6ebc..19a1bfc 100644 --- a/tildes/tildes/templates/macros/comments.jinja2 +++ b/tildes/tildes/templates/macros/comments.jinja2 @@ -21,7 +21,7 @@ {# only add depth attr if we're rendering multiple comments at once #} {% if not is_individual_comment %} - data-comment-depth="{{ loop.depth0 }}" + data-comment-depth="{{ comment.depth }}" {% endif %} {% if request.has_permission("label", comment) %}