Skip to content

Commit

Permalink
Extracted chaning node to callback
Browse files Browse the repository at this point in the history
  • Loading branch information
zfurtak committed Jun 7, 2024
1 parent d20c63f commit 8d86dad
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -331,21 +331,31 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
}
}, [multiline, onContentSizeChange]);

const handleInsertSpan = useCallback(() => {
if (!divRef?.current) {
return;
}

const firstChild = divRef.current.firstElementChild;
if (!firstChild || firstChild?.tagName.toLowerCase() === 'span') {
return;
}
// Create a <span> element and replace the first child with it
const spanElement = document.createElement('span');
spanElement.innerHTML = firstChild.innerHTML;
divRef.current.replaceChild(spanElement, firstChild);

// Move the cursor to the end of the text
const selectionInput = window.getSelection();
selectionInput?.collapse(divRef.current, divRef.current.childNodes.length);
}, []);

const handleOnChangeText = useCallback(
(e: SyntheticEvent<HTMLDivElement>) => {
if (!divRef?.current || !(e.target instanceof HTMLElement)) {
return;
}
const allElements = divRef.current.querySelectorAll('*');
const element = allElements[0];
if (element && element.tagName.toLowerCase() !== 'span') {
const spanElement = document.createElement('span');
spanElement.innerHTML = element.innerHTML;
divRef.current.replaceChild(spanElement, element);
divRef.current.focus();
const selectionInput = window.getSelection();
selectionInput?.collapse(divRef.current, divRef.current.childNodes.length);
}
handleInsertSpan();

const changedText = e.target.innerText;
if (compositionRef.current && !BrowserUtils.isMobile) {
Expand Down Expand Up @@ -393,7 +403,7 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(

handleContentSizeChange();
},
[updateTextColor, handleContentSizeChange, onChange, onChangeText, undo, redo, parseText, processedMarkdownStyle, updateSelection, setEventProps],
[updateTextColor, handleContentSizeChange, onChange, onChangeText, undo, redo, parseText, processedMarkdownStyle, updateSelection, setEventProps, handleInsertSpan],
);

const handleKeyPress = useCallback(
Expand Down

0 comments on commit 8d86dad

Please sign in to comment.