Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Web: each weight figure answers for the read it came from (#181)
Carter610aabd26e6b
diff --git a/web/src/pages/Weight.test.tsx b/web/src/pages/Weight.test.tsxnew file mode 100644index 0000000..194f6b8--- /dev/null+++ b/web/src/pages/Weight.test.tsx@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, waitFor } from '@testing-library/react'+import { MemoryRouter } from 'react-router-dom'+import Weight from './Weight'++// Each figure on this screen comes from exactly one read: on "All" the server aggregate+// from /weight/stats, on every other period the period-scoped trend list. The bug these+// pin: the tiles were keyed on *either* read having failed, so a dead trend beside a+// healthy stats call rendered "0 lb" — a measurement, in the same type as a real one —+// under a line claiming it was the last figure we had loaded.++const list = vi.fn()+const stats = vi.fn()++vi.mock('../services/api', () => ({+ weightAPI: {+ list: (...args: unknown[]) => list(...args),+ stats: () => stats(),+ log: vi.fn(),+ delete: vi.fn(),+ },+}))++// The history list underneath: not what these tests are about, and left healthy so the+// page never reaches its whole-screen error.+const HISTORY = [+ { id: 1, weight: 183, logged_at: '2026-08-29T12:00:00Z', logged_on: '2026-08-29', notes: '' },+ { id: 2, weight: 181, logged_at: '2026-08-27T12:00:00Z', logged_on: '2026-08-27', notes: '' },+]++const renderPage = () => render(<MemoryRouter><Weight /></MemoryRouter>)++// The trend call is the one carrying limit: 1000; the paged history list is not.+const isTrendCall = (args: unknown[]) =>+ typeof args[0] === 'object' && args[0] !== null && (args[0] as { limit?: number }).limit === 1000++beforeEach(() => {+ vi.clearAllMocks()+ stats.mockResolvedValue({+ latest: 183, starting: 181, avg: 182, min: 181, max: 183, change_7d: 2, total_entries: 2,+ })+})++describe('Weight figures', () => {+ it('marks the tiles as failed when the read behind them died, instead of showing 0', async () => {+ list.mockImplementation((...args: unknown[]) =>+ isTrendCall(args) ? Promise.reject(new Error('trend is down')) : Promise.resolve(HISTORY))++ renderPage()++ // One mark per tile (Avg, Low, High), and no invented measurement in their place.+ await waitFor(() => {+ expect(screen.getAllByLabelText(/Couldn't load (avg|low|high) weight/i)).toHaveLength(3)+ })+ expect(screen.queryByText('0')).toBeNull()+ // Nothing was loaded, so nothing can be "the last we loaded".+ expect(screen.queryByText(/showing the last we loaded/i)).toBeNull()+ })++ it('keeps the server aggregate on All when only the trend read failed', async () => {+ list.mockImplementation((...args: unknown[]) =>+ isTrendCall(args) ? Promise.reject(new Error('trend is down')) : Promise.resolve(HISTORY))++ const { container } = renderPage()+ await waitFor(() => expect(stats).toHaveBeenCalled())++ // On All the tiles read /weight/stats, which answered — so they hold real figures+ // and the trend's failure is confined to the chart.+ const all = Array.from(container.querySelectorAll('button')).find(b => b.textContent === 'All')+ expect(all).toBeTruthy()+ all!.click()++ await waitFor(() => {+ expect(screen.getByText('182')).toBeTruthy() // avg, from the aggregate+ })+ expect(screen.queryByLabelText(/Couldn't load avg weight/i)).toBeNull()+ })++ it('does not label another period as the one on screen when a switch fails', async () => {+ // Every window answers except the one we switch to.+ const ninetyDaysAgo = daysAgo(90)+ list.mockImplementation((...args: unknown[]) => {+ if (!isTrendCall(args)) return Promise.resolve(HISTORY)+ const from = (args[0] as { from?: string }).from+ return from === ninetyDaysAgo ? Promise.reject(new Error('trend is down')) : Promise.resolve(HISTORY)+ })++ const { container } = renderPage()+ // 30d's own figures are on screen first (the average of 183 and 181).+ await waitFor(() => expect(screen.getAllByText('182').length).toBeGreaterThan(0))+ expect(screen.queryByLabelText(/Couldn't load avg weight/i)).toBeNull()++ const ninety = Array.from(container.querySelectorAll('button')).find(b => b.textContent === '90d')+ ninety!.click()++ // 30d's figures must not reappear under the 90d label; the failure takes their place.+ await waitFor(() => {+ expect(screen.getAllByLabelText(/Couldn't load (avg|low|high) weight/i)).toHaveLength(3)+ })+ expect(screen.queryByText(/showing the last we loaded/i)).toBeNull()+ })+})++// The page asks for its window as a `from` day; mirror that rather than freezing a date.+function daysAgo(n: number): string {+ const d = new Date()+ d.setDate(d.getDate() - n)+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`+}diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsxindex 5a82e07..3a228bf 100644--- a/web/src/pages/Weight.tsx+++ b/web/src/pages/Weight.tsx@@ -227,6 +227,12 @@ export default function Weight() {// Both of these used to swallow their failure. Nothing recorded it, so the aggregates// below fell back to 0 and the page rendered three measurements it had never received.const [chartError, setChartError] = useState<string | null>(null)+ // Which window chartLogs answers, and whether the window now selected has been+ // answered at all. Keeping the series through a failure is right when the same+ // question was asked again; under a different period it is not stale data, it is+ // another window's answer wearing this window's label.+ const [chartPeriod, setChartPeriod] = useState<Period | null>(null)+ const [chartLoading, setChartLoading] = useState(true)const [statsError, setStatsError] = useState<string | null>(null)const [retryKey, setRetryKey] = useState(0)@@ -239,11 +245,18 @@ export default function Weight() {let cancelled = falseconst days = PERIOD_DAYS[period]const from = days != null ? daysAgoStr(days) : undefined+ setChartLoading(true)weightAPI.list({ limit: 1000, from })// chartLogs is deliberately left alone on failure: a failed refetch keeps the// series already on screen rather than blanking a chart that was working.- .then(data => { if (!cancelled) { setChartLogs(data || []); setChartError(null) } })+ .then(data => {+ if (cancelled) return+ setChartLogs(data || [])+ setChartPeriod(period)+ setChartError(null)+ }).catch(err => { if (!cancelled) setChartError(apiErrorMessage(err, "Couldn't load your weight trend.")) })+ .finally(() => { if (!cancelled) setChartLoading(false) })return () => { cancelled = true }}, [period, retryKey])@@ -283,14 +296,16 @@ export default function Weight() {// Oldest → newest for the chartconst chartPoints: ChartPoint[] = useMemo(() => {- return chartLogs+ // Same provenance rule as the figures: a series fetched for another window is not+ // this window's trend, however recent it is.+ return (chartPeriod === period ? chartLogs : []).slice().reverse().map(l => {const d = dayToLocalDate(entryDay(l))return { ts: d.getTime(), weight: lbsToDisplay(l.weight, settings.weight_unit), date: d }})- }, [chartLogs, settings.weight_unit])+ }, [chartLogs, chartPeriod, period, settings.weight_unit])const log = useAsyncAction(async (w: number) => {const real = await weightAPI.log({@@ -335,7 +350,10 @@ export default function Weight() {// Period stats computed from chartLogs (period-scoped server fetch).// For "All" period prefer server-computed stats since they're not capped at 1000.- const periodValues = chartLogs.map(l => l.weight) // raw lbs from DB, newest first+ // The window on screen has not been answered yet: not empty, not unknown, pending.+ const chartPending = chartLoading && chartPeriod !== period+ const answeredLogs = chartPeriod === period ? chartLogs : []+ const periodValues = answeredLogs.map(l => l.weight) // raw lbs from DB, newest firstconst useServerAggregate = period === 'All' && stats != nullconst currentLbs = periodValues[0] ?? stats?.latest ?? items[0]?.weight ?? 0const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? currentLbs@@ -371,14 +389,19 @@ export default function Weight() {// the same type as a real one — while the true latest weight sat in `items` below it.const currentKnown = periodValues.length > 0 || stats != null || items.length > 0const changeKnown = periodValues.length > 1- const noValues = periodValues.length === 0 && (stats == null || stats.total_entries === 0)- const figuresFailed = noValues && (chartError != null || statsError != null)+ // Each tile has exactly one source — the server aggregate on All, the trend read on+ // every other period — so only that read's failure can explain it. Blamed on either,+ // a failed trend beside a healthy stats call rendered "0 lb" and claimed it was the+ // last figure we had loaded.+ const tilesError = useServerAggregate ? statsError : chartError+ const noValues = useServerAggregate ? stats!.total_entries === 0 : periodValues.length === 0+ const figuresFailed = noValues && tilesError != nullconst aggregatesUnknown = noValues && !figuresFailed// We do hold values, but the refresh that would have updated them failed. Keep them —// discarding data we have to report a failed refetch is worse — and say so under the// figures it applies to.- const figuresStale = !everythingFailed && !noValues && (chartError != null || statsError != null)+ const figuresStale = !everythingFailed && !noValues && tilesError != nullconst current = displayWeight(currentLbs, settings.weight_unit)const change = displayWeight(changeLbs, settings.weight_unit)@@ -581,7 +604,9 @@ export default function Weight() {<span className="stat-label">{s.label}</span><HelpTip content={s.tip} /></div>- {figuresFailed ? (+ {chartPending ? (+ <span className="inline-block h-6 w-14 rounded bg-surface-muted animate-pulse align-middle" />+ ) : figuresFailed ? (<StatFailure label={`Couldn't load ${s.label.toLowerCase()} weight`} />) : (<>@@ -612,7 +637,9 @@ export default function Weight() {<PeriodSelector options={PERIODS} value={period} onChange={setPeriod} /></div>- {chartPoints.length === 0 && chartError ? (+ {chartPending ? (+ <div className="h-44 rounded-xl bg-surface-muted animate-pulse" role="status" aria-label="Loading your trend" />+ ) : chartPoints.length === 0 && chartError ? (<ErrorState size="section" title="Couldn't load your trend" message={chartError} onRetry={retryAll} />) : chartPoints.length === 0 ? (<div className="flex items-center justify-center h-44 text-tx-muted text-sm">