Extensive UI changes
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 28s

This commit is contained in:
Elijah 2026-10-20 19:46:08 -07:00
parent 6fc0a01c56
commit ddea7fc512
16 changed files with 675 additions and 493 deletions

View file

@ -5,10 +5,12 @@ A single-user, self-hosted nutrition journal. PWA first, with a responsive deskt
## Included
- Daily calorie vessel with colliding physics bubbles, week navigation, meal journal, editable entries, fractional servings. New bubbles drop from the top as calories increase.
- Food names are optional: unnamed daily entries use the meal name and next available number, such as `Dinner 1`. The main Add food action suggests breakfast from 5–11am, lunch from 11am–4pm, dinner from 4–10pm and snacks overnight, using the device's local time. Meal-specific add buttons preserve their category; the selection remains editable.
- Food entries include an editable local clock time, shown in the journal and all export formats. Existing entries without a time remain valid and show “Time not recorded” until you add one. Entries sort by time within each meal.
- Saved foods and reusable plates. Logging a plate creates an atomic batch of independent food entries. Logs retain a nutrition snapshot when library foods change.
- Independently enabled calorie, protein, carbohydrate, fat, fiber, sugar and sodium goals.
- Weight journal in lb or kg; internally stored in kg. Multiple weigh-ins are retained, with the latest measurement per day used in charts.
- 7 / 30 / 90 / 365 day nutrition and weight trends. Unlogged days are excluded from intake averages.
- Dedicated Weight tab on desktop and mobile, with its own logging, graph and journal. Nutrition trends live under Library → Trends. Both support 7 / 30 / 90 / 365 day periods. Unlogged days are excluded from intake averages.
- Markdown, CSV and JSON export with date range, nutrient and weight selections. Markdown is designed for LLM analysis. Data is downloaded locally, never submitted to an LLM. Save preferences to remember the export format, range preset and selections.
- Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and explicit PWA update prompts.
@ -66,9 +68,9 @@ To restore a database backup: stop Calio, preserve the current data directory, r
### Bubble motion
Tap **Enable tilt** beneath the calorie circle to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that tap; the public site must use HTTPS. The app remembers the choice for the current page session and does not transmit sensor readings. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity and the **Give a nudge** control.
Enable **Settings → Look & feel → Tilt calorie bubbles** to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that gesture; the public site must use HTTPS. The preference is stored only on this device, and iOS may require enabling it again after reopening the app. Sensor readings are never transmitted. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity.
The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top, and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity; near a full vessel, the numeric readout moves below the circle so it does not hide dots. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. The animation sleeps when settled, pauses in hidden tabs, and honors the device's reduced-motion preference with a still arrangement. The graphic is an approximate visual; the numeric calorie total is authoritative.
The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top at 30 per second (50% faster than the original pace), and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity. The numeric readout always sits below the circle, leaving every dot visible. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. Macro bars animate when totals change, and rows with one or two tracked macros are centered. Motion honors the device's reduced-motion preference. The physics animation sleeps when settled and pauses in hidden tabs. The graphic is an approximate visual; the numeric calorie total is authoritative.
## Forgejo CI and container registry

View file

@ -102,7 +102,8 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) {
}
function step(delta = 1000 / 60) {
spawnTime += delta;
if (balls.length < target && spawnTime >= 45) {
// Two 60 Hz frames per bubble, previously three: 50% more arrivals/second.
if (balls.length < target && spawnTime >= 1000 / 30) {
spawnTime = 0;
// Each new bubble enters at the upper inside edge, then falls naturally.
const x = 160 + (random() - 0.5) * 55;

View file

@ -31,6 +31,10 @@ const food = z.object({
const entry = food
.extend({
date,
time: z
.string()
.regex(/^([01]\d|2[0-3]):[0-5]\d$/)
.optional(),
meal: z.enum(["Breakfast", "Lunch", "Dinner", "Snacks"]),
quantity: z.number().finite().positive().max(1000),
})

22
shared/entry.js Normal file
View file

@ -0,0 +1,22 @@
/** @returns {'Breakfast' | 'Lunch' | 'Dinner' | 'Snacks'} */
export function suggestedMeal(date = new Date()) {
const hour = date.getHours();
if (hour >= 5 && hour < 11) return "Breakfast";
if (hour >= 11 && hour < 16) return "Lunch";
if (hour >= 16 && hour < 22) return "Dinner";
return "Snacks";
}
export function localTime(date = new Date()) {
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
}
export function nextFoodName(prefix, names) {
let highest = 0;
for (const name of names) {
if (!name.startsWith(prefix + " ")) continue;
const suffix = name.slice(prefix.length + 1);
if (/^\d+$/.test(suffix)) highest = Math.max(highest, Number(suffix));
}
return `${prefix} ${highest + 1}`;
}

View file

@ -1,13 +1,17 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Activity,
useCallback,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import {
ArrowRight,
ArrowUpRight,
BookOpen,
Check,
ChevronLeft,
ChevronRight,
CircleHelp,
CloudOff,
Coffee,
Home,
@ -15,7 +19,6 @@ import {
LoaderCircle,
LockKeyhole,
Moon,
MoreHorizontal,
Pencil,
Plus,
Scale,
@ -31,6 +34,7 @@ import {
} from "lucide-react";
import { defaultSettings, totalNutrients } from "../shared/domain.js";
import { accentPalette } from "../shared/theme.js";
import { suggestedMeal } from "../shared/entry.js";
import {
deleteRecord,
initStore,
@ -53,11 +57,11 @@ import {
import {
dayDate,
displayDate,
displayTime,
number,
offsetDay,
recordsOf,
today,
weightValue,
} from "./utils";
import {
CalorieOrb,
@ -70,7 +74,7 @@ import {
import { Trends } from "./Trends";
import { Settings } from "./Settings";
type Page = "today" | "library" | "trends" | "settings";
type Page = "today" | "library" | "weight" | "settings";
type Editor =
| { kind: "log"; meal: Meal; record?: JournalRecord<Entry> }
| { kind: "food"; record?: JournalRecord<Food> }
@ -109,7 +113,7 @@ function SignIn({
</p>
</div>
<div className="login-orb">
<CalorieOrb value={1050} goal={2000} enabled interactive={false} />
<CalorieOrb value={1050} goal={2000} enabled />
<span className="art-label">
<Leaf size={16} />
Room to grow.
@ -141,7 +145,6 @@ function SignIn({
<span className="login-lock">
<LockKeyhole size={24} />
</span>
<span className="eyebrow">YOUR PERSONAL SPACE</span>
<h2>{reauth ? "Welcome back." : "A fresh perspective."}</h2>
<p>
{reauth
@ -213,7 +216,6 @@ function Dashboard({
edit,
remove,
openLibrary,
logWeight,
}: {
records: JournalRecord[];
settings: SettingsData;
@ -223,7 +225,6 @@ function Dashboard({
edit: (r: JournalRecord<Entry>) => void;
remove: (r: JournalRecord) => void;
openLibrary: () => void;
logWeight: () => void;
}) {
const entries = recordsOf<Entry>(records, "entry");
const dayEntries = entries.filter((r) => r.data.date === date);
@ -242,11 +243,6 @@ function Dashboard({
(m) => m.key !== "calories" && settings.goals[m.key].enabled,
);
const goal = settings.goals.calories;
const latestWeight = recordsOf<Weight>(records, "weight").sort(
(a, b) =>
b.data.date.localeCompare(a.data.date) ||
b.updatedAt.localeCompare(a.updatedAt),
)[0];
const mealIcons = {
Breakfast: Coffee,
Lunch: Sun,
@ -290,7 +286,10 @@ function Dashboard({
/>
<ChevronRight size={16} />
</button>
<button className="primary desktop-add" onClick={() => add("Snacks")}>
<button
className="primary desktop-add"
onClick={() => add(suggestedMeal())}
>
<Plus size={18} />
Add food
</button>
@ -415,7 +414,13 @@ function Dashboard({
</span>
</div>
{meals.map((meal) => {
const rows = dayEntries.filter((r) => r.data.meal === meal);
const rows = dayEntries
.filter((r) => r.data.meal === meal)
.sort(
(a, b) =>
(a.data.time || "").localeCompare(b.data.time || "") ||
a.id.localeCompare(b.id),
);
const calories = totalNutrients(rows.map((r) => r.data)).calories;
const Icon = mealIcons[meal];
return (
@ -447,7 +452,10 @@ function Dashboard({
>
<strong>{r.data.name}</strong>
<small>
{number(r.data.quantity, 2)} × {r.data.serving}
{r.data.time
? displayTime(r.data.time)
: "Time not recorded"}{" "}
· {number(r.data.quantity, 2)} × {r.data.serving}
{settings.goals.protein.enabled
? ` · ${number(r.data.nutrients.protein * r.data.quantity, 1)}g protein`
: ""}
@ -486,31 +494,6 @@ function Dashboard({
</span>
<ArrowUpRight size={21} />
</button>
<section className="card quick-weight">
<div className="weight-icon">
<Scale size={22} />
</div>
<div>
<span className="eyebrow">A SMALL CHECK-IN</span>
<h3>
{latestWeight
? `${number(weightValue(latestWeight.data.valueKg, settings.unit), 1)} ${settings.unit}`
: "How are you feeling?"}
</h3>
<p>
{latestWeight
? `Latest weigh-in · ${displayDate(latestWeight.data.date, { month: "short", day: "numeric" })}`
: "Log your weight. See the bigger picture."}
</p>
</div>
<button
className="icon-button"
aria-label="Log weight"
onClick={logWeight}
>
<Plus size={20} />
</button>
</section>
</div>
</div>
<div className="page-footnote">
@ -529,6 +512,7 @@ function Library({
editPlate,
log,
remove,
trends,
}: {
foods: JournalRecord<Food>[];
plates: JournalRecord<Plate>[];
@ -538,6 +522,7 @@ function Library({
editPlate: (r: JournalRecord<Plate>) => void;
log: () => void;
remove: (r: JournalRecord) => void;
trends: ReactNode;
}) {
const [tab, setTab] = useState("foods");
const [search, setSearch] = useState("");
@ -551,13 +536,15 @@ function Library({
</h1>
<p>A little less effort, every time you log.</p>
</div>
<button
className="primary"
onClick={tab === "foods" ? newFood : newPlate}
>
<Plus size={18} />
{tab === "foods" ? "New food" : "New plate"}
</button>
{tab !== "trends" && (
<button
className="primary"
onClick={tab === "foods" ? newFood : newPlate}
>
<Plus size={18} />
{tab === "foods" ? "New food" : "New plate"}
</button>
)}
</div>
<div className="library-controls">
<div className="segmented">
@ -573,19 +560,29 @@ function Library({
>
My plates <span>{plates.length}</span>
</button>
<button
className={tab === "trends" ? "active" : ""}
onClick={() => setTab("trends")}
>
Trends
</button>
</div>
<label className="search-field">
<Search size={18} />
<input
aria-label="Search saved foods and plates"
type="search"
placeholder="Find a favorite…"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
{tab !== "trends" && (
<label className="search-field">
<Search size={18} />
<input
aria-label="Search saved foods and plates"
type="search"
placeholder="Find a favorite…"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</label>
)}
</div>
{(tab === "foods" ? foods : plates).length === 0 ? (
{tab === "trends" ? (
trends
) : (tab === "foods" ? foods : plates).length === 0 ? (
<section className="card library-empty">
<Empty
icon={
@ -704,17 +701,19 @@ function Library({
)}
</div>
)}
<div className="library-bottom">
<Leaf size={18} />
<span>
Saved foods are a starting point. Your past entries keep their
original nutrition.
</span>
<button className="text-button" onClick={log}>
Log something
<ArrowUpRight size={15} />
</button>
</div>
{tab !== "trends" && (
<div className="library-bottom">
<Leaf size={18} />
<span>
Saved foods are a starting point. Your past entries keep their
original nutrition.
</span>
<button className="text-button" onClick={log}>
Log something
<ArrowUpRight size={15} />
</button>
</div>
)}
</>
);
}
@ -851,7 +850,7 @@ export function App() {
const nav = [
{ key: "today", label: "Today", icon: Home },
{ key: "library", label: "My library", icon: BookOpen },
{ key: "trends", label: "Trends", icon: Activity },
{ key: "weight", label: "Weight", icon: Scale },
{ key: "settings", label: "Settings", icon: Settings2 },
] as const;
const syncLabel = !status.online
@ -891,21 +890,6 @@ export function App() {
</button>
))}
</nav>
<div className="sidebar-bottom">
<div className="sidebar-note">
<span className="little-star">✳</span>
<p>
Progress looks
<br />
different every day.
</p>
<span>Keep showing up for you.</span>
</div>
<div className="private-label">
<ShieldCheck size={16} />
Your personal space
</div>
</div>
</aside>
<div className="main-wrap">
<header className="topbar">
@ -977,7 +961,6 @@ export function App() {
}
remove={setDeleting}
openLibrary={() => setPage("library")}
logWeight={() => setEditor({ kind: "weight" })}
/>
)}
{page === "library" && (
@ -988,12 +971,20 @@ export function App() {
newPlate={() => setEditor({ kind: "plate" })}
editFood={(record) => setEditor({ kind: "food", record })}
editPlate={(record) => setEditor({ kind: "plate", record })}
log={() => setEditor({ kind: "log", meal: "Snacks" })}
log={() => setEditor({ kind: "log", meal: suggestedMeal() })}
remove={setDeleting}
trends={
<Trends
mode="nutrition"
records={journal.records}
settings={settings}
/>
}
/>
)}
{page === "trends" && (
{page === "weight" && (
<Trends
mode="weight"
records={journal.records}
settings={settings}
logWeight={() => setEditor({ kind: "weight" })}
@ -1039,7 +1030,7 @@ export function App() {
<button
className="nav-add"
aria-label="Add food"
onClick={() => setEditor({ kind: "log", meal: "Snacks" })}
onClick={() => setEditor({ kind: "log", meal: suggestedMeal() })}
>
<Plus size={28} />
</button>

View file

@ -17,6 +17,7 @@ import { metrics } from "./types";
import { downloadExport, offsetDay, today } from "./utils";
import { logout, saveRecord, sync, useSyncStatus } from "./store";
import { accentPresets, DEFAULT_ACCENT } from "../shared/theme.js";
import { useTilt } from "./useTilt";
export function Settings({
settings,
@ -36,6 +37,7 @@ export function Settings({
update: (() => void) | null;
}) {
const [draft, setDraft] = useState(settings);
const tilt = useTilt();
const [busy, setBusy] = useState(false);
const [format, setFormat] = useState(settings.exportFormat);
const [range, setRange] = useState(settings.exportDays);
@ -174,6 +176,26 @@ export function Settings({
))}
<div className="settings-section">
<h3>Look & feel</h3>
<div className="preference-row">
<label className="toggle-label">
<input
className="switch"
type="checkbox"
checked={tilt.enabled}
onChange={() => void tilt.toggleTilt()}
/>
Tilt calorie bubbles
</label>
</div>
<p className="small muted" role="status">
{tilt.status === "denied"
? "Motion permission was not granted. Check your browser’s website permissions."
: tilt.status === "unavailable"
? "Orientation sensors are unavailable on this device. Bubbles still fall normally."
: tilt.status === "permission"
? "Enable tilt again to grant motion access for this session."
: "Uses this device’s orientation. iPhone may request permission again after reopening. Reduced motion pauses the animation."}
</p>
<div className="segmented theme-control">
{(
[

View file

@ -29,12 +29,14 @@ export function Trends({
logWeight,
editWeight,
remove,
mode = "nutrition",
}: {
records: JournalRecord[];
settings: Settings;
logWeight: () => void;
editWeight: (r: JournalRecord<Weight>) => void;
remove: (r: JournalRecord) => void;
mode?: "nutrition" | "weight";
logWeight?: () => void;
editWeight?: (r: JournalRecord<Weight>) => void;
remove?: (r: JournalRecord) => void;
}) {
const [period, setPeriod] = useState(7);
const [end, setEnd] = useState(today());
@ -87,19 +89,21 @@ export function Trends({
const delta = values.length > 1 ? values.at(-1)! - values[0] : null;
return (
<>
<div className="page-heading">
<div>
<span className="eyebrow">THE BIGGER PICTURE</span>
<h1>
Your rhythms<span>.</span>
</h1>
<p>Small moments. A little perspective.</p>
{mode === "weight" && (
<div className="page-heading">
<div>
<span className="eyebrow">THE BIGGER PICTURE</span>
<h1>
Weight<span>.</span>
</h1>
<p>Your weigh-ins and changes over time.</p>
</div>
<button className="primary" onClick={logWeight}>
<Plus size={18} />
Log weight
</button>
</div>
<button className="primary" onClick={logWeight}>
<Plus size={18} />
Log weight
</button>
</div>
)}
<div className="trend-controls">
<div className="segmented">
{[7, 30, 90, 365].map((n) => (
@ -150,221 +154,227 @@ export function Trends({
</button>
</div>
</div>
<div className="trends-grid">
<section className="card chart-card">
<div className="card-title">
<div>
<span className="eyebrow">DAILY INTAKE</span>
<h2>{chosen.label}</h2>
<div className="trends-grid single-trend">
{mode === "nutrition" && (
<section className="card chart-card">
<div className="card-title">
<div>
<span className="eyebrow">DAILY INTAKE</span>
<h2>{chosen.label}</h2>
</div>
<select
aria-label="Trend nutrient"
value={metric}
onChange={(e) => setMetric(e.target.value as Metric)}
>
{metrics.map((m) => (
<option value={m.key} key={m.key}>
{m.label}
</option>
))}
</select>
</div>
<select
aria-label="Trend nutrient"
value={metric}
onChange={(e) => setMetric(e.target.value as Metric)}
<div className="stat-large">
{number(avg)} <span>{chosen.unit} / logged day</span>
</div>
<div
className="bar-chart"
role="img"
aria-label={`${chosen.label}: ${number(avg)} ${chosen.unit} average over ${loggedDays.length} logged days`}
>
{metrics.map((m) => (
<option value={m.key} key={m.key}>
{m.label}
</option>
))}
</select>
</div>
<div className="stat-large">
{number(avg)} <span>{chosen.unit} / logged day</span>
</div>
<div
className="bar-chart"
role="img"
aria-label={`${chosen.label}: ${number(avg)} ${chosen.unit} average over ${loggedDays.length} logged days`}
>
<div className="chart-grid-lines">
<span>{number(maximum)}</span>
<span>{number(maximum / 2)}</span>
<span>0</span>
</div>
<div className="bars">
{goal.enabled && (
<div
className="goal-line"
style={{ bottom: `${(goal.target / maximum) * 100}%` }}
>
<span>Goal {number(goal.target)}</span>
</div>
)}
{days.map((d) => (
<div
className={"bar-slot " + (!d.logged ? "unlogged" : "")}
key={d.date}
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit : "Not logged"}`}
>
<div className="chart-grid-lines">
<span>{number(maximum)}</span>
<span>{number(maximum / 2)}</span>
<span>0</span>
</div>
<div className="bars">
{goal.enabled && (
<div
className="bar"
style={{
height: `${d.logged ? Math.max(1, (d.total / maximum) * 100) : 2}%`,
background: d.logged ? chosen.color : undefined,
}}
/>
{period === 7 && (
<span>
{displayDate(d.date, { weekday: "short" }).slice(0, 1)}
</span>
)}
</div>
))}
className="goal-line"
style={{ bottom: `${(goal.target / maximum) * 100}%` }}
>
<span>Goal {number(goal.target)}</span>
</div>
)}
{days.map((d) => (
<div
className={"bar-slot " + (!d.logged ? "unlogged" : "")}
key={d.date}
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit : "Not logged"}`}
>
<div
className="bar"
style={{
height: `${d.logged ? Math.max(1, (d.total / maximum) * 100) : 2}%`,
background: d.logged ? chosen.color : undefined,
}}
/>
{period === 7 && (
<span>
{displayDate(d.date, { weekday: "short" }).slice(0, 1)}
</span>
)}
</div>
))}
</div>
</div>
</div>
<p className="chart-note">
{loggedDays.length} of {period} days logged · Empty days are
excluded from the average.
</p>
</section>
<section className="card chart-card">
<p className="chart-note">
{loggedDays.length} of {period} days logged · Empty days are
excluded from the average.
</p>
</section>
)}
{mode === "weight" && (
<section className="card chart-card">
<div className="card-title">
<div>
<span className="eyebrow">YOUR JOURNEY</span>
<h2>Weight</h2>
</div>
<Scale size={22} className="muted" />
</div>
{dailyWeights.length ? (
<>
<div className="stat-large">
{number(values.at(-1)!, 1)} <span>{settings.unit}</span>
</div>
<div className="weight-chart">
<svg
viewBox="0 0 600 210"
role="img"
aria-label={`${dailyWeights.length} weigh-ins, latest ${number(values.at(-1)!, 1)} ${settings.unit}`}
>
<line
x1="28"
x2="572"
y1="30"
y2="30"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="100"
y2="100"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="170"
y2="170"
className="grid-line"
/>
<polyline
points={points.map((p) => `${p.x},${p.y}`).join(" ")}
fill="none"
stroke="var(--accent)"
strokeWidth="3"
strokeLinejoin="round"
/>
{points.map((p, i) => (
<circle
key={i}
cx={p.x}
cy={p.y}
r="4"
fill="var(--accent)"
>
<title>
{dailyWeights[i].data.date}: {number(values[i], 1)}{" "}
{settings.unit}
</title>
</circle>
))}
<text x="28" y="202">
{displayDate(start, { month: "short", day: "numeric" })}
</text>
<text x="572" y="202" textAnchor="end">
{displayDate(end, { month: "short", day: "numeric" })}
</text>
</svg>
<div className="weight-axis">
<span>{number(maxWeight, 1)}</span>
<span>{number(minWeight, 1)}</span>
</div>
</div>
<p className="chart-note">
{delta === null ? (
"Log another day to see a change over time."
) : (
<>
{delta < 0 ? (
<ArrowDownRight size={15} />
) : (
<ArrowUpRight size={15} />
)}{" "}
{number(Math.abs(delta), 1)} {settings.unit}{" "}
{delta < 0 ? "down" : "up"} in this period
</>
)}
</p>
</>
) : (
<Empty
icon={<Activity size={28} />}
title="A starting point, whenever you’re ready"
text="Your weigh-ins will become a simple picture of your progress."
action={
<button className="text-button" onClick={logWeight}>
Log your first weight <ArrowUpRight size={16} />
</button>
}
/>
)}
</section>
)}
</div>
{mode === "weight" && (
<section className="card weight-journal">
<div className="card-title">
<div>
<span className="eyebrow">YOUR JOURNEY</span>
<h2>Weight</h2>
<span className="eyebrow">ONE CHECK-IN AT A TIME</span>
<h2>Weight journal</h2>
</div>
<Scale size={22} className="muted" />
<span className="pill">{weights.length} in this period</span>
</div>
{dailyWeights.length ? (
<>
<div className="stat-large">
{number(values.at(-1)!, 1)} <span>{settings.unit}</span>
</div>
<div className="weight-chart">
<svg
viewBox="0 0 600 210"
role="img"
aria-label={`${dailyWeights.length} weigh-ins, latest ${number(values.at(-1)!, 1)} ${settings.unit}`}
>
<line
x1="28"
x2="572"
y1="30"
y2="30"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="100"
y2="100"
className="grid-line"
/>
<line
x1="28"
x2="572"
y1="170"
y2="170"
className="grid-line"
/>
<polyline
points={points.map((p) => `${p.x},${p.y}`).join(" ")}
fill="none"
stroke="var(--accent)"
strokeWidth="3"
strokeLinejoin="round"
/>
{points.map((p, i) => (
<circle
key={i}
cx={p.x}
cy={p.y}
r="4"
fill="var(--accent)"
>
<title>
{dailyWeights[i].data.date}: {number(values[i], 1)}{" "}
{settings.unit}
</title>
</circle>
))}
<text x="28" y="202">
{displayDate(start, { month: "short", day: "numeric" })}
</text>
<text x="572" y="202" textAnchor="end">
{displayDate(end, { month: "short", day: "numeric" })}
</text>
</svg>
<div className="weight-axis">
<span>{number(maxWeight, 1)}</span>
<span>{number(minWeight, 1)}</span>
</div>
</div>
<p className="chart-note">
{delta === null ? (
"Log another day to see a change over time."
) : (
<>
{delta < 0 ? (
<ArrowDownRight size={15} />
) : (
<ArrowUpRight size={15} />
)}{" "}
{number(Math.abs(delta), 1)} {settings.unit}{" "}
{delta < 0 ? "down" : "up"} in this period
</>
)}
</p>
</>
{weights.length === 0 ? (
<p className="muted">No weigh-ins in this date range.</p>
) : (
<Empty
icon={<Activity size={28} />}
title="A starting point, whenever you’re ready"
text="Your weigh-ins will become a simple picture of your progress."
action={
<button className="text-button" onClick={logWeight}>
Log your first weight <ArrowUpRight size={16} />
[...weights].reverse().map((r) => (
<div className="journal-row" key={r.id}>
<div className="food-avatar weight-avatar">
<Scale size={19} />
</div>
<div className="row-copy">
<strong>
{number(weightValue(r.data.valueKg, settings.unit), 1)}{" "}
{settings.unit}
</strong>
<small>
{displayDate(r.data.date)}
{r.data.notes ? " · " + r.data.notes : ""}
</small>
</div>
<button
className="icon-button"
aria-label={`Edit weight ${r.data.date}`}
onClick={() => editWeight?.(r)}
>
<Pencil size={16} />
</button>
}
/>
<button
className="icon-button danger-hover"
aria-label={`Delete weight ${r.data.date}`}
onClick={() => remove?.(r)}
>
<Trash2 size={16} />
</button>
</div>
))
)}
</section>
</div>
<section className="card weight-journal">
<div className="card-title">
<div>
<span className="eyebrow">ONE CHECK-IN AT A TIME</span>
<h2>Weight journal</h2>
</div>
<span className="pill">{weights.length} in this period</span>
</div>
{weights.length === 0 ? (
<p className="muted">No weigh-ins in this date range.</p>
) : (
[...weights].reverse().map((r) => (
<div className="journal-row" key={r.id}>
<div className="food-avatar weight-avatar">
<Scale size={19} />
</div>
<div className="row-copy">
<strong>
{number(weightValue(r.data.valueKg, settings.unit), 1)}{" "}
{settings.unit}
</strong>
<small>
{displayDate(r.data.date)}
{r.data.notes ? " · " + r.data.notes : ""}
</small>
</div>
<button
className="icon-button"
aria-label={`Edit weight ${r.data.date}`}
onClick={() => editWeight(r)}
>
<Pencil size={16} />
</button>
<button
className="icon-button danger-hover"
aria-label={`Delete weight ${r.data.date}`}
onClick={() => remove(r)}
>
<Trash2 size={16} />
</button>
</div>
))
)}
</section>
)}
</>
);
}

View file

@ -1,13 +1,5 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
X,
ArrowUpRight,
Plus,
Minus,
Leaf,
Smartphone,
RotateCcw,
} from "lucide-react";
import { X, ArrowUpRight, Plus, Minus, Leaf } from "lucide-react";
import { bubbleCount } from "../shared/bubble-physics.js";
import { useBubblePhysics } from "./useBubblePhysics";
import {
@ -22,7 +14,8 @@ import {
type Weight,
} from "./types";
import { emptyNutrients } from "../shared/domain.js";
import { saveRecord, putRecords } from "./store";
import { saveRecord, putRecords, useJournal } from "./store";
import { localTime, nextFoodName } from "../shared/entry.js";
import { displayDate, number, today, weightValue } from "./utils";
export function Modal({
@ -91,15 +84,12 @@ export function CalorieOrb({
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 = (
<>
@ -141,55 +131,8 @@ export function CalorieOrb({
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>
)}
</>
)}
{!small && <div className="orb-number orb-number-outside">{readout}</div>}
</div>
);
}
@ -272,6 +215,7 @@ export function FoodEditor({
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");
@ -287,6 +231,24 @@ export function FoodEditor({
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("");
@ -296,7 +258,13 @@ export function FoodEditor({
setBusy(true);
setError("");
try {
const food = { name: name.trim(), serving: serving.trim(), nutrients };
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",
@ -304,7 +272,13 @@ export function FoodEditor({
data:
mode === "food"
? food
: { ...food, date: selectedDate, meal: selectedMeal, quantity },
: {
...food,
date: selectedDate,
...(time ? { time } : {}),
meal: selectedMeal,
quantity,
},
},
];
if (saveFood && mode === "log") items.push({ type: "food", data: food });
@ -327,10 +301,12 @@ export function FoodEditor({
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, meal: selectedMeal },
data: { ...item, date: selectedDate, time, meal: selectedMeal },
})),
);
notify(`${plate.name} added to your day`);
@ -379,7 +355,7 @@ export function FoodEditor({
</div>
)}
{mode === "log" && (
<div className="form-row">
<div className="form-row entry-details">
<label>
Day
<input
@ -390,6 +366,16 @@ export function FoodEditor({
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
@ -446,7 +432,7 @@ export function FoodEditor({
)
.map((r) => (
<button
disabled={busy || !selectedDate}
disabled={busy || !selectedDate || !time}
className="picker-row"
key={r.id}
onClick={() => void addPlate(r.data)}
@ -480,12 +466,11 @@ export function FoodEditor({
) : (
<form onSubmit={submit}>
<label>
Food name
Food name <span className="muted">(optional)</span>
<input
autoFocus
required
maxLength={160}
placeholder="e.g. Greek yogurt & berries"
placeholder={fallbackName}
value={name}
onChange={(e) => setName(e.target.value)}
/>

View file

@ -570,38 +570,6 @@ main {
height: 100%;
pointer-events: none;
}
.orb-motion-controls {
display: flex;
justify-content: center;
align-items: center;
gap: 13px;
margin: -2px 0 10px;
}
.orb-motion-controls button {
min-height: 36px;
display: inline-flex;
gap: 5px;
align-items: center;
color: var(--muted);
font-size: 9px;
padding: 4px;
}
.orb-motion-controls button[aria-pressed="true"],
.orb-motion-controls button:hover {
color: var(--accent-text);
}
.orb-motion-controls > span {
width: 1px;
height: 10px;
background: var(--line);
}
.motion-help {
font-size: 9px;
color: var(--muted);
text-align: center;
max-width: 270px;
margin: 0 auto 12px;
}
.orb-number {
z-index: 1;
position: absolute;
@ -628,27 +596,21 @@ main {
color: var(--muted);
margin-top: 4px;
}
.orb-number-high {
background: var(--surface);
box-shadow: 0 0 20px 10px var(--surface);
border-radius: 60%;
inset: 26% 22% auto;
}
.orb-number.orb-number-outside {
position: static;
flex-direction: row;
flex-direction: column;
justify-content: center;
gap: 8px;
margin: 9px 0 5px;
gap: 3px;
margin: 10px 0 16px;
min-height: 32px;
}
.orb-number.orb-number-outside strong {
font-size: 26px;
font-size: 42px;
letter-spacing: -1px;
margin: 0;
}
.orb-number.orb-number-outside .eyebrow {
font-size: 7px;
font-size: 8px;
}
.orb-number.orb-number-outside .orb-unit {
margin: 0;
@ -681,12 +643,20 @@ main {
background: var(--line);
}
.macro-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 19px;
padding: 24px 0 26px;
border-top: 1px solid var(--line);
}
.macro-grid > .macro {
flex: 0 1 calc((100% - 40px) / 3);
min-width: 0;
}
.trends-grid.single-trend {
grid-template-columns: minmax(0, 1fr);
}
.macro-label {
display: flex;
align-items: center;
@ -722,6 +692,7 @@ main {
display: block;
height: 100%;
border-radius: 4px;
transition: width 650ms cubic-bezier(0.22, 1, 0.36, 1);
}
.balance-footer {
border-top: 1px solid var(--line);
@ -1046,6 +1017,12 @@ main {
.sheet-head > .icon-button {
margin: -7px -8px 0 0;
}
.sheet-head > div {
min-width: 0;
}
.sheet-head .eyebrow {
white-space: normal;
}
.sheet .eyebrow {
font-size: 8px;
}
@ -1084,10 +1061,13 @@ textarea {
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 15px;
margin-bottom: 18px;
}
.entry-details {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.unit-input {
display: flex;
align-items: center;
@ -1124,10 +1104,11 @@ textarea {
}
.nutrient-fields {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 15px;
}
.nutrient-fields label {
min-width: 0;
font-size: 10px;
color: var(--muted);
}
@ -1624,7 +1605,12 @@ textarea {
gap: 25px;
align-items: start;
}
.settings-grid > *, .settings-stack, .settings-card, .form-row > label { min-width: 0; }
.settings-grid > *,
.settings-stack,
.settings-card,
.form-row > label {
min-width: 0;
}
.settings-card {
padding: 26px;
}
@ -2550,6 +2536,8 @@ textarea {
}
.sheet .segmented button {
font-size: 11px;
padding-inline: 10px;
min-width: 0;
}
.section-caption > span:last-child {
font-size: 8px;
@ -2557,6 +2545,12 @@ textarea {
.form-row {
gap: 12px;
}
.entry-details {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.entry-details > label:first-child {
grid-column: 1 / -1;
}
.sheet .picker-row {
min-height: 64px;
}

View file

@ -3,7 +3,12 @@ export type Metric =
export type Nutrients = Record<Metric, number>;
export type Food = { name: string; serving: string; nutrients: Nutrients };
export type Meal = "Breakfast" | "Lunch" | "Dinner" | "Snacks";
export type Entry = Food & { date: string; meal: Meal; quantity: number };
export type Entry = Food & {
date: string;
time?: string;
meal: Meal;
quantity: number;
};
export type Plate = { name: string; items: (Food & { quantity: number })[] };
export type Weight = { date: string; valueKg: number; notes: string };
export type Settings = {

View file

@ -1,19 +1,17 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useTilt } from "./useTilt";
import {
createBubbleWorld,
screenGravity,
DRAW_BUBBLE_RADIUS,
} from "../shared/bubble-physics.js";
let tiltAllowedThisSession = false;
type MotionStatus = "off" | "waiting" | "on" | "denied" | "unavailable";
export function useBubblePhysics(count: number) {
const canvas = useRef<HTMLCanvasElement>(null);
const world = useRef<ReturnType<typeof createBubbleWorld> | null>(null);
const kick = useRef<() => void>(() => {});
const redraw = useRef<() => void>(() => {});
const [enabled, setEnabled] = useState(tiltAllowedThisSession);
const [motion, setMotion] = useState<MotionStatus>("off");
const { enabled } = useTilt();
const [reduced, setReduced] = useState(
() => matchMedia("(prefers-reduced-motion: reduce)").matches,
);
@ -154,8 +152,6 @@ export function useBubblePhysics(count: number) {
kick.current();
return;
}
setMotion("waiting");
let received = false;
let lastBeta = 0;
let lastGamma = 0;
const apply = () => {
@ -177,57 +173,15 @@ export function useBubblePhysics(count: number) {
return;
lastBeta = event.beta;
lastGamma = event.gamma;
if (!received) {
received = true;
setMotion("on");
}
apply();
};
window.addEventListener("deviceorientation", orientation);
screen.orientation?.addEventListener("change", apply);
const timeout = setTimeout(() => {
if (!received) setMotion("unavailable");
}, 5000);
return () => {
clearTimeout(timeout);
window.removeEventListener("deviceorientation", orientation);
screen.orientation?.removeEventListener("change", apply);
};
}, [enabled, reduced]);
const toggleTilt = useCallback(async () => {
if (enabled) {
setEnabled(false);
setMotion("off");
tiltAllowedThisSession = false;
return;
}
if (typeof DeviceOrientationEvent === "undefined") {
setMotion("unavailable");
return;
}
try {
const sensor = DeviceOrientationEvent as typeof DeviceOrientationEvent & {
requestPermission?: () => Promise<string>;
};
if (
sensor.requestPermission &&
(await sensor.requestPermission()) !== "granted"
) {
setMotion("denied");
return;
}
tiltAllowedThisSession = true;
setEnabled(true);
} catch {
setMotion("denied");
}
}, [enabled]);
const nudge = useCallback(() => {
if (!reduced) {
world.current?.nudge();
kick.current();
}
}, [reduced]);
return { canvas, motion, enabled, reduced, toggleTilt, nudge };
return { canvas };
}

68
src/useTilt.ts Normal file
View file

@ -0,0 +1,68 @@
import { useSyncExternalStore } from "react";
type Sensor = typeof DeviceOrientationEvent & {
requestPermission?: () => Promise<string>;
};
type TiltState = {
enabled: boolean;
status: "off" | "enabled" | "permission" | "denied" | "unavailable";
};
const needsPermission = () =>
typeof DeviceOrientationEvent !== "undefined" &&
Boolean((DeviceOrientationEvent as Sensor).requestPermission);
let wanted = false;
try {
wanted = localStorage.getItem("calio-tilt") === "true";
} catch {}
let state: TiltState = {
enabled: wanted && !needsPermission(),
status: wanted ? (needsPermission() ? "permission" : "enabled") : "off",
};
const listeners = new Set<() => void>();
function update(next: TiltState) {
state = next;
listeners.forEach((fn) => fn());
}
function remember(enabled: boolean) {
try {
localStorage.setItem("calio-tilt", String(enabled));
} catch {}
}
async function toggleTilt() {
if (state.enabled) {
remember(false);
update({ enabled: false, status: "off" });
return;
}
if (typeof DeviceOrientationEvent === "undefined") {
update({ enabled: false, status: "unavailable" });
return;
}
try {
const sensor = DeviceOrientationEvent as Sensor;
// Invoke directly from the settings gesture, before any other async work (iOS).
if (
sensor.requestPermission &&
(await sensor.requestPermission()) !== "granted"
) {
update({ enabled: false, status: "denied" });
return;
}
remember(true);
update({ enabled: true, status: "enabled" });
} catch {
update({ enabled: false, status: "denied" });
}
}
export function useTilt() {
const snapshot = useSyncExternalStore(
(fn) => {
listeners.add(fn);
return () => {
listeners.delete(fn);
};
},
() => state,
);
return { ...snapshot, toggleTilt };
}

View file

@ -21,6 +21,12 @@ export const displayDate = (
);
export const number = (value: number, decimals = 0) =>
value.toLocaleString(undefined, { maximumFractionDigits: decimals });
export function displayTime(time: string) {
return new Date(`2000-01-01T${time}:00`).toLocaleTimeString(undefined, {
hour: "numeric",
minute: "2-digit",
});
}
export const weightValue = (kg: number, unit: Settings["unit"]) =>
unit === "lb" ? kg * 2.2046226218 : kg;
export function recordsOf<T>(records: JournalRecord[], type: string) {
@ -44,7 +50,8 @@ export function downloadExport(
.sort(
(a, b) =>
a.data.date.localeCompare(b.data.date) ||
a.updatedAt.localeCompare(b.updatedAt),
(a.data.time || "").localeCompare(b.data.time || "") ||
a.id.localeCompare(b.id),
)
: [];
const weights = includeWeight
@ -76,13 +83,14 @@ export function downloadExport(
goals: Object.fromEntries(
selected.map((key) => [key, settings.goals[key]]),
),
note: "Days without food entries are unlogged, not zero-intake days. Entry nutrients are totals for the recorded quantity. Weight is stored in kg.",
note: "Days without food entries are unlogged, not zero-intake days. Entry times are local clock times as entered; older entries may have no time. Entry nutrients are totals for the recorded quantity. Weight is stored in kg.",
};
const logs = entries.map(
(r) =>
({
id: r.id,
date: r.data.date,
time: r.data.time || null,
meal: r.data.meal,
name: r.data.name,
serving: r.data.serving,
@ -96,6 +104,7 @@ export function downloadExport(
}) as {
id: string;
date: string;
time: string | null;
meal: string;
name: string;
serving: string;
@ -123,6 +132,7 @@ export function downloadExport(
const header = [
"record_type",
"date",
"time",
"meal",
"name",
"serving",
@ -135,6 +145,7 @@ export function downloadExport(
...logs.map((r) => [
"entry",
r.date,
r.time,
r.meal,
r.name,
r.serving,
@ -150,6 +161,7 @@ export function downloadExport(
"",
"",
"",
"",
...selected.map((k) => r[k]),
"",
"",
@ -161,6 +173,7 @@ export function downloadExport(
"",
"",
"",
"",
...selected.map(() => ""),
r.data.valueKg,
r.data.notes,
@ -176,16 +189,46 @@ export function downloadExport(
`# Calio nutrition journal\n\n${start} to ${end}\n\n${metadata.note}\nPending local changes: ${pending}`,
];
if (selected.length) {
sections.push("## Goals\n" + selected.map(k => `- ${k}: ${settings.goals[k].enabled ? settings.goals[k].target + " " + metadata.units[k] : "disabled"}`).join("\n"));
sections.push([
"## Daily totals (logged days)",
`| Date | ${selected.map(k => k + " (" + metadata.units[k] + ")").join(" | ")} |`,
`| --- | ${selected.map(() => "---").join(" | ")} |`,
...days.map(d => "| " + [d.date, ...selected.map(k => d[k])].join(" | ") + " |"),
].join("\n"));
sections.push("## Food entries\n" + logs.map(r => `- ${r.date} · ${r.meal} · ${clean(r.name)} · ${r.quantity} × ${clean(r.serving)}: ${selected.map(k => `${r[k]} ${metadata.units[k]} ${k}`).join(", ")}`).join("\n"));
sections.push(
"## Goals\n" +
selected
.map(
(k) =>
`- ${k}: ${settings.goals[k].enabled ? settings.goals[k].target + " " + metadata.units[k] : "disabled"}`,
)
.join("\n"),
);
sections.push(
[
"## Daily totals (logged days)",
`| Date | ${selected.map((k) => k + " (" + metadata.units[k] + ")").join(" | ")} |`,
`| --- | ${selected.map(() => "---").join(" | ")} |`,
...days.map(
(d) =>
"| " + [d.date, ...selected.map((k) => d[k])].join(" | ") + " |",
),
].join("\n"),
);
sections.push(
"## Food entries\n" +
logs
.map(
(r) =>
`- ${r.date}${r.time ? " " + r.time : ""} · ${r.meal} · ${clean(r.name)} · ${r.quantity} × ${clean(r.serving)}: ${selected.map((k) => `${r[k]} ${metadata.units[k]} ${k}`).join(", ")}`,
)
.join("\n"),
);
}
if (includeWeight) sections.push("## Weight (kg)\n" + weights.map(r => `- ${r.data.date}: ${number(r.data.valueKg, 2)} kg${r.data.notes ? " · " + clean(r.data.notes) : ""}`).join("\n"));
if (includeWeight)
sections.push(
"## Weight (kg)\n" +
weights
.map(
(r) =>
`- ${r.data.date}: ${number(r.data.valueKg, 2)} kg${r.data.notes ? " · " + clean(r.data.notes) : ""}`,
)
.join("\n"),
);
content = sections.join("\n\n") + "\n";
}
const blob = new Blob([content], {

67
tests/entry.test.js Normal file
View file

@ -0,0 +1,67 @@
import test from "node:test";
import assert from "node:assert/strict";
import { suggestedMeal, localTime, nextFoodName } from "../shared/entry.js";
import { recordSchema, emptyNutrients } from "../shared/domain.js";
test("meal suggestions follow local time at each meal boundary, including overnight snacks", () => {
for (const [hour, expected] of [
[0, "Snacks"],
[4, "Snacks"],
[5, "Breakfast"],
[7, "Breakfast"],
[10, "Breakfast"],
[11, "Lunch"],
[15, "Lunch"],
[16, "Dinner"],
[21, "Dinner"],
[22, "Snacks"],
[23, "Snacks"],
]) {
assert.equal(suggestedMeal(new Date(2026, 9, 20, hour, 28)), expected);
}
assert.equal(localTime(new Date(2026, 9, 20, 6, 28)), "06:28");
assert.equal(localTime(new Date(2026, 9, 20, 0, 5)), "00:05");
});
test("unnamed entries advance the category sequence without collisions after removals", () => {
assert.equal(nextFoodName("Dinner", []), "Dinner 1");
assert.equal(
nextFoodName("Dinner", ["Dinner 1", "Dinner 3", "Pasta", "Lunch 8"]),
"Dinner 4",
);
assert.equal(
nextFoodName("Breakfast", ["Breakfast 1", "Breakfast toast"]),
"Breakfast 2",
);
assert.equal(nextFoodName("Food", ["Food 1"]), "Food 2");
});
test("entry times validate, while legacy records without a time remain compatible", () => {
const entry = {
id: "e1",
type: "entry",
updatedAt: "2026-10-20T12:00:00.000Z",
deleted: false,
data: {
name: "Dinner 1",
date: "2026-10-20",
meal: "Dinner",
quantity: 1,
serving: "1 serving",
nutrients: emptyNutrients(),
},
};
assert.equal(recordSchema.safeParse(entry).success, true);
for (const time of ["00:00", "06:28", "23:59"])
assert.equal(
recordSchema.safeParse({ ...entry, data: { ...entry.data, time } })
.success,
true,
);
for (const time of ["24:00", "12:60", "6:28", "invalid", ""])
assert.equal(
recordSchema.safeParse({ ...entry, data: { ...entry.data, time } })
.success,
false,
);
});

View file

@ -11,6 +11,7 @@ const record = (id, type, data, deleted = false) => ({
});
const entry = {
date: "2026-10-20",
time: "06:28",
meal: "Lunch",
name: "=danger|\nfood",
serving: "1 bowl",
@ -64,6 +65,7 @@ test("JSON export includes fractional serving totals, chosen dates/metrics, kg w
assert.equal(data.pendingChanges, 2);
assert.equal(data.entries.length, 1);
assert.equal(data.entries[0].calories, 300);
assert.equal(data.entries[0].time, "06:28");
assert.equal(data.entries[0].protein, 30);
assert.equal("fat" in data.entries[0], false);
assert.equal(data.weights[0].valueKg, 75);
@ -74,9 +76,11 @@ test("CSV quotes text and guards spreadsheet formula fields; Markdown keeps clea
assert.match(csv, /"'=danger\|\nfood"/);
assert.match(csv, /"'=untrusted"/);
assert.match(csv, /"daily_total"/);
assert.match(csv, /"06:28"/);
const markdown = await capture("markdown");
assert.match(markdown, /\| 2026-10-20 \| 300 \| 30 \|/);
assert.match(markdown, /=danger\/ food/);
assert.match(markdown, /2026-10-20 06:28/);
assert.doesNotMatch(markdown, /2026-10-19/);
});
test("weight-only exports omit food records; excluding weight omits all weigh-ins", async () => {

View file

@ -17,6 +17,16 @@ test("bubble count tracks calories, remains visible at small amounts, and caps o
assert.equal(bubbleCount(2000, 2000, true), MAX_BUBBLES);
assert.equal(bubbleCount(20000, 2000, true), MAX_BUBBLES);
});
test("an 800 calorie meal drops in with 50 percent more bubbles per second", () => {
const world = createBubbleWorld(0, () => 0.5);
const target = bubbleCount(800, 2000, true);
world.setTarget(target);
for (let i = 0; i < 60; i++) world.step();
assert.equal(world.balls.length, 30);
for (let i = 0; i < target * 2 - 60; i++) world.step();
assert.equal(world.balls.length, target);
world.dispose();
});
test("new bubbles enter at the top, fall, collide and stay inside the calorie vessel", () => {
const world = createBubbleWorld(0, () => 0.5);
world.setTarget(8);