diff --git a/src/MarkdownTextInput.web.tsx b/src/MarkdownTextInput.web.tsx index 676908882..6ef411898 100644 --- a/src/MarkdownTextInput.web.tsx +++ b/src/MarkdownTextInput.web.tsx @@ -307,11 +307,12 @@ const MarkdownTextInput = React.forwardRef( const currentSelection = CursorUtils.getCurrentCursorPosition(divRef.current); if (contentSelection.current.start !== currentSelection.start || contentSelection.current.end !== currentSelection.end) { - const markdownHTMLInput = divRef.current as HTMLInputElement; - markdownHTMLInput.selectionStart = currentSelection.start; - markdownHTMLInput.selectionEnd = currentSelection.end; - contentSelection.current = currentSelection; - + if (contentSelection.current.start >= 0 && contentSelection.current.end >= 0) { + const markdownHTMLInput = divRef.current as HTMLInputElement; + markdownHTMLInput.selectionStart = currentSelection.start; + markdownHTMLInput.selectionEnd = currentSelection.end; + contentSelection.current = currentSelection; + } if (e) { handleSelectionChange(e); } diff --git a/src/web/cursorUtils.ts b/src/web/cursorUtils.ts index 0c6e0babe..1d6224131 100644 --- a/src/web/cursorUtils.ts +++ b/src/web/cursorUtils.ts @@ -62,31 +62,22 @@ function moveCursorToEnd(target: HTMLElement) { } } -function getIndexedPosition(target: HTMLElement, range: Range, isStart: boolean) { - const marker = document.createTextNode('\0'); - const rangeClone = range.cloneRange(); - - rangeClone.collapse(isStart); - - rangeClone.insertNode(marker); - const position = target.innerText.indexOf('\0'); - if (marker.parentNode) { - marker.parentNode.removeChild(marker); - } +function getCurrentCursorPosition(target: HTMLElement) { + const sel = window.getSelection(); - return position; -} + if (sel && sel.rangeCount > 0) { + const range = sel.getRangeAt(0); + const preSelectionRange = range.cloneRange(); + preSelectionRange.selectNodeContents(target); + preSelectionRange.setEnd(range.startContainer, range.startOffset); + const start = preSelectionRange.toString().length; -function getCurrentCursorPosition(target: HTMLElement) { - const selection = document.getSelection(); - if (!selection || selection.rangeCount === 0) { - return {start: target.innerText.length, end: target.innerText.length}; + return { + start, + end: start + range.toString().length, + }; } - - const range = selection.getRangeAt(0); - const start = getIndexedPosition(target, range, true); - const end = getIndexedPosition(target, range, false); - return {start, end}; + return {start: -1, end: -1}; } export {getCurrentCursorPosition, moveCursorToEnd, setCursorPosition};