From 7742b1c35922a66adf17afe48cf3523dcfcdea8d Mon Sep 17 00:00:00 2001 From: edave64 Date: Fri, 19 Jul 2024 11:47:11 +0200 Subject: [PATCH] Make the emitter work with multiple documents --- packages/quill/src/core/emitter.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/quill/src/core/emitter.ts b/packages/quill/src/core/emitter.ts index 7e981ed47b..851dbbe580 100644 --- a/packages/quill/src/core/emitter.ts +++ b/packages/quill/src/core/emitter.ts @@ -5,17 +5,6 @@ import logger from './logger.js'; const debug = logger('quill:events'); const EVENTS = ['selectionchange', 'mousedown', 'mouseup', 'click']; -EVENTS.forEach((eventName) => { - document.addEventListener(eventName, (...args) => { - Array.from(document.querySelectorAll('.ql-container')).forEach((node) => { - const quill = instances.get(node); - if (quill && quill.emitter) { - quill.emitter.handleDOM(...args); - } - }); - }); -}); - class Emitter extends EventEmitter { static events = { EDITOR_CHANGE: 'editor-change', @@ -39,6 +28,24 @@ class Emitter extends EventEmitter { USER: 'user', } as const; + private static registeredDocuments = new WeakMap(); + + static registerEventsOnDocument(doc: Document) { + if (Emitter.registeredDocuments.get(doc)) return; + Emitter.registeredDocuments.set(doc, true); + + EVENTS.forEach((eventName) => { + doc.addEventListener(eventName, (...args) => { + Array.from(doc.querySelectorAll('.ql-container')).forEach((node) => { + const quill = instances.get(node); + if (quill && quill.emitter) { + quill.emitter.handleDOM(...args); + } + }); + }); + }); + } + protected domListeners: Record; constructor() { @@ -62,6 +69,7 @@ class Emitter extends EventEmitter { } listenDOM(eventName: string, node: Node, handler: EventListener) { + Emitter.registerEventsOnDocument(node.ownerDocument ?? document); if (!this.domListeners[eventName]) { this.domListeners[eventName] = []; }