Calio/src/components.tsx
Elijah 7288e56c02
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 32s
Polish PWA gestures, transitions and nutrition averages
2026-10-22 09:16:52 -07:00

811 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<HTMLDialogElement>(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 (
<dialog
ref={ref}
className={"sheet" + (exiting ? " sheet-exiting" : "")}
inert={exiting}
aria-labelledby={titleId}
onClick={(event) => {
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();
}
}}
>
<div
className="sheet-head"
onPointerDown={(event) => {
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");
}}
>
<span className="sheet-grip" aria-hidden="true" />
<div>
<span className="eyebrow">A LITTLE EVERYDAY CARE</span>
<h2 id={titleId}>{title}</h2>
{subtitle && <p>{subtitle}</p>}
</div>
<button
className="icon-button"
aria-label="Close dialog"
onClick={close}
>
<X size={21} />
</button>
</div>
{children}
</dialog>
);
}
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 = (
<>
<span className="eyebrow">
{enabled
? value > goal
? "OVER YOUR GOAL"
: "CALORIES REMAINING"
: "CALORIES LOGGED"}
</span>
<strong>{number(enabled ? Math.abs(goal - value) : value)}</strong>
<span className="orb-unit">kcal</span>
</>
);
return (
<div className="orb-shell">
<div
className={
"orb " +
(small ? "orb-small" : "") +
(enabled && value > goal ? " over" : "")
}
role="img"
aria-label={`${number(value)} calories${enabled ? ` of ${number(goal)} calorie goal` : ""}`}
>
<svg viewBox="0 0 320 320" aria-hidden="true">
<circle cx="160" cy="160" r="145" className="orb-track" />
<circle
cx="160"
cy="160"
r="145"
className="orb-progress"
strokeDasharray={`${enabled ? Math.min(value / goal, 1) * 911 : 0} 911`}
transform="rotate(-90 160 160)"
/>
</svg>
<canvas
className="bubble-canvas"
ref={physics.canvas}
aria-hidden="true"
/>
</div>
{!small && <div className="orb-number orb-number-outside">{readout}</div>}
</div>
);
}
export function Empty({
icon = <Leaf size={25} />,
title,
text,
action,
}: {
icon?: ReactNode;
title: string;
text: string;
action?: ReactNode;
}) {
return (
<div className="empty">
<span className="empty-icon">{icon}</span>
<h3>{title}</h3>
<p>{text}</p>
{action}
</div>
);
}
export function NutrientFields({
nutrients,
set,
}: {
nutrients: Nutrients;
set: (n: Nutrients) => void;
}) {
return (
<div className="nutrient-fields">
{metrics.map((metric) => (
<label key={metric.key}>
{metric.label}
<span className="unit-input">
<input
type="number"
inputMode="decimal"
min="0"
max="100000"
step="any"
required
value={nutrients[metric.key]}
onChange={(e) =>
set({
...nutrients,
[metric.key]:
e.target.value === ""
? ("" as unknown as number)
: +e.target.value,
})
}
/>
<span>{metric.unit}</span>
</span>
</label>
))}
</div>
);
}
export function FoodEditor({
close,
date,
meal,
existing,
foods,
plates,
mode = "log",
notify,
}: {
close: () => void;
date: string;
meal: Meal;
existing?: JournalRecord<Entry | Food>;
foods: JournalRecord<Food>[];
plates: JournalRecord<Plate>[];
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<Nutrients>(
initial?.nutrients || (emptyNutrients() as Nutrients),
);
const [quantity, setQuantity] = useState(
existing?.type === "entry" ? (initial as Entry).quantity : 1,
);
const [selectedMeal, setMeal] = useState<Meal>(
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<typeof putRecords>[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 (
<Modal
title={
existing
? "Edit " + (mode === "food" ? "food" : "entry")
: mode === "food"
? "A new favorite"
: "What’s on your plate?"
}
subtitle={
mode === "log"
? displayDate(selectedDate, {
weekday: "long",
month: "short",
day: "numeric",
})
: "Save the nutrition for one serving."
}
close={close}
>
{mode === "log" && !existing && (
<div className="segmented">
{(["manual", "saved", "plates"] as const).map((value) => (
<button
className={tab === value ? "active" : ""}
key={value}
onClick={() => setTab(value)}
>
{value === "manual"
? "Quick entry"
: value === "saved"
? "My foods"
: "My plates"}
</button>
))}
</div>
)}
{mode === "log" && (
<div className="form-row entry-details">
<label>
Day
<input
aria-label="Entry date"
type="date"
required
value={selectedDate}
onChange={(e) => setDate(e.target.value)}
/>
</label>
<label>
Time
<input
aria-label="Entry time"
type="time"
required={!existing}
value={time}
onChange={(e) => setTime(e.target.value)}
/>
</label>
<label>
Meal
<select
value={selectedMeal}
onChange={(e) => setMeal(e.target.value as Meal)}
>
{["Breakfast", "Lunch", "Dinner", "Snacks"].map((m) => (
<option key={m}>{m}</option>
))}
</select>
</label>
</div>
)}
{tab !== "manual" ? (
<div className="picker panel-arrive" key={tab}>
<input
type="search"
placeholder={
tab === "saved" ? "Find a saved food…" : "Find a plate…"
}
aria-label="Search library"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
{tab === "saved"
? foods
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
)
.map((r) => (
<button
className="picker-row"
key={r.id}
onClick={() => {
setName(r.data.name);
setServing(r.data.serving);
setNutrients(r.data.nutrients);
setTab("manual");
}}
>
<span>
<strong>{r.data.name}</strong>
<small>
{r.data.serving} · {number(r.data.nutrients.calories)}{" "}
kcal
</small>
</span>
<ArrowUpRight size={18} />
</button>
))
: plates
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
)
.map((r) => (
<button
disabled={busy || !selectedDate || !time}
className="picker-row"
key={r.id}
onClick={() => void addPlate(r.data)}
>
<span>
<strong>{r.data.name}</strong>
<small>
{r.data.items.length}{" "}
{r.data.items.length === 1 ? "food" : "foods"} · Add to{" "}
{selectedMeal.toLowerCase()}
</small>
</span>
<Plus size={18} />
</button>
))}
{(tab === "saved" ? foods : plates).length === 0 && (
<Empty
title={
tab === "saved"
? "Your favorites live here"
: "A plate makes it easy"
}
text={
tab === "saved"
? "Create a food in your library, or save one while logging."
: "Combine your saved foods into a reusable plate in the library."
}
/>
)}
</div>
) : (
<form className="panel-arrive" onSubmit={submit}>
<label>
Food name <span className="muted">(optional)</span>
<input
autoFocus
maxLength={160}
placeholder={fallbackName}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<div className="form-row">
<label>
Serving description
<input
required
maxLength={100}
value={serving}
onChange={(e) => setServing(e.target.value)}
/>
</label>
{mode === "log" && (
<label>
Servings
<input
type="number"
inputMode="decimal"
min="0.001"
max="1000"
step="any"
required
value={quantity}
onChange={(e) => setQuantity(+e.target.value)}
/>
</label>
)}
</div>
<div className="section-caption">
<span>Nutrition per serving</span>
<span>From your label or recipe</span>
</div>
<NutrientFields nutrients={nutrients} set={setNutrients} />
{mode === "log" && !existing && (
<label className="check-row">
<input
type="checkbox"
checked={saveFood}
onChange={(e) => setSaveFood(e.target.checked)}
/>
Save this food to my library
</label>
)}
{error && (
<p className="error" role="alert">
{error}
</p>
)}
<button className="primary wide" disabled={busy}>
{busy
? "Saving…"
: existing
? "Save changes"
: mode === "food"
? "Save food"
: `Add ${number(nutrients.calories * quantity)} kcal`}
<Plus size={18} />
</button>
</form>
)}
{tab !== "manual" && error && (
<p className="error" role="alert">
{error}
</p>
)}
</Modal>
);
}
export function PlateEditor({
close,
foods,
existing,
notify,
}: {
close: () => void;
foods: JournalRecord<Food>[];
existing?: JournalRecord<Plate>;
notify: (text: string) => void;
}) {
const [name, setName] = useState(existing?.data.name || "");
const [items, setItems] = useState<Plate["items"]>(
existing?.data.items || [],
);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<Modal
title={existing ? "Edit plate" : "Better together"}
subtitle="A few favorites, ready in one tap."
close={close}
>
<form
onSubmit={async (e) => {
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);
}
}}
>
<label>
Plate name
<input
required
autoFocus
maxLength={160}
placeholder="e.g. My usual breakfast"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
{items.map((item, i) => (
<div className="plate-item" key={i}>
<span>
<strong>{item.name}</strong>
<small>{item.serving}</small>
</span>
<input
aria-label={`Servings of ${item.name}`}
type="number"
min="0.001"
max="1000"
step="any"
required
value={item.quantity}
onChange={(e) =>
setItems(
items.map((v, n) =>
n === i ? { ...v, quantity: +e.target.value } : v,
),
)
}
/>
<button
type="button"
className="icon-button"
aria-label={`Remove ${item.name}`}
onClick={() => setItems(items.filter((_, n) => n !== i))}
>
<Minus size={18} />
</button>
</div>
))}
<label>
Add a saved food
<select
value=""
onChange={(e) => {
const food = foods.find((r) => r.id === e.target.value);
if (food) setItems([...items, { ...food.data, quantity: 1 }]);
}}
>
<option value="">Choose from your library…</option>
{foods.map((r) => (
<option key={r.id} value={r.id}>
{r.data.name}
</option>
))}
</select>
</label>
{foods.length === 0 && (
<p className="muted">
Save a food first, then combine your favorites here.
</p>
)}
{error && (
<p role="alert" className="error">
{error}
</p>
)}
<button
className="primary wide"
disabled={busy || items.length === 0 || items.length > 100}
>
Save plate
<Plus size={18} />
</button>
</form>
</Modal>
);
}
export function WeightEditor({
close,
unit,
existing,
notify,
}: {
close: () => void;
unit: Settings["unit"];
existing?: JournalRecord<Weight>;
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 (
<Modal
title={existing ? "Edit weigh-in" : "A moment to check in"}
subtitle="One measurement in a bigger picture."
close={close}
>
<form
onSubmit={async (e) => {
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);
}
}}
>
<div className="form-row">
<label>
Weight ({unit})
<input
autoFocus
type="number"
inputMode="decimal"
step="any"
min="0.1"
max={unit === "lb" ? "2204" : "1000"}
required
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</label>
<label>
Day
<input
type="date"
required
value={date}
onChange={(e) => setDate(e.target.value)}
/>
</label>
</div>
<label>
Note <span className="muted">(optional)</span>
<textarea
maxLength={500}
placeholder="Anything you’d like to remember"
value={notes}
onChange={(e) => setNotes(e.target.value)}
/>
</label>
{error && (
<p role="alert" className="error">
{error}
</p>
)}
<button className="primary wide" disabled={busy}>
Save weigh-in
<Plus size={18} />
</button>
</form>
</Modal>
);
}