This commit is contained in:
j3d1 2024-06-06 19:58:10 +02:00
parent 2fd9ae4dbc
commit f3eb64b488

View file

@ -18,7 +18,7 @@ export default {
}, },
data() { data() {
return { return {
selection: null, selection: {start: 0, end: 0}
}; };
}, },
emits: ['input'], emits: ['input'],
@ -31,8 +31,35 @@ export default {
} }
}, },
onchange(event) { onchange(event) {
this.selection = window.getSelection(); const div = this.$refs.text;
const sel = window.getSelection();
if (sel.rangeCount > 0) {
this.selection.start = this.calculateOffset(div, sel.anchorNode, sel.anchorOffset);
this.selection.end = this.calculateOffset(div, sel.focusNode, sel.focusOffset);
}
this.$emit('input', event.target.innerText); this.$emit('input', event.target.innerText);
},
calculateOffset(container, node, offset) {
let position = 0;
let found = false;
const walk = (node) => {
if (node === container) {
found = true;
return;
}
if (node.nodeType === 3) {
position += node.length;
} else {
for (let i = 0; i < node.childNodes.length; i++) {
walk(node.childNodes[i]);
if (found) {
return;
}
}
}
};
walk(node);
return position + offset;
} }
}, },
watch: { watch: {
@ -40,9 +67,9 @@ export default {
if (this.selection) { if (this.selection) {
const div = this.$refs.text; const div = this.$refs.text;
const range = document.createRange(); const range = document.createRange();
console.log(this.selection.anchorOffset, this.selection.focusOffset); console.log(this.selection);
range.setStart(div, Math.min(this.selection.anchorOffset, div.childNodes[0].length)); range.setStart(div, Math.min(this.selection.anchorOffset, this.value.length));
range.setEnd(div, Math.min(this.selection.focusOffset, div.childNodes[0].length)); range.setEnd(div, Math.min(this.selection.focusOffset, this.value.length));
this.selection.removeAllRanges(); this.selection.removeAllRanges();
this.selection.addRange(range); this.selection.addRange(range);
} }