Skip to content

Instantly share code, notes, and snippets.

@kenakingkong
Last active April 19, 2024 17:37
Show Gist options
  • Save kenakingkong/5ca1dc1ef0b2fd52804c41f7d74860a1 to your computer and use it in GitHub Desktop.
Save kenakingkong/5ca1dc1ef0b2fd52804c41f7d74860a1 to your computer and use it in GitHub Desktop.
Trix Editor - Stimulus Controller and CSS styles
/* https://medium.com/@makenakong/how-to-add-and-customize-the-trix-editor-for-your-ruby-on-rails-application-c0a5d3082254 */
.trix-button--icon-strike,
.trix-button--icon-link,
.trix-button-group--block-tools,
.trix-button-group--file-tools,
.trix-button-group--history-tools {
display: none;
}
.trix-button {
background-image: none; // you may need an !important
}
// https://medium.com/@makenakong/how-to-add-and-customize-the-trix-editor-for-your-ruby-on-rails-application-c0a5d3082254
import { Controller } from "@hotwired/stimulus";
export default class TrixController extends Controller {
static UNUSED_TOOLBAR_CLASSES = [
".trix-button--icon-strike",
".trix-button--icon-link",
".trix-button-group--block-tools",
".trix-button-group--file-tools",
".trix-button-group--history-tools"
];
static TOOLBAR_BUTTON_ICONS = [
{ identifier: "trix-button--icon-bold", icon: "<svg ....></svg>"},
{ identifier: "trix-button--icon-italic", icon: "<svg ....></svg>"},
{ identifier: "trix-button--icon-underline", icon: "<svg ....></svg>"},
]
connect() {
addEventListener("trix-initialize",function (event) {
// initialize underline attribute
Trix.config.textAttributes.underline = {
tagName: "u",
style: { textDecoration: "underline" },
inheritable: true,
parser: function (element) {
var style = window.getComputedStyle(element);
return style.textDecoration === "underline";
},
};
// create underline button
let underlineEl = document.createElement("button");
underlineEl.setAttribute("type", "button");
underlineEl.setAttribute("data-trix-attribute", "underline");
underlineEl.setAttribute("data-trix-key", "u");
underlineEl.setAttribute("tabindex", -1);
underlineEl.setAttribute("title", "underline");
underlineEl.classList.add("trix-button", "trix-button--icon-underline");
underlineEl.innerHTML = "U";
// add button to toolbar
document.querySelector(".trix-button-group--text-tools").appendChild(underlineEl);
// remove unused toolbar buttons
TrixController.UNUSED_TOOLBAR_CLASSES.forEach((cls) => {
document.querySelector(cls).remove();
});
// update toolbar icons
TrixController.TOOLBAR_BUTTON_ICONS.forEach((group) => {
document.querySelector(group.identifier).innerHTML = group.icon;
});
}, true);
addEventListener("trix-file-accept", function (e) {
e.preventDefault();
}, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment