From 7288e56c02b10a405e8e22026689f96ddfe66ccc Mon Sep 17 00:00:00 2001 From: Elijah Date: Thu, 22 Oct 2026 09:16:52 -0700 Subject: [PATCH] Polish PWA gestures, transitions and nutrition averages --- README.md | 3 +- shared/domain.js | 1 + shared/navigation.js | 9 + shared/nutrition-trends.js | 39 ++ src/App.tsx | 455 +++++++++++---------- src/Presence.tsx | 34 ++ src/Settings.tsx | 41 +- src/Trends.tsx | 53 ++- src/components.tsx | 69 +++- src/main.tsx | 1 + src/motion.css | 193 +++++++++ src/types.ts | 9 +- src/useNavigation.ts | 187 +++++++++ tests/browser/native-interactions.check.js | 81 ++++ tests/navigation.test.js | 16 + tests/nutrition-trends.test.js | 73 ++++ 16 files changed, 1019 insertions(+), 245 deletions(-) create mode 100644 shared/navigation.js create mode 100644 shared/nutrition-trends.js create mode 100644 src/Presence.tsx create mode 100644 src/motion.css create mode 100644 src/useNavigation.ts create mode 100644 tests/browser/native-interactions.check.js create mode 100644 tests/navigation.test.js create mode 100644 tests/nutrition-trends.test.js diff --git a/README.md b/README.md index d9edad9..d887c23 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/shared/domain.js b/shared/domain.js index 2801e26..eb02c6e 100644 --- a/shared/domain.js +++ b/shared/domain.js @@ -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 diff --git a/shared/navigation.js b/shared/navigation.js new file mode 100644 index 0000000..76b012e --- /dev/null +++ b/shared/navigation.js @@ -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; +} diff --git a/shared/nutrition-trends.js b/shared/nutrition-trends.js new file mode 100644 index 0000000..117f3b2 --- /dev/null +++ b/shared/nutrition-trends.js @@ -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} */ + 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, + }; +} diff --git a/src/App.tsx b/src/App.tsx index 6f27dc0..7983171 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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 } | { kind: "food"; record?: JournalRecord } @@ -540,30 +542,32 @@ function Dashboard({ - {journalOpen && ( - - { - closeJournal(); - add(meal); - }} - edit={(record) => { - closeJournal(); - edit(record); - }} - remove={(record) => { - closeJournal(); - remove(record); - }} - /> - - )} + + {journalOpen && ( + + { + closeJournal(); + add(meal); + }} + edit={(record) => { + closeJournal(); + edit(record); + }} + remove={(record) => { + closeJournal(); + remove(record); + }} + /> + + )} +
✳A little consistency. A lot of possibility. @@ -648,127 +652,133 @@ function Library({ )}
- {tab === "trends" ? ( - trends - ) : (tab === "foods" ? foods : plates).length === 0 ? ( -
- : - } - 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={ - - } - /> -
- ) : ( -
- {tab === "foods" - ? foods - .filter((r) => - r.data.name.toLowerCase().includes(search.toLowerCase()), +
+ {tab === "trends" ? ( + trends + ) : (tab === "foods" ? foods : plates).length === 0 ? ( +
+ + ) : ( + ) - .map((r, i) => ( -
-
- -
-
-

{r.data.name}

-

{r.data.serving}

- - {number(r.data.nutrients.calories)} kcal - -
- P {number(r.data.nutrients.protein, 1)}g - C {number(r.data.nutrients.carbs, 1)}g - F {number(r.data.nutrients.fat, 1)}g -
-
-
- - -
-
- )) - : 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={ + + } + /> +
+ ) : ( +
+ {tab === "foods" + ? foods + .filter((r) => + r.data.name.toLowerCase().includes(search.toLowerCase()), + ) + .map((r, i) => (
-
- +
+

{r.data.name}

-

- {r.data.items.map((item) => item.name).join(" + ")} -

+

{r.data.serving}

- {number(totals.calories)} kcal + {number(r.data.nutrients.calories)} kcal
- {r.data.items.length} foods - P {number(totals.protein, 1)}g + P {number(r.data.nutrients.protein, 1)}g + C {number(r.data.nutrients.carbs, 1)}g + F {number(r.data.nutrients.fat, 1)}g
- ); - })} - {(tab === "foods" ? foods : plates).filter((r) => - r.data.name.toLowerCase().includes(search.toLowerCase()), - ).length === 0 && ( -

No favorites match “{search}”.

- )} -
- )} + )) + : plates + .filter((r) => + r.data.name.toLowerCase().includes(search.toLowerCase()), + ) + .map((r) => { + const totals = totalNutrients(r.data.items); + return ( +
+
+ +
+
+

{r.data.name}

+

+ {r.data.items.map((item) => item.name).join(" + ")} +

+ + {number(totals.calories)} kcal + +
+ {r.data.items.length} foods + P {number(totals.protein, 1)}g +
+
+
+ + +
+
+ ); + })} + {(tab === "foods" ? foods : plates).filter((r) => + r.data.name.toLowerCase().includes(search.toLowerCase()), + ).length === 0 && ( +

No favorites match “{search}”.

+ )} +
+ )} +
{tab !== "trends" && (
@@ -790,7 +800,11 @@ export function App() { const status = useSyncStatus(); const [ready, setReady] = useState(false); const [fatal, setFatal] = useState(""); - const [page, setPage] = useState("today"); + const { + page, + navigate, + ref: pageRef, + } = useNavigation(ready && journal.unlocked); const [date, setDate] = useState(today()); const [editor, setEditor] = useState(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"); }} > @@ -973,8 +984,9 @@ export function App() { {nav.map(({ key, label, icon: Icon }) => (
)} - {page === "today" && ( + setPage("library")} + openLibrary={() => navigate("library")} syncControl={syncControl} /> - )} - {page === "library" && ( + + } /> - )} - {page === "weight" && ( + + setEditor({ kind: "weight", record })} remove={setDeleting} /> - )} - {page === "settings" && ( + + (journal.records, "settings")[0] @@ -1086,15 +1103,16 @@ export function App() { } update={waiting ? () => void update() : null} /> - )} + - {editor?.kind === "log" && ( - - )} - {editor?.kind === "food" && ( - - )} - {editor?.kind === "plate" && ( - - )} - {editor?.kind === "weight" && ( - - )} - {deleting && ( - setDeleting(null)} - > -

- {deleting.type === "food" || deleting.type === "plate" - ? "Past food entries will keep their original values." - : "This entry will no longer count toward your journal."} -

-
- - -
-
- )} - {reauth && setReauth(false)} />} + + {editor && ( + <> + {editor?.kind === "log" && ( + + )} + {editor?.kind === "food" && ( + + )} + {editor?.kind === "plate" && ( + + )} + {editor?.kind === "weight" && ( + + )} + + )} + + + {deleting && ( + setDeleting(null)} + > +

+ {deleting.type === "food" || deleting.type === "plate" + ? "Past food entries will keep their original values." + : "This entry will no longer count toward your journal."} +

+
+ + +
+
+ )} +
+ + {reauth && setReauth(false)} />} + {toast && (
diff --git a/src/Presence.tsx b/src/Presence.tsx new file mode 100644 index 0000000..c4c9001 --- /dev/null +++ b/src/Presence.tsx @@ -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(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 ( + {visible ? children : last.current} + ); +} diff --git a/src/Settings.tsx b/src/Settings.tsx index b1bc58d..249566f 100644 --- a/src/Settings.tsx +++ b/src/Settings.tsx @@ -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({
))} +
+

Nutrition averages

+ +

+ 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. +

+

Look & feel

diff --git a/src/Trends.tsx b/src/Trends.tsx index fd62aa0..3d127da 100644 --- a/src/Trends.tsx +++ b/src/Trends.tsx @@ -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({
- {number(avg)} {chosen.unit} / logged day + {summary.includedCount ? number(avg) : "—"}{" "} + {chosen.unit} / qualifying day
{number(maximum)} @@ -209,9 +210,16 @@ export function Trends({ )} {days.map((d) => (

- {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.

)} diff --git a/src/components.tsx b/src/components.tsx index 263312e..ec9ccd6 100644 --- a/src/components.tsx +++ b/src/components.tsx @@ -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(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 ( { if (event.target === event.currentTarget) { const r = event.currentTarget.getBoundingClientRect(); @@ -61,10 +80,42 @@ export function Modal({ } }} > -
+
{ + 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"); + }} + > +