From 7b86cf726d4416c4a613a564c795016d3e21df58 Mon Sep 17 00:00:00 2001 From: Cy Date: Mon, 1 Jun 2020 01:35:00 +0000 Subject: [PATCH] Viewing threads as a tree, not flattened I couldn't tell who was replying to whom, so I thought I'd give a shot at implementing a tree of threads, instead of a flattened list, with only the root distinguishable from the rest. --- brutaldon/threadtree.py | 54 +++++++++++++++++++++++++++++++++++++++++ brutaldon/views.py | 6 ++++- 2 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 brutaldon/threadtree.py diff --git a/brutaldon/threadtree.py b/brutaldon/threadtree.py new file mode 100644 index 0000000..32aee85 --- /dev/null +++ b/brutaldon/threadtree.py @@ -0,0 +1,54 @@ +def maketree(descendants): + lookup = {(descendant.id, descendant) for descendant in descendants} + replies = {} + roots = set() + for descendant in descendants: + if not descendant.in_reply_to_id: + roots.add(descendant.id) + if descendant.in_reply_to_id in replies: + reps = replies[descendant.in_reply_to_id] + reps.add(descendant.id) + else: + reps = set() + replies[descendant.in_reply_to_id] = set([descendant.id]) + seen = set() + def onelevel(reps): + for rep in reps: + if rep in seen: continue + seen.add(rep) + subreps = replies.get(rep) + if subreps: + yield lookup[rep], onelevel(subreps) + else: + yield lookup[rep], () + for root in roots: + seen.add(root) + reps = replies.get(root) + if reps: + yield lookup[root], onelevel(reps) + else: + yield lookup[root], () +# returns (status, gen[(status, gen[(status, ...), (status, ())]), ...]) + +# django can't do recursion well so we'll turn the tree +# ((A, (B, C))) +# into +# (in, in, A, in, B, C, out, out, out) +class OPERATION: pass +IN = OPERATION() +OUT = OPERATION() +class POST(OPERATION): + post = None + def __init__(self, post): + self.post = post + +def unmaketree(tree): + for post, children in tree: + yield POST(post) + if children: + yield IN + yield from unmaketree(children) + yield OUT + +def threadtree(descendants): + return unmaketree(maketree(descendants)) diff --git a/brutaldon/views.py b/brutaldon/views.py index ef76ebf..e4d7ee0 100644 --- a/brutaldon/views.py +++ b/brutaldon/views.py @@ -687,6 +687,10 @@ def thread(request, id): notifications = _notes_count(account, mastodon) filters = get_filters(mastodon, context="thread") + import pprint + pprint.pprint(context) + raise SystemExit(23) + # Apply filters descendants = [ x for x in context.descendants if not toot_matches_filters(x, filters) @@ -699,7 +703,7 @@ def thread(request, id): "context": context, "toot": toot, "root": root, - "descendants": descendants, + "descendants": unmaketree(maketree(descendants)), "own_acct": request.session["active_user"], "notifications": notifications, "preferences": account.preferences,