import { useRef } from 'react' import type { ComponentProps } from 'react' import { Input as InputPrimitive } from '@base-ui/react/input' import { cn } from '@/client/lib/cn' type InputPrimitiveProps = ComponentProps type InputFocusEvent = Parameters>[0] type InputKeyboardEvent = Parameters>[0] type InlineInputProps = Omit & { onValueChange?: (value: string) => void onValueCommit?: (value: string) => void selectOnFocus?: boolean } function InlineInput({ className, onBlur, onFocus, onKeyDown, onValueChange, onValueCommit, selectOnFocus, ...props }: InlineInputProps) { const valueBeforeEditRef = useRef(null) function handleBlur(event: InputFocusEvent) { const shouldCommit = valueBeforeEditRef.current !== null valueBeforeEditRef.current = null onBlur?.(event) if (!event.defaultPrevented && shouldCommit) { onValueCommit?.(event.currentTarget.value) } } function handleFocus(event: InputFocusEvent) { valueBeforeEditRef.current = event.currentTarget.value if (selectOnFocus) { const input = event.currentTarget input.select() requestAnimationFrame(() => { input.scrollLeft = 0 }) } onFocus?.(event) } function handleKeyDown(event: InputKeyboardEvent) { onKeyDown?.(event) if (event.defaultPrevented) return if (event.key === 'Enter') { event.preventDefault() event.currentTarget.blur() } else if (event.key === 'Escape') { event.preventDefault() const valueBeforeEdit = valueBeforeEditRef.current ?? event.currentTarget.value valueBeforeEditRef.current = null event.currentTarget.value = valueBeforeEdit onValueChange?.(valueBeforeEdit) event.currentTarget.blur() } } return ( onValueChange?.(event.target.value)} onFocus={handleFocus} onKeyDown={handleKeyDown} {...props} /> ) } export { InlineInput }