From 3c1be1fc10201ba10f8f72a69ff7a9fa21d6d85b Mon Sep 17 00:00:00 2001 From: Carlos Valente <34649812+cpvalente@users.noreply.github.com> Date: Wed, 17 Jan 2024 23:16:22 +0100 Subject: [PATCH] fix: issue with loosing cursor position on message (#719) --- .../src/features/control/message/InputRow.tsx | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/client/src/features/control/message/InputRow.tsx b/apps/client/src/features/control/message/InputRow.tsx index 561c19740..58c58e609 100644 --- a/apps/client/src/features/control/message/InputRow.tsx +++ b/apps/client/src/features/control/message/InputRow.tsx @@ -1,3 +1,4 @@ +import { useEffect, useRef } from 'react'; import { IconButton, Input } from '@chakra-ui/react'; import { IoEye } from '@react-icons/all-files/io5/IoEye'; import { IoEyeOffOutline } from '@react-icons/all-files/io5/IoEyeOffOutline'; @@ -22,9 +23,22 @@ interface InputRowProps { export default function InputRow(props: InputRowProps) { const { label, placeholder, text, visible, actionHandler, changeHandler, className, readonly } = props; - const handleInputChange = (newValue: string) => { - changeHandler(newValue); + const inputRef = useRef(null); + const cursorPositionRef = useRef(0); + + // sync cursor position with text + useEffect(() => { + if (inputRef.current) { + inputRef.current.selectionStart = cursorPositionRef.current; + inputRef.current.selectionEnd = cursorPositionRef.current; + } + }, [text]); + + const handleInputChange = (event: React.ChangeEvent) => { + cursorPositionRef.current = event.target.selectionStart ?? 0; + changeHandler(event.target.value); }; + const classes = cx([style.inputRow, className]); return ( @@ -32,12 +46,13 @@ export default function InputRow(props: InputRowProps) {
handleInputChange(event.target.value)} + onChange={handleInputChange} placeholder={placeholder} /> {readonly ? (