| 25 | * aligned to the proven sidebar pattern as the first step. |
| 26 | */ |
| 27 | export function useInlineRename({ onSave }: UseInlineRenameProps) { |
| 28 | const onSaveRef = useRef(onSave) |
| 29 | onSaveRef.current = onSave |
| 30 | |
| 31 | const originalNameRef = useRef('') |
| 32 | const doneRef = useRef(false) |
| 33 | const [editingId, setEditingId] = useState<string | null>(null) |
| 34 | const editingIdRef = useRef(editingId) |
| 35 | editingIdRef.current = editingId |
| 36 | const [editValue, setEditValue] = useState('') |
| 37 | const editValueRef = useRef(editValue) |
| 38 | editValueRef.current = editValue |
| 39 | const [isSaving, setIsSaving] = useState(false) |
| 40 | |
| 41 | const startRename = useCallback((id: string, currentName: string) => { |
| 42 | doneRef.current = false |
| 43 | setEditingId(id) |
| 44 | /** |
| 45 | * Sync the ref eagerly (not just via the render-time assignment) so an |
| 46 | * in-flight save's `finally` that resolves before the next render still |
| 47 | * sees this id as the active edit and leaves the new session alone. |
| 48 | */ |
| 49 | editingIdRef.current = id |
| 50 | setEditValue(currentName) |
| 51 | originalNameRef.current = currentName |
| 52 | setIsSaving(false) |
| 53 | }, []) |
| 54 | |
| 55 | const submitRename = useCallback(async () => { |
| 56 | if (doneRef.current) return |
| 57 | doneRef.current = true |
| 58 | const id = editingIdRef.current |
| 59 | const trimmed = editValueRef.current.trim() |
| 60 | if (!id || !trimmed || trimmed === originalNameRef.current) { |
| 61 | setEditingId(null) |
| 62 | return |
| 63 | } |
| 64 | setIsSaving(true) |
| 65 | try { |
| 66 | await onSaveRef.current(id, trimmed) |
| 67 | /** |
| 68 | * Only clear editing state if this submit still owns the edit session. |
| 69 | * Without the guard, a slow save for row A would tear down a rename of |
| 70 | * row B started while A's save was in flight. A superseded submit's |
| 71 | * cleanup is a no-op — `startRename` already reset `isSaving` for the |
| 72 | * new session, and the new session's own submit handles its lifecycle. |
| 73 | */ |
| 74 | if (editingIdRef.current === id) { |
| 75 | setEditingId(null) |
| 76 | } |
| 77 | } catch (error) { |
| 78 | logger.error('Failed to rename item', { error, id, newName: trimmed }) |
| 79 | /** |
| 80 | * Mirror `useItemRename`'s failure path: stay in edit mode with the |
| 81 | * original name restored (no silent data loss, no unhandled rejection) |
| 82 | * and re-arm `doneRef` so the revived session can submit or cancel again. |
| 83 | */ |
| 84 | if (editingIdRef.current === id) { |