From 7fc063650ce326942506e24ac1186e3af7a028d9 Mon Sep 17 00:00:00 2001 From: Simon Rozman Date: Tue, 6 Feb 2024 16:23:47 +0100 Subject: [PATCH] Cache correction panel element We will create this element dynamically in the future. Not to collide with sibling editors, we'd need to assign it a unique ID. --OR-- Just cache the element we will be creating and we won't need countless document.getElementById() calls. --- online-editor.js | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/online-editor.js b/online-editor.js index 494da2c..0da9713 100644 --- a/online-editor.js +++ b/online-editor.js @@ -5,7 +5,7 @@ class BesEditor { this.el = edit this.timer = null this.children = [] - + this.correctionPanel = document.getElementById('correction-panel') // TODO: use document.createElement('div') and insert it before edit element in DOM. this.proof(edit) edit.addEventListener( 'beforeinput', @@ -96,7 +96,7 @@ class BesEditor { matches.push({ range: range, - rects: BesEditor.addMistake(range, match), + rects: this.addMistake(range, match), match: match }) }) @@ -179,10 +179,9 @@ class BesEditor { let filteredChildren = this.children.filter(child => child.elements === el) if (!filteredChildren.length) return - const correctionPanel = document.getElementById('correction-panel') filteredChildren[0].matches.forEach(match => { for (const rect of match.rects) { - for (let child of correctionPanel.children) { + for (let child of this.correctionPanel.children) { let childRect = child.getBoundingClientRect() const isWithinRect = childRect.left >= rect.left && @@ -198,8 +197,7 @@ class BesEditor { } // Adds grammar mistake markup - static addMistake(range, match) { - const correctionPanel = document.getElementById('correction-panel') + addMistake(range, match) { const clientRects = range.getClientRects() for (let i = 0, n = clientRects.length; i < n; ++i) { const rect = clientRects[i] @@ -209,7 +207,7 @@ class BesEditor { highlight.style.top = `${rect.top}px` highlight.style.width = `${rect.width}px` highlight.style.height = `${rect.height}px` - correctionPanel.appendChild(highlight) + this.correctionPanel.appendChild(highlight) } return clientRects } @@ -305,7 +303,7 @@ window.onresize = () => { editor.children.forEach(child => { editor.clearAllMistakes(child.elements) child.matches.forEach(match => { - match.rects = BesEditor.addMistake(match.range, match) + match.rects = editor.addMistake(match.range, match) }) }) })