"use client" import * as React from "react" import { Input } from "@/components/ui/input" import { cn } from "@/lib/utils" export type InlineEditableProps = Omit, "value" | "onChange"> & { value: string onValueChange: (value: string) => void placeholder?: string disabled?: boolean inputClassName?: string displayClassName?: string } function InlineEditable({ value, onValueChange, placeholder = "Click to edit", disabled, className, inputClassName, displayClassName, ...props }: InlineEditableProps) { const [isEditing, setIsEditing] = React.useState(false) const [editValue, setEditValue] = React.useState(value) const inputRef = React.useRef(null) React.useEffect(() => { setEditValue(value) }, [value]) React.useEffect(() => { if (isEditing) { inputRef.current?.focus() } }, [isEditing]) const handleCommit = () => { if (!disabled) { onValueChange(editValue) setIsEditing(false) } } const handleCancel = () => { setEditValue(value) setIsEditing(false) } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault() handleCommit() } else if (e.key === "Escape") { e.preventDefault() handleCancel() } } if (isEditing) { return (
setEditValue(e.target.value)} onKeyDown={handleKeyDown} onBlur={handleCommit} disabled={disabled} placeholder={placeholder} className={cn("h-8 text-sm", inputClassName)} />
) } return (
{ if (!disabled) { setIsEditing(true) } }} tabIndex={disabled ? undefined : 0} onKeyDown={(e) => { if (!disabled && (e.key === "Enter" || e.key === " ")) { e.preventDefault() setIsEditing(true) } }} {...props} > {value || placeholder}
) } export { InlineEditable }