Skip to content

Instantly share code, notes, and snippets.

@hkan
Created April 28, 2020 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkan/56a7949e99dab0eec1e26f39c02c424c to your computer and use it in GitHub Desktop.
Save hkan/56a7949e99dab0eec1e26f39c02c424c to your computer and use it in GitHub Desktop.
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