import { Modal } from "./design-system/Modal"; import { useRef, useState, type FormEvent } from "react"; import { Button } from "./design-system/primitives"; import { Field } from "./design-system/Field"; import { ScheduleEditor } from "./design-system/EditingWorkbench"; import { HabitColorPicker } from "./design-system/HabitColorPicker"; import { habitInput, type Schedule } from "../habits/contracts"; import { habitRequest } from "../lib/dashboard"; /** Account behavior composed from the design system's existing form components. */ export function HabitForm({ date, onCancel, onCreated, onExpired, }: { date: string; onCancel: () => void; onCreated: (name: string) => void; onExpired: () => void; }) { const form = useRef(null); const saving = useRef(false); const [name, setName] = useState(""); const [method, setMethod] = useState<"manual" | "count" | "tasks">("manual"); const [target, setTarget] = useState(10); const [unit, setUnit] = useState("pages"); const [tasks, setTasks] = useState([""]); const [schedule, setSchedule] = useState({ type: "daily" }); const [color, setColor] = useState("#3e805d"); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); async function submit(event: FormEvent) { event.preventDefault(); if (saving.current) return; const parsed = habitInput.safeParse({ name, method, schedule, color, ...(method === "count" ? { target, unit } : {}), ...(method === "tasks" ? { tasks: tasks.map((name) => ({ name })) } : {}), }); if (!parsed.success) { setError(parsed.error.issues.map((issue) => issue.message).join(" ")); return; } saving.current = true; setBusy(true); setError(""); try { await habitRequest("/habits", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(parsed.data), }); onCreated(parsed.data.name); } catch (error) { if ( error instanceof Error && error.message.includes("session has expired") ) onExpired(); else setError( error instanceof Error ? error.message : "Could not create your habit.", ); } finally { saving.current = false; setBusy(false); } } return ( document.getElementById("add-habit")}>
{(id) => ( setName(event.target.value)} /> )} {(id) => ( )} {method === "count" && (
{(id) => ( setTarget(event.target.valueAsNumber)} /> )} {(id) => ( setUnit(event.target.value)} /> )}
)} {method === "tasks" && (
{tasks.map((task, index) => ( {(id) => (
setTasks((current) => current.map((value, i) => i === index ? event.target.value : value, ), ) } />
)}
))}
)}
{error && (

{error}

)}
); }