Skip to content

Commit

Permalink
Fix setting selection variables in ref at the beginning
Browse files Browse the repository at this point in the history
  • Loading branch information
Skalakid committed Mar 5, 2024
1 parent e24c365 commit 226da3f
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,12 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
[onSelectionChange, setEventProps],
);

const updateRefSelectionVariables = useCallback((start: number, end: number) => {
const markdownHTMLInput = divRef.current as HTMLInputElement;
markdownHTMLInput.selectionStart = start;
markdownHTMLInput.selectionEnd = end;
}, []);

const updateSelection = useCallback((e: SyntheticEvent<HTMLDivElement> | null = null) => {
if (!divRef.current) {
return;
Expand All @@ -308,9 +314,7 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(

if (contentSelection.current.start !== currentSelection.start || contentSelection.current.end !== currentSelection.end) {
if (contentSelection.current.start >= 0 && contentSelection.current.end >= 0) {
const markdownHTMLInput = divRef.current as HTMLInputElement;
markdownHTMLInput.selectionStart = currentSelection.start;
markdownHTMLInput.selectionEnd = currentSelection.end;
updateRefSelectionVariables(contentSelection.current.start, contentSelection.current.end);
contentSelection.current = currentSelection;
}
if (e) {
Expand Down Expand Up @@ -519,11 +523,14 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
}, []);

useEffect(() => {
// focus the input on mount if autoFocus is set
if (!(divRef.current && autoFocus)) {
if (!divRef.current) {
return;
}
divRef.current.focus();
// focus the input on mount if autoFocus is set
if (autoFocus) {
divRef.current.focus();
}
updateRefSelectionVariables(contentSelection.current.start, contentSelection.current.end);
}, []);

useEffect(() => {
Expand Down

0 comments on commit 226da3f

Please sign in to comment.