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 { interface EditableCellProps {
value: string; value: string;
@ -26,13 +26,27 @@ export function EditableCell({
className = '' className = ''
}: EditableCellProps) { }: EditableCellProps) {
const [localValue, setLocalValue] = useState(value); const [localValue, setLocalValue] = useState(value);
const [isExternalUpdate, setIsExternalUpdate] = useState(false);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null);
// Update local value when prop changes // Update local value when prop changes (including external updates)
useEffect(() => { useEffect(() => {
setLocalValue(value); if (value !== localValue) {
}, [value]); 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 // Handle focus when this cell becomes focused
useEffect(() => { useEffect(() => {
@ -40,11 +54,13 @@ export function EditableCell({
const element = inputType === 'textarea' ? textareaRef.current : inputRef.current; const element = inputType === 'textarea' ? textareaRef.current : inputRef.current;
if (element) { if (element) {
element.focus(); element.focus();
// Select all text when focusing // Select all text when focusing, but not during external updates
element.select(); if (!isExternalUpdate) {
element.select();
}
} }
} }
}, [focusedCell, cellKey, inputType]); }, [focusedCell, cellKey, inputType, isExternalUpdate]);
const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => { const handleInput = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const newValue = e.target.value; const newValue = e.target.value;