import { useEffect, useRef, useState, type InputHTMLAttributes } from "react"; import { Download, Check, LogOut, ShieldCheck, Smartphone, Cloud, RefreshCw, Sun, Moon, Monitor, ArrowUpRight, ScanBarcode, } from "lucide-react"; import type { JournalRecord, Metric, Settings as SettingsData } from "./types"; import { metrics } from "./types"; import { downloadExport, offsetDay, today } from "./utils"; import { api, logout, saveRecord, sync, useSyncStatus } from "./store"; import { accentPalette, accentPresets, DEFAULT_ACCENT, } from "../shared/theme.js"; import { useTilt } from "./useTilt"; type ProductSource = { source: "usda" | "off"; imported_at: string | null; rows: number | null; error: string | null; }; const sourceNames = { usda: "USDA FoodData Central", off: "Open Food Facts", }; // Status of the server's product databases, refreshed in the background. function ProductDatabases() { const [sources, setSources] = useState(null); const [failed, setFailed] = useState(false); useEffect(() => { api("/products") .then((data) => setSources(data.sources)) .catch(() => setFailed(true)); }, []); return (
SCAN AND GO

Barcode database

{(["usda", "off"] as const).map((key) => { const source = sources?.find((item) => item.source === key); return (
{sourceNames[key]} {failed ? "Status unavailable while offline." : !sources ? "Checking…" : source?.imported_at ? `${(source.rows ?? 0).toLocaleString()} products · updated ${new Date(source.imported_at).toLocaleDateString()}` : source?.error ? `Download failed: ${source.error}` : "First download in progress on the server."}
); })}

Scans check your saved foods first, then these copies on your server, then Open Food Facts online. Both copies refresh automatically.

); } // 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, pending, lastSync, notify, install, update, }: { settings: SettingsData; records: JournalRecord[]; pending: number; lastSync: string | null; notify: (text: string, error?: boolean) => void; install: (() => void) | null; update: (() => void) | null; }) { const tilt = useTilt(); // 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( offsetDay( today(), 1 - Number(settings.exportDays === "all" ? 30 : settings.exportDays), ), ); const [end, setEnd] = useState(today()); const [selected, setSelected] = useState( settings.exportMetrics || metrics.filter((m) => settings.goals[m.key].enabled).map((m) => m.key), ); const [includeWeight, setIncludeWeight] = useState( settings.exportWeight ?? true, ); 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.deleted && (r.data as { date?: string }).date; return date && date < value ? date : value; }, today()) : start; const effectiveEnd = range === "all" ? records.reduce((value, r) => { const date = !r.deleted && (r.data as { date?: string }).date; return date && date > value ? date : value; }, today()) : end; return ( <>
MAKE ROOM FOR YOU

Settings.

Goals, appearance and exports. Changes save automatically.

FOCUS ON WHAT MATTERS

Daily goals

PERSONAL

Choose what you track. Turning a goal off keeps your past nutrition data.

Track Daily target
{metrics.map((m) => (
))}

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

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

{tilt.status === "denied" ? "Tilt stays saved, but motion access was not granted. Allow motion or check your browser’s website permissions." : tilt.status === "unavailable" ? "Orientation sensors are unavailable on this device. Bubbles still fall normally." : tilt.status === "permission" ? "Tilt is saved. Motion access resumes on your next tap, or use Allow motion below." : "Saved on this device. If iOS asks for motion access after reopening, allow it to resume tilt. Reduced motion pauses the animation."}

{tilt.enabled && (tilt.status === "permission" || tilt.status === "denied") && ( )}
{error && (

{error}

)}
YOUR DATA, TO GO

Export your journal

A clear, portable record for your own analysis or a conversation with an LLM.

{range !== "all" && (
)} INCLUDE IN EXPORT
{metrics.map((m) => ( ))}

Includes locally saved changes. No data is sent to an LLM.

READY WHEN YOU ARE

On your devices

{pending ? `${pending} change${pending === 1 ? "" : "s"} waiting to sync` : "Your journal is saved"} {lastSync ? `Last synced ${new Date(lastSync).toLocaleString()}` : "Your first sync will prepare your offline journal."}

Your synced journal and new entries stay on this device for offline use. Open Calio while online before heading out; sync resumes when you return to the app.

{install ? ( ) : (

On iPhone: open in Safari, tap Share, then{" "} Add to Home Screen. On Android: use your browser’s Install app menu.

)} {update && ( )}
Your space. Your data. Calio 0.1.0 · A personal nutrition journal
); }