Skip to content

Commit 2c08bfb

Browse files
committed
Make Trix compatible with morphing
Morphing the trix editor will leave it in an unusuable state because morphing will replace the bootstrapping elements without triggering the connection logic. The solution is based on adding an attribute to flag the editor as initialized and detect when that attribute is modified. See hotwired/turbo-rails#533 (comment)
1 parent 7bf3e5a commit 2c08bfb

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/trix/elements/trix_editor_element.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,8 @@ class LegacyDelegate {
348348
export default class TrixEditorElement extends HTMLElement {
349349
static formAssociated = "ElementInternals" in window
350350

351+
static observedAttributes = [ "initialized" ]
352+
351353
#delegate
352354

353355
constructor() {
@@ -410,6 +412,7 @@ export default class TrixEditorElement extends HTMLElement {
410412
} else if (this.parentNode) {
411413
const toolbarId = `trix-toolbar-${this.trixId}`
412414
this.setAttribute("toolbar", toolbarId)
415+
this.setAttribute("internal-toolbar", "")
413416
const element = makeElement("trix-toolbar", { id: toolbarId })
414417
this.parentNode.insertBefore(element, this)
415418
return element
@@ -453,6 +456,14 @@ export default class TrixEditorElement extends HTMLElement {
453456
this.editor?.loadHTML(this.defaultValue)
454457
}
455458

459+
// Element callbacks
460+
461+
attributeChangedCallback(name, oldValue, newValue) {
462+
if (name === "initialized" && oldValue && oldValue !== newValue) {
463+
requestAnimationFrame(() => this.reconnect())
464+
}
465+
}
466+
456467
// Controller delegate methods
457468

458469
notify(message, data) {
@@ -485,6 +496,8 @@ export default class TrixEditorElement extends HTMLElement {
485496
}
486497
this.editorController.registerSelectionManager()
487498
this.#delegate.connectedCallback()
499+
500+
this.setAttribute("initialized", "true")
488501
autofocus(this)
489502
}
490503
}
@@ -494,6 +507,18 @@ export default class TrixEditorElement extends HTMLElement {
494507
this.#delegate.disconnectedCallback()
495508
}
496509

510+
async reconnect() {
511+
this.removeInternalToolbar()
512+
this.disconnectedCallback()
513+
this.connectedCallback()
514+
}
515+
516+
removeInternalToolbar() {
517+
if (this.toolbarElement?.hasAttribute("internal-toolbar")) {
518+
this.toolbarElement.remove()
519+
}
520+
}
521+
497522
// Form support
498523

499524
checkValidity() {

0 commit comments

Comments
 (0)