diff --git a/README.md b/README.md index c4ad7bd..a441ae0 100644 --- a/README.md +++ b/README.md @@ -5,10 +5,12 @@ A single-user, self-hosted nutrition journal. PWA first, with a responsive deskt ## Included - Daily calorie vessel with colliding physics bubbles, week navigation, meal journal, editable entries, fractional servings. New bubbles drop from the top as calories increase. +- Food names are optional: unnamed daily entries use the meal name and next available number, such as `Dinner 1`. The main Add food action suggests breakfast from 5–11am, lunch from 11am–4pm, dinner from 4–10pm and snacks overnight, using the device's local time. Meal-specific add buttons preserve their category; the selection remains editable. +- Food entries include an editable local clock time, shown in the journal and all export formats. Existing entries without a time remain valid and show “Time not recorded” until you add one. Entries sort by time within each meal. - Saved foods and reusable plates. Logging a plate creates an atomic batch of independent food entries. Logs retain a nutrition snapshot when library foods change. - Independently enabled calorie, protein, carbohydrate, fat, fiber, sugar and sodium goals. - Weight journal in lb or kg; internally stored in kg. Multiple weigh-ins are retained, with the latest measurement per day used in charts. -- 7 / 30 / 90 / 365 day nutrition and weight trends. Unlogged days are excluded from intake averages. +- Dedicated Weight tab on desktop and mobile, with its own logging, graph and journal. Nutrition trends live under Library → Trends. Both support 7 / 30 / 90 / 365 day periods. Unlogged days are excluded from intake averages. - Markdown, CSV and JSON export with date range, nutrient and weight selections. Markdown is designed for LLM analysis. Data is downloaded locally, never submitted to an LLM. Save preferences to remember the export format, range preset and selections. - Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and explicit PWA update prompts. @@ -66,9 +68,9 @@ To restore a database backup: stop Calio, preserve the current data directory, r ### Bubble motion -Tap **Enable tilt** beneath the calorie circle to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that tap; the public site must use HTTPS. The app remembers the choice for the current page session and does not transmit sensor readings. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity and the **Give a nudge** control. +Enable **Settings → Look & feel → Tilt calorie bubbles** to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that gesture; the public site must use HTTPS. The preference is stored only on this device, and iOS may require enabling it again after reopening the app. Sensor readings are never transmitted. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity. -The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top, and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity; near a full vessel, the numeric readout moves below the circle so it does not hide dots. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. The animation sleeps when settled, pauses in hidden tabs, and honors the device's reduced-motion preference with a still arrangement. The graphic is an approximate visual; the numeric calorie total is authoritative. +The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top at 30 per second (50% faster than the original pace), and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity. The numeric readout always sits below the circle, leaving every dot visible. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. Macro bars animate when totals change, and rows with one or two tracked macros are centered. Motion honors the device's reduced-motion preference. The physics animation sleeps when settled and pauses in hidden tabs. The graphic is an approximate visual; the numeric calorie total is authoritative. ## Forgejo CI and container registry diff --git a/shared/bubble-physics.js b/shared/bubble-physics.js index 91e0f2f..6b2515b 100644 --- a/shared/bubble-physics.js +++ b/shared/bubble-physics.js @@ -102,7 +102,8 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { } function step(delta = 1000 / 60) { spawnTime += delta; - if (balls.length < target && spawnTime >= 45) { + // Two 60 Hz frames per bubble, previously three: 50% more arrivals/second. + if (balls.length < target && spawnTime >= 1000 / 30) { spawnTime = 0; // Each new bubble enters at the upper inside edge, then falls naturally. const x = 160 + (random() - 0.5) * 55; diff --git a/shared/domain.js b/shared/domain.js index 1932cfd..2801e26 100644 --- a/shared/domain.js +++ b/shared/domain.js @@ -31,6 +31,10 @@ const food = z.object({ const entry = food .extend({ date, + time: z + .string() + .regex(/^([01]\d|2[0-3]):[0-5]\d$/) + .optional(), meal: z.enum(["Breakfast", "Lunch", "Dinner", "Snacks"]), quantity: z.number().finite().positive().max(1000), }) diff --git a/shared/entry.js b/shared/entry.js new file mode 100644 index 0000000..29fc2c9 --- /dev/null +++ b/shared/entry.js @@ -0,0 +1,22 @@ +/** @returns {'Breakfast' | 'Lunch' | 'Dinner' | 'Snacks'} */ +export function suggestedMeal(date = new Date()) { + const hour = date.getHours(); + if (hour >= 5 && hour < 11) return "Breakfast"; + if (hour >= 11 && hour < 16) return "Lunch"; + if (hour >= 16 && hour < 22) return "Dinner"; + return "Snacks"; +} + +export function localTime(date = new Date()) { + return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; +} + +export function nextFoodName(prefix, names) { + let highest = 0; + for (const name of names) { + if (!name.startsWith(prefix + " ")) continue; + const suffix = name.slice(prefix.length + 1); + if (/^\d+$/.test(suffix)) highest = Math.max(highest, Number(suffix)); + } + return `${prefix} ${highest + 1}`; +} diff --git a/src/App.tsx b/src/App.tsx index 7fdfea3..b88181e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,13 +1,17 @@ -import { useCallback, useEffect, useMemo, useState } from "react"; import { - Activity, + useCallback, + useEffect, + useMemo, + useState, + type ReactNode, +} from "react"; +import { ArrowRight, ArrowUpRight, BookOpen, Check, ChevronLeft, ChevronRight, - CircleHelp, CloudOff, Coffee, Home, @@ -15,7 +19,6 @@ import { LoaderCircle, LockKeyhole, Moon, - MoreHorizontal, Pencil, Plus, Scale, @@ -31,6 +34,7 @@ import { } from "lucide-react"; import { defaultSettings, totalNutrients } from "../shared/domain.js"; import { accentPalette } from "../shared/theme.js"; +import { suggestedMeal } from "../shared/entry.js"; import { deleteRecord, initStore, @@ -53,11 +57,11 @@ import { import { dayDate, displayDate, + displayTime, number, offsetDay, recordsOf, today, - weightValue, } from "./utils"; import { CalorieOrb, @@ -70,7 +74,7 @@ import { import { Trends } from "./Trends"; import { Settings } from "./Settings"; -type Page = "today" | "library" | "trends" | "settings"; +type Page = "today" | "library" | "weight" | "settings"; type Editor = | { kind: "log"; meal: Meal; record?: JournalRecord } | { kind: "food"; record?: JournalRecord } @@ -109,7 +113,7 @@ function SignIn({

- + Room to grow. @@ -141,7 +145,6 @@ function SignIn({ - YOUR PERSONAL SPACE

{reauth ? "Welcome back." : "A fresh perspective."}

{reauth @@ -213,7 +216,6 @@ function Dashboard({ edit, remove, openLibrary, - logWeight, }: { records: JournalRecord[]; settings: SettingsData; @@ -223,7 +225,6 @@ function Dashboard({ edit: (r: JournalRecord) => void; remove: (r: JournalRecord) => void; openLibrary: () => void; - logWeight: () => void; }) { const entries = recordsOf(records, "entry"); const dayEntries = entries.filter((r) => r.data.date === date); @@ -242,11 +243,6 @@ function Dashboard({ (m) => m.key !== "calories" && settings.goals[m.key].enabled, ); const goal = settings.goals.calories; - const latestWeight = recordsOf(records, "weight").sort( - (a, b) => - b.data.date.localeCompare(a.data.date) || - b.updatedAt.localeCompare(a.updatedAt), - )[0]; const mealIcons = { Breakfast: Coffee, Lunch: Sun, @@ -290,7 +286,10 @@ function Dashboard({ /> - @@ -415,7 +414,13 @@ function Dashboard({

{meals.map((meal) => { - const rows = dayEntries.filter((r) => r.data.meal === meal); + const rows = dayEntries + .filter((r) => r.data.meal === meal) + .sort( + (a, b) => + (a.data.time || "").localeCompare(b.data.time || "") || + a.id.localeCompare(b.id), + ); const calories = totalNutrients(rows.map((r) => r.data)).calories; const Icon = mealIcons[meal]; return ( @@ -447,7 +452,10 @@ function Dashboard({ > {r.data.name} - {number(r.data.quantity, 2)} × {r.data.serving} + {r.data.time + ? displayTime(r.data.time) + : "Time not recorded"}{" "} + · {number(r.data.quantity, 2)} × {r.data.serving} {settings.goals.protein.enabled ? ` · ${number(r.data.nutrients.protein * r.data.quantity, 1)}g protein` : ""} @@ -486,31 +494,6 @@ function Dashboard({ -
-
- -
-
- A SMALL CHECK-IN -

- {latestWeight - ? `${number(weightValue(latestWeight.data.valueKg, settings.unit), 1)} ${settings.unit}` - : "How are you feeling?"} -

-

- {latestWeight - ? `Latest weigh-in · ${displayDate(latestWeight.data.date, { month: "short", day: "numeric" })}` - : "Log your weight. See the bigger picture."} -

-
- -
@@ -529,6 +512,7 @@ function Library({ editPlate, log, remove, + trends, }: { foods: JournalRecord[]; plates: JournalRecord[]; @@ -538,6 +522,7 @@ function Library({ editPlate: (r: JournalRecord) => void; log: () => void; remove: (r: JournalRecord) => void; + trends: ReactNode; }) { const [tab, setTab] = useState("foods"); const [search, setSearch] = useState(""); @@ -551,13 +536,15 @@ function Library({

A little less effort, every time you log.

- + {tab !== "trends" && ( + + )}
@@ -573,19 +560,29 @@ function Library({ > My plates {plates.length} +
- + {tab !== "trends" && ( + + )}
- {(tab === "foods" ? foods : plates).length === 0 ? ( + {tab === "trends" ? ( + trends + ) : (tab === "foods" ? foods : plates).length === 0 ? (
)} -
- - - Saved foods are a starting point. Your past entries keep their - original nutrition. - - -
+ {tab !== "trends" && ( +
+ + + Saved foods are a starting point. Your past entries keep their + original nutrition. + + +
+ )} ); } @@ -851,7 +850,7 @@ export function App() { const nav = [ { key: "today", label: "Today", icon: Home }, { key: "library", label: "My library", icon: BookOpen }, - { key: "trends", label: "Trends", icon: Activity }, + { key: "weight", label: "Weight", icon: Scale }, { key: "settings", label: "Settings", icon: Settings2 }, ] as const; const syncLabel = !status.online @@ -891,21 +890,6 @@ export function App() { ))} -
-
- ✳ -

- Progress looks -
- different every day. -

- Keep showing up for you. -
-
- - Your personal space -
-
@@ -977,7 +961,6 @@ export function App() { } remove={setDeleting} openLibrary={() => setPage("library")} - logWeight={() => setEditor({ kind: "weight" })} /> )} {page === "library" && ( @@ -988,12 +971,20 @@ export function App() { newPlate={() => setEditor({ kind: "plate" })} editFood={(record) => setEditor({ kind: "food", record })} editPlate={(record) => setEditor({ kind: "plate", record })} - log={() => setEditor({ kind: "log", meal: "Snacks" })} + log={() => setEditor({ kind: "log", meal: suggestedMeal() })} remove={setDeleting} + trends={ + + } /> )} - {page === "trends" && ( + {page === "weight" && ( setEditor({ kind: "weight" })} @@ -1039,7 +1030,7 @@ export function App() { diff --git a/src/Settings.tsx b/src/Settings.tsx index 16b7a06..c90fcd1 100644 --- a/src/Settings.tsx +++ b/src/Settings.tsx @@ -17,6 +17,7 @@ import { metrics } from "./types"; import { downloadExport, offsetDay, today } from "./utils"; import { logout, saveRecord, sync, useSyncStatus } from "./store"; import { accentPresets, DEFAULT_ACCENT } from "../shared/theme.js"; +import { useTilt } from "./useTilt"; export function Settings({ settings, @@ -36,6 +37,7 @@ export function Settings({ update: (() => void) | null; }) { const [draft, setDraft] = useState(settings); + const tilt = useTilt(); const [busy, setBusy] = useState(false); const [format, setFormat] = useState(settings.exportFormat); const [range, setRange] = useState(settings.exportDays); @@ -174,6 +176,26 @@ export function Settings({ ))}

Look & feel

+
+ +
+

+ {tilt.status === "denied" + ? "Motion permission was not granted. Check your browser’s website permissions." + : tilt.status === "unavailable" + ? "Orientation sensors are unavailable on this device. Bubbles still fall normally." + : tilt.status === "permission" + ? "Enable tilt again to grant motion access for this session." + : "Uses this device’s orientation. iPhone may request permission again after reopening. Reduced motion pauses the animation."} +

{( [ diff --git a/src/Trends.tsx b/src/Trends.tsx index c55bcc3..c770c77 100644 --- a/src/Trends.tsx +++ b/src/Trends.tsx @@ -29,12 +29,14 @@ export function Trends({ logWeight, editWeight, remove, + mode = "nutrition", }: { records: JournalRecord[]; settings: Settings; - logWeight: () => void; - editWeight: (r: JournalRecord) => void; - remove: (r: JournalRecord) => void; + mode?: "nutrition" | "weight"; + logWeight?: () => void; + editWeight?: (r: JournalRecord) => void; + remove?: (r: JournalRecord) => void; }) { const [period, setPeriod] = useState(7); const [end, setEnd] = useState(today()); @@ -87,19 +89,21 @@ export function Trends({ const delta = values.length > 1 ? values.at(-1)! - values[0] : null; return ( <> -
-
- THE BIGGER PICTURE -

- Your rhythms. -

-

Small moments. A little perspective.

+ {mode === "weight" && ( +
+
+ THE BIGGER PICTURE +

+ Weight. +

+

Your weigh-ins and changes over time.

+
+
- -
+ )}
{[7, 30, 90, 365].map((n) => ( @@ -150,221 +154,227 @@ export function Trends({
-
-
-
-
- DAILY INTAKE -

{chosen.label}

+
+ {mode === "nutrition" && ( +
+
+
+ DAILY INTAKE +

{chosen.label}

+
+
- -
-
- {number(avg)} {chosen.unit} / logged day -
-
-
- {number(maximum)} - {number(maximum / 2)} - 0 -
-
- {goal.enabled && ( -
- Goal {number(goal.target)} -
- )} - {days.map((d) => ( -
+
+ {number(maximum)} + {number(maximum / 2)} + 0 +
+
+ {goal.enabled && (
- {period === 7 && ( - - {displayDate(d.date, { weekday: "short" }).slice(0, 1)} - - )} -
- ))} + className="goal-line" + style={{ bottom: `${(goal.target / maximum) * 100}%` }} + > + Goal {number(goal.target)} +
+ )} + {days.map((d) => ( +
+
+ {period === 7 && ( + + {displayDate(d.date, { weekday: "short" }).slice(0, 1)} + + )} +
+ ))} +
-
-

- {loggedDays.length} of {period} days logged · Empty days are - excluded from the average. -

-
-
+

+ {loggedDays.length} of {period} days logged · Empty days are + excluded from the average. +

+
+ )} + {mode === "weight" && ( +
+
+
+ YOUR JOURNEY +

Weight

+
+ +
+ {dailyWeights.length ? ( + <> +
+ {number(values.at(-1)!, 1)} {settings.unit} +
+
+ + + + + `${p.x},${p.y}`).join(" ")} + fill="none" + stroke="var(--accent)" + strokeWidth="3" + strokeLinejoin="round" + /> + {points.map((p, i) => ( + + + {dailyWeights[i].data.date}: {number(values[i], 1)}{" "} + {settings.unit} + + + ))} + + {displayDate(start, { month: "short", day: "numeric" })} + + + {displayDate(end, { month: "short", day: "numeric" })} + + +
+ {number(maxWeight, 1)} + {number(minWeight, 1)} +
+
+

+ {delta === null ? ( + "Log another day to see a change over time." + ) : ( + <> + {delta < 0 ? ( + + ) : ( + + )}{" "} + {number(Math.abs(delta), 1)} {settings.unit}{" "} + {delta < 0 ? "down" : "up"} in this period + + )} +

+ + ) : ( + } + title="A starting point, whenever you’re ready" + text="Your weigh-ins will become a simple picture of your progress." + action={ + + } + /> + )} +
+ )} +
+ {mode === "weight" && ( +
- YOUR JOURNEY -

Weight

+ ONE CHECK-IN AT A TIME +

Weight journal

- + {weights.length} in this period
- {dailyWeights.length ? ( - <> -
- {number(values.at(-1)!, 1)} {settings.unit} -
-
- - - - - `${p.x},${p.y}`).join(" ")} - fill="none" - stroke="var(--accent)" - strokeWidth="3" - strokeLinejoin="round" - /> - {points.map((p, i) => ( - - - {dailyWeights[i].data.date}: {number(values[i], 1)}{" "} - {settings.unit} - - - ))} - - {displayDate(start, { month: "short", day: "numeric" })} - - - {displayDate(end, { month: "short", day: "numeric" })} - - -
- {number(maxWeight, 1)} - {number(minWeight, 1)} -
-
-

- {delta === null ? ( - "Log another day to see a change over time." - ) : ( - <> - {delta < 0 ? ( - - ) : ( - - )}{" "} - {number(Math.abs(delta), 1)} {settings.unit}{" "} - {delta < 0 ? "down" : "up"} in this period - - )} -

- + {weights.length === 0 ? ( +

No weigh-ins in this date range.

) : ( - } - title="A starting point, whenever you’re ready" - text="Your weigh-ins will become a simple picture of your progress." - action={ - - } - /> + +
+ )) )}
- -
-
-
- ONE CHECK-IN AT A TIME -

Weight journal

-
- {weights.length} in this period -
- {weights.length === 0 ? ( -

No weigh-ins in this date range.

- ) : ( - [...weights].reverse().map((r) => ( -
-
- -
-
- - {number(weightValue(r.data.valueKg, settings.unit), 1)}{" "} - {settings.unit} - - - {displayDate(r.data.date)} - {r.data.notes ? " · " + r.data.notes : ""} - -
- - -
- )) - )} -
+ )} ); } diff --git a/src/components.tsx b/src/components.tsx index 98d5956..263312e 100644 --- a/src/components.tsx +++ b/src/components.tsx @@ -1,13 +1,5 @@ import { useEffect, useRef, useState, type ReactNode } from "react"; -import { - X, - ArrowUpRight, - Plus, - Minus, - Leaf, - Smartphone, - RotateCcw, -} from "lucide-react"; +import { X, ArrowUpRight, Plus, Minus, Leaf } from "lucide-react"; import { bubbleCount } from "../shared/bubble-physics.js"; import { useBubblePhysics } from "./useBubblePhysics"; import { @@ -22,7 +14,8 @@ import { type Weight, } from "./types"; import { emptyNutrients } from "../shared/domain.js"; -import { saveRecord, putRecords } from "./store"; +import { saveRecord, putRecords, useJournal } from "./store"; +import { localTime, nextFoodName } from "../shared/entry.js"; import { displayDate, number, today, weightValue } from "./utils"; export function Modal({ @@ -91,15 +84,12 @@ export function CalorieOrb({ goal, enabled, small = false, - interactive = true, }: { value: number; goal: number; enabled: boolean; small?: boolean; - interactive?: boolean; }) { - const ratio = enabled ? Math.min(value / goal, 1) : Math.min(value / 2500, 1); const physics = useBubblePhysics(bubbleCount(value, goal, enabled)); const readout = ( <> @@ -141,55 +131,8 @@ export function CalorieOrb({ ref={physics.canvas} aria-hidden="true" /> - {!small && ratio < 0.85 && ( -
0.47 ? "orb-number-high" : "")} - > - {readout} -
- )} - {!small && ratio >= 0.85 && ( -
{readout}
- )} - {interactive && !small && ( - <> -
- - - -
- {physics.motion === "denied" && ( -

- Motion access was not granted. You can allow it in your browser’s - website settings. -

- )} - {physics.motion === "unavailable" && ( -

- No tilt data yet. Falling bubbles still work on this device. -

- )} - - )} + {!small &&
{readout}
} ); } @@ -272,6 +215,7 @@ export function FoodEditor({ notify: (text: string) => void; }) { const initial = existing?.data; + const { records } = useJournal(); const [tab, setTab] = useState<"manual" | "saved" | "plates">("manual"); const [name, setName] = useState(initial?.name || ""); const [serving, setServing] = useState(initial?.serving || "1 serving"); @@ -287,6 +231,24 @@ export function FoodEditor({ const [selectedDate, setDate] = useState( existing?.type === "entry" ? (initial as Entry).date : date, ); + const [time, setTime] = useState( + existing?.type === "entry" ? (initial as Entry).time || "" : localTime(), + ); + const fallbackName = nextFoodName( + mode === "food" ? "Food" : selectedMeal, + records + .filter( + (r) => + !r.deleted && + r.id !== existing?.id && + (mode === "food" + ? r.type === "food" + : r.type === "entry" && + (r.data as Entry).date === selectedDate && + (r.data as Entry).meal === selectedMeal), + ) + .map((r) => (r.data as Food).name), + ); const [saveFood, setSaveFood] = useState(false); const [search, setSearch] = useState(""); const [error, setError] = useState(""); @@ -296,7 +258,13 @@ export function FoodEditor({ setBusy(true); setError(""); try { - const food = { name: name.trim(), serving: serving.trim(), nutrients }; + if (mode === "log" && (!selectedDate || (!existing && !time))) + throw new Error("Choose an entry date and time."); + const food = { + name: name.trim() || fallbackName, + serving: serving.trim(), + nutrients, + }; const items: Parameters[0] = [ { type: mode === "food" ? "food" : "entry", @@ -304,7 +272,13 @@ export function FoodEditor({ data: mode === "food" ? food - : { ...food, date: selectedDate, meal: selectedMeal, quantity }, + : { + ...food, + date: selectedDate, + ...(time ? { time } : {}), + meal: selectedMeal, + quantity, + }, }, ]; if (saveFood && mode === "log") items.push({ type: "food", data: food }); @@ -327,10 +301,12 @@ export function FoodEditor({ setBusy(true); setError(""); try { + if (!selectedDate || !time) + throw new Error("Choose an entry date and time."); await putRecords( plate.items.map((item) => ({ type: "entry", - data: { ...item, date: selectedDate, meal: selectedMeal }, + data: { ...item, date: selectedDate, time, meal: selectedMeal }, })), ); notify(`${plate.name} added to your day`); @@ -379,7 +355,7 @@ export function FoodEditor({ )} {mode === "log" && ( -
+
+