Enhance replaceText logic for CKEditor

This commit is contained in:
Aljaž Grilc 2024-03-13 08:48:00 +01:00
parent dde1010026
commit 374dd0045a

View File

@ -536,24 +536,36 @@ class BesEditor {
// This function should be able to handle both cases or find a way that works for both.
static replaceText(el, rect, match, replacement, editor) {
// const tags = this.getTagsAndText(el)
const text = el.textContent
const newText =
text.substring(0, match.offset) +
replacement +
text.substring(match.offset + match.length)
el.textContent = newText
if (editor.CKEditorInstance) {
if (!editor.CKEditorInstance) {
const text = el.textContent
const newText =
text.substring(0, match.offset) +
replacement +
text.substring(match.offset + match.length)
el.textContent = newText
} else {
const { CKEditorInstance } = editor
CKEditorInstance.model.change(writer => {
// Find the corresponding element in the model.
const viewElement =
CKEditorInstance.editing.view.domConverter.mapDomToView(el)
const modelElement =
CKEditorInstance.editing.mapper.toModelElement(viewElement)
if (modelElement) {
writer.remove(writer.createRangeIn(modelElement))
writer.insertText(newText, modelElement, 'end')
const elementRange = writer.createRangeIn(modelElement)
// TODO: This logic should work once the HTML tags are removed from match.offset and match.length if is possible.
if (
elementRange.start.offset <= match.offset &&
elementRange.end.offset >= match.offset + match.length
) {
const start = writer.createPositionAt(modelElement, match.offset)
const end = writer.createPositionAt(
modelElement,
match.offset + match.length
)
const range = writer.createRange(start, end)
writer.remove(range)
writer.insertText(replacement, start)
}
}
})
}