More on Mastodon Comments

This post uses interactive code blocks! Feel free to edit and experiment with the code. All code listings here are MIT licensed with no warranty.

In my previous post, I demonstrated Mastodon comments being used for in-page discussions on this website, but didn’t explain how it worked. (Honestly, the post was barely a post and just demonstrated the concept)

So how does it work?

The Mastodon API has an extremely handy function context for a given status, with which we can ask a Mastodon instance to give us all the ancestors and descendants for a specific status.

By taking the public post URL, we can split out the domain and comment id:

URL    = https://fediscience.org/@johnvidler/110921679945683327
Domain = ^^^^^^^^^^^^^^^^^^^^^^^
UID = ^^^^^^^^^^^^^^^^^^

Somewhat strangely, we don’t need the username… but anyway, we can then reconstruct this into a REST API address like so:

REST URL = https://fediscience.org/api/v1/statuses/110921679945683327/context
Domain = ^^^^^^^^^^^^^^^^^^^^^^^
UID = ^^^^^^^^^^^^^^^^^^

An in-browser demonstration for the previous post’s comments is shown here; click ‘Run’ to see the data.

Unfortunately, the statuses are returned in a flat list (in time order), and ideally we’d like to be able to do comment threading where the parent comment has its replies as part of the parent context, so we can recursively render the reply list and get the nested comments seen on the previous post.

To do this, I threw together the treeifyComments which recursively wanders a tree structure looking for where the status property in_reply_to_id matches a node, and adds the status to the node’s replies list, with a few fallbacks for cases where no mapping can be found.

The following code is an annotated version of this function, and if you click ‘Run’ it will populate the root object with a nested set of comments.

With this structure loaded (and cached by my static build system to keep requests infrequent!) we can now render this into a series of nested <div>s and style it to our hearts content.

Taa-daa!

If you have questions, do reach out via the links below.

Comments

Join the discussion this post on Mastodon

Comments and content are copyright their authors below.

(Comments are updated when the site rebuilds, so may take up to 24 hours to appear!)