From 2220ea6833ecbaf527f64d5b72e6df462158f4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Ska=C5=82ka?= <39538890+Skalakid@users.noreply.github.com> Date: Wed, 24 Apr 2024 12:58:05 +0200 Subject: [PATCH] Fix selection prop (#313) --- src/MarkdownTextInput.web.tsx | 9 ++++++--- src/web/cursorUtils.ts | 9 +++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/MarkdownTextInput.web.tsx b/src/MarkdownTextInput.web.tsx index 8384f6d0..4ded68c5 100644 --- a/src/MarkdownTextInput.web.tsx +++ b/src/MarkdownTextInput.web.tsx @@ -580,9 +580,12 @@ const MarkdownTextInput = React.forwardRef( if (!divRef.current || !selection || (contentSelection.current && selection.start === contentSelection.current.start && selection.end === contentSelection.current.end)) { return; } - CursorUtils.setCursorPosition(divRef.current, selection.start, selection.end); - updateSelection(null, {start: selection.start, end: selection.end || selection.start}); - }, [selection, updateSelection]); + + const newSelection: Selection = {start: selection.start, end: selection.end ?? selection.start}; + contentSelection.current = newSelection; + updateRefSelectionVariables(newSelection); + CursorUtils.setCursorPosition(divRef.current, newSelection.start, newSelection.end); + }, [selection, updateRefSelectionVariables]); useEffect(() => { if (history.current?.history.length !== 0) { diff --git a/src/web/cursorUtils.ts b/src/web/cursorUtils.ts index af0b97ae..98c50ca0 100644 --- a/src/web/cursorUtils.ts +++ b/src/web/cursorUtils.ts @@ -60,21 +60,18 @@ function setCursorPosition(target: HTMLElement, start: number, end: number | nul if (!startNode && start >= charCount && (start <= nextCharCount || (start === nextCharCount && i < n - 1))) { startNode = textNode; - // There are 4(/5) cases to consider here: + // There are 4 cases to consider here: // 1. Caret in front of a character, when pressing enter // 2. Caret at the end of a line (not last one) - // 3a. Caret at the end of whole input, when pressing enter - On firefox - // 3b. Caret at the end of whole input, when pressing enter - On other browsers + // 3. Caret at the end of whole input, when pressing enter // 4. All other placements if (prevChar === '\n' && prevTextLength !== undefined && prevTextLength < textCharacters.length) { if (nextChar !== '\n') { range.setStart(textNodes[i + 1] as Node, 0); } else if (i !== textNodes.length - 1) { range.setStart(textNodes[i] as Node, 1); - } else if (BrowserUtils.isFirefox) { - range.setStart(textNode, start - charCount); } else { - range.setStart(textNodes[i] as Node, 2); + range.setStart(textNode, start - charCount); } } else { range.setStart(textNode, start - charCount);