"use client"; import { ArrowIcon } from "../ui/icons.tsx"; import { useState, useRef, useId, useEffect } from "react"; export function InlineEdit({ value, onValueChange, label, validate, className = "", }: { value: string; onValueChange: (value: string) => void; label: string; validate?: (value: string) => string | undefined; className?: string; }) { const [editing, setEditing] = useState(false), [draft, setDraft] = useState(value), [error, setError] = useState(), trigger = useRef(null), id = useId(), restore = useRef(false); useEffect(() => { if (!editing && restore.current) { restore.current = false; trigger.current?.focus(); } }, [editing]); const close = () => { setEditing(false); setError(undefined); restore.current = true; }; const save = () => { const message = validate?.(draft); if (message) { setError(message); return; } onValueChange(draft); close(); }; return (
{editing ? (
{ setDraft(e.target.value); setError(undefined); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); save(); } if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(); } }} />
{error && ( )}
) : ( )}
); }