fix: issue with loosing cursor position on message (#719)

This commit is contained in:
Carlos Valente
2024-01-17 23:16:22 +01:00
committed by GitHub
parent a2950442d8
commit 3c1be1fc10
@@ -1,3 +1,4 @@
import { useEffect, useRef } from 'react';
import { IconButton, Input } from '@chakra-ui/react'; import { IconButton, Input } from '@chakra-ui/react';
import { IoEye } from '@react-icons/all-files/io5/IoEye'; import { IoEye } from '@react-icons/all-files/io5/IoEye';
import { IoEyeOffOutline } from '@react-icons/all-files/io5/IoEyeOffOutline'; import { IoEyeOffOutline } from '@react-icons/all-files/io5/IoEyeOffOutline';
@@ -22,9 +23,22 @@ interface InputRowProps {
export default function InputRow(props: InputRowProps) { export default function InputRow(props: InputRowProps) {
const { label, placeholder, text, visible, actionHandler, changeHandler, className, readonly } = props; const { label, placeholder, text, visible, actionHandler, changeHandler, className, readonly } = props;
const handleInputChange = (newValue: string) => { const inputRef = useRef<HTMLInputElement>(null);
changeHandler(newValue); 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<HTMLInputElement>) => {
cursorPositionRef.current = event.target.selectionStart ?? 0;
changeHandler(event.target.value);
}; };
const classes = cx([style.inputRow, className]); const classes = cx([style.inputRow, className]);
return ( return (
@@ -32,12 +46,13 @@ export default function InputRow(props: InputRowProps) {
<label className={`${style.label} ${visible ? style.active : ''}`}>{label}</label> <label className={`${style.label} ${visible ? style.active : ''}`}>{label}</label>
<div className={style.inputItems}> <div className={style.inputItems}>
<Input <Input
ref={inputRef}
size='sm' size='sm'
variant='ontime-filled' variant='ontime-filled'
readOnly={readonly} readOnly={readonly}
disabled={readonly} disabled={readonly}
value={text} value={text}
onChange={(event) => handleInputChange(event.target.value)} onChange={handleInputChange}
placeholder={placeholder} placeholder={placeholder}
/> />
{readonly ? ( {readonly ? (