Created
April 28, 2020 17:23
-
-
Save hkan/56a7949e99dab0eec1e26f39c02c424c to your computer and use it in GitHub Desktop.
Alpine's x-text directive improved to support contenteditable elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function handleTextDirective(el, output, expression) { | |
// If nested model key is undefined, set the default value to empty string. | |
if (output === undefined && expression.match(/\./).length) { | |
output = '' | |
} | |
let selection | |
let anchorNode | |
let position | |
let isElBeingEdited | |
if (el.isContentEditable) { | |
selection = window.getSelection() | |
anchorNode = selection.anchorNode | |
position = selection.anchorOffset | |
isElBeingEdited = el.contains(anchorNode) | |
} | |
el.innerText = output | |
if (el.isContentEditable && isElBeingEdited) { | |
const textNode = Array.from(el.childNodes).find(node => node.nodeType === el.TEXT_NODE); | |
if (textNode) { | |
const range = new Range() | |
range.selectNode(el) | |
range.setStart(textNode, position) | |
range.setEnd(textNode, position) | |
selection.empty() | |
selection.addRange(range) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment