diff --git a/README.md b/README.md index 2d1d9a7..2c0c75a 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,24 @@ # Calio -A single-user, self-hosted nutrition journal. PWA first, with a responsive desktop layout, light/dark/system themes, configurable accent colors, and no third-party analytics, fonts, or nutrition services. Dark mode uses neutral near-black and charcoal surfaces; choose a preset or custom accent under Settings → Look & feel, then save preferences. Accent preferences sync between devices and remain available offline. +A single-user, self-hosted nutrition journal. PWA first, with a responsive desktop layout, light/dark/system themes, configurable accent colors, and no third-party analytics, fonts, or nutrition services. Dark mode uses neutral near-black and charcoal surfaces; choose a preset or custom accent under Settings → Look & feel; it applies immediately. Accent preferences sync between devices and remain available offline. ## 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. +- Saved foods and reusable plates; **Log** on a library card opens the food sheet pre-filled. 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. 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. +- 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. Any settings change stores the cutoff in kcal, independently of later goal changes. +- Settings save automatically as you change them: theme and accent switch instantly, and number fields commit after a short pause, on Return, or when you leave the field. - On phones, swipe left/right through Today → Library → Weight → Settings. Neighboring screens are already rendered and move together under your finger; settling uses a composited slide with no fade-to-blank delay. Every tab retains its own scroll position. Vertical scrolling, form controls, horizontal macro scrolling, and browser edge gestures remain independent. The calorie simulation pauses on other tabs. 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. Each download remembers the export format, range preset and selections for next time. - Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and explicit PWA update prompts. ### Phone layout -On phones, Today fills the available screen, including iPhone safe areas, with the calorie circle, readout, macros and navigation visible together. **Food journal** opens the selected day's meals in a separate scrollable sheet; adding, editing and removing entries from it uses the same offline journal. Desktop retains the side-by-side dashboard and meals. Compact screens use the date picker instead of the full week strip, and landscape arranges the circle beside the totals. If more than three nutrient goals are enabled, swipe the macro row horizontally to see the rest. +On phones, Today fills the available screen, including iPhone safe areas, with the calorie circle, readout, macros and navigation visible together. **Food journal** opens the selected day's meals in a separate scrollable sheet; adding, editing and removing entries open on top of it, and you return to the journal afterwards. Desktop retains the side-by-side dashboard and meals. Compact screens use the date picker instead of the full week strip, and landscape arranges the circle beside the totals. If more than three nutrient goals are enabled, swipe the macro row horizontally to see the rest. Phone controls use larger type, 44–56 px tap targets, and 51×31 px switches. Food entry uses full-width day/time/meal rows, explicitly constrained native input widths, and a sticky sheet header. Library, Weight and Settings scroll normally. diff --git a/shared/bubble-physics.js b/shared/bubble-physics.js index 6b2515b..827c2f1 100644 --- a/shared/bubble-physics.js +++ b/shared/bubble-physics.js @@ -44,6 +44,8 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { }); engine.gravity.scale = 0.00035; const balls = []; + // Removed bubbles leave the simulation at once but fade out where they were. + const fading = []; let target = initialCount; let spawnTime = 0; const walls = Array.from({ length: 72 }, (_, i) => { @@ -82,6 +84,7 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { function seed(count) { for (const ball of balls) Composite.remove(engine.world, ball); balls.length = 0; + fading.length = 0; target = Math.min(MAX_BUBBLES, Math.max(0, count)); for (let i = 0; i < target; i++) add(packedPositions[i].x, packedPositions[i].y); @@ -89,7 +92,16 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { seed(initialCount); function setTarget(count) { target = Math.min(MAX_BUBBLES, Math.max(0, count)); - while (balls.length > target) Composite.remove(engine.world, balls.pop()); + while (balls.length > target) { + const ball = balls.pop(); + Composite.remove(engine.world, ball); + fading.push({ + id: ball.id, + x: ball.position.x, + y: ball.position.y, + life: 1, + }); + } wake(); } function gravity(x, y) { @@ -102,6 +114,9 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { } function step(delta = 1000 / 60) { spawnTime += delta; + for (const bubble of fading) bubble.life -= delta / 220; + for (let i = fading.length - 1; i >= 0; i--) + if (fading[i].life <= 0) fading.splice(i, 1); // Two 60 Hz frames per bubble, previously three: 50% more arrivals/second. if (balls.length < target && spawnTime >= 1000 / 30) { spawnTime = 0; @@ -143,13 +158,16 @@ export function createBubbleWorld(initialCount = 0, random = Math.random) { return { engine, balls, + fading, step, seed, setTarget, gravity, nudge, awake: () => - balls.length < target || balls.some((ball) => !ball.isSleeping), + fading.length > 0 || + balls.length < target || + balls.some((ball) => !ball.isSleeping), dispose: () => { Composite.clear(engine.world, false); Engine.clear(engine); diff --git a/src/App.tsx b/src/App.tsx index b240fb8..a292c0f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, + useRef, useState, type ReactNode, } from "react"; @@ -10,6 +11,7 @@ import { ArrowRight, ArrowUpRight, BookOpen, + CalendarDays, Check, ChevronLeft, ChevronRight, @@ -40,6 +42,7 @@ import { deleteRecord, initStore, login, + pendingChanges, sync, useJournal, useSyncStatus, @@ -79,6 +82,7 @@ import { Presence } from "./Presence"; import { useNavigation, type Page } from "./useNavigation"; import { PageActivity } from "./PageActivity"; import { useTiltResume } from "./useTilt"; +import { useFollowToday } from "./useToday"; function PagePanel({ name, page, @@ -110,8 +114,52 @@ function PagePanel({ ); } +// A manual popover joins the top layer, so confirmations stay visible above +// any open sheet instead of behind its backdrop. +function Toast({ + text, + error, + dismiss, +}: { + text: string; + error: boolean; + dismiss: () => void; +}) { + const ref = useRef(null); + useEffect(() => { + const element = ref.current; + if (!element?.showPopover) return; + try { + if (element.matches(":popover-open")) element.hidePopover(); + element.showPopover(); + } catch { + // Unsupported browsers render it as a fixed element. + } + }, [text]); + return ( +
+ {error ? : } + {text} + +
+ ); +} + type Editor = - | { kind: "log"; meal: Meal; record?: JournalRecord } + | { + kind: "log"; + meal: Meal; + record?: JournalRecord; + template?: Food; + tab?: "manual" | "saved" | "plates"; + } | { kind: "food"; record?: JournalRecord } | { kind: "plate"; record?: JournalRecord } | { kind: "weight"; record?: JournalRecord } @@ -424,7 +472,7 @@ function Dashboard({ if (e.target.value) setDate(e.target.value); }} /> - + - + setToast("")} /> )} ); diff --git a/src/Presence.tsx b/src/Presence.tsx index c4c9001..0ff8ca7 100644 --- a/src/Presence.tsx +++ b/src/Presence.tsx @@ -23,7 +23,7 @@ export function Presence({ children }: { children: ReactNode }) { } const timer = setTimeout( () => setRetained(false), - matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 190, + matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 250, ); return () => clearTimeout(timer); }, [children, visible]); diff --git a/src/Settings.tsx b/src/Settings.tsx index 5b2be7a..7ae89c9 100644 --- a/src/Settings.tsx +++ b/src/Settings.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useEffect, useRef, useState, type InputHTMLAttributes } from "react"; import { Download, Check, @@ -16,9 +16,86 @@ import type { JournalRecord, Metric, Settings as SettingsData } from "./types"; 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 { + accentPalette, + accentPresets, + DEFAULT_ACCENT, +} from "../shared/theme.js"; import { useTilt } from "./useTilt"; +// Edits a number locally and commits once it is valid: after a short pause, on +// blur, or on Enter. External changes (sync) apply only while it is not focused. +function NumberField({ + value, + min, + max, + exclusiveMin = false, + onCommit, + ...props +}: { + value: number; + min: number; + max: number; + exclusiveMin?: boolean; + onCommit: (value: number) => void; +} & Omit< + InputHTMLAttributes, + "value" | "min" | "max" | "onChange" +>) { + const [text, setText] = useState(String(value)); + const focused = useRef(false); + const timer = useRef(0); + const latest = useRef({ text, value, onCommit }); + latest.current = { text, value, onCommit }; + useEffect(() => { + if (!focused.current) setText(String(value)); + }, [value]); + const valid = (raw: string) => { + const n = Number(raw); + return ( + raw.trim() !== "" && + Number.isFinite(n) && + (exclusiveMin ? n > min : n >= min) && + n <= max + ); + }; + const commit = (final: boolean) => { + clearTimeout(timer.current); + const { text: raw, value: current, onCommit: save } = latest.current; + if (valid(raw)) { + if (Number(raw) !== current) save(Number(raw)); + if (final) setText(String(Number(raw))); + } else if (final) setText(String(current)); + }; + useEffect(() => () => commit(false), []); + return ( + { + focused.current = true; + event.currentTarget.select(); + }} + onChange={(event) => { + setText(event.target.value); + clearTimeout(timer.current); + timer.current = window.setTimeout(() => commit(false), 700); + }} + onBlur={() => { + focused.current = false; + commit(true); + }} + onKeyDown={(event) => { + if (event.key === "Enter") event.currentTarget.blur(); + }} + /> + ); +} + export function Settings({ settings, records, @@ -32,18 +109,29 @@ export function Settings({ records: JournalRecord[]; pending: number; lastSync: string | null; - notify: (text: string) => void; + notify: (text: string, error?: boolean) => void; install: (() => void) | null; update: (() => void) | null; }) { - const [draft, setDraft] = useState({ - ...settings, - minimumAverageCalories: - settings.minimumAverageCalories ?? - Math.round(settings.goals.calories.target / 2), - }); const tilt = useTilt(); - const [busy, setBusy] = useState(false); + // Latest settings, including saves still being written, so quick successive + // changes build on each other instead of on a stale render. + const current = useRef(settings); + const received = useRef(settings); + if (received.current !== settings) { + received.current = settings; + current.current = settings; + } + const cutoff = + settings.minimumAverageCalories ?? + Math.round(settings.goals.calories.target / 2); + const [accentPreview, setAccentPreview] = useState(null); + const accentTimer = useRef(0); + const accent = ( + accentPreview || + settings.accentColor || + DEFAULT_ACCENT + ).toLowerCase(); const [format, setFormat] = useState(settings.exportFormat); const [range, setRange] = useState(settings.exportDays); const [start, setStart] = useState( @@ -62,10 +150,43 @@ export function Settings({ ); const [error, setError] = useState(""); const status = useSyncStatus(); + // While dragging the custom color, preview it before the debounced save. + useEffect(() => { + if (!accentPreview) return; + const dark = document.documentElement.dataset.theme === "dark"; + for (const [key, value] of Object.entries( + accentPalette(accentPreview, dark), + )) + document.documentElement.style.setProperty(key, value); + }, [accentPreview]); + // Preferences apply as soon as they change, like iOS Settings. The averages + // cutoff is stored in kcal so later calorie-goal changes do not move it. + function persist(change: Partial) { + const base = current.current; + const next = { + ...base, + minimumAverageCalories: + base.minimumAverageCalories ?? + Math.round(base.goals.calories.target / 2), + ...change, + }; + current.current = next; + setError(""); + saveRecord("settings", next, "settings").catch(() => + setError("Could not save that change. Please try again."), + ); + } + const setGoal = (key: Metric, change: Partial) => + persist({ + goals: { + ...current.current.goals, + [key]: { ...current.current.goals[key], ...change }, + }, + }); const effectiveStart = range === "all" ? records.reduce((value, r) => { - const date = (r.data as { date?: string }).date; + const date = !r.deleted && (r.data as { date?: string }).date; return date && date < value ? date : value; }, today()) : start; @@ -76,29 +197,6 @@ export function Settings({ return date && date > value ? date : value; }, today()) : end; - async function save(event: React.FormEvent) { - event.preventDefault(); - setBusy(true); - setError(""); - try { - await saveRecord( - "settings", - { - ...draft, - exportFormat: format, - exportDays: range, - exportMetrics: selected, - exportWeight: includeWeight, - }, - "settings", - ); - notify("Your preferences are saved"); - } catch { - setError("Could not save. Check that each goal is a positive number."); - } finally { - setBusy(false); - } - } return ( <>
@@ -107,11 +205,11 @@ export function Settings({

Settings.

-

Goals, appearance and exports.

+

Goals, appearance and exports. Changes save automatically.

-
+
FOCUS ON WHAT MATTERS @@ -133,47 +231,22 @@ export function Settings({ - setDraft({ - ...draft, - goals: { - ...draft.goals, - [m.key]: { - ...draft.goals[m.key], - enabled: e.target.checked, - }, - }, - }) - } + role="switch" + checked={settings.goals[m.key].enabled} + onChange={(e) => setGoal(m.key, { enabled: e.target.checked })} /> {m.label} @@ -184,23 +257,15 @@ export function Settings({

Look & feel

+
+ {( + [ + { key: "light", icon: Sun }, + { key: "dark", icon: Moon }, + { key: "system", icon: Monitor }, + ] as const + ).map(({ key, icon: Icon }) => ( + + ))} +
+
+ ACCENT COLOR +
+ {accentPresets.map((preset) => ( + + ))} +
+ +