How do I customise the styling of "solved topics" in the main list?

TL;DR

This will add a topic-solution class to posts marked as the answer.

api.addPostClassesCallback((attrs) => {
  if (attrs.accepted_answer) return ["topic-solution"];
});

The classes that a post has are determined here.

The hook you want already exists at the very end of that… like so.

The plugin-api has a method that allows you to add classes to a post based on a condition.

What that does is that it applies a given callback and returns a class to be added if the condition is met.

When the callback is fired, Discourse passes the post attributes to it. So, you can, for example, do something like this.

api.addPostClassesCallback((attrs) => {
  console.log(attrs);
});

If you check the console, you’ll see that it displays the attributes of each post.

These are just examples; there’s more in there.

Lucky for you, when a post is marked as the solution, Discourse keeps track of that, and it gets added to the post attributes. The property is called accepted_answer

So, you only need to check if that’s true and add your custom class if it is. Like so

api.addPostClassesCallback((attrs) => {
  if (attrs.accepted_answer) return ["topic-solution"];
});

That should be enough to toggle the class even when the OP changes their mind and picks a different solution. It will remove the class from the old answer and add it to the new one.

4 Likes