import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { X, ArrowUpRight, Plus, Minus, Leaf } from "lucide-react"; import { bubbleCount } from "../shared/bubble-physics.js"; import { useBubblePhysics } from "./useBubblePhysics"; import { metrics, type Entry, type Food, type JournalRecord, type Meal, type Nutrients, type Plate, type Settings, type Weight, } from "./types"; import { emptyNutrients } from "../shared/domain.js"; import { saveRecord, putRecords, useJournal } from "./store"; import { localTime, nextFoodName } from "../shared/entry.js"; import { displayDate, number, today, weightValue } from "./utils"; import { useExiting } from "./Presence"; let sheetLocks = 0; let previousBodyOverflow = ""; export function Modal({ title, subtitle, close, children, }: { title: string; subtitle?: string; close: () => void; children: ReactNode; }) { const ref = useRef(null); const titleId = useId(); const closeRef = useRef(close); closeRef.current = close; const exiting = useExiting(); const drag = useRef<{ y: number; distance: number } | null>(null); useEffect(() => { const dialog = ref.current!; dialog.showModal(); const listener = (event: Event) => { event.preventDefault(); closeRef.current(); }; dialog.addEventListener("cancel", listener); return () => { dialog.removeEventListener("cancel", listener); dialog.close(); }; }, []); useEffect(() => { if (!ref.current) return; if (sheetLocks++ === 0) previousBodyOverflow = document.body.style.overflow; document.body.style.overflow = "hidden"; return () => { if (--sheetLocks === 0) document.body.style.overflow = previousBodyOverflow; }; }, []); return ( { if (event.target === event.currentTarget) { const r = event.currentTarget.getBoundingClientRect(); if ( event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom ) close(); } }} >
{ if ( event.pointerType !== "touch" || !event.isPrimary || (event.target as HTMLElement).closest("button, input, select") ) return; drag.current = { y: event.clientY, distance: 0 }; event.currentTarget.setPointerCapture(event.pointerId); }} onPointerMove={(event) => { if (!drag.current) return; drag.current.distance = Math.max(0, event.clientY - drag.current.y); if (!matchMedia("(prefers-reduced-motion: reduce)").matches) ref.current?.style.setProperty( "translate", `0 ${Math.min(180, drag.current.distance * 0.65)}px`, ); }} onPointerUp={() => { const dismiss = (drag.current?.distance || 0) > 85; drag.current = null; ref.current?.style.removeProperty("translate"); if (dismiss) close(); }} onPointerCancel={() => { drag.current = null; ref.current?.style.removeProperty("translate"); }} >
{children}
); } export function CalorieOrb({ value, goal, enabled, small = false, }: { value: number; goal: number; enabled: boolean; small?: boolean; }) { const physics = useBubblePhysics(bubbleCount(value, goal, enabled)); const readout = ( <> {enabled ? value > goal ? "OVER YOUR GOAL" : "CALORIES REMAINING" : "CALORIES LOGGED"} {number(enabled ? Math.abs(goal - value) : value)} kcal ); return (
goal ? " over" : "") } role="img" aria-label={`${number(value)} calories${enabled ? ` of ${number(goal)} calorie goal` : ""}`} >
{!small &&
{readout}
}
); } export function Empty({ icon = , title, text, action, }: { icon?: ReactNode; title: string; text: string; action?: ReactNode; }) { return (
{icon}

{title}

{text}

{action}
); } export function NutrientFields({ nutrients, set, }: { nutrients: Nutrients; set: (n: Nutrients) => void; }) { return (
{metrics.map((metric) => ( ))}
); } export function FoodEditor({ close, date, meal, existing, foods, plates, mode = "log", notify, }: { close: () => void; date: string; meal: Meal; existing?: JournalRecord; foods: JournalRecord[]; plates: JournalRecord[]; mode?: "log" | "food"; notify: (text: string) => void; }) { const initial = existing?.data; const { records } = useJournal(); const [tab, setTab] = useState<"manual" | "saved" | "plates">("manual"); const [name, setName] = useState(initial?.name || ""); const [serving, setServing] = useState(initial?.serving || "1 serving"); const [nutrients, setNutrients] = useState( initial?.nutrients || (emptyNutrients() as Nutrients), ); const [quantity, setQuantity] = useState( existing?.type === "entry" ? (initial as Entry).quantity : 1, ); const [selectedMeal, setMeal] = useState( existing?.type === "entry" ? (initial as Entry).meal : meal, ); const [selectedDate, setDate] = useState( existing?.type === "entry" ? (initial as Entry).date : date, ); const [time, setTime] = useState( existing?.type === "entry" ? (initial as Entry).time || "" : localTime(), ); const fallbackName = nextFoodName( mode === "food" ? "Food" : selectedMeal, records .filter( (r) => !r.deleted && r.id !== existing?.id && (mode === "food" ? r.type === "food" : r.type === "entry" && (r.data as Entry).date === selectedDate && (r.data as Entry).meal === selectedMeal), ) .map((r) => (r.data as Food).name), ); const [saveFood, setSaveFood] = useState(false); const [search, setSearch] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); async function submit(event: React.FormEvent) { event.preventDefault(); setBusy(true); setError(""); try { if (mode === "log" && (!selectedDate || (!existing && !time))) throw new Error("Choose an entry date and time."); const food = { name: name.trim() || fallbackName, serving: serving.trim(), nutrients, }; const items: Parameters[0] = [ { type: mode === "food" ? "food" : "entry", id: existing?.id, data: mode === "food" ? food : { ...food, date: selectedDate, ...(time ? { time } : {}), meal: selectedMeal, quantity, }, }, ]; if (saveFood && mode === "log") items.push({ type: "food", data: food }); await putRecords(items); notify( mode === "food" ? "Food saved to your library" : "Added to your day", ); close(); } catch (err) { setError( err instanceof Error ? err.message : "Could not save. Please try again.", ); } finally { setBusy(false); } } async function addPlate(plate: Plate) { setBusy(true); setError(""); try { if (!selectedDate || !time) throw new Error("Choose an entry date and time."); await putRecords( plate.items.map((item) => ({ type: "entry", data: { ...item, date: selectedDate, time, meal: selectedMeal }, })), ); notify(`${plate.name} added to your day`); close(); } catch { setError("Could not save this plate. Please try again."); } finally { setBusy(false); } } return ( {mode === "log" && !existing && (
{(["manual", "saved", "plates"] as const).map((value) => ( ))}
)} {mode === "log" && (
)} {tab !== "manual" ? (
setSearch(e.target.value)} /> {tab === "saved" ? foods .filter((r) => r.data.name.toLowerCase().includes(search.toLowerCase()), ) .map((r) => ( )) : plates .filter((r) => r.data.name.toLowerCase().includes(search.toLowerCase()), ) .map((r) => ( ))} {(tab === "saved" ? foods : plates).length === 0 && ( )}
) : (
{mode === "log" && ( )}
Nutrition per serving From your label or recipe
{mode === "log" && !existing && ( )} {error && (

{error}

)} )} {tab !== "manual" && error && (

{error}

)}
); } export function PlateEditor({ close, foods, existing, notify, }: { close: () => void; foods: JournalRecord[]; existing?: JournalRecord; notify: (text: string) => void; }) { const [name, setName] = useState(existing?.data.name || ""); const [items, setItems] = useState( existing?.data.items || [], ); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); return (
{ e.preventDefault(); setBusy(true); try { await saveRecord( "plate", { name: name.trim(), items }, existing?.id, ); notify("Plate saved"); close(); } catch { setError("Could not save this plate. Check its name and servings."); } finally { setBusy(false); } }} > {items.map((item, i) => (
{item.name} {item.serving} setItems( items.map((v, n) => n === i ? { ...v, quantity: +e.target.value } : v, ), ) } />
))} {foods.length === 0 && (

Save a food first, then combine your favorites here.

)} {error && (

{error}

)}
); } export function WeightEditor({ close, unit, existing, notify, }: { close: () => void; unit: Settings["unit"]; existing?: JournalRecord; notify: (text: string) => void; }) { const [date, setDate] = useState(existing?.data.date || today()); const [value, setValue] = useState( existing ? +weightValue(existing.data.valueKg, unit).toFixed(2) : "", ); const [notes, setNotes] = useState(existing?.data.notes || ""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); return (
{ e.preventDefault(); setBusy(true); try { await saveRecord( "weight", { date, valueKg: unit === "lb" ? +value / 2.2046226218 : +value, notes, }, existing?.id, ); notify("Weight logged"); close(); } catch { setError("Could not save. Check the weight and date."); } finally { setBusy(false); } }} >