import { useRef, useState } from 'react' import { flushSync } from 'react-dom' export function EditableText({ fieldName, value, inputClassName, inputLabel, buttonClassName, buttonLabel, onChange, editState, }: { fieldName: string value: string inputClassName: string inputLabel: string buttonClassName: string buttonLabel: string onChange: (value: string) => void editState?: [boolean, (value: boolean) => void] }) { const localEditState = useState(false) const [edit, setEdit] = editState || localEditState const inputRef = useRef(null) const buttonRef = useRef(null) return edit ? (
{ event.preventDefault() onChange(inputRef.current!.value) flushSync(() => { setEdit(false) }) buttonRef.current?.focus() }} > { if (event.key === 'Escape') { flushSync(() => { setEdit(false) }) buttonRef.current?.focus() } }} onBlur={(event) => { if ( inputRef.current?.value !== value && inputRef.current?.value.trim() !== '' ) { onChange(inputRef.current!.value) } setEdit(false) }} />
) : ( ) }