From 5cf7087754ff9a9e501863dfb2e18c6e712e6513 Mon Sep 17 00:00:00 2001 From: Aakansha Doshi Date: Tue, 22 Feb 2022 18:24:06 +0530 Subject: [PATCH] fix: restore cursor position after bound text container value updated (#4836) * fix: restore cursor position after bound text container value updated * only restore cursor when the cursor is not at the end of the line * compute diff before setting the cursor --- src/element/textWysiwyg.tsx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/element/textWysiwyg.tsx b/src/element/textWysiwyg.tsx index b02eada741..a62efb4539 100644 --- a/src/element/textWysiwyg.tsx +++ b/src/element/textWysiwyg.tsx @@ -165,7 +165,24 @@ export const textWysiwyg = ({ } const [viewportX, viewportY] = getViewportCoords(coordX, coordY); const { textAlign } = updatedElement; + const initialSelectionStart = editable.selectionStart; + const initialSelectionEnd = editable.selectionEnd; + const initialLength = editable.value.length; editable.value = updatedElement.originalText; + + // restore cursor positon after value updated so it doesn't + // go to the end of text when container auto expanded + if ( + initialSelectionStart === initialSelectionEnd && + initialSelectionEnd !== initialLength + ) { + // get diff between length and selection end and shift + // the cursor by "diff" times to position correctly + const diff = initialLength - initialSelectionEnd; + editable.selectionStart = editable.value.length - diff; + editable.selectionEnd = editable.value.length - diff; + } + const lines = updatedElement.originalText.split("\n"); const lineHeight = updatedElement.containerId ? approxLineHeight