From 8d86dadcc807c24f286fac788eb06343a96e5c5d Mon Sep 17 00:00:00 2001 From: zfurtak Date: Fri, 7 Jun 2024 11:19:23 +0200 Subject: [PATCH] Extracted chaning node to callback --- src/MarkdownTextInput.web.tsx | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/src/MarkdownTextInput.web.tsx b/src/MarkdownTextInput.web.tsx index 7adcc0ec..84e42ca3 100644 --- a/src/MarkdownTextInput.web.tsx +++ b/src/MarkdownTextInput.web.tsx @@ -331,21 +331,31 @@ const MarkdownTextInput = React.forwardRef( } }, [multiline, onContentSizeChange]); + const handleInsertSpan = useCallback(() => { + if (!divRef?.current) { + return; + } + + const firstChild = divRef.current.firstElementChild; + if (!firstChild || firstChild?.tagName.toLowerCase() === 'span') { + return; + } + // Create a 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) => { 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) { @@ -393,7 +403,7 @@ const MarkdownTextInput = React.forwardRef( 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(