first commit
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s

This commit is contained in:
Elijah 2026-10-20 19:04:12 -07:00
commit 6fc0a01c56
51 changed files with 11319 additions and 0 deletions

775
src/components.tsx Normal file
View file

@ -0,0 +1,775 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
X,
ArrowUpRight,
Plus,
Minus,
Leaf,
Smartphone,
RotateCcw,
} 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 } from "./store";
import { displayDate, number, today, weightValue } from "./utils";
export function Modal({
title,
subtitle,
close,
children,
}: {
title: string;
subtitle?: string;
close: () => void;
children: ReactNode;
}) {
const ref = useRef<HTMLDialogElement>(null);
useEffect(() => {
const dialog = ref.current!;
dialog.showModal();
const listener = (event: Event) => {
event.preventDefault();
close();
};
dialog.addEventListener("cancel", listener);
return () => {
dialog.removeEventListener("cancel", listener);
dialog.close();
};
}, [close]);
return (
<dialog
ref={ref}
className="sheet"
aria-labelledby="sheet-title"
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">
<div>
<span className="eyebrow">A LITTLE EVERYDAY CARE</span>
<h2 id="sheet-title">{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,
interactive = true,
}: {
value: number;
goal: number;
enabled: boolean;
small?: boolean;
interactive?: boolean;
}) {
const ratio = enabled ? Math.min(value / goal, 1) : Math.min(value / 2500, 1);
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"
/>
{!small && ratio < 0.85 && (
<div
className={"orb-number " + (ratio > 0.47 ? "orb-number-high" : "")}
>
{readout}
</div>
)}
</div>
{!small && ratio >= 0.85 && (
<div className="orb-number orb-number-outside">{readout}</div>
)}
{interactive && !small && (
<>
<div className="orb-motion-controls">
<button
disabled={physics.reduced}
aria-pressed={physics.enabled}
onClick={() => void physics.toggleTilt()}
>
<Smartphone size={12} />
{physics.reduced
? "Reduced motion"
: physics.motion === "on"
? "Tilt enabled"
: physics.motion === "waiting"
? "Waiting for tilt…"
: physics.enabled
? "Turn tilt off"
: "Enable tilt"}
</button>
<span />
<button disabled={physics.reduced} onClick={physics.nudge}>
<RotateCcw size={12} />
Give a nudge
</button>
</div>
{physics.motion === "denied" && (
<p className="motion-help" role="status">
Motion access was not granted. You can allow it in your browser’s
website settings.
</p>
)}
{physics.motion === "unavailable" && (
<p className="motion-help" role="status">
No tilt data yet. Falling bubbles still work on this device.
</p>
)}
</>
)}
</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 [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 [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 {
const food = { name: name.trim(), 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, 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 {
await putRecords(
plate.items.map((item) => ({
type: "entry",
data: { ...item, date: selectedDate, 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">
<label>
Day
<input
aria-label="Entry date"
type="date"
required
value={selectedDate}
onChange={(e) => setDate(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">
<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}
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 onSubmit={submit}>
<label>
Food name
<input
autoFocus
required
maxLength={160}
placeholder="e.g. Greek yogurt & berries"
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>
);
}