Polish PWA gestures, transitions and nutrition averages
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 32s

This commit is contained in:
Elijah 2026-10-22 09:16:52 -07:00
parent b19de6f9ea
commit 7288e56c02
16 changed files with 1019 additions and 245 deletions

View file

@ -10,7 +10,8 @@ A single-user, self-hosted nutrition journal. PWA first, with a responsive deskt
- 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.
- 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.
- 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. Nutrition averages exclude empty and likely incomplete days: the initial cutoff is half the calorie target, adjustable under Settings → Nutrition averages (0 includes all logged days). Every nutrient uses the same qualifying days; faded bars and exports retain actual totals. This is a logging heuristic, so adjust it for your own routine. Saving preferences stores the cutoff in kcal independently of later goal changes.
- On phones, swipe left/right through Today → Library → Weight → Settings. Vertical scrolling, form controls, horizontal macro scrolling, and browser edge gestures remain independent. Pages and sheets animate with touch feedback; pull down from a sheet header to dismiss it. System Reduce Motion disables these transitions.
- 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.

View file

@ -60,6 +60,7 @@ const settings = z
exportDays: z.enum(["7", "30", "90", "all"]),
exportMetrics: z.array(z.enum(metricKeys)).max(7).optional(),
exportWeight: z.boolean().optional(),
minimumAverageCalories: amount.optional(),
})
.strict();
export const recordSchema = z

9
shared/navigation.js Normal file
View file

@ -0,0 +1,9 @@
// Direction is the next tab (+1) or previous tab (-1). Vertical scrolling wins
// unless a gesture has a clear horizontal intent; small jitter never navigates.
export function swipeStep(dx, dy, elapsed, width) {
if (Math.abs(dx) < Math.abs(dy) * 1.4) return 0;
const distance = Math.abs(dx);
const deliberate = distance >= Math.min(90, Math.max(55, width * 0.18));
const flick = distance >= 36 && distance / Math.max(1, elapsed) >= 0.5;
return deliberate || flick ? (dx < 0 ? 1 : -1) : 0;
}

View file

@ -0,0 +1,39 @@
import { emptyNutrients, totalNutrients } from "./domain.js";
// The cutoff is a logging preference, not a nutritional recommendation.
// A fixed kcal cutoff remains predictable even if a calorie goal is disabled.
/**
* @param {import("../src/types").Entry[]} entries
* @param {string[]} dates
* @param {number} minimumCalories
*/
export function nutritionSummary(entries, dates, minimumCalories) {
/** @type {Map<string, import("../src/types").Entry[]>} */
const grouped = new Map();
for (const entry of entries) {
const group = grouped.get(entry.date) || [];
group.push(entry);
grouped.set(entry.date, group);
}
const days = dates.map((date) => {
const logs = grouped.get(date) || [];
const nutrients = totalNutrients(logs);
return {
date,
logged: logs.length > 0,
included: logs.length > 0 && nutrients.calories >= minimumCalories,
nutrients,
};
});
const included = days.filter((day) => day.included);
const average = emptyNutrients();
for (const day of included)
for (const key of Object.keys(average))
average[key] += day.nutrients[key] / included.length;
return {
days,
average,
includedCount: included.length,
excludedCount: days.filter((day) => day.logged && !day.included).length,
};
}

View file

@ -1,4 +1,5 @@
import {
Activity,
useCallback,
useEffect,
useMemo,
@ -74,7 +75,8 @@ import {
import { Trends } from "./Trends";
import { Settings } from "./Settings";
type Page = "today" | "library" | "weight" | "settings";
import { Presence } from "./Presence";
import { useNavigation } from "./useNavigation";
type Editor =
| { kind: "log"; meal: Meal; record?: JournalRecord<Entry> }
| { kind: "food"; record?: JournalRecord<Food> }
@ -540,30 +542,32 @@ function Dashboard({
</button>
</div>
</div>
{journalOpen && (
<Modal
title="Food journal"
subtitle={displayDate(date)}
close={closeJournal}
>
<MealJournal
dayEntries={dayEntries}
settings={settings}
add={(meal) => {
closeJournal();
add(meal);
}}
edit={(record) => {
closeJournal();
edit(record);
}}
remove={(record) => {
closeJournal();
remove(record);
}}
/>
</Modal>
)}
<Presence>
{journalOpen && (
<Modal
title="Food journal"
subtitle={displayDate(date)}
close={closeJournal}
>
<MealJournal
dayEntries={dayEntries}
settings={settings}
add={(meal) => {
closeJournal();
add(meal);
}}
edit={(record) => {
closeJournal();
edit(record);
}}
remove={(record) => {
closeJournal();
remove(record);
}}
/>
</Modal>
)}
</Presence>
<div className="page-footnote">
<span className="little-star">✳</span>A little consistency. A lot of
possibility.
@ -648,127 +652,133 @@ function Library({
</label>
)}
</div>
{tab === "trends" ? (
trends
) : (tab === "foods" ? foods : plates).length === 0 ? (
<section className="card library-empty">
<Empty
icon={
tab === "foods" ? <Utensils size={30} /> : <BookOpen size={30} />
}
title={
tab === "foods"
? "Make room for your favorites"
: "Your usual, in one tap"
}
text={
tab === "foods"
? "Save a food once. Keep its serving size and nutrition ready for the next time."
: "Combine foods from your library into a plate you can log all at once."
}
action={
<button
className="primary"
onClick={tab === "foods" ? newFood : newPlate}
>
<Plus size={17} />
{tab === "foods" ? "Save your first food" : "Create a plate"}
</button>
}
/>
</section>
) : (
<div className="library-grid">
{tab === "foods"
? foods
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
<div className="panel-arrive" key={tab}>
{tab === "trends" ? (
trends
) : (tab === "foods" ? foods : plates).length === 0 ? (
<section className="card library-empty">
<Empty
icon={
tab === "foods" ? (
<Utensils size={30} />
) : (
<BookOpen size={30} />
)
.map((r, i) => (
<section className="card library-card" key={r.id}>
<div className={"food-avatar avatar-" + (i % 4)}>
<Utensils size={23} />
</div>
<div className="library-food-info">
<h3>{r.data.name}</h3>
<p>{r.data.serving}</p>
<strong>
{number(r.data.nutrients.calories)} <span>kcal</span>
</strong>
<div className="food-macros">
<span>P {number(r.data.nutrients.protein, 1)}g</span>
<span>C {number(r.data.nutrients.carbs, 1)}g</span>
<span>F {number(r.data.nutrients.fat, 1)}g</span>
</div>
</div>
<div className="library-card-actions">
<button
className="text-button"
onClick={() => editFood(r)}
>
<Pencil size={14} />
Edit food
</button>
<button
className="icon-button danger-hover"
aria-label={`Delete saved ${r.data.name}`}
onClick={() => remove(r)}
>
<Trash2 size={15} />
</button>
</div>
</section>
))
: plates
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
)
.map((r) => {
const totals = totalNutrients(r.data.items);
return (
}
title={
tab === "foods"
? "Make room for your favorites"
: "Your usual, in one tap"
}
text={
tab === "foods"
? "Save a food once. Keep its serving size and nutrition ready for the next time."
: "Combine foods from your library into a plate you can log all at once."
}
action={
<button
className="primary"
onClick={tab === "foods" ? newFood : newPlate}
>
<Plus size={17} />
{tab === "foods" ? "Save your first food" : "Create a plate"}
</button>
}
/>
</section>
) : (
<div className="library-grid">
{tab === "foods"
? foods
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
)
.map((r, i) => (
<section className="card library-card" key={r.id}>
<div className="food-avatar avatar-2">
<BookOpen size={23} />
<div className={"food-avatar avatar-" + (i % 4)}>
<Utensils size={23} />
</div>
<div className="library-food-info">
<h3>{r.data.name}</h3>
<p>
{r.data.items.map((item) => item.name).join(" + ")}
</p>
<p>{r.data.serving}</p>
<strong>
{number(totals.calories)} <span>kcal</span>
{number(r.data.nutrients.calories)} <span>kcal</span>
</strong>
<div className="food-macros">
<span>{r.data.items.length} foods</span>
<span>P {number(totals.protein, 1)}g</span>
<span>P {number(r.data.nutrients.protein, 1)}g</span>
<span>C {number(r.data.nutrients.carbs, 1)}g</span>
<span>F {number(r.data.nutrients.fat, 1)}g</span>
</div>
</div>
<div className="library-card-actions">
<button
className="text-button"
onClick={() => editPlate(r)}
onClick={() => editFood(r)}
>
<Pencil size={14} />
Edit plate
Edit food
</button>
<button
className="icon-button danger-hover"
aria-label={`Delete ${r.data.name}`}
aria-label={`Delete saved ${r.data.name}`}
onClick={() => remove(r)}
>
<Trash2 size={15} />
</button>
</div>
</section>
);
})}
{(tab === "foods" ? foods : plates).filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
).length === 0 && (
<p className="muted">No favorites match “{search}”.</p>
)}
</div>
)}
))
: plates
.filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
)
.map((r) => {
const totals = totalNutrients(r.data.items);
return (
<section className="card library-card" key={r.id}>
<div className="food-avatar avatar-2">
<BookOpen size={23} />
</div>
<div className="library-food-info">
<h3>{r.data.name}</h3>
<p>
{r.data.items.map((item) => item.name).join(" + ")}
</p>
<strong>
{number(totals.calories)} <span>kcal</span>
</strong>
<div className="food-macros">
<span>{r.data.items.length} foods</span>
<span>P {number(totals.protein, 1)}g</span>
</div>
</div>
<div className="library-card-actions">
<button
className="text-button"
onClick={() => editPlate(r)}
>
<Pencil size={14} />
Edit plate
</button>
<button
className="icon-button danger-hover"
aria-label={`Delete ${r.data.name}`}
onClick={() => remove(r)}
>
<Trash2 size={15} />
</button>
</div>
</section>
);
})}
{(tab === "foods" ? foods : plates).filter((r) =>
r.data.name.toLowerCase().includes(search.toLowerCase()),
).length === 0 && (
<p className="muted">No favorites match “{search}”.</p>
)}
</div>
)}
</div>
{tab !== "trends" && (
<div className="library-bottom">
<Leaf size={18} />
@ -790,7 +800,11 @@ export function App() {
const status = useSyncStatus();
const [ready, setReady] = useState(false);
const [fatal, setFatal] = useState("");
const [page, setPage] = useState<Page>("today");
const {
page,
navigate,
ref: pageRef,
} = useNavigation(ready && journal.unlocked);
const [date, setDate] = useState(today());
const [editor, setEditor] = useState<Editor>(null);
const [toast, setToast] = useState("");
@ -833,9 +847,6 @@ export function App() {
const timer = setTimeout(() => setToast(""), 5500);
return () => clearTimeout(timer);
}, [toast]);
useEffect(() => {
window.scrollTo({ top: 0, behavior: "instant" });
}, [page]);
useEffect(() => {
const media = matchMedia("(prefers-color-scheme: dark)");
const apply = () => {
@ -962,7 +973,7 @@ export function App() {
href="#today"
onClick={(e) => {
e.preventDefault();
setPage("today");
navigate("today");
}}
>
<img src="/icon.svg" alt="" />
@ -973,8 +984,9 @@ export function App() {
{nav.map(({ key, label, icon: Icon }) => (
<button
key={key}
aria-current={page === key ? "page" : undefined}
className={page === key ? "active" : ""}
onClick={() => setPage(key)}
onClick={() => navigate(key)}
>
<Icon size={20} />
{label}
@ -997,7 +1009,12 @@ export function App() {
E<span />
</span>
</header>
<main>
<main
ref={pageRef}
tabIndex={-1}
className="page-content"
aria-label={nav.find((n) => n.key === page)?.label}
>
{status.needsLogin && (
<div className="notice">
<LockKeyhole size={17} />
@ -1021,7 +1038,7 @@ export function App() {
<button onClick={() => void update()}>Update</button>
</div>
)}
{page === "today" && (
<Activity mode={page === "today" ? "visible" : "hidden"}>
<Dashboard
records={journal.records}
settings={settings}
@ -1032,11 +1049,11 @@ export function App() {
setEditor({ kind: "log", meal: record.data.meal, record })
}
remove={setDeleting}
openLibrary={() => setPage("library")}
openLibrary={() => navigate("library")}
syncControl={syncControl}
/>
)}
{page === "library" && (
</Activity>
<Activity mode={page === "library" ? "visible" : "hidden"}>
<Library
foods={foods}
plates={plates}
@ -1054,8 +1071,8 @@ export function App() {
/>
}
/>
)}
{page === "weight" && (
</Activity>
<Activity mode={page === "weight" ? "visible" : "hidden"}>
<Trends
mode="weight"
records={journal.records}
@ -1064,8 +1081,8 @@ export function App() {
editWeight={(record) => setEditor({ kind: "weight", record })}
remove={setDeleting}
/>
)}
{page === "settings" && (
</Activity>
<Activity mode={page === "settings" ? "visible" : "hidden"}>
<Settings
key={
recordsOf<SettingsData>(journal.records, "settings")[0]
@ -1086,15 +1103,16 @@ export function App() {
}
update={waiting ? () => void update() : null}
/>
)}
</Activity>
</main>
</div>
<nav className="bottom-nav" aria-label="Mobile navigation">
{nav.slice(0, 2).map(({ key, label, icon: Icon }) => (
<button
key={key}
aria-current={page === key ? "page" : undefined}
className={page === key ? "active" : ""}
onClick={() => setPage(key)}
onClick={() => navigate(key)}
>
<Icon size={21} />
<span>{label === "My library" ? "Library" : label}</span>
@ -1110,87 +1128,98 @@ export function App() {
{nav.slice(2).map(({ key, label, icon: Icon }) => (
<button
key={key}
aria-current={page === key ? "page" : undefined}
className={page === key ? "active" : ""}
onClick={() => setPage(key)}
onClick={() => navigate(key)}
>
<Icon size={21} />
<span>{label}</span>
</button>
))}
</nav>
{editor?.kind === "log" && (
<FoodEditor
close={close}
date={date}
meal={editor.meal}
existing={editor.record}
foods={foods}
plates={plates}
notify={notify}
/>
)}
{editor?.kind === "food" && (
<FoodEditor
close={close}
date={date}
meal="Snacks"
existing={editor.record}
foods={foods}
plates={plates}
mode="food"
notify={notify}
/>
)}
{editor?.kind === "plate" && (
<PlateEditor
close={close}
foods={foods}
existing={editor.record}
notify={notify}
/>
)}
{editor?.kind === "weight" && (
<WeightEditor
close={close}
unit={settings.unit}
existing={editor.record}
notify={notify}
/>
)}
{deleting && (
<Modal
title="Remove this item?"
subtitle="This deletion will sync to your other devices."
close={() => setDeleting(null)}
>
<p className="muted">
{deleting.type === "food" || deleting.type === "plate"
? "Past food entries will keep their original values."
: "This entry will no longer count toward your journal."}
</p>
<div className="confirm-actions">
<button className="secondary" onClick={() => setDeleting(null)}>
Keep it
</button>
<button
className="danger-button"
onClick={async () => {
try {
await deleteRecord(deleting);
setDeleting(null);
notify("Item removed");
} catch {
notify("Could not remove this item. Please try again.");
}
}}
>
<Trash2 size={16} />
Remove
</button>
</div>
</Modal>
)}
{reauth && <SignIn reauth onCancel={() => setReauth(false)} />}
<Presence>
{editor && (
<>
{editor?.kind === "log" && (
<FoodEditor
close={close}
date={date}
meal={editor.meal}
existing={editor.record}
foods={foods}
plates={plates}
notify={notify}
/>
)}
{editor?.kind === "food" && (
<FoodEditor
close={close}
date={date}
meal="Snacks"
existing={editor.record}
foods={foods}
plates={plates}
mode="food"
notify={notify}
/>
)}
{editor?.kind === "plate" && (
<PlateEditor
close={close}
foods={foods}
existing={editor.record}
notify={notify}
/>
)}
{editor?.kind === "weight" && (
<WeightEditor
close={close}
unit={settings.unit}
existing={editor.record}
notify={notify}
/>
)}
</>
)}
</Presence>
<Presence>
{deleting && (
<Modal
title="Remove this item?"
subtitle="This deletion will sync to your other devices."
close={() => setDeleting(null)}
>
<p className="muted">
{deleting.type === "food" || deleting.type === "plate"
? "Past food entries will keep their original values."
: "This entry will no longer count toward your journal."}
</p>
<div className="confirm-actions">
<button className="secondary" onClick={() => setDeleting(null)}>
Keep it
</button>
<button
className="danger-button"
onClick={async () => {
try {
await deleteRecord(deleting);
setDeleting(null);
notify("Item removed");
} catch {
notify("Could not remove this item. Please try again.");
}
}}
>
<Trash2 size={16} />
Remove
</button>
</div>
</Modal>
)}
</Presence>
<Presence>
{reauth && <SignIn reauth onCancel={() => setReauth(false)} />}
</Presence>
{toast && (
<div className="toast" role="status">
<Check size={17} />

34
src/Presence.tsx Normal file
View file

@ -0,0 +1,34 @@
import {
createContext,
useContext,
useEffect,
useRef,
useState,
type ReactNode,
} from "react";
const Exiting = createContext(false);
export const useExiting = () => useContext(Exiting);
// Retain the last rendered sheet during dismissal, including after save/delete.
export function Presence({ children }: { children: ReactNode }) {
const last = useRef<ReactNode>(null);
const [retained, setRetained] = useState(false);
const visible = Boolean(children);
useEffect(() => {
if (visible) {
last.current = children;
setRetained(true);
return;
}
const timer = setTimeout(
() => setRetained(false),
matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 190,
);
return () => clearTimeout(timer);
}, [children, visible]);
if (!visible && !retained) return null;
return (
<Exiting value={!visible}>{visible ? children : last.current}</Exiting>
);
}

View file

@ -36,7 +36,12 @@ export function Settings({
install: (() => void) | null;
update: (() => void) | null;
}) {
const [draft, setDraft] = useState(settings);
const [draft, setDraft] = useState({
...settings,
minimumAverageCalories:
settings.minimumAverageCalories ??
Math.round(settings.goals.calories.target / 2),
});
const tilt = useTilt();
const [busy, setBusy] = useState(false);
const [format, setFormat] = useState(settings.exportFormat);
@ -174,6 +179,40 @@ export function Settings({
</label>
</div>
))}
<div className="settings-section">
<h3>Nutrition averages</h3>
<label className="average-cutoff">
Minimum calories for averages
<span className="unit-input">
<input
aria-label="Minimum calories for averages"
type="number"
inputMode="numeric"
min="0"
max="100000"
step="1"
required
value={draft.minimumAverageCalories}
onChange={(event) =>
setDraft({
...draft,
minimumAverageCalories:
event.target.value === ""
? ("" as unknown as number)
: +event.target.value,
})
}
/>
<span>kcal</span>
</span>
</label>
<p className="small muted">
Days below this amount are treated as incomplete in every
nutrition average. Starts at half your calorie target. Set to 0 to
include all logged days. Charts and exports always keep every
entry.
</p>
</div>
<div className="settings-section">
<h3>Look & feel</h3>
<div className="preference-row">

View file

@ -20,7 +20,7 @@ import {
today,
weightValue,
} from "./utils";
import { totalNutrients } from "../shared/domain.js";
import { nutritionSummary } from "../shared/nutrition-trends.js";
import { Empty } from "./components";
export function Trends({
@ -66,19 +66,19 @@ export function Trends({
observer.observe(chartRef.current);
return () => observer.disconnect();
}, [mode, hasWeights]);
const days = Array.from({ length: period }, (_, i) => {
const date = offsetDay(start, i);
const logs = entries.filter((r) => r.data.date === date);
return {
date,
logged: logs.length > 0,
total: totalNutrients(logs.map((r) => r.data))[metric],
};
});
const loggedDays = days.filter((d) => d.logged);
const avg = loggedDays.length
? loggedDays.reduce((sum, d) => sum + d.total, 0) / loggedDays.length
: 0;
const cutoff =
settings.minimumAverageCalories ??
Math.round(settings.goals.calories.target / 2);
const summary = nutritionSummary(
entries.map((r) => r.data),
Array.from({ length: period }, (_, i) => offsetDay(start, i)),
cutoff,
);
const days = summary.days.map((day) => ({
...day,
total: day.nutrients[metric],
}));
const avg = summary.average[metric];
const goal = settings.goals[metric];
const maximum =
Math.max(...days.map((d) => d.total), goal.enabled ? goal.target : 1, 1) *
@ -186,12 +186,13 @@ export function Trends({
</select>
</div>
<div className="stat-large">
{number(avg)} <span>{chosen.unit} / logged day</span>
{summary.includedCount ? number(avg) : "—"}{" "}
<span>{chosen.unit} / qualifying day</span>
</div>
<div
className="bar-chart"
role="img"
aria-label={`${chosen.label}: ${number(avg)} ${chosen.unit} average over ${loggedDays.length} logged days`}
aria-label={`${chosen.label}: ${summary.includedCount ? number(avg) + " " + chosen.unit + " average over " + summary.includedCount + " qualifying days" : "No qualifying days"}`}
>
<div className="chart-grid-lines">
<span>{number(maximum)}</span>
@ -209,9 +210,16 @@ export function Trends({
)}
{days.map((d) => (
<div
className={"bar-slot " + (!d.logged ? "unlogged" : "")}
className={
"bar-slot " +
(!d.logged
? "unlogged"
: !d.included
? "incomplete-day"
: "")
}
key={d.date}
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit : "Not logged"}`}
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit + (!d.included ? " · Below calorie cutoff; excluded from average" : "") : "Not logged"}`}
>
<div
className="bar"
@ -230,8 +238,13 @@ export function Trends({
</div>
</div>
<p className="chart-note">
{loggedDays.length} of {period} days logged · Empty days are
excluded from the average.
{summary.includedCount} of {period} days in average ·{" "}
{summary.excludedCount} low-calorie{" "}
{summary.excludedCount === 1 ? "day" : "days"} excluded.
{cutoff > 0
? ` Days under ${number(cutoff)} kcal are excluded; faded bars still show their actual totals.`
: " All logged days count."}{" "}
Adjust the cutoff in Settings.
</p>
</section>
)}

View file

@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
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";
@ -17,6 +17,10 @@ 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,
@ -30,24 +34,39 @@ export function Modal({
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();
close();
closeRef.current();
};
dialog.addEventListener("cancel", listener);
return () => {
dialog.removeEventListener("cancel", listener);
dialog.close();
};
}, [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"
aria-labelledby="sheet-title"
className={"sheet" + (exiting ? " sheet-exiting" : "")}
inert={exiting}
aria-labelledby={titleId}
onClick={(event) => {
if (event.target === event.currentTarget) {
const r = event.currentTarget.getBoundingClientRect();
@ -61,10 +80,42 @@ export function Modal({
}
}}
>
<div className="sheet-head">
<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="sheet-title">{title}</h2>
<h2 id={titleId}>{title}</h2>
{subtitle && <p>{subtitle}</p>}
</div>
<button
@ -390,7 +441,7 @@ export function FoodEditor({
</div>
)}
{tab !== "manual" ? (
<div className="picker">
<div className="picker panel-arrive" key={tab}>
<input
type="search"
placeholder={
@ -464,7 +515,7 @@ export function FoodEditor({
)}
</div>
) : (
<form onSubmit={submit}>
<form className="panel-arrive" onSubmit={submit}>
<label>
Food name <span className="muted">(optional)</span>
<input

View file

@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
import { App } from "./App";
import "./styles.css";
import "./mobile.css";
import "./motion.css";
createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />

193
src/motion.css Normal file
View file

@ -0,0 +1,193 @@
/* Short composited transitions, with no dependency on sync or network access. */
html {
overflow-x: clip;
}
.sheet-grip {
display: none;
}
button,
a,
input,
select,
textarea {
-webkit-tap-highlight-color: transparent;
}
button {
touch-action: manipulation;
}
.page-content {
outline: none;
transition:
translate 180ms ease-out,
transform 100ms ease-in,
opacity 100ms ease-in;
}
.page-content.page-leaving {
animation: none;
transform: translateX(var(--exit-shift));
opacity: 0;
pointer-events: none;
}
.page-content.page-dragging {
transition: none;
user-select: none;
}
.sheet[open] {
animation: sheet-arrive 260ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
transition: translate 160ms ease-out;
}
.sheet[open]::backdrop {
background: #08090d88;
animation: backdrop-arrive 220ms ease-out both;
}
.sheet[open].sheet-exiting {
animation: sheet-depart 180ms ease-in both;
pointer-events: none;
}
.sheet[open].sheet-exiting::backdrop {
animation: backdrop-depart 180ms ease-in both;
}
@keyframes sheet-arrive {
from {
opacity: 0;
transform: translateY(24px) scale(0.98);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
@keyframes sheet-depart {
to {
opacity: 0;
transform: translateY(24px) scale(0.98);
}
}
@keyframes backdrop-arrive {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes backdrop-depart {
to {
opacity: 0;
}
}
.segmented > button,
.bottom-nav > button,
.sidebar nav > button {
transition:
background-color 180ms ease,
color 180ms ease,
transform 140ms ease;
}
.bottom-nav > button:active,
.primary:active,
.secondary:active,
.icon-button:active {
transform: scale(0.95);
}
.toast {
animation: toast-arrive 240ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
}
@keyframes toast-arrive {
from {
opacity: 0;
translate: 0 12px;
}
to {
opacity: 1;
translate: 0 0;
}
}
.incomplete-day .bar {
opacity: 0.32;
}
.panel-arrive {
animation: panel-arrive 180ms ease-out both;
}
@keyframes panel-arrive {
from {
opacity: 0;
translate: 0 6px;
}
to {
opacity: 1;
translate: 0 0;
}
}
.average-cutoff {
display: grid;
grid-template-columns: 1fr 140px;
align-items: center;
gap: 16px;
}
.average-cutoff .unit-input {
min-width: 0;
}
@media (max-width: 760px), (max-width: 1000px) and (max-height: 500px) {
.sheet-head {
touch-action: none;
cursor: grab;
}
.sheet::before {
display: none;
}
.sheet-grip {
display: block;
position: absolute;
top: -24px;
left: calc(50% - 36px);
width: 72px;
height: 24px;
touch-action: none;
}
.sheet-grip::before {
content: "";
display: block;
width: 34px;
height: 4px;
margin: 8px auto;
border-radius: 9px;
background: var(--muted);
opacity: 0.4;
}
.sheet[open] {
animation-name: mobile-sheet-arrive;
}
.sheet[open].sheet-exiting {
animation-name: mobile-sheet-depart;
}
@keyframes mobile-sheet-arrive {
from {
opacity: 0.5;
transform: translateY(100%);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes mobile-sheet-depart {
to {
opacity: 0.5;
transform: translateY(100%);
}
}
.average-cutoff {
grid-template-columns: 1fr;
gap: 10px;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation: none !important;
transition: none !important;
scroll-behavior: auto !important;
}
}

View file

@ -1,5 +1,11 @@
export type Metric =
"calories" | "protein" | "carbs" | "fat" | "fiber" | "sugar" | "sodium";
| "calories"
| "protein"
| "carbs"
| "fat"
| "fiber"
| "sugar"
| "sodium";
export type Nutrients = Record<Metric, number>;
export type Food = { name: string; serving: string; nutrients: Nutrients };
export type Meal = "Breakfast" | "Lunch" | "Dinner" | "Snacks";
@ -20,6 +26,7 @@ export type Settings = {
exportDays: "7" | "30" | "90" | "all";
exportMetrics?: Metric[];
exportWeight?: boolean;
minimumAverageCalories?: number;
};
export type RecordType = "entry" | "food" | "plate" | "weight" | "settings";
export type JournalRecord<T = Entry | Food | Plate | Weight | Settings> = {

187
src/useNavigation.ts Normal file
View file

@ -0,0 +1,187 @@
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
import { swipeStep } from "../shared/navigation.js";
export const pages = ["today", "library", "weight", "settings"] as const;
export type Page = (typeof pages)[number];
const mobile = () =>
matchMedia("(max-width: 760px), (max-width: 1000px) and (max-height: 500px)")
.matches;
const reduced = () => matchMedia("(prefers-reduced-motion: reduce)").matches;
export function useNavigation(enabled: boolean) {
const [page, setPage] = useState<Page>("today");
const [direction, setDirection] = useState(1);
const ref = useRef<HTMLElement>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
const scroll = useRef<Partial<Record<Page, number>>>({});
const suppressClick = useRef(0);
const navigate = useCallback(
(next: Page) => {
if (timer.current) {
clearTimeout(timer.current);
timer.current = null;
}
if (next === page) {
ref.current?.classList.remove("page-leaving");
return;
}
const step = pages.indexOf(next) > pages.indexOf(page) ? 1 : -1;
scroll.current[page] = window.scrollY;
const commit = () => {
timer.current = null;
setDirection(step);
setPage(next);
};
if (reduced()) commit();
else {
ref.current?.style.setProperty("--exit-shift", `${step * -24}px`);
ref.current?.classList.add("page-leaving");
timer.current = setTimeout(commit, 100);
}
},
[page, enabled],
);
useEffect(
() => () => {
if (timer.current) clearTimeout(timer.current);
},
[],
);
useLayoutEffect(() => {
const element = ref.current;
if (!element) return;
element.classList.remove("page-leaving");
const animation = !reduced()
? element.animate(
[
{ opacity: 0, transform: `translateX(${direction * 24}px)` },
{ opacity: 1, transform: "translateX(0)" },
],
{ duration: 240, easing: "cubic-bezier(.2,.75,.25,1)" },
)
: null;
window.scrollTo({ top: scroll.current[page] || 0, behavior: "instant" });
return () => animation?.cancel();
}, [page, direction, enabled]);
useEffect(() => {
const element = ref.current;
if (!element) return;
let gesture: {
x: number;
y: number;
start: number;
locked: boolean;
} | null = null;
const clear = () => {
gesture = null;
element.style.removeProperty("translate");
element.classList.remove("page-dragging");
};
const start = (event: TouchEvent) => {
clear();
suppressClick.current = 0;
if (
!mobile() ||
timer.current ||
event.touches.length !== 1 ||
document.querySelector("dialog[open]") ||
window.getSelection()?.isCollapsed === false
)
return;
const target = event.target as HTMLElement;
if (
target.closest(
"input, textarea, select, button, a, [contenteditable], .segmented, [data-swipe-ignore]",
)
)
return;
// Leave the browser's edge back gesture and horizontal carousels alone.
const touch = event.touches[0];
if (touch.clientX < 24 || touch.clientX > innerWidth - 24) return;
for (
let node: HTMLElement | null = target;
node && node !== element;
node = node.parentElement
) {
if (
node.scrollWidth > node.clientWidth + 2 &&
/auto|scroll/.test(getComputedStyle(node).overflowX)
)
return;
}
gesture = {
x: touch.clientX,
y: touch.clientY,
start: performance.now(),
locked: false,
};
};
const move = (event: TouchEvent) => {
if (!gesture) return;
if (event.touches.length !== 1) {
clear();
return;
}
const dx = event.touches[0].clientX - gesture.x;
const dy = event.touches[0].clientY - gesture.y;
if (!gesture.locked) {
if (Math.abs(dy) > 10 && Math.abs(dy) > Math.abs(dx) * 0.8) {
clear();
return;
}
if (Math.abs(dx) < 12 || Math.abs(dx) < Math.abs(dy) * 1.4) return;
gesture.locked = true;
}
event.preventDefault();
const index = pages.indexOf(page);
const edge =
(dx > 0 && index === 0) || (dx < 0 && index === pages.length - 1);
element.classList.add("page-dragging");
if (!reduced())
element.style.translate = `${Math.max(-90, Math.min(90, dx * (edge ? 0.12 : 0.4)))}px 0`;
};
const end = (event: TouchEvent) => {
if (!gesture) return;
const touch = event.changedTouches[0];
const step =
gesture.locked && touch
? swipeStep(
touch.clientX - gesture.x,
touch.clientY - gesture.y,
performance.now() - gesture.start,
innerWidth,
)
: 0;
if (gesture.locked) suppressClick.current = performance.now() + 400;
clear();
const next = pages[pages.indexOf(page) + step];
if (step && next) navigate(next);
};
const click = (event: MouseEvent) => {
if (event.detail !== 0 && performance.now() < suppressClick.current) {
event.preventDefault();
event.stopPropagation();
}
};
element.addEventListener("touchstart", start, { passive: true });
element.addEventListener("touchmove", move, { passive: false });
element.addEventListener("touchend", end);
element.addEventListener("touchcancel", clear);
element.addEventListener("click", click, true);
return () => {
clear();
element.removeEventListener("touchstart", start);
element.removeEventListener("touchmove", move);
element.removeEventListener("touchend", end);
element.removeEventListener("touchcancel", clear);
element.removeEventListener("click", click, true);
};
}, [page, navigate, enabled]);
return { page, navigate, ref };
}

View file

@ -0,0 +1,81 @@
// Development-only browser regression probe. Run on an unlocked localhost preview
// with Runtime.evaluate (awaitPromise: true). It changes navigation and draft input
// only, restores the draft, and never saves or deletes journal records.
(async () => {
const checks = {};
const pause = (ms = 380) => new Promise(resolve => setTimeout(resolve, ms));
const visible = selector => [...document.querySelectorAll(selector)].filter(e => e.getBoundingClientRect().width > 0);
const page = () => document.querySelector('main').getAttribute('aria-label');
const nav = async label => {
visible('.bottom-nav button').find(e => e.textContent.trim() === label).click();
await pause();
};
const swipe = async (selector, dx, dy = 1, cancel = false) => {
const target = visible(selector)[0];
const rect = target.getBoundingClientRect();
const x = Math.max(30, Math.min(innerWidth - 30, rect.x + rect.width / 2));
const y = rect.y + Math.min(rect.height / 2, 90);
const emit = (type, px, py, ended = false) => {
const touch = new Touch({ identifier: 11, target, clientX: px, clientY: py });
target.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true, touches: ended ? [] : [touch], changedTouches: [touch] }));
};
emit('touchstart', x, y);
emit('touchmove', x + dx / 2, y + dy / 2);
emit('touchmove', x + dx, y + dy);
emit(cancel ? 'touchcancel' : 'touchend', x + dx, y + dy, true);
await pause();
};
await nav('Today');
await swipe('.orb', 150);
checks.firstTabDoesNotWrap = page() === 'Today';
await swipe('.orb', -150, 1, true);
checks.cancelDoesNotNavigate = page() === 'Today';
await swipe('.orb', -150);
checks.leftSwipeNavigates = page() === 'My library';
await swipe('.page-heading h1', 4, -160);
checks.verticalScrollDoesNotNavigate = page() === 'My library';
const libraryTabs = visible('.library-controls .segmented button');
libraryTabs.at(-1).click();
await pause();
visible('.trend-controls .segmented button')[1].click();
await pause();
await swipe('.page-heading h1', -150);
checks.nextTabIsWeight = page() === 'Weight';
await swipe('.page-heading h1', 150);
checks.rightSwipeNavigates = page() === 'My library';
checks.libraryStateIsRetained = visible('.library-controls .segmented .active')[0]?.textContent.trim() === 'Trends' && visible('.trend-controls .segmented .active')[0]?.textContent.trim() === 'Month';
await nav('Settings');
const cutoff = document.querySelector('[aria-label="Minimum calories for averages"]');
const original = cutoff.value;
const changeValue = value => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(cutoff, value);
cutoff.dispatchEvent(new Event('input', { bubbles: true }));
};
changeValue('987');
await swipe('[aria-label="Minimum calories for averages"]', -150);
checks.inputsDoNotNavigate = page() === 'Settings';
await swipe('.page-heading h1', -150);
checks.lastTabDoesNotWrap = page() === 'Settings';
await nav('Weight');
await nav('Settings');
checks.unsavedPreferencesSurviveNavigation = cutoff.value === '987';
changeValue(original);
visible('.bottom-nav button').find(e => e.textContent.trim() === 'Library').click();
visible('.bottom-nav button').find(e => e.textContent.trim() === 'Weight').click();
await pause();
checks.rapidTapsUseLatestDestination = page() === 'Weight';
await nav('Today');
visible('.bottom-nav .nav-add')[0].click();
await pause();
checks.sheetOpens = Boolean(document.querySelector('dialog[open]'));
await swipe('dialog input[type="date"]', -150);
checks.dialogDoesNotNavigate = page() === 'Today';
visible('dialog .sheet-head button')[0].click();
await pause(20);
checks.sheetHasExitAnimation = Boolean(document.querySelector('dialog.sheet-exiting'));
await pause();
checks.sheetCloses = !document.querySelector('dialog[open]');
checks.scrollLockReleased = document.body.style.overflow === '';
checks.noHorizontalOverflow = document.documentElement.scrollWidth <= innerWidth + 1;
return { pass: Object.values(checks).every(Boolean), checks };
})()

16
tests/navigation.test.js Normal file
View file

@ -0,0 +1,16 @@
import test from "node:test";
import assert from "node:assert/strict";
import { swipeStep } from "../shared/navigation.js";
test("phone swipes accept deliberate travel and short fast flicks in both directions", () => {
assert.equal(swipeStep(-100, 8, 500, 393), 1);
assert.equal(swipeStep(100, -8, 500, 393), -1);
assert.equal(swipeStep(-40, 2, 65, 393), 1);
assert.equal(swipeStep(60, 0, 500, 320), -1);
});
test("scrolling, diagonal travel, slow small movements and jitter never switch tabs", () => {
assert.equal(swipeStep(12, 150, 250, 393), 0);
assert.equal(swipeStep(100, 100, 150, 393), 0);
assert.equal(swipeStep(40, 2, 500, 393), 0);
assert.equal(swipeStep(8, 0, 5, 393), 0);
});

View file

@ -0,0 +1,73 @@
import test from "node:test";
import assert from "node:assert/strict";
import { nutritionSummary } from "../shared/nutrition-trends.js";
import {
defaultSettings,
emptyNutrients,
recordSchema,
} from "../shared/domain.js";
const entry = (date, calories, protein, quantity = 1) => ({
date,
quantity,
nutrients: { ...emptyNutrients(), calories, protein },
});
const dates = ["2026-10-19", "2026-10-20", "2026-10-21", "2026-10-22"];
test("incomplete and empty days do not dilute calorie or macro averages; bars keep raw totals", () => {
const entries = [
entry(dates[0], 1000, 50, 2),
entry(dates[1], 200, 5),
entry(dates[2], 1800, 0),
];
const before = structuredClone(entries);
const stats = nutritionSummary(entries, dates, 1000);
assert.equal(stats.average.calories, 1900);
assert.equal(stats.average.protein, 50); // A real zero macro on a complete day counts.
assert.equal(stats.includedCount, 2);
assert.equal(stats.excludedCount, 1);
assert.equal(stats.days[1].nutrients.calories, 200);
assert.equal(stats.days[1].included, false);
assert.equal(stats.days[3].logged, false);
assert.deepEqual(entries, before);
});
test("cutoff boundary counts; disabling the cutoff includes all logged days, even a zero", () => {
const entries = [entry(dates[0], 1000, 20), entry(dates[1], 0, 10)];
assert.equal(nutritionSummary(entries, dates, 1000).includedCount, 1);
assert.equal(nutritionSummary(entries, dates, 0).average.calories, 500);
assert.equal(nutritionSummary(entries, dates, 0).average.protein, 15);
});
test("no qualifying data yields a finite empty result and dates outside the period stay excluded", () => {
const stats = nutritionSummary(
[entry(dates[0], 200, 2), entry("2025-01-01", 2200, 100)],
dates,
1000,
);
assert.equal(stats.includedCount, 0);
assert.deepEqual(stats.average, emptyNutrients());
});
test("average preference is optional for old journals and rejects invalid synced settings", () => {
const record = {
id: "settings",
type: "settings",
deleted: false,
updatedAt: "2026-10-22T12:00:00.000Z",
data: defaultSettings,
};
assert.equal(recordSchema.safeParse(record).success, true);
for (const cutoff of [0, 1000, 100000])
assert.equal(
recordSchema.safeParse({
...record,
data: { ...defaultSettings, minimumAverageCalories: cutoff },
}).success,
true,
);
for (const cutoff of [-1, Infinity, "1000", 100001])
assert.equal(
recordSchema.safeParse({
...record,
data: { ...defaultSettings, minimumAverageCalories: cutoff },
}).success,
false,
);
});