I’ve experience building custom solutions with other platforms/frameworks, and want to understand if this is the correct way to create a theme component in Discourse.
It seems to be working, but doesn’t necessarily mean it’s the correct way.
In short, this should hide reaction depending on the category a topic is within. Is this the right way to do it?
<script type="text/discourse-plugin" version="0.1">
$(document).ready(function() {
try {
const isTopicPage = /^\/t\//.test(window.location.pathname);
if (!isTopicPage) return;
const allowedCategories = ['ask-a-question'];
const topic = Discourse.__container__.lookup("controller:topic");
const categorySlug = topic && topic.get("model.category.slug");
const isAllowedCategory = categorySlug && allowedCategories.includes(categorySlug);
const toggleReactionEmoji = () => {
const emoji = document.querySelector("[data-reaction='frog']");
if (emoji) {
emoji.style.display = isAllowedCategory ? '' : 'none';
console.log(`Emoji with data-reaction='frog' ${isAllowedCategory ? 'shown' : 'hidden'}.`);
}
};
toggleReactionEmoji();
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) {
const emoji = node.querySelector("[data-reaction='frog']");
if (emoji) {
emoji.style.display = isAllowedCategory ? '' : 'none';
console.log(`Emoji with data-reaction='frog' found in mutation and ${isAllowedCategory ? 'shown' : 'hidden'}.`);
}
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
api.cleanupStream(() => observer.disconnect());
} catch (error) {
console.error("An error occurred in the emoji toggle script:", error);
}
});
</script>