Skip to content

Instantly share code, notes, and snippets.

@hkan
Created Apr 28, 2020
Embed
What would you like to do?
Alpine's x-text directive improved to support contenteditable elements
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