import { useEffect, useRef, useState, type ReactNode } from "react"; import { Button } from "./design-system/primitives"; import { Field } from "./design-system/Field"; export type ItemMode = "edit" | "delete"; /** In-place editing and confirmation, shared by habit headings and task rows. */ export function InlineItemForm({ name, kind, mode, disabled, children, onSave, onDelete, onClose, submitLabel, formLabel }: { name: string; kind: "habit" | "task"; mode: ItemMode; disabled?: boolean; children?: ReactNode; submitLabel?: string; formLabel?: string; onSave: (name: string) => Promise; onDelete: () => Promise; onClose: () => void; }) { const form = useRef(null); const saving = useRef(false); const [draft, setDraft] = useState(name); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); useEffect(() => { const previous = document.activeElement as HTMLElement | null; form.current?.querySelector(mode === "edit" ? "input" : "button")?.focus(); return () => { if (previous?.isConnected) previous.focus(); }; }, [mode]); return (
{ if (event.key === "Escape" && !saving.current) { event.preventDefault(); onClose(); } }} onSubmit={async (event) => { event.preventDefault(); if (saving.current || disabled) return; if (mode === "edit" && !draft.trim()) { setError("Enter a name."); return; } saving.current = true; setBusy(true); setError(""); try { if (mode === "delete") await onDelete(); else await onSave(draft.trim()); onClose(); } catch (error) { setError(error instanceof Error ? error.message : "Could not save your change. Try again."); } finally { saving.current = false; setBusy(false); } }}> {mode === "edit" ? (
{(id) => setDraft(event.target.value)} />} {children}
) : (

{kind === "habit" ? "Archive" : "Delete"} {name}? {kind === "habit" ? "This removes the habit from your dashboard starting today. Earlier history is kept. You can restore it from Archived habits." : "This removes the task from today and future check-ins. Earlier history is kept."}

)} {error &&

{error}

}
{mode === "delete" && } {mode === "edit" && }
); }