Refactor service.js to enhance the logic for repositioning grammar mistakes

This commit is contained in:
2024-04-15 10:17:55 +02:00
parent 37855374bb
commit 38b0b87644
2 changed files with 66 additions and 8 deletions

View File

@@ -299,6 +299,19 @@ class BesService {
element: el,
matches: matches
})
const dataToChange = this
let observer = new MutationObserver(function (mutations) {
mutations.forEach(mutation => {
if (mutation.type === 'characterData') {
const el = dataToChange.children?.find(
child => child.element === mutation.target
)
if (el) el.isProofed = false
}
})
})
observer.observe(el, { characterData: true, subtree: true })
}
/**
@@ -309,7 +322,6 @@ class BesService {
clearMistakeMarkup(el) {
let child = this.children.find(child => child.element === el)
if (!child) return
child.isProofed = false
child.matches.forEach(match => {
if (match?.highlights) {
match.highlights.forEach(h => h.remove())
@@ -646,9 +658,11 @@ class BesCKService extends BesService {
super(hostElement)
this.ckEditorInstance = ckEditorInstance
this.disableCKEditorSpellcheck(this.ckEditorInstance)
this.ckEditorInstance.model.document.on('change:data', () => {
this.handleCKInput(hostElement, ckEditorInstance)
})
hostElement.addEventListener(
'beforeinput',
e => this.handleBeforeCKInput(e),
false
)
}
/**
@@ -664,6 +678,50 @@ class BesCKService extends BesService {
return service
}
handleBeforeCKInput(event) {
const hostElement = event.target
let service = besServices.find(e => e.hostElement === hostElement)
if (!service) return
if (service.timer) clearTimeout(service.timer)
service.abortController.abort()
let blockElements = new Set()
event.getTargetRanges().forEach(range => {
BesService.getNodesInRange(range).forEach(el => {
console.log(el)
if (
el === hostElement ||
Array.from(hostElement.childNodes).includes(el)
) {
blockElements.add(service.getBlockParent(el))
}
})
})
console.log(blockElements)
blockElements.forEach(block => {
service.clearMistakeMarkup(block)
service.removeChild(block)
})
// Not a nice way to do it, but it works for now the repositionMistakes function is called before the DOM updates are finished.
// If users will experience performance issues, we can consider debouncing this function.
// The lagginess becomes noticeable if the text is long and has many grammar mistakes.
service.repositionMistakes()
setTimeout(() => {
window.dispatchEvent(new Event('resize'))
}, 100)
service.timer = setTimeout(function () {
service.abortController = new AbortController()
service.proof(hostElement)
}, 1000)
}
clearAllMistakes(el) {
if (el.children.length) {
for (let i = 0; i < el.children.length; i++) {
el.children[i].remove()
}
}
}
handleCKInput(hostElement, ckEditorInstance) {
let service = besServices.find(e => e.hostElement === hostElement)
if (!service) return