Add horizontal rule to trix editor

This commit is contained in:
Jean-Baptiste Bellet
2023-07-06 22:24:04 +02:00
parent 4c27e79519
commit a8a35318f5
3 changed files with 38 additions and 1 deletions

View File

@@ -2,7 +2,7 @@
class TrixScrubber < Rails::Html::PermitScrubber
ALLOWED_TAGS = ["p", "b", "strong", "em", "i", "a", "u", "br", "del", "h1", "blockquote", "pre",
"ul", "ol", "li", "div"].freeze
"ul", "ol", "li", "div", "hr"].freeze
ALLOWED_ATTRIBUTES = ["href", "target", "src", "alt"].freeze
def initialize

View File

@@ -3,10 +3,43 @@ import { Controller } from "stimulus";
export default class extends Controller {
connect() {
window.addEventListener("trix-change", this.#trixChange);
this.#trixInitialize();
window.addEventListener("trix-initialize", this.#trixInitialize);
}
#trixChange = (event) => {
// trigger a change event on the form that contains the Trix editor
event.target.form.dispatchEvent(new Event("change", { bubbles: true }));
};
#trixActionInvoke = (event) => {
if (event.actionName === "hr") {
this.element.editor.insertAttachment(
new Trix.Attachment({ content: "<hr />", contentType: "text/html" })
);
}
};
#trixInitialize = () => {
// Add HR button to the Trix toolbar if it's not already there and the editor is present
if (
this.element.editor &&
!this.element.toolbarElement.querySelector(".trix-button--icon-hr")
) {
this.#addHRButton();
}
};
#addHRButton = () => {
const button_html = `
<button type="button" class="trix-button trix-button--icon trix-button--icon-hr" data-trix-action="hr" title="Horizontal Rule" tabindex="-1">HR</button>`;
const buttonGroup = this.element.toolbarElement.querySelector(
".trix-button-group--block-tools"
);
buttonGroup.insertAdjacentHTML("beforeend", button_html);
buttonGroup.querySelector(".trix-button--icon-hr").addEventListener("click", (event) => {
event.actionName = "hr";
this.#trixActionInvoke(event);
});
};
}

View File

@@ -2,6 +2,10 @@ trix-toolbar [data-trix-button-group="file-tools"] {
display: none;
}
trix-toolbar .trix-button--icon-hr::before {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M3 12h18v2H3z'/%3E%3C/svg%3E");
}
// Match the rendering into the shopfront (see ../darkswarm/)
trix-editor {
color: #222;