Add custom markdown quote bbcode tags

I was able to get it working by keeping the source text in an attribute on the html, and then in the addTagDecorateCallback() callback function, I just return that in order to get the original text.

Here’s a bit of code for anyone wanting to know what I did.

In assets/javascripts/lib/discourse-markdown/snapblocks-discourse.js where it initializes the bbcode tags, I made it store the original text inside a snapblocks-source attribute so I can grab it later.

In the assets\javascripts\discourse\initializers\snapblocks-discourse.js file, I add the code to handle the quoting.

// assets\javascripts\discourse\initializers\snapblocks-discourse.js

import {
  addBlockDecorateCallback, // block bbcode tags
  addTagDecorateCallback, // inline bbcode tags
} from "discourse/lib/to-markdown";

function initializeSnapblocks(api, siteSettings) {
  addTagDecorateCallback(function () {
    // this.element is not an HTML element
    // but it does include all the html attributes
    const { attributes } = this.element;

    // Normally you would check if the "class" is your class
    // but all I need here is "snapblocks-source"
    if (attributes["snapblocks-source"]) {
      let prefix = "[sb";

      // Adding attributes to the bbcode tag (which are also stored
     // on the element as attributes).
      const attrs = [
        "blockstyle",
        "wrap",
        "wrapsize",
        "zebra",
        "showspaces",
        "santa",
      ];
      for (const attr of attrs) {
        if (attributes[attr]) {
          prefix += ` ${attr}=${attributes[attr]}`;
        }
      }

      prefix += "]";

      this.prefix = prefix;
      this.suffix = "[/sb]";
      // if you return text, this will be used instead of the selected text
      return attributes["snapblocks-source"];
    }
  });
}

This is the same for the block bbcode tags, you just have to use addBlockDecorateCallback() instead.

Now unfortunately I will have to rebake posts if I want old snapblocks snippets to be quotable. This also doesn’t handle if you select the text on the svg, it only works if you select some text before and/or after as well as at least part of the svg text.

3 Likes