From bb30bee737b74e97b14ce7bc2a0fb78c09aa41a7 Mon Sep 17 00:00:00 2001 From: zane Date: Thu, 30 Oct 2025 11:16:57 +0800 Subject: [PATCH] fix(core):multiple-instances-style --- .changeset/chatty-items-build.md | 5 ++++ packages/core/src/Editor.ts | 42 +++++++++++++++++++++++--------- 2 files changed, 35 insertions(+), 12 deletions(-) create mode 100644 .changeset/chatty-items-build.md diff --git a/.changeset/chatty-items-build.md b/.changeset/chatty-items-build.md new file mode 100644 index 0000000000..8462d07384 --- /dev/null +++ b/.changeset/chatty-items-build.md @@ -0,0 +1,5 @@ +--- +'@tiptap/core': patch +--- + +fix(core):multiple-instances-style diff --git a/packages/core/src/Editor.ts b/packages/core/src/Editor.ts index b42426e2a3..f6dd9fd7e5 100644 --- a/packages/core/src/Editor.ts +++ b/packages/core/src/Editor.ts @@ -162,8 +162,13 @@ export class Editor extends EventEmitter { this.createView(el) this.emit('mount', { editor: this }) - if (this.css && !document.head.contains(this.css)) { - document.head.appendChild(this.css) + if (this.css) { + if (document.head.contains(this.css)) { + const refCount = this.css.getAttribute('ref-count') || '1' + this.css.setAttribute('ref-count', `${Number(refCount) + 1}`) + } else { + document.head.appendChild(this.css) + } } window.setTimeout(() => { @@ -197,21 +202,34 @@ export class Editor extends EventEmitter { // Safely remove CSS element with fallback for test environments // Only remove CSS if no other editors exist in the document after unmount if (this.css && !document.querySelectorAll(`.${this.className}`).length) { - try { - if (typeof this.css.remove === 'function') { - this.css.remove() - } else if (this.css.parentNode) { - this.css.parentNode.removeChild(this.css) - } - } catch (error) { - // Silently handle any unexpected DOM removal errors in test environments - console.warn('Failed to remove CSS element:', error) + const refCount = this.css.getAttribute('ref-count') || '1' + if (Number(refCount) <= 1) { + this.removeCss() + } else { + this.css.setAttribute('ref-count', `${Number(refCount) - 1}`) } } - this.css = null this.emit('unmount', { editor: this }) } + private removeCss() { + if (!this.css) { + return + } + try { + if (typeof this.css.remove === 'function') { + this.css.remove() + } else if (this.css.parentNode) { + this.css.parentNode.removeChild(this.css) + } + } catch (error) { + // Silently handle any unexpected DOM removal errors in test environments + console.warn('Failed to remove CSS element:', error) + } + + this.css = null + } + /** * Returns the editor storage. */