BBcode color tags in a theme

Themes have improved a lot since this plugin was created. You can already do this with a post decorator if you’re OK with the non-standard BBCode.

common > header

<script type="text/discourse-plugin" version="0.8">
  const hasAlpha = /(.,){3}|\//;
  const MAX_LENGTH = 25;

  const getVariable = value => {
    const color = value.replace(/\s/g, "");
    return hasAlpha.test(color) || color.length > MAX_LENGTH ? "" : color;
  };

  api.decorateCookedElement(
    post => {
      post
        .querySelectorAll("[data-color]")
        .forEach(i =>
          i.style.setProperty("--color", getVariable(i.dataset.color))
        );

      post
        .querySelectorAll("[data-bgcolor]")
        .forEach(i =>
          i.style.setProperty("--bgcolor", getVariable(i.dataset.bgcolor))
        );
    },
    { id: "wrap-colors" }
  );
</script>

common > css

.cooked,
.d-editor-preview {
  [data-color] {
    color: var(--color);
  }

  [data-bgcolor] {
    background-color: var(--bgcolor);
  }
}

It will accept any valid CSS color (color name, hex, RGB, HSL). It won’t accept RGBA or HSLA colors if they set an alpha value.

In the composer, you add this

color only
[wrap=color color=yellow]Hi there![/wrap] Welcome!

background only
[wrap=color bgcolor=red]Hi there![/wrap] Welcome!

color and background
[wrap=color color=#ff0000 bgcolor=white]Hi there![/wrap] Welcome!

and change the color to whatever you want.

Note that if you want to use HSL or RGB, you have to wrap them in quotes like so

bgcolor="rgba(0,0,0)"

This is safe with regard to user input and XSS since Discourse already escapes [wrap] tags, plus there’s also CSP. However…

4 Likes