I know cursor questions have been asked to death so bear with me. I haven't found a solution that works for caret position in inline style elements when there are multiple text nodes e.g. normal text bold sentence normal text.
If I getCaret position, update the block content, setCaret position it will work if the entire block is bold or italic etc. I've been doing that using treewalker.
I can use range.commonAncestorContainer to get the deepest node in the getCaret selection, however, applying that node as my range.setStart(node, offset) in my setCaret function errors as selection 1 is not of type node. Is there a way to retain the node being a valid node from one function to another for this? Thanks for your help.
const handleContentChange = (e) => {
const caretAt = getCaret();
function getCaret() {
let sel = window.getSelection()
let range = document.createRange()
let node = range.commonAncestorContainer
console.log(range)
let offset = sel.anchorOffset
return {node, offset}
}
const sanitizedInput = DOMPurify.sanitize(e.target.innerHTML);
onContentChange(sanitizedInput);
setTimeout(() => {
setCaret(caretAt);
}, 0);
function setCaret(caretAt) {
let sel = window.getSelection();
if (!sel.rangeCount) return;
let range = document.createRange();
range.setStart(caretAt.node, caretAt.anchorOffset)
let node = el.childNodes[0];
let offset = caretAtRef.current;
// If the first child is an element, find the appropriate text node
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
I've tried iterating through treewalker filtered text nodes and doing a cloned range, getting caret position, applying to new range.