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

View file

@ -20,7 +20,7 @@ import {
today, today,
weightValue, weightValue,
} from "./utils"; } from "./utils";
import { totalNutrients } from "../shared/domain.js"; import { nutritionSummary } from "../shared/nutrition-trends.js";
import { Empty } from "./components"; import { Empty } from "./components";
export function Trends({ export function Trends({
@ -66,19 +66,19 @@ export function Trends({
observer.observe(chartRef.current); observer.observe(chartRef.current);
return () => observer.disconnect(); return () => observer.disconnect();
}, [mode, hasWeights]); }, [mode, hasWeights]);
const days = Array.from({ length: period }, (_, i) => { const cutoff =
const date = offsetDay(start, i); settings.minimumAverageCalories ??
const logs = entries.filter((r) => r.data.date === date); Math.round(settings.goals.calories.target / 2);
return { const summary = nutritionSummary(
date, entries.map((r) => r.data),
logged: logs.length > 0, Array.from({ length: period }, (_, i) => offsetDay(start, i)),
total: totalNutrients(logs.map((r) => r.data))[metric], cutoff,
}; );
}); const days = summary.days.map((day) => ({
const loggedDays = days.filter((d) => d.logged); ...day,
const avg = loggedDays.length total: day.nutrients[metric],
? loggedDays.reduce((sum, d) => sum + d.total, 0) / loggedDays.length }));
: 0; const avg = summary.average[metric];
const goal = settings.goals[metric]; const goal = settings.goals[metric];
const maximum = const maximum =
Math.max(...days.map((d) => d.total), goal.enabled ? goal.target : 1, 1) * Math.max(...days.map((d) => d.total), goal.enabled ? goal.target : 1, 1) *
@ -186,12 +186,13 @@ export function Trends({
</select> </select>
</div> </div>
<div className="stat-large"> <div className="stat-large">
{number(avg)} <span>{chosen.unit} / logged day</span> {summary.includedCount ? number(avg) : "—"}{" "}
<span>{chosen.unit} / qualifying day</span>
</div> </div>
<div <div
className="bar-chart" className="bar-chart"
role="img" 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"> <div className="chart-grid-lines">
<span>{number(maximum)}</span> <span>{number(maximum)}</span>
@ -209,9 +210,16 @@ export function Trends({
)} )}
{days.map((d) => ( {days.map((d) => (
<div <div
className={"bar-slot " + (!d.logged ? "unlogged" : "")} className={
"bar-slot " +
(!d.logged
? "unlogged"
: !d.included
? "incomplete-day"
: "")
}
key={d.date} 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 <div
className="bar" className="bar"
@ -230,8 +238,13 @@ export function Trends({
</div> </div>
</div> </div>
<p className="chart-note"> <p className="chart-note">
{loggedDays.length} of {period} days logged · Empty days are {summary.includedCount} of {period} days in average ·{" "}
excluded from the 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> </p>
</section> </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 { X, ArrowUpRight, Plus, Minus, Leaf } from "lucide-react";
import { bubbleCount } from "../shared/bubble-physics.js"; import { bubbleCount } from "../shared/bubble-physics.js";
import { useBubblePhysics } from "./useBubblePhysics"; import { useBubblePhysics } from "./useBubblePhysics";
@ -17,6 +17,10 @@ import { emptyNutrients } from "../shared/domain.js";
import { saveRecord, putRecords, useJournal } from "./store"; import { saveRecord, putRecords, useJournal } from "./store";
import { localTime, nextFoodName } from "../shared/entry.js"; import { localTime, nextFoodName } from "../shared/entry.js";
import { displayDate, number, today, weightValue } from "./utils"; import { displayDate, number, today, weightValue } from "./utils";
import { useExiting } from "./Presence";
let sheetLocks = 0;
let previousBodyOverflow = "";
export function Modal({ export function Modal({
title, title,
@ -30,24 +34,39 @@ export function Modal({
children: ReactNode; children: ReactNode;
}) { }) {
const ref = useRef<HTMLDialogElement>(null); 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(() => { useEffect(() => {
const dialog = ref.current!; const dialog = ref.current!;
dialog.showModal(); dialog.showModal();
const listener = (event: Event) => { const listener = (event: Event) => {
event.preventDefault(); event.preventDefault();
close(); closeRef.current();
}; };
dialog.addEventListener("cancel", listener); dialog.addEventListener("cancel", listener);
return () => { return () => {
dialog.removeEventListener("cancel", listener); dialog.removeEventListener("cancel", listener);
dialog.close(); 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 ( return (
<dialog <dialog
ref={ref} ref={ref}
className="sheet" className={"sheet" + (exiting ? " sheet-exiting" : "")}
aria-labelledby="sheet-title" inert={exiting}
aria-labelledby={titleId}
onClick={(event) => { onClick={(event) => {
if (event.target === event.currentTarget) { if (event.target === event.currentTarget) {
const r = event.currentTarget.getBoundingClientRect(); 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> <div>
<span className="eyebrow">A LITTLE EVERYDAY CARE</span> <span className="eyebrow">A LITTLE EVERYDAY CARE</span>
<h2 id="sheet-title">{title}</h2> <h2 id={titleId}>{title}</h2>
{subtitle && <p>{subtitle}</p>} {subtitle && <p>{subtitle}</p>}
</div> </div>
<button <button
@ -390,7 +441,7 @@ export function FoodEditor({
</div> </div>
)} )}
{tab !== "manual" ? ( {tab !== "manual" ? (
<div className="picker"> <div className="picker panel-arrive" key={tab}>
<input <input
type="search" type="search"
placeholder={ placeholder={
@ -464,7 +515,7 @@ export function FoodEditor({
)} )}
</div> </div>
) : ( ) : (
<form onSubmit={submit}> <form className="panel-arrive" onSubmit={submit}>
<label> <label>
Food name <span className="muted">(optional)</span> Food name <span className="muted">(optional)</span>
<input <input

View file

@ -3,6 +3,7 @@ import { createRoot } from "react-dom/client";
import { App } from "./App"; import { App } from "./App";
import "./styles.css"; import "./styles.css";
import "./mobile.css"; import "./mobile.css";
import "./motion.css";
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<React.StrictMode> <React.StrictMode>
<App /> <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 = 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 Nutrients = Record<Metric, number>;
export type Food = { name: string; serving: string; nutrients: Nutrients }; export type Food = { name: string; serving: string; nutrients: Nutrients };
export type Meal = "Breakfast" | "Lunch" | "Dinner" | "Snacks"; export type Meal = "Breakfast" | "Lunch" | "Dinner" | "Snacks";
@ -20,6 +26,7 @@ export type Settings = {
exportDays: "7" | "30" | "90" | "all"; exportDays: "7" | "30" | "90" | "all";
exportMetrics?: Metric[]; exportMetrics?: Metric[];
exportWeight?: boolean; exportWeight?: boolean;
minimumAverageCalories?: number;
}; };
export type RecordType = "entry" | "food" | "plate" | "weight" | "settings"; export type RecordType = "entry" | "food" | "plate" | "weight" | "settings";
export type JournalRecord<T = 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,
);
});