feat(EditableCell): enhance handling of external updates and focus behavior

This commit is contained in:
ryan 2025-06-20 18:05:36 +03:00
parent e1992af634
commit fa65fb666b

View file

@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import React, { useState, useEffect, useCallback, useRef } from 'react';
interface EditableCellProps {
value: string;
@ -26,13 +26,27 @@ export function EditableCell({
className = ''
}: EditableCellProps) {
const [localValue, setLocalValue] = useState(value);
const [isExternalUpdate, setIsExternalUpdate] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Update local value when prop changes
// Update local value when prop changes (including external updates)
useEffect(() => {
setLocalValue(value);
}, [value]);
if (value !== localValue) {
setLocalValue(value);
setIsExternalUpdate(true);
}
}, [value, localValue]);
// Reset external update flag after a short delay
useEffect(() => {
if (isExternalUpdate) {
const timer = setTimeout(() => {
setIsExternalUpdate(false);
}, 100);
return () => clearTimeout(timer);
}
}, [isExternalUpdate]);
// Handle focus when this cell becomes focused
useEffect(() => {
@ -40,11 +54,13 @@ export function EditableCell({
const element = inputType === 'textarea' ? textareaRef.current : inputRef.current;
if (element) {
element.focus();
// Select all text when focusing
element.select();
// Select all text when focusing, but not during external updates
if (!isExternalUpdate) {
element.select();
}
}
}
}, [focusedCell, cellKey, inputType]);
}, [focusedCell, cellKey, inputType, isExternalUpdate]);
const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const newValue = e.target.value;