Calio/src/Settings.tsx
Elijah 80fc48b9f1
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m2s
Add barcode and nutrition label scanning
Barcode scanning
- Scan barcode in the food sheet reads UPC-A/E and EAN-13/8 live from
  the camera with ZXing WebAssembly (bundled, precached, CSP allows
  wasm), with photo and typed-digit fallbacks
- Lookups check saved foods first (offline), then local copies of USDA
  FoodData Central Branded Foods and Open Food Facts, then the live
  Open Food Facts API; API answers and misses are cached
- Server imports refresh in a low-priority child process: USDA when a
  new archive is published, Open Food Facts weekly by streaming its CSV
  export; each import builds a new table and swaps it in atomically
- Every available nutrient is kept: foods and entries gain optional
  barcode (GTIN-14) and extra nutrients, shown under More nutrients and
  included in JSON exports
- Settings shows the size, date and any error for each product copy

Label scanning
- Scan label sends a downscaled photo to the server, read with
  PaddleOCR PP-OCRv5 (server detection, English recognition) on ONNX
  Runtime CPU, about 1.3 s median
- Parser handles US/Canadian, linear, Spanish and EU per-100 g panels,
  tilted photos, OCR misspellings and %DV cross-checks
- Models are pinned and checksum-verified at image build time

Container
- Runtime moves to Debian slim for ONNX Runtime's glibc build; other
  platforms' binaries are pruned
- Smoke tests now read a fixture label inside the container
- README and Unraid docs cover disk use, network access and refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:41:44 -07:00

668 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<ProductSource[] | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
api("/products")
.then((data) => setSources(data.sources))
.catch(() => setFailed(true));
}, []);
return (
<section className="card settings-card">
<div className="card-title">
<div>
<span className="eyebrow">SCAN AND GO</span>
<h2>Barcode database</h2>
</div>
<ScanBarcode size={22} className="muted" />
</div>
{(["usda", "off"] as const).map((key) => {
const source = sources?.find((item) => item.source === key);
return (
<div className="status-detail" key={key}>
<div>
<strong>{sourceNames[key]}</strong>
<small>
{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."}
</small>
</div>
</div>
);
})}
<p className="small muted">
Scans check your saved foods first, then these copies on your server,
then Open Food Facts online. Both copies refresh automatically.
</p>
</section>
);
}
// 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<HTMLInputElement>,
"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 (
<input
{...props}
type="number"
min={exclusiveMin ? undefined : min}
max={max}
value={text}
aria-invalid={!valid(text) || undefined}
onFocus={(event) => {
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<string | null>(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<Metric[]>(
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<SettingsData>) {
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<SettingsData["goals"][Metric]>) =>
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 (
<>
<div className="page-heading">
<div>
<span className="eyebrow">MAKE ROOM FOR YOU</span>
<h1>
Settings<span>.</span>
</h1>
<p>Goals, appearance and exports. Changes save automatically.</p>
</div>
</div>
<div className="settings-grid">
<section className="card settings-card">
<div className="card-title">
<div>
<span className="eyebrow">FOCUS ON WHAT MATTERS</span>
<h2>Daily goals</h2>
</div>
<span className="tiny-badge">PERSONAL</span>
</div>
<p className="muted">
Choose what you track. Turning a goal off keeps your past nutrition
data.
</p>
<div className="goal-head">
<span>Track</span>
<span>Daily target</span>
</div>
{metrics.map((m) => (
<div className="goal-row" key={m.key}>
<label className="toggle-label">
<input
className="switch"
type="checkbox"
role="switch"
checked={settings.goals[m.key].enabled}
onChange={(e) => setGoal(m.key, { enabled: e.target.checked })}
/>
<span>{m.label}</span>
</label>
<label className="unit-input goal-input">
<NumberField
aria-label={`${m.label} daily goal`}
inputMode="decimal"
step="any"
min={0}
exclusiveMin
max={100000}
value={settings.goals[m.key].target}
onCommit={(target) => setGoal(m.key, { target })}
/>
<span>{m.unit}</span>
</label>
</div>
))}
<div className="settings-section">
<h3>Nutrition averages</h3>
<label className="average-cutoff">
Minimum calories for averages
<span className="unit-input">
<NumberField
aria-label="Minimum calories for averages"
inputMode="numeric"
min={0}
max={100000}
step="1"
value={cutoff}
onCommit={(value) =>
persist({ minimumAverageCalories: Math.round(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">
<h3>Look & feel</h3>
<div className="segmented theme-control">
{(
[
{ key: "light", icon: Sun },
{ key: "dark", icon: Moon },
{ key: "system", icon: Monitor },
] as const
).map(({ key, icon: Icon }) => (
<button
key={key}
type="button"
aria-pressed={settings.theme === key}
className={settings.theme === key ? "active" : ""}
onClick={() => persist({ theme: key })}
>
<Icon size={16} />
{key[0].toUpperCase() + key.slice(1)}
</button>
))}
</div>
<div className="accent-preference">
<span className="field-caption">ACCENT COLOR</span>
<div className="accent-swatches">
{accentPresets.map((preset) => (
<button
type="button"
key={preset.color}
aria-label={`${preset.name} accent`}
aria-pressed={accent === preset.color}
onClick={() => {
setAccentPreview(null);
persist({ accentColor: preset.color });
}}
>
<span style={{ background: preset.color }} />
{accent === preset.color && <Check size={15} />}
</button>
))}
</div>
<label className="custom-accent">
<span>Custom color</span>
<code>{accent.toUpperCase()}</code>
<input
aria-label="Custom accent color"
type="color"
value={accent}
onChange={(e) => {
const color = e.target.value;
setAccentPreview(color);
clearTimeout(accentTimer.current);
accentTimer.current = window.setTimeout(() => {
persist({ accentColor: color });
setAccentPreview(null);
}, 350);
}}
/>
</label>
</div>
<div className="preference-row" data-tilt-control>
<label className="toggle-label">
<input
className="switch"
type="checkbox"
role="switch"
checked={tilt.enabled}
onChange={() => void tilt.toggleTilt()}
/>
Tilt calorie bubbles
</label>
</div>
<p className="small muted" role="status">
{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."}
</p>
{tilt.enabled &&
(tilt.status === "permission" || tilt.status === "denied") && (
<button
className="secondary"
type="button"
data-tilt-control
onClick={() => void tilt.requestTiltPermission()}
>
Allow motion
</button>
)}
<div className="preference-row">
<label htmlFor="weight-unit">Weight unit</label>
<select
id="weight-unit"
value={settings.unit}
onChange={(e) =>
persist({ unit: e.target.value as "kg" | "lb" })
}
>
<option value="lb">Pounds (lb)</option>
<option value="kg">Kilograms (kg)</option>
</select>
</div>
</div>
{error && (
<p role="alert" className="error">
{error}
</p>
)}
</section>
<div className="settings-stack">
<section className="card settings-card">
<div className="card-title">
<div>
<span className="eyebrow">YOUR DATA, TO GO</span>
<h2>Export your journal</h2>
</div>
<Download size={23} className="muted" />
</div>
<p className="muted">
A clear, portable record for your own analysis or a conversation
with an LLM.
</p>
<div className="form-row">
<label>
Format
<select
value={format}
onChange={(e) => setFormat(e.target.value as typeof format)}
>
<option value="markdown">Markdown · LLM friendly</option>
<option value="csv">CSV · spreadsheet</option>
<option value="json">JSON · structured</option>
</select>
</label>
<label>
Date range
<select
value={range}
onChange={(e) => {
const value = e.target.value as typeof range;
setRange(value);
if (value !== "all") {
setStart(offsetDay(today(), 1 - +value));
setEnd(today());
}
}}
>
<option value="7">Last 7 days</option>
<option value="30">Last 30 days</option>
<option value="90">Last 90 days</option>
<option value="all">All time</option>
</select>
</label>
</div>
{range !== "all" && (
<div className="form-row">
<label>
From
<input
type="date"
required
value={start}
max={end}
onChange={(e) => setStart(e.target.value)}
/>
</label>
<label>
Through
<input
type="date"
required
value={end}
min={start}
onChange={(e) => setEnd(e.target.value)}
/>
</label>
</div>
)}
<span className="field-caption">INCLUDE IN EXPORT</span>
<div className="export-options">
{metrics.map((m) => (
<label className="check-row" key={m.key}>
<input
type="checkbox"
checked={selected.includes(m.key)}
onChange={(e) =>
setSelected(
e.target.checked
? [...selected, m.key]
: selected.filter((v) => v !== m.key),
)
}
/>
{m.label}
</label>
))}
<label className="check-row">
<input
type="checkbox"
checked={includeWeight}
onChange={(e) => setIncludeWeight(e.target.checked)}
/>
Weight
</label>
</div>
<button
className="secondary wide"
disabled={
!effectiveStart ||
!effectiveEnd ||
effectiveStart > effectiveEnd ||
(!selected.length && !includeWeight)
}
onClick={() => {
downloadExport(
records,
settings,
effectiveStart,
effectiveEnd,
selected,
includeWeight,
format,
pending,
);
persist({
exportFormat: format,
exportDays: range,
exportMetrics: selected,
exportWeight: includeWeight,
});
notify("Export downloaded");
}}
>
<Download size={17} />
Download export
</button>
<p className="small muted">
Includes locally saved changes. No data is sent to an LLM.
</p>
</section>
<section className="card settings-card">
<div className="card-title">
<div>
<span className="eyebrow">READY WHEN YOU ARE</span>
<h2>On your devices</h2>
</div>
<Smartphone size={22} className="muted" />
</div>
<div className="status-detail">
<Cloud size={22} />
<div>
<strong>
{pending
? `${pending} change${pending === 1 ? "" : "s"} waiting to sync`
: "Your journal is saved"}
<span className="status-dot" />
</strong>
<small>
{lastSync
? `Last synced ${new Date(lastSync).toLocaleString()}`
: "Your first sync will prepare your offline journal."}
</small>
</div>
</div>
<button
className="secondary wide"
disabled={status.busy || !status.online}
onClick={() => void sync()}
>
<RefreshCw size={16} className={status.busy ? "spin" : ""} />
{status.busy ? "Syncing…" : "Sync now"}
</button>
<p className="small muted">
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.
</p>
{install ? (
<button className="text-button" onClick={install}>
Install Calio
<ArrowUpRight size={16} />
</button>
) : (
<p className="install-tip">
<Smartphone size={18} />
<span>
On iPhone: open in Safari, tap Share, then{" "}
<strong>Add to Home Screen</strong>. On Android: use your
browser’s Install app menu.
</span>
</p>
)}
{update && (
<button className="primary wide" onClick={update}>
Update Calio
<ArrowUpRight size={17} />
</button>
)}
</section>
<ProductDatabases />
<section className="account-row">
<div>
<ShieldCheck size={20} />
<span>
Your space. Your data.
<small>Calio 0.1.0 · A personal nutrition journal</small>
</span>
</div>
<button
className="text-button"
onClick={async () => {
try {
await logout();
} catch (err) {
notify((err as Error).message, true);
}
}}
>
<LogOut size={16} />
Sign out
</button>
</section>
</div>
</div>
</>
);
}