diff --git a/app/assets/javascripts/02-editor.js b/app/assets/javascripts/02-editor.js index 5d383cf..746141c 100644 --- a/app/assets/javascripts/02-editor.js +++ b/app/assets/javascripts/02-editor.js @@ -25,6 +25,17 @@ const restoreContent = (editorEl, contentEl) => { contentEl.innerHTML = content } +/* getRangeAt puede fallar si no hay una selección + */ +function safeGetRangeAt (num) { + try { + return window.getSelection().getRangeAt(num) + } catch (error) { + console.warn("No hay una selección!") + return null; + } +} + function uploadFile (file) { return new Promise((resolve, reject) => { const upload = new ActiveStorage.DirectUpload( @@ -108,7 +119,8 @@ function setupMarkButton (button, mark, contentEl) { let parentEl = getElementParent(sel.anchorNode) //if (sel.anchorNode == parentEl) parentEl = parentEl.firstChild - const range = sel.getRangeAt(0) + const range = safeGetRangeAt(0) + if (!range) return if (parentEl.matches(mark.selector)) { const [left, right] = splitNode(parentEl, range) @@ -169,7 +181,8 @@ function setupBlockButton (button, block, contentEl, editorEl) { || sel.focusNode == contentEl ) return - const range = sel.getRangeAt(0) + const range = safeGetRangeAt(0) + if (!range) return let parentEl = sel.anchorNode while (!isDirectChild(contentEl, parentEl)) parentEl = parentEl.parentElement @@ -202,7 +215,8 @@ function setupParentBlockButton (button, parentBlock, contentEl) { || sel.focusNode == contentEl ) return - const range = sel.getRangeAt(0) + const range = safeGetRangeAt(0) + if (!range) return let parentEl = sel.anchorNode while (!isDirectChild(contentEl, parentEl)) parentEl = parentEl.parentElement @@ -320,7 +334,8 @@ function cleanNode (node, contentEl) { child.parentNode.removeChild(child.nextSibling) } } else if (child.nodeType === Node.ELEMENT_NODE) { - if (!hasContent(child) && !window.getSelection().getRangeAt(0).intersectsNode(child)) + const range = safeGetRangeAt(0) + if (!hasContent(child) && (!range || !range.intersectsNode(child))) child.parentNode.removeChild(child) for (const mark of Object.values(marks)) {