From 6bdb339b88fcf529fd92141b4522012be6442356 Mon Sep 17 00:00:00 2001 From: Aljaz Grilc Date: Tue, 13 Feb 2024 09:55:37 +0100 Subject: [PATCH] Add MutationObserver for Editor Changes. This allows detection and handling of deleted 'div' elements, thereby improving error correction and overall editor functionality. --- online-editor.js | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/online-editor.js b/online-editor.js index 56c5a95..6dd1e7f 100644 --- a/online-editor.js +++ b/online-editor.js @@ -17,6 +17,7 @@ class BesEditor { edit.addEventListener('scroll', () => this.handleScrollEvent(this.el, this.scrollPanel) ) + this.observeDeletions(this.el) } // Register editor @@ -160,20 +161,44 @@ class BesEditor { } // Marks section of text that is about to change as not-yet-grammar-proofed. - handleBeforeInput(event) { + handleBeforeInput() { if (this.timer) clearTimeout(this.timer) let editor = this this.timer = setTimeout(function () { editor.proof(editor.el) }, 1000) + } - // No need to invalidate elements after range.startContainer since they will - // get either deleted or replaced. - event - .getTargetRanges() - .forEach(range => - this.clearProofed(this.getBlockParent(range.startContainer)) - ) + observeDeletions(editor) { + const observer = new MutationObserver(mutations => { + mutations.forEach(mutation => { + if (mutation.type === 'characterData') { + this.clearProofed(this.getBlockParent(mutation.target)) + } + if (mutation.type === 'childList' && mutation.removedNodes.length) { + mutation.removedNodes.forEach(node => { + // TODO: This is a temporary solution. We need to handle all cases such as

,
, etc. + if (node.nodeName === 'DIV') { + this.children = this.children.filter( + child => child.elements !== node + ) + } else console.log(node) + }) + this.children.forEach(child => { + this.clearMistakeMarkup(child.elements) + child.matches.forEach(match => { + match.rects = this.addMistakeMarkup(match.range, this.scrollPanel) + }) + }) + } + }) + }) + + observer.observe(editor, { + childList: true, + characterData: true, + subtree: true + }) } // Test if given block element has already been grammar-proofed.