From 9f64aa732ad916a0885b96887bacde5bc88c6608 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Ska=C5=82ka?= <39538890+Skalakid@users.noreply.github.com> Date: Tue, 12 Mar 2024 13:31:38 +0100 Subject: [PATCH] Fix selection setting when pasting text and auto-focusing (#222) --- src/MarkdownTextInput.web.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/MarkdownTextInput.web.tsx b/src/MarkdownTextInput.web.tsx index bc1d2d33..5d69381e 100644 --- a/src/MarkdownTextInput.web.tsx +++ b/src/MarkdownTextInput.web.tsx @@ -161,8 +161,7 @@ const MarkdownTextInput = React.forwardRef( const compositionRef = useRef(false); const divRef = useRef(null); const currentlyFocusedField = useRef(null); - const valueLength = value ? value.length : 0; - const contentSelection = useRef({start: valueLength, end: valueLength}); + const contentSelection = useRef(null); const className = `react-native-live-markdown-input-${multiline ? 'multiline' : 'singleline'}`; const history = useRef(); if (!history.current) { @@ -280,6 +279,7 @@ const MarkdownTextInput = React.forwardRef( default: text = parseText(divRef.current, e.target.innerText, processedMarkdownStyle).text; } + updateSelection(e); updateTextColor(divRef.current, e.target.innerText); if (onChange) { @@ -321,7 +321,7 @@ const MarkdownTextInput = React.forwardRef( } const newSelection = CursorUtils.getCurrentCursorPosition(divRef.current); - if (newSelection && (contentSelection.current.start !== newSelection.start || contentSelection.current.end !== newSelection.end)) { + if (newSelection && (!contentSelection.current || contentSelection.current.start !== newSelection.start || contentSelection.current.end !== newSelection.end)) { updateRefSelectionVariables(newSelection); contentSelection.current = newSelection; @@ -405,8 +405,10 @@ const MarkdownTextInput = React.forwardRef( const hostNode = e.target as unknown as HTMLDivElement; currentlyFocusedField.current = hostNode; setEventProps(e); - if (divRef.current && contentSelection.current) { - CursorUtils.setCursorPosition(divRef.current, contentSelection.current.end || contentSelection.current.start); + if (divRef.current) { + const valueLength = value ? value.length : 0; + CursorUtils.setCursorPosition(divRef.current, contentSelection.current ? contentSelection.current.end : valueLength); + updateSelection(event); } if (onFocus) { @@ -546,11 +548,10 @@ const MarkdownTextInput = React.forwardRef( if (autoFocus) { divRef.current.focus(); } - updateRefSelectionVariables(contentSelection.current); }, []); useEffect(() => { - if (!divRef.current || !selection || (selection.start === contentSelection.current.start && selection.end === contentSelection.current.end)) { + 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);