import { Controller } from "@hotwired/stimulus"; import "trix"; // Note, action_text 7.1.2 changes how Trix is bundled and loaded. This // seems to have broken the default export from trix. This is a workaround // that relies on the backwards compatibility of the old export to window.Trix. const Trix = window.Trix; // Stimulus controller doesn't do anything, but having one ensures that trix // will be lazy loaded when a trix-editor is added to the dom. export default class TrixController extends Controller { trixInitialize(e) { this.element.addEventListener( "turbo:before-morph-attribute", this.suppressMorph, ); this.element.addEventListener( "turbo:before-morph-element", this.suppressMorph, ); if (this.element.toolbarElement) { this.element.toolbarElement.addEventListener( "turbo:before-morph-attribute", this.suppressMorph, ); this.element.toolbarElement.addEventListener( "turbo:before-morph-element", this.suppressMorph, ); } } disconnect() { this.element.removeEventListener( "turbo:before-morph-attribute", this.suppressMorph, ); this.element.removeEventListener( "turbo:before-morph-element", this.suppressMorph, ); if (this.element.toolbarElement) { this.element.toolbarElement.removeEventListener( "turbo:before-morph-attribute", this.suppressMorph, ); this.element.toolbarElement.removeEventListener( "turbo:before-morph-element", this.suppressMorph, ); } } suppressMorph = (e) => { // https://github.com/hotwired/turbo-rails/issues/533 // Note that this will prevent updates from the server from making their way // to the trix element. Once the upstream issue is resolved we should remove // this compatibility patch. if ( e.target.tagName === "TRIX-EDITOR" || e.target.tagName === "TRIX-TOOLBAR" ) { e.preventDefault(); } }; } // Add H4 as an acceptable tag Trix.config.blockAttributes["heading4"] = { tagName: "h4", terminal: true, breakOnReturn: true, group: false, }; // Remove H1 from trix list of acceptable tags delete Trix.config.blockAttributes.heading1; /** * Allow users to enter path and fragment URIs which the input[type=url] browser * input does not permit. Uses a permissive regex pattern which is not suitable * for untrusted use cases. */ const LINK_PATTERN = "(https?|mailto:|tel:|/|#).*?"; /** * Customize default toolbar: * * * headings: h4 instead of h1 * * links: use type=text instead of type=url * * @returns {String} toolbar html fragment */ Trix.config.toolbar.getDefaultHTML = () => { const { lang } = Trix.config; return `
`; }; /** * If the element is in the HTML when Trix loads, then Trix will have already injected the toolbar content * before our code gets a chance to run. Fix that now. * * Note: in Trix 2 this is likely to no longer be necessary. */ document.querySelectorAll("trix-toolbar").forEach((e) => { e.innerHTML = Trix.config.toolbar.getDefaultHTML(); });