Skip to content

Commit

Permalink
chore: create func to restore cursor imperatively
Browse files Browse the repository at this point in the history
- revert the use of contentSelection to restore cursor pos during text update to cursor jumping around funny since contentSelection ref value can get outdated.
- create func to restore cursor in the ref object

Signed-off-by: dominictb <[email protected]>
  • Loading branch information
dominictb committed Jun 9, 2024
1 parent 945c704 commit 81be965
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -364,11 +364,6 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
text = parseText(divRef.current, changedText, processedMarkdownStyle).text;
}

const selectionAfterTextChange = CursorUtils.getCurrentCursorPosition(divRef.current);
if (selectionAfterTextChange) {
contentSelection.current = selectionAfterTextChange;
}

if (pasteRef?.current) {
pasteRef.current = false;
updateSelection(e);
Expand Down Expand Up @@ -536,6 +531,15 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
updateTextColor(r, '');
};

(r as any).restoreSelectionPosition = () => {
if (contentSelection.current) {
CursorUtils.setCursorPosition(r, contentSelection.current.start, contentSelection.current.end);
} else {
const valueLength = value ? value.length : r.innerText.length;
CursorUtils.setCursorPosition(r, valueLength, null);
}
};

if (value === '' || value === undefined) {
// update to placeholder color when value is empty
updateTextColor(r, r.innerText);
Expand Down Expand Up @@ -566,7 +570,7 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(

const text = processedValue !== undefined ? processedValue : '';

parseText(divRef.current, text, processedMarkdownStyle, contentSelection.current?.end);
parseText(divRef.current, text, processedMarkdownStyle, text.length);
updateTextColor(divRef.current, value);
},
[multiline, processedMarkdownStyle, processedValue],
Expand Down

0 comments on commit 81be965

Please sign in to comment.