Fix measuring caret position

This commit is contained in:
morethanwords 2021-11-15 05:34:06 +04:00
parent ad66af68e7
commit 4e5c61e31f
2 changed files with 16 additions and 6 deletions

View File

@ -105,8 +105,8 @@ export default function getRichElementValue(node: HTMLElement, lines: string[],
if(isBlock && line.length || node.tagName === 'BR') { if(isBlock && line.length || node.tagName === 'BR') {
lines.push(line.join('')); lines.push(line.join(''));
line.splice(0, line.length); line.splice(0, line.length);
} else if(node.tagName === 'IMG') { } else if(node instanceof HTMLImageElement) {
const alt = (node as HTMLImageElement).alt; const alt = node.alt;
if(alt) { if(alt) {
line.push(alt); line.push(alt);
offset.offset += alt.length; offset.offset += alt.length;

View File

@ -28,11 +28,21 @@ export default function getRichValueWithCaret(field: HTMLElement, withEntities =
range.startContainer == range.endContainer && range.startContainer == range.endContainer &&
startOffset == range.endOffset startOffset == range.endOffset
) { ) {
// * if focused on img // * if focused on img, or caret has been set via placeCaretAtEnd
const possibleChildrenFocusOffset = startOffset - 1; const possibleChildrenFocusOffset = startOffset - 1;
if(range.startContainer === field && field.childNodes[possibleChildrenFocusOffset]) { const childNodes = field.childNodes;
selNode = field.childNodes[possibleChildrenFocusOffset]; if(range.startContainer === field && childNodes[possibleChildrenFocusOffset]) {
selOffset = 1; selNode = childNodes[possibleChildrenFocusOffset];
selOffset = 0;
for(let i = 0; i < range.endOffset; ++i) {
const node = childNodes[i];
const value = node.nodeValue || (node as HTMLImageElement).alt;
if(value) {
selOffset += value.length;
}
}
} else { } else {
selNode = range.startContainer; selNode = range.startContainer;
selOffset = startOffset; selOffset = startOffset;