The cartoon Mastodon mascot on the left, with the hugo logo on the right.

Threaded Mastodon Comments

Already before I set up this website using Hugo, I wanted to integrate Mastodon comments into the posts. I had already come across this implementation by Carl Schwan before, and it seems to work really well.

Integrating it was fairly straightforward, and is already explained in his post. I modified it a bit to remove the dialog box and include the core of those instructions in the comment section preamble. Aside from that, I was happy with the original setup as a starting point.

Adding Threads

The main modification I wanted to make was to make the comments threaded. Although only into two levels, as anything deeper just makes it difficult to style it properly.

Looking at the JSON response from the Mastodon API, it was fairly easy to spot the solution. The ID of the post a comment is replying to is listed in the data. To check whether the reply is directed towards the root post (the one referenced in the blog post front matter), or a reply to another comment, is just a matter of comparing the IDs. So, I added the following line in the JavaScript:

reply.account.reply_class =
  reply.in_reply_to_id == "{{ .id }}" ? "reply-original" : "reply-child";

The reply_class value is then inserted into the div element that shows the SVG icon with the reply arrow symbol (I used one from Font Awesome, and rotated it 180⁰):

<div class="comment-level ${reply.account.reply_class}">
  <svg [...]>[...]</svg>
</div>

The div is part of a flex box setup with the comment itself as its sibling, so my CSS looks like this:

#article-comments div.reply-original {
  display: none;
}

#article-comments div.reply-child {
  display: block;
  flex: 0 0 1.75rem;
  text-align: right;
}

That’s it. It’s all that was needed to make the comments minimally threaded.

The result looks like this:

An example of threaded comments

Comments

You can use your Mastodon account to comment on this post by replying to this thread.

Alternatively, you can copy and paste the URL below into the search field of your Fediverse app or the web interface of your Mastodon server.

The Mastodon integration is based on the implementation by Carl Schwan.