Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Say when something failed, instead of drawing the wreckage (#163)

Carteraa7cb466db41
diff --git a/mobile/src/components/ui/ConfirmSheet.tsx b/mobile/src/components/ui/ConfirmSheet.tsx
index b72e4f5..f22269c 100644
--- a/mobile/src/components/ui/ConfirmSheet.tsx
+++ b/mobile/src/components/ui/ConfirmSheet.tsx
@@ -39,7 +39,9 @@ export function ConfirmSheet({
const badgeIconColor = destructive ? (isDark ? brand.errorSoft : brand.error) : accent
return (
- <Sheet open={open} onClose={onCancel} haptic={destructive ? 'warning' : 'selection'}>
+ // Scrim tap and Android back both come through onClose, and neither may dismiss a
+ // confirmed action still in flight: the sheet is where its failure gets reported.
+ <Sheet open={open} onClose={busy ? () => {} : onCancel} haptic={destructive ? 'warning' : 'selection'}>
<View className="px-6">
{Icon ? (
<View
@@ -62,7 +64,7 @@ export function ConfirmSheet({
<View className="flex-row gap-3">
<View className="flex-1">
- <SheetButton label={cancelLabel} variant="muted" onPress={onCancel} />
+ <SheetButton label={cancelLabel} variant="muted" disabled={busy} onPress={onCancel} />
</View>
<View className="flex-1">
<SheetButton
diff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.ts
index 681e449..68452b0 100644
--- a/packages/shared/src/utils/food.test.ts
+++ b/packages/shared/src/utils/food.test.ts
@@ -1,4 +1,4 @@
-import { entryToResult, findSavedFood, normaliseFoodKey, savedToResult, scaleServing } from './food'
+import { entryToResult, findSavedFood, isDailyStats, normaliseFoodKey, savedToResult, scaleServing } from './food'
import type { FoodLog, SavedFood } from '../types'
const log = (over: Partial<FoodLog> = {}): FoodLog => ({
@@ -169,3 +169,39 @@ describe('normaliseFoodKey', () => {
expect(normaliseFoodKey(undefined)).toBe('')
})
})
+
+describe('isDailyStats', () => {
+ const ok = {
+ date: '2026-08-29', total_calories: 1840, total_protein: 128,
+ total_carbs: 190, total_fat: 61, total_fiber: 22, workout_count: 1,
+ }
+
+ it('accepts the real payload', () => {
+ expect(isDailyStats(ok)).toBe(true)
+ })
+
+ // A server that adds a field must not make an older client call the answer broken.
+ it('accepts a payload carrying fields it does not know about', () => {
+ expect(isDailyStats({ ...ok, total_alcohol: 3 })).toBe(true)
+ })
+
+ // Each of these arrived with a 200, so no catch ever fired for them. The dashboard
+ // rendered NaN and the food screen rendered 0 — a measurement — for every one.
+ it.each([
+ ['a string', 'nonsense'],
+ ['a number', 42],
+ ['an array', [1, 2, 3]],
+ ['null', null],
+ ['undefined', undefined],
+ ['an empty object', {}],
+ ['a partial object', { total_calories: 1840 }],
+ // Calories and protein valid is not enough: the dashboard's macro rows read these too.
+ ['missing carbs', { ...ok, total_carbs: undefined }],
+ ['missing fat', { ...ok, total_fat: undefined }],
+ ['a stringified fat', { ...ok, total_fat: '61' }],
+ ['NaN in a number field', { ...ok, total_calories: NaN }],
+ ['a stringified number', { ...ok, total_calories: '1840' }],
+ ])('rejects %s', (_label, value) => {
+ expect(isDailyStats(value)).toBe(false)
+ })
+})
diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.ts
index b53d092..652aa11 100644
--- a/packages/shared/src/utils/food.ts
+++ b/packages/shared/src/utils/food.ts
@@ -86,3 +86,24 @@ export function findSavedFood(
export function normaliseFoodKey(value: string | undefined): string {
return (value ?? '').trim()
}
+
+// A 200 is not the same as an answer we can read.
+//
+// The day's totals are fetched with a `.catch` that substitutes zeros, which handles a
+// 500 — but a response that succeeds and carries the wrong shape never reaches it. The
+// web dashboard then ran Math.round over a missing field and rendered "NaN" beside the
+// calorie ring, and the food screen rendered "0", which is the "hasn't eaten yet" lie
+// this whole change exists to remove.
+//
+// So the shape is checked where the value is read, and anything unreadable is treated as
+// a failed load rather than as data. Every macro a screen renders is required — the
+// dashboard's macro rows read carbs and fat too, so checking only calories and protein
+// let a payload missing those through to render NaN. Extra fields are still fine: a server
+// that grows one must not make an older client call the payload broken.
+const RENDERED_MACROS = ['total_calories', 'total_protein', 'total_carbs', 'total_fat'] as const
+
+export function isDailyStats(value: unknown): value is import('../types').DailyStats {
+ if (typeof value !== 'object' || value === null) return false
+ const v = value as Record<string, unknown>
+ return RENDERED_MACROS.every(k => typeof v[k] === 'number' && Number.isFinite(v[k]))
+}
diff --git a/web/e2e/weight.spec.ts b/web/e2e/weight.spec.ts
index 7acdd43..0a7cc6a 100644
--- a/web/e2e/weight.spec.ts
+++ b/web/e2e/weight.spec.ts
@@ -143,4 +143,41 @@ test.describe('Weight', () => {
await page.waitForURL('/weight', { timeout: 5000 })
await expect(page.getByRole('heading', { name: 'Weight', exact: true })).toBeVisible()
})
+
+ // A delete in flight cannot be dismissed. ConfirmSheet refuses Escape and Cancel while
+ // busy, and its own unit test proves that — but this page kept the Escape listener from
+ // the hand-rolled dialog ConfirmSheet replaced, and that listener ignored `busy`. Escape
+ // mid-delete closed the sheet, and the failure then landed with nowhere to be shown. A
+ // component test cannot see a page wiring its own second handler; only this can.
+ test('a delete in flight cannot be dismissed into silence', async ({ page }) => {
+ const headers = { Authorization: `Bearer ${authToken}` }
+ const r = await page.request.post(`${API}/weight`, {
+ headers,
+ data: { weight: 998, notes: 'E2E in-flight target', logged_at: new Date(Date.now() - 31 * 86400000).toISOString() },
+ })
+ const { data } = await r.json()
+
+ await page.goto(`/weight/${data.id}`)
+ await expect(page.getByText('Weight Entry')).toBeVisible()
+
+ // DELETE only, and only once the page is up: the detail screen loads from the same
+ // URL it deletes, so hanging every method would hang the page before the delete.
+ await page.route(`**/api/v1/weight/${data.id}`, route =>
+ route.request().method() === 'DELETE' ? undefined : route.fallback())
+
+ await page.getByRole('button', { name: 'Delete entry' }).click()
+ const sheet = page.getByRole('alertdialog', { name: 'Delete Entry?' })
+ await expect(sheet).toBeVisible()
+ await sheet.getByRole('button', { name: 'Delete' }).click()
+ await expect(sheet.getByRole('button', { name: 'Deleting…' })).toBeDisabled()
+
+ await page.keyboard.press('Escape')
+ await expect(sheet.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+ // Still up after both ways out were tried. Checked after the Cancel assertion so the
+ // Escape has had a render to take effect in, rather than asserting on the same tick.
+ await expect(sheet).toBeVisible()
+
+ await page.unroute(`**/api/v1/weight/${data.id}`)
+ await page.request.delete(`${API}/weight/${data.id}`, { headers })
+ })
})
diff --git a/web/src/components/DiscardConfirm.tsx b/web/src/components/DiscardConfirm.tsx
deleted file mode 100644
index 6f98454..0000000
--- a/web/src/components/DiscardConfirm.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { createPortal } from 'react-dom'
-import { Trash2 } from 'lucide-react'
-import { useEscapeKey } from '../hooks/useEscapeKey'
-import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
-
-interface Props {
- open: boolean
- onKeep: () => void
- onDiscard: () => void
-}
-
-// Discard-workout confirmation bottom sheet, shared by every gym-mode phase (was
-// triplicated inline). Renders to document.body so it overlays the full-screen gym;
-// uses the shared escape/scroll-lock hooks like every other sheet.
-export default function DiscardConfirm({ open, onKeep, onDiscard }: Props) {
- useBodyScrollLock(open)
- useEscapeKey(open, onKeep) // Escape dismisses (the non-destructive choice)
- if (!open) return null
- return createPortal(
- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Discard workout?</h3>
- <p className="text-sm text-tx-muted mb-5">This ends the workout without saving — all progress is lost.</p>
- <div className="flex gap-3">
- <button onClick={onKeep} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>
- <button onClick={onDiscard} className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Trash2 className="w-3.5 h-3.5" />Discard
- </button>
- </div>
- </div>
- </div>,
- document.body,
- )
-}
diff --git a/web/src/components/ErrorBoundary.tsx b/web/src/components/ErrorBoundary.tsx
new file mode 100644
index 0000000..2debc78
--- /dev/null
+++ b/web/src/components/ErrorBoundary.tsx
@@ -0,0 +1,54 @@
+import { Component, type ReactNode } from 'react'
+import ErrorState from './ui/ErrorState'
+
+// The last net under a PR whose whole subject is that a failure must be visible.
+//
+// Everything else here catches failures we ANTICIPATED — a rejected promise, a 502, a
+// list page that never arrived. A render that throws is the one we did not, and React's
+// answer to an uncaught throw is to unmount the entire tree: a white screen, no nav, no
+// way back except a manual reload, which is the least visible failure the app can have.
+// Found by feeding the workout list a row whose started_at would not parse — one bad row
+// out of ten took down the page, and React logged the standard "Consider adding an error
+// boundary" warning because there was not one anywhere in the codebase.
+//
+// This does not excuse a crash: the underlying bug still gets fixed. It bounds the damage
+// to the region that threw, so an unknown future throw costs a section instead of the app.
+interface Props {
+ children: ReactNode
+ /** What was on screen, so the copy can say it: "Couldn't show your workouts". */
+ subject?: string
+ /** page inside a route, section around a widget — same rule as ErrorState. */
+ size?: 'page' | 'section'
+}
+
+interface State {
+ failed: boolean
+}
+
+export default class ErrorBoundary extends Component<Props, State> {
+ state: State = { failed: false }
+
+ static getDerivedStateFromError(): State {
+ return { failed: true }
+ }
+
+ componentDidCatch(error: unknown) {
+ // Keep the stack in the console: the boundary hides the crash from the user, and
+ // a crash nobody can see in development is worse than the white screen was.
+ console.error('Unhandled render error:', error)
+ }
+
+ render() {
+ if (!this.state.failed) return this.props.children
+ return (
+ <ErrorState
+ size={this.props.size ?? 'page'}
+ title={`Couldn't show ${this.props.subject ?? 'this page'}`}
+ message="Something went wrong on our side. Try again, and if it keeps happening reload the page."
+ // Remounting the subtree is the retry: state that got us into the bad
+ // render is thrown away with it.
+ onRetry={() => this.setState({ failed: false })}
+ />
+ )
+ }
+}
diff --git a/web/src/components/ExercisePicker.test.tsx b/web/src/components/ExercisePicker.test.tsx
index f5061b6..a6c4f2a 100644
--- a/web/src/components/ExercisePicker.test.tsx
+++ b/web/src/components/ExercisePicker.test.tsx
@@ -106,4 +106,35 @@ describe('ExercisePicker', () => {
expect(call[0]?.limit ?? 50).toBeLessThanOrEqual(100)
}
})
+ // A list that failed to load is not an empty list. Before useServerList reported its
+ // error, the catch set hasMore=false and nothing else, so the picker fell through to
+ // "No exercises found" — an empty catalogue, rather than a connection that dropped.
+ it('says the load failed instead of reporting an empty catalogue', async () => {
+ const err: any = new Error("timeout of 20000ms exceeded")
+ err.code = 'ECONNABORTED'
+ listMock.mockRejectedValue(err)
+
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+
+ await waitFor(() =>
+ expect(screen.getByText(/didn't respond in time/i)).toBeTruthy())
+ expect(screen.queryByText(/no exercises found/i)).toBeNull()
+ expect(screen.getByRole('button', { name: /try again/i })).toBeTruthy()
+ })
+
+ // Retry resumes rather than reloading, and a success clears the message.
+ it('recovers when Try again succeeds', async () => {
+ const err: any = new Error("Network Error")
+ listMock
+ .mockRejectedValueOnce(err)
+ .mockResolvedValue([exercise(1, 'Barbell Squat')])
+
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+ await waitFor(() => expect(screen.getByRole('button', { name: /try again/i })).toBeTruthy())
+
+ fireEvent.click(screen.getByRole('button', { name: /try again/i }))
+
+ await waitFor(() => expect(screen.getByText('Barbell Squat')).toBeTruthy())
+ expect(screen.queryByRole('button', { name: /try again/i })).toBeNull()
+ })
})
diff --git a/web/src/components/ExercisePicker.tsx b/web/src/components/ExercisePicker.tsx
index 27a4f0e..b0766da 100644
--- a/web/src/components/ExercisePicker.tsx
+++ b/web/src/components/ExercisePicker.tsx
@@ -2,8 +2,9 @@ import { useState, useEffect, useRef, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { ArrowLeft, Search, Dumbbell } from 'lucide-react'
import { useVirtualizer } from '@tanstack/react-virtual'
+import { useServerList, types } from '@lyftr/shared'
+import { ListError } from './ui'
import { exerciseAPI } from '../services/api'
-import { types } from '@lyftr/shared'
import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'
// Must match the server's default page size, since a short page is what signals
@@ -11,6 +12,8 @@ import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'
const PAGE_SIZE = 50
// How close to the end of the loaded rows to get before fetching the next page.
const PREFETCH_ROWS = 10
+// Matches the debounce the hand-rolled version of this picker shipped with.
+const DEBOUNCE_MS = 250
interface Props {
selectedIds: number[]
@@ -19,57 +22,34 @@ interface Props {
}
export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
- const [exercises, setExercises] = useState<types.Exercise[]>([])
const [query, setQuery] = useState('')
- const [loading, setLoading] = useState(false)
- const [page, setPage] = useState(1)
- const [exhausted, setExhausted] = useState(false)
+ const [debouncedQuery, setDebouncedQuery] = useState('')
const scrollRef = useRef<HTMLDivElement>(null)
- // Guards against the virtualizer asking for the next page repeatedly while the
- // first request for it is still in flight — it fires on every scroll frame, not
- // once per boundary crossing. It only ever suppresses an append: a new search
- // must never be dropped because a page fetch is outstanding.
- const loadingRef = useRef(false)
- // Identifies the newest request so a slow earlier one cannot overwrite it. Typing
- // fast enough to outrun a response otherwise leaves the list showing results for
- // a query the user has already moved on from.
- const reqRef = useRef(0)
+
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)
+ return () => clearTimeout(t)
+ }, [query])
// Results come a page at a time from the server, which queries open-exercise-db.
// Nothing downloads the catalog to filter it here: with ~873 exercises upstream
// and growing, the browser is the wrong place to do that, and it put the whole
// library behind one slow request before the picker could render anything.
- const load = useCallback(async (q: string, nextPage: number, append = false) => {
- if (append && loadingRef.current) return
- const id = ++reqRef.current
- loadingRef.current = true
- setLoading(true)
- try {
- const data = await exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage }) || []
- if (reqRef.current !== id) return // a newer request has taken over
- setExercises(prev => (append ? [...prev, ...data] : data))
- // A short page means the server has nothing left for this query. Asking again
- // would just repeat the request for every remaining scroll event.
- setExhausted(data.length < PAGE_SIZE)
- setPage(nextPage)
- } catch { /* a failed search keeps the previous list rather than blanking it */ }
- finally {
- if (reqRef.current === id) {
- loadingRef.current = false
- setLoading(false)
- }
- }
- }, [])
-
- useEffect(() => { load('', 1) }, [load])
+ const fetcher = useCallback(
+ (offset: number, limit: number) =>
+ exerciseAPI
+ .list({ ...(debouncedQuery ? { q: debouncedQuery } : {}), page: offset / limit + 1 })
+ .then(data => data ?? []),
+ [debouncedQuery]
+ )
- useEffect(() => {
- const t = setTimeout(() => {
- setExhausted(false)
- load(query, 1)
- }, 250)
- return () => clearTimeout(t)
- }, [query, load])
+ const {
+ items: exercises, loadMore, hasMore, loading, initialLoading, error, retry,
+ } = useServerList<types.Exercise>({
+ fetcher,
+ pageSize: PAGE_SIZE,
+ deps: [debouncedQuery],
+ })
const available = exercises.filter(e => !selectedIds.includes(e.id))
@@ -87,9 +67,9 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
// with the virtualizer's own windowing.
const lastVisible = virtualItems.length ? virtualItems[virtualItems.length - 1].index : 0
useEffect(() => {
- if (exhausted || loading || available.length === 0) return
- if (lastVisible >= available.length - PREFETCH_ROWS) load(query, page + 1, true)
- }, [lastVisible, available.length, exhausted, loading, query, page, load])
+ if (!hasMore || loading || available.length === 0) return
+ if (lastVisible >= available.length - PREFETCH_ROWS) loadMore()
+ }, [lastVisible, available.length, hasMore, loading, loadMore])
return createPortal(
<div className="fixed inset-0 z-[60] bg-surface-base flex flex-col animate-slide-up">
@@ -103,9 +83,15 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
</button>
<div>
<h2 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h2>
- <p className="text-xs text-tx-muted">
- {available.length} loaded{exhausted ? '' : '…'}
- </p>
+ {/* Derived from the rows we actually hold, so it is only true if the fetch
+ landed. On a failure `available` is empty and this read "0 loaded" directly
+ above a message saying we could not load anything — the same claim the
+ error state exists to stop. */}
+ {!error && (
+ <p className="text-xs text-tx-muted">
+ {available.length} loaded{hasMore ? '…' : ''}
+ </p>
+ )}
</div>
</div>
@@ -126,15 +112,23 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
{/* List */}
<div ref={scrollRef} className="flex-1 overflow-y-auto">
- {loading && exercises.length === 0 ? (
+ {initialLoading ? (
<div className="flex items-center justify-center py-16 text-tx-muted text-sm">
<Dumbbell className="w-5 h-5 mr-2 animate-pulse text-brand-500" />
Loading exercises…
</div>
) : available.length === 0 ? (
- <div className="flex items-center justify-center py-16 text-tx-muted text-sm">
- No exercises found
- </div>
+ // "No exercises found" is only true if we heard back. On a failed fetch it
+ // reads as an empty catalogue rather than a connection that dropped.
+ error ? (
+ <div className="p-4">
+ <ListError subject="these exercises" message={error} onRetry={retry} />
+ </div>
+ ) : (
+ <div className="flex items-center justify-center py-16 text-tx-muted text-sm">
+ No exercises found
+ </div>
+ )
) : (
<div
className="px-4 py-2 relative"
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index a890020..bb3c769 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -14,6 +14,7 @@ import { useSettingsStore, weightShort } from '../stores/settings'
import GymModeWorkout from '../pages/GymModeWorkout'
import RestTimerBanner from './RestTimerBanner'
import Logo from './Logo'
+import ErrorBoundary from './ErrorBoundary'
const NAV = [
{ path: '/', label: 'Home', icon: Home },
@@ -185,7 +186,12 @@ export default function Layout() {
inert={gymOverlayUp}
className="flex-1 max-w-6xl mx-auto w-full min-w-0 overflow-x-hidden px-5 py-7 animate-fade-in"
>
- <Outlet />
+ {/* Keyed on the path so the boundary RESETS on navigation: without the key a
+ crash on one route would follow the user to every other one, turning a bad
+ row on /workouts into an app that looks broken everywhere. */}
+ <ErrorBoundary key={pathname} subject="this page">
+ <Outlet />
+ </ErrorBoundary>
</main>
{/* Gym mode overlay — rendered at root so it persists across routes */}
diff --git a/web/src/components/ProgramPicker.tsx b/web/src/components/ProgramPicker.tsx
index ba20780..79280a5 100644
--- a/web/src/components/ProgramPicker.tsx
+++ b/web/src/components/ProgramPicker.tsx
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { X, BookOpen, ChevronRight, Dumbbell, AlertCircle, Moon } from 'lucide-react'
import { programAPI } from '../services/api'
-import { workoutDays, dayLabel, todaysDay, types } from '@lyftr/shared'
+import { apiErrorMessage, workoutDays, dayLabel, todaysDay, types } from '@lyftr/shared'
interface Props {
onSelect: (program: types.Program, day: types.ProgramDay) => void
@@ -21,7 +21,7 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {
useEffect(() => {
programAPI.list()
.then(data => setPrograms(data || []))
- .catch(() => setError('Failed to load programs'))
+ .catch(err => setError(apiErrorMessage(err, "Couldn't load your programs.")))
.finally(() => setLoading(false))
}, [])
@@ -36,7 +36,7 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {
const subtitle = dayPickFor ? 'Pick a day to pre-fill exercises' : 'Pick a program to pre-fill exercises'
// Portalled to document.body like every other overlay here (ExercisePicker,
- // DiscardConfirm, QuickWeighInSheet, BarcodeScanner, Toast). Rendered inline it
+ // ConfirmSheet, QuickWeighInSheet, BarcodeScanner, Toast). Rendered inline it
// sat inside AddWorkout's `.animate-slide-up`, whose `animation-fill-mode: both`
// leaves `transform: translateY(0)` applied for good. A transform — even an
// identity one — makes that element the containing block for `position: fixed`
diff --git a/web/src/components/QuickWeighInSheet.tsx b/web/src/components/QuickWeighInSheet.tsx
index bd07c64..e084781 100644
--- a/web/src/components/QuickWeighInSheet.tsx
+++ b/web/src/components/QuickWeighInSheet.tsx
@@ -5,7 +5,7 @@ import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs , weightError, maxWeight } from '../stores/settings'
import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types } from '@lyftr/shared'
+import { useAsyncAction, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types } from '@lyftr/shared'
import StepperTile from './ui/StepperTile'
import NumberField from './ui/NumberField'
@@ -25,7 +25,6 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
const [date, setDate] = useState(todayStr())
const [notes, setNotes] = useState('')
const [showExtras, setShowExtras] = useState(false)
- const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
const duplicateWarningDismissedRef = useRef(false)
@@ -38,11 +37,20 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
setNotes('')
setShowExtras(false)
setError('')
- setSaving(false)
setShowDuplicateWarning(false)
duplicateWarningDismissedRef.current = false
}, [isOpen, lastValue])
+ const save = useAsyncAction(async (w: number) => {
+ const log = await weightAPI.log({
+ weight: displayToLbs(w, settings.weight_unit),
+ notes: notes.trim(),
+ logged_at: dayToInstant(date),
+ })
+ onSuccess(log)
+ onClose()
+ }, 'Failed to save')
+
const handleClose = () => { setError(''); onClose() }
useBodyScrollLock(isOpen)
@@ -52,7 +60,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
- if (saving) return
+ if (save.busy) return
const w = parseFloat(value)
const wErr = weightError(w, settings.weight_unit)
if (wErr) {
@@ -65,21 +73,9 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
return
}
- setSaving(true)
setError('')
setShowDuplicateWarning(false)
- try {
- const log = await weightAPI.log({
- weight: displayToLbs(w, settings.weight_unit),
- notes: notes.trim(),
- logged_at: dayToInstant(date),
- })
- onSuccess(log)
- onClose()
- } catch (err: any) {
- setError(err?.response?.data?.error || 'Failed to save')
- setSaving(false)
- }
+ void save.run(w)
}
return createPortal((
@@ -111,10 +107,10 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
</div>
<form ref={formRef} onSubmit={handleSubmit} className="p-5 space-y-4">
- {error && (
+ {(error || save.error) && (
<div className="alert-error" role="alert" aria-live="polite">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -197,11 +193,11 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,
<button
type="submit"
- disabled={!(parseFloat(value) > 0) || saving}
+ disabled={!(parseFloat(value) > 0) || save.busy}
className="btn-primary btn-lg w-full"
>
<Save className="w-4 h-4" />
- {saving ? 'Saving…' : 'Save'}
+ {save.busy ? 'Saving…' : 'Save'}
</button>
</form>
</div>
diff --git a/web/src/components/ui/ConfirmSheet.test.tsx b/web/src/components/ui/ConfirmSheet.test.tsx
new file mode 100644
index 0000000..40f7025
--- /dev/null
+++ b/web/src/components/ui/ConfirmSheet.test.tsx
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi } from 'vitest'
+import { render, screen, fireEvent } from '@testing-library/react'
+import ConfirmSheet from './ConfirmSheet'
+
+const props = {
+ open: true,
+ title: 'Delete Program?',
+ message: '"PPL" will be permanently deleted.',
+ confirmLabel: 'Delete',
+ destructive: true,
+ onConfirm: vi.fn(),
+ onCancel: vi.fn(),
+}
+
+// The sheet is the only place a failed confirmation has to report itself: the row it came
+// from is still on screen unchanged, so a sheet that dismisses on failure says nothing at
+// all. Everything below is about it staying put long enough to do that.
+describe('ConfirmSheet', () => {
+ it('says what is about to happen and offers both ways out', () => {
+ render(<ConfirmSheet {...props} />)
+ expect(screen.getByRole('alertdialog')).toBeTruthy()
+ expect(screen.getByText('"PPL" will be permanently deleted.')).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Delete' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeTruthy()
+ })
+
+ it('shows why the last confirm failed, without dismissing', () => {
+ render(<ConfirmSheet {...props} error="The server is restarting or unreachable." />)
+ expect(screen.getByRole('alertdialog')).toBeTruthy()
+ expect(screen.getByRole('alert').textContent).toContain('restarting or unreachable')
+ })
+
+ // Both dismissals were live while `busy`. Escape or Cancel mid-delete closed the sheet,
+ // the request carried on, and the 502 landed with nowhere to be shown — the exact
+ // silent failure this component was written to end. Driven in a browser against a
+ // black-holed DELETE before being pinned here.
+ it('refuses Cancel while the confirmed action is in flight', () => {
+ const onCancel = vi.fn()
+ render(<ConfirmSheet {...props} busy onCancel={onCancel} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onCancel).not.toHaveBeenCalled()
+ })
+
+ it('refuses Escape while the confirmed action is in flight', () => {
+ const onCancel = vi.fn()
+ render(<ConfirmSheet {...props} busy onCancel={onCancel} />)
+ fireEvent.keyDown(window, { key: 'Escape' })
+ expect(onCancel).not.toHaveBeenCalled()
+ })
+
+ it('refuses a second confirm while the first is in flight', () => {
+ const onConfirm = vi.fn()
+ render(<ConfirmSheet {...props} busy busyLabel="Deleting…" onConfirm={onConfirm} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Deleting…' }))
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
+ // The counterweight to the three above: refusing dismissal only while in flight, never
+ // after. A sheet that stayed locked once the request settled would be a trap.
+ it('lets go again once the action has settled', () => {
+ const onCancel = vi.fn()
+ render(<ConfirmSheet {...props} error="The server is restarting or unreachable." onCancel={onCancel} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ fireEvent.keyDown(window, { key: 'Escape' })
+ expect(onCancel).toHaveBeenCalledTimes(2)
+ })
+
+ it('renders nothing when closed', () => {
+ const { container } = render(<ConfirmSheet {...props} open={false} />)
+ expect(container.textContent).toBe('')
+ expect(screen.queryByRole('alertdialog')).toBeNull()
+ })
+})
diff --git a/web/src/components/ui/ConfirmSheet.tsx b/web/src/components/ui/ConfirmSheet.tsx
new file mode 100644
index 0000000..641c9d6
--- /dev/null
+++ b/web/src/components/ui/ConfirmSheet.tsx
@@ -0,0 +1,89 @@
+import type { ComponentType } from 'react'
+import { createPortal } from 'react-dom'
+import { AlertCircle } from 'lucide-react'
+import { useEscapeKey } from '../../hooks/useEscapeKey'
+import { useBodyScrollLock } from '../../hooks/useBodyScrollLock'
+
+interface Props {
+ open: boolean
+ title: string
+ /** Body copy under the title — what is about to happen, or what will be lost. */
+ message: string
+ confirmLabel: string
+ /** Confirm label while `busy`. Defaults to the confirm label. */
+ busyLabel?: string
+ cancelLabel?: string
+ /** Red confirm button, for anything that destroys something. */
+ destructive?: boolean
+ /** Small glyph on the confirm button (the page's own verb — a flag, a trash can). */
+ icon?: ComponentType<{ className?: string }>
+ busy?: boolean
+ /** Why the last confirm failed. Keeps the sheet up so the retry is under the same
+ * pointer, instead of dismissing to a banner the user has scrolled away from. */
+ error?: string
+ onConfirm: () => void
+ onCancel: () => void
+}
+
+// The confirmation sheet, once. Seven pages had hand-rolled this same portal — same
+// scrim, same rounded-top panel, same grabber, same Cancel/confirm pair — and they had
+// drifted: some disabled the confirm while busy and some did not, and none of them had
+// anywhere to put an error, so a confirm that failed just closed and left the user
+// looking at an unchanged list.
+//
+// Mirrors mobile's ConfirmSheet prop-for-prop, `error` included, so a fix to how a failed
+// confirmation behaves is one change on each platform rather than eight.
+export default function ConfirmSheet({
+ open, title, message, confirmLabel, busyLabel, cancelLabel = 'Cancel',
+ destructive = false, icon: Icon, busy = false, error, onConfirm, onCancel,
+}: Props) {
+ useBodyScrollLock(open)
+ // Escape dismisses — always the non-destructive choice — but not while the confirmed
+ // action is in flight: dismissing then leaves the request to fail into a sheet that is
+ // no longer there, which is the silent failure this component exists to prevent.
+ useEscapeKey(open && !busy, onCancel)
+ if (!open) return null
+
+ return createPortal(
+ <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
+ <div
+ role="alertdialog"
+ aria-modal="true"
+ aria-label={title}
+ className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6"
+ >
+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
+ <h3 className="font-display font-bold text-lg text-tx-primary mb-1">{title}</h3>
+ <p className="text-sm text-tx-muted mb-5">{message}</p>
+
+ {error && (
+ <div className="alert-error mb-5" role="alert">
+ <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />
+ <span>{error}</span>
+ </div>
+ )}
+
+ <div className="flex gap-3">
+ <button
+ onClick={onCancel}
+ disabled={busy}
+ className="flex-1 py-3 disabled:opacity-50 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm"
+ >
+ {cancelLabel}
+ </button>
+ <button
+ onClick={onConfirm}
+ disabled={busy}
+ className={`flex-1 py-3 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5 ${
+ destructive ? 'bg-error-500 hover:bg-error-600' : 'bg-brand-500 hover:bg-brand-600'
+ }`}
+ >
+ {Icon && <Icon className="w-3.5 h-3.5" />}
+ {busy ? (busyLabel ?? confirmLabel) : confirmLabel}
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body,
+ )
+}
diff --git a/web/src/components/ui/StatFailure.tsx b/web/src/components/ui/StatFailure.tsx
new file mode 100644
index 0000000..44f58b3
--- /dev/null
+++ b/web/src/components/ui/StatFailure.tsx
@@ -0,0 +1,31 @@
+import BarbellBrokenSVG from '../BarbellBrokenSVG'
+
+// A figure that never arrived, in a slot too small to say so in words.
+//
+// The smallest size of the one failure mark. ErrorState draws BARBELL_DROPPED at 64px for
+// a page and 44px for a section, both above a title, a sentence and a retry — which is
+// what anything card-sized or larger should use. A stat tile has none of that room: its
+// value slot is a single line of about 26px. This is the same drawing at that size,
+// standing exactly where the number would have been.
+//
+// So the rule across the app is only about room:
+// tile → this, the mark alone
+// card or chart → ErrorState size="section": mark, sentence, button
+// whole page → ErrorState size="page"
+//
+// What it deliberately does NOT do: say why, or offer a retry. There is no room for
+// either, and a truncated reason is worse than none. It also never renders "0" — a
+// measurement — or a dash, which cannot be told apart from "nothing yet". Its only job is
+// to stop the slot asserting a number it never received; the reason rides on the
+// accessible name, and the section that owns the figure carries the sentence and the way
+// to recover.
+//
+// It repeats when several tiles in a row fail, and that is intended: each tile makes its
+// own claim, so each has to withdraw its own.
+export default function StatFailure({ label = "Couldn't load this figure" }: { label?: string }) {
+ return (
+ <span className="inline-flex items-center" role="img" aria-label={label}>
+ <BarbellBrokenSVG className="w-[26px] h-[26px] text-[color:var(--alert-error)]" />
+ </span>
+ )
+}
diff --git a/web/src/components/ui/index.ts b/web/src/components/ui/index.ts
index c694f96..5ef96a5 100644
--- a/web/src/components/ui/index.ts
+++ b/web/src/components/ui/index.ts
@@ -6,7 +6,9 @@ export { default as SectionHeader } from './SectionHeader'
export { default as PageHeader } from './PageHeader'
export { default as NumberField } from './NumberField'
export { default as StepperTile } from './StepperTile'
+export { default as ConfirmSheet } from './ConfirmSheet'
+export { default as ListError } from './ListError'
+export { default as ErrorState } from './ErrorState'
+export { default as StatFailure } from './StatFailure'
export { default as Toast } from './Toast'
export type { ToastVariant } from './Toast'
-export { default as ErrorState } from './ErrorState'
-export { default as ListError } from './ListError'
diff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsx
index 97b7c8d..c7a1c1f 100644
--- a/web/src/pages/ActiveWorkout.tsx
+++ b/web/src/pages/ActiveWorkout.tsx
@@ -1,16 +1,16 @@
import { useState, useEffect, useRef } from 'react'
-import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router-dom'
import {
Timer, CheckCircle2, Plus, Trash2, X, Dumbbell, Flag,
- AlertCircle, ChevronRight, ChevronLeft, Info,
+ ChevronRight, ChevronLeft, Info,
} from 'lucide-react'
import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore, weightShort, displayToLbs, displayWeight } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import { workoutAPI } from '../services/api'
import { muscleColor } from '../utils/exerciseUtils'
-import { formatElapsed, useElapsedSeconds } from '@lyftr/shared'
+import { formatElapsed, useAsyncAction, useElapsedSeconds } from '@lyftr/shared'
+import { ConfirmSheet } from '../components/ui'
function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {
const [editing, setEditing] = useState(false)
@@ -57,8 +57,6 @@ export default function ActiveWorkout() {
const elapsed = useElapsedSeconds(session?.started_at)
const [confirmCancel, setConfirmCancel] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
- const [saveError, setSaveError] = useState('')
- const [saving, setSaving] = useState(false)
const [activeExIdx, setActiveExIdx] = useState(0)
const cardRefs = useRef<(HTMLDivElement | null)[]>([])
@@ -68,6 +66,16 @@ export default function ActiveWorkout() {
if (settings.workout_layout === 'gym' && session) openGym()
}, [])
+ // The sheet stays open when this fails and shows why: the session is intact and the
+ // server may be reachable again in a moment, so the retry belongs under the same
+ // pointer. It used to dismiss to a banner at the top of a page the user had scrolled.
+ const finish = useAsyncAction(async () => {
+ const saved = await workoutAPI.create(buildPayload())
+ cancelSession()
+ // Surface the routine auto-progression as a toast on the workouts list (#40).
+ navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
+ }, 'Failed to save workout')
+
// Workout elapsed timer
if (!session) {
return (
@@ -82,21 +90,6 @@ export default function ActiveWorkout() {
)
}
- const handleFinish = async () => {
- setSaving(true)
- setSaveError('')
- try {
- const payload = buildPayload()
- const saved = await workoutAPI.create(payload)
- cancelSession()
- // Surface the routine auto-progression as a toast on the workouts list (#40).
- navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
- } catch (err: any) {
- setSaveError(err.response?.data?.error || 'Failed to save workout')
- setSaving(false)
- setConfirmFinish(false)
- }
- }
const handleCompleteSet = (exIdx: number, setIdx: number) => {
completeSet(exIdx, setIdx)
@@ -194,12 +187,6 @@ export default function ActiveWorkout() {
)}
</div>
- {saveError && (
- <div className="alert-error mb-4">
- <AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{saveError}</span>
- </div>
- )}
{/* ── Exercise list ───────────────────────────────────── */}
<>
@@ -447,61 +434,32 @@ export default function ActiveWorkout() {
</>
{/* ── Finish confirm ─────────────────────────────────── */}
- {confirmFinish && createPortal(
- <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Finish Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">
- {completedSets} of {totalSets} sets completed. Workout will be saved.
- </p>
- <div className="flex gap-3">
- <button
- onClick={() => setConfirmFinish(false)}
- className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm"
- >
- Keep Going
- </button>
- <button
- onClick={handleFinish}
- disabled={saving}
- className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5"
- >
- <Flag className="w-3.5 h-3.5" />
- {saving ? 'Saving…' : 'Finish'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
+ <ConfirmSheet
+ open={confirmFinish}
+ icon={Flag}
+ title="Finish Workout?"
+ message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}
+ confirmLabel="Finish"
+ busyLabel="Saving…"
+ cancelLabel="Keep Going"
+ busy={finish.busy}
+ error={finish.error}
+ onConfirm={() => { void finish.run() }}
+ onCancel={() => { setConfirmFinish(false); finish.reset() }}
+ />
{/* ── Cancel confirm ─────────────────────────────────── */}
- {confirmCancel && createPortal(
- <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Cancel Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">All progress will be lost.</p>
- <div className="flex gap-3">
- <button
- onClick={() => setConfirmCancel(false)}
- className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm"
- >
- Keep Going
- </button>
- <button
- onClick={() => { cancelSession(); navigate('/') }}
- className="flex-1 py-3 bg-error-500 hover:bg-error-600 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5"
- >
- <Trash2 className="w-3.5 h-3.5" />
- Cancel
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
+ <ConfirmSheet
+ open={confirmCancel}
+ icon={Trash2}
+ destructive
+ title="Cancel Workout?"
+ message="All progress will be lost."
+ confirmLabel="Cancel"
+ cancelLabel="Keep Going"
+ onConfirm={() => { cancelSession(); navigate('/') }}
+ onCancel={() => setConfirmCancel(false)}
+ />
</div>
)
}
diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsx
index 51656f2..cd0f257 100644
--- a/web/src/pages/AddProgram.tsx
+++ b/web/src/pages/AddProgram.tsx
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
import { ArrowLeft, AlertCircle, BookOpen, FileText, CalendarDays } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'
-import { hasWorkoutExercises, types } from '@lyftr/shared'
+import { useAsyncAction, hasWorkoutExercises, types } from '@lyftr/shared'
import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'
import type { DayDraft } from '../components/programs/types'
@@ -17,41 +17,42 @@ export default function AddProgram() {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
- const [loading, setLoading] = useState(false)
+ // `error` is for what the FORM can tell the user before anything is sent (a missing
+ // name, an empty day). What the SERVER says lives on the hook below — different
+ // questions, kept apart on purpose, and rendered in the same place.
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
- useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
const cacheExercise = (ex: types.Exercise) => setPickerExercises(prev => ({ ...prev, [ex.id]: ex }))
- const handleSubmit = async (e: React.FormEvent) => {
+ const save = useAsyncAction(async () => {
+ const payload = {
+ name: formData.name,
+ notes: formData.notes,
+ days: formData.days.map(d => ({
+ ...d,
+ exercises: d.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ })),
+ })),
+ }
+ await programAPI.create(payload)
+ navigate('/programs')
+ }, 'Failed to create program')
+
+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])
+
+ const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
if (formData.days.length === 0) { setError('Add at least one day'); return }
const hasAnyExercise = hasWorkoutExercises(formData.days)
if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
- setLoading(true)
- try {
- const payload = {
- name: formData.name,
- notes: formData.notes,
- days: formData.days.map(d => ({
- ...d,
- exercises: d.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
- })),
- })),
- }
- await programAPI.create(payload)
- navigate('/programs')
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to create program')
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
@@ -72,10 +73,10 @@ export default function AddProgram() {
</div>
<form onSubmit={handleSubmit} className="space-y-6">
- {error && (
+ {(error || save.error) && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -144,9 +145,9 @@ export default function AddProgram() {
<button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
Cancel
</button>
- <button type="submit" disabled={loading} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
+ <button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
<BookOpen className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Program'}
+ {save.busy ? 'Saving…' : 'Save Program'}
</button>
</div>
</form>
diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsx
index fb780bd..8f1006e 100644
--- a/web/src/pages/AddWorkout.tsx
+++ b/web/src/pages/AddWorkout.tsx
@@ -7,7 +7,7 @@ import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
import ProgramPicker from '../components/ProgramPicker'
import RestPicker from '../components/RestPicker'
-import { types, todayStr, dayToInstant } from '@lyftr/shared'
+import { useAsyncAction, types, todayStr, dayToInstant } from '@lyftr/shared'
interface WorkoutFormData {
name: string
@@ -23,12 +23,13 @@ export default function AddWorkout() {
const wUnit = weightShort(settings.weight_unit)
const [showPicker, setShowPicker] = useState(false)
const [showProgramPicker, setShowProgramPicker] = useState(false)
- const [loading, setLoading] = useState(false)
+ // `error` is for what the FORM can tell the user before anything is sent (a missing
+ // name, an empty day). What the SERVER says lives on the hook below — different
+ // questions, kept apart on purpose, and rendered in the same place.
const [error, setError] = useState('')
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, date: todayStr(), exercises: [] })
- useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
const loadFromProgram = (_program: types.Program, day: types.ProgramDay) => {
const newMap: Record<number, types.Exercise> = { ...pickerExercises }
@@ -83,28 +84,28 @@ export default function AddWorkout() {
})
}
- const handleSubmit = async (e: React.FormEvent) => {
+ const save = useAsyncAction(async () => {
+ const payload = {
+ ...formData,
+ duration: formData.duration * 60,
+ started_at: dayToInstant(formData.date),
+ exercises: formData.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
+ })),
+ }
+ await workoutAPI.create(payload)
+ navigate('/workouts')
+ }, 'Failed to create workout')
+
+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])
+
+ const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Workout name required'); return }
if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
- setLoading(true)
- try {
- const payload = {
- ...formData,
- duration: formData.duration * 60,
- started_at: dayToInstant(formData.date),
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
- })),
- }
- await workoutAPI.create(payload)
- navigate('/workouts')
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to create workout')
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
const selectedIds = formData.exercises.map(e => e.exercise_id)
@@ -124,10 +125,10 @@ export default function AddWorkout() {
</div>
<form onSubmit={handleSubmit} className="space-y-6">
- {error && (
+ {(error || save.error) && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -272,9 +273,9 @@ export default function AddWorkout() {
<button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
Cancel
</button>
- <button type="submit" disabled={loading} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
+ <button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
<Dumbbell className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Workout'}
+ {save.busy ? 'Saving…' : 'Save Workout'}
</button>
</div>
</form>
diff --git a/web/src/pages/ChangePassword.tsx b/web/src/pages/ChangePassword.tsx
index 17049b0..bcdfdbc 100644
--- a/web/src/pages/ChangePassword.tsx
+++ b/web/src/pages/ChangePassword.tsx
@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom'
import { ArrowLeft, AlertCircle, Loader, ShieldCheck } from 'lucide-react'
import { userAPI } from '../services/api'
import { useAuthStore } from '../stores/auth'
-import { apiErrorMessage, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
+import { useAsyncAction, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'
import PageHeader from '../components/ui/PageHeader'
import PasswordField, { Rule } from '../components/ui/PasswordField'
@@ -16,31 +16,25 @@ export default function ChangePassword() {
const [current, setCurrent] = useState('')
const [next, setNext] = useState('')
const [confirm, setConfirm] = useState('')
- const [saving, setSaving] = useState(false)
- const [error, setError] = useState<string | null>(null)
const [done, setDone] = useState(false)
const rules = newPasswordRules({ password: next, confirm, current })
+ const save = useAsyncAction(async () => {
+ await userAPI.changePassword({ current_password: current, new_password: next })
+ setCurrent(''); setNext(''); setConfirm('')
+ setDone(true)
+ }, "Couldn't change your password. Please try again.")
+
const submit = async (e: React.FormEvent) => {
e.preventDefault()
- setError(null)
// The rules above already show these states while typing and the button is disabled
// until they pass, so this is a backstop rather than the primary feedback — a form
// can still be submitted by other means, and the server is the real authority.
if (!rules.ready) return
- setSaving(true)
- try {
- await userAPI.changePassword({ current_password: current, new_password: next })
- setCurrent(''); setNext(''); setConfirm('')
- setDone(true)
- } catch (err) {
- setError(apiErrorMessage(err, "Couldn't change your password. Please try again."))
- } finally {
- setSaving(false)
- }
+ void save.run()
}
// Success replaces the form. Leaving three filled-looking boxes under a success banner
@@ -128,20 +122,20 @@ export default function ChangePassword() {
{/* Server-side failures only — a wrong current password, or a change that landed
elsewhere first. Everything checkable in the browser is a Rule above, so this
box appearing always means the request was actually made and refused. */}
- {error && (
+ {save.error && (
<div className="alert-error">
<AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
+ <span>{save.error}</span>
</div>
)}
<div className="flex gap-2 pt-1">
<button
type="submit"
- disabled={saving || !rules.ready}
+ disabled={save.busy || !rules.ready}
className="btn-primary btn-sm flex-1 flex items-center justify-center gap-2"
>
- {saving ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update password'}
+ {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update password'}
</button>
<Link to="/settings" className="btn-secondary btn-sm flex-1 flex items-center justify-center">
Cancel
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index a7dd08c..ac3ad72 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useMemo } from 'react'
import { format, startOfWeek, isSameDay, eachDayOfInterval, endOfWeek, subWeeks } from 'date-fns'
import {
Dumbbell, Flame, ArrowRight, Beef, BookOpen,
- AlertCircle, Play, Timer, TrendingUp, Scale, Activity, Plus,
+ Play, Timer, TrendingUp, Scale, Activity, Plus,
} from 'lucide-react'
import {
BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell,
@@ -10,13 +10,14 @@ import {
} from 'recharts'
import Loading from '../components/Loading'
import SectionHeader from '../components/ui/SectionHeader'
+import { ErrorState, StatFailure } from '../components/ui'
import PeriodSelector from '../components/PeriodSelector'
import QuickWeighInSheet from '../components/QuickWeighInSheet'
-import { workoutAPI, foodAPI, weightAPI, userAPI, programAPI } from '../services/api'
+import { workoutAPI, foodAPI, weightAPI, programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useAuthStore } from '../stores/auth'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
-import { workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
import { useNavigate, Link } from 'react-router-dom'
import { muscleColor } from '../utils/exerciseUtils'
@@ -24,10 +25,7 @@ const DEFAULT_FOOD: types.DailyStats = {
date: '',
total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,
}
-const DEFAULT_SETTINGS: types.UserSettings = {
- user_id: 0, weight_unit: 'lbs', calorie_target: 2000,
- protein_target: 150, carb_target: 250, fat_target: 65, timezone: 'UTC',
-}
+
function MuscleSparkline({ values, color, isTop }: { values: number[], color: string, isTop: boolean }) {
if (values.length < 2) return <div className="w-14 h-6 flex-shrink-0" />
@@ -79,49 +77,87 @@ export default function Dashboard() {
const navigate = useNavigate()
const { session, startSession } = useWorkoutSession()
const { user } = useAuthStore()
- const { settings: storedSettings } = useSettingsStore()
+ // Settings come from the store, not a page-local fetch. This page used to make
+ // its OWN /settings request with its OWN defaults literal — a third copy of the
+ // fallback the store already owns, and one the store's loadFailed flag could
+ // never see. The store fetch no-ops when already loaded and retries when the
+ // last read fell back, so this costs nothing on the happy path.
+ const { settings, fetch: fetchSettings } = useSettingsStore()
const [workouts, setWorkouts] = useState<types.Workout[]>([])
const [programs, setPrograms] = useState<types.Program[]>([])
const [food, setFood] = useState<types.DailyStats>(DEFAULT_FOOD)
const [weightLogs, setWeightLogs] = useState<types.WeightLog[]>([])
const [weightStats, setWeightStats] = useState<types.WeightStats | null>(null)
- const [settings, setSettings] = useState<types.UserSettings>(storedSettings)
+
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // Bumping this re-runs the load effect. A lifted useCallback would be the tidier
+ // shape, but it would mean restructuring a working effect to gain a retry button;
+ // this does the same job in three lines.
+ const [retryKey, setRetryKey] = useState(0)
const [sheetOpen, setSheetOpen] = useState(false)
+ // The four secondary reads are caught so one dead endpoint cannot blank a working
+ // dashboard — that part is deliberate. What was missing is that they then said nothing:
+ // a 500 from /food/stats substituted DEFAULT_FOOD and rendered today as 0 kcal, which
+ // is what "hasn't eaten yet" looks like. The page stays up; the numbers it never
+ // received read "—", and one marker names what is missing.
+ // Name -> what the server actually said. Keeping the message matters for the two
+ // areas big enough to show one: a card that never loaded can say why, and a generic
+ // sentence there would be us inventing a cause we were handed.
+ const [missing, setMissing] = useState<Record<string, string>>({})
+ const FALLBACK = "The server didn't say what went wrong."
+
+ const foodMissing = "today's food" in missing
+ const weightMissing = 'your weight' in missing
+
const [volumePeriod, setVolumePeriod] = useState<'7' | '14' | '30'>('7')
+ const retry = () => { setLoading(true); setRetryKey(k => k + 1) }
const wUnit = weightShort(settings.weight_unit)
useEffect(() => {
+ void fetchSettings()
+ const absent: Record<string, string> = {}
Promise.all([
workoutAPI.list({ limit: 84 }), // 12 weeks × 7 days max
- programAPI.list({ limit: 100 }).catch(() => []), // backend's max — Up Next must see every program
- foodAPI.stats(format(TODAY, 'yyyy-MM-dd')).catch(() => DEFAULT_FOOD),
- weightAPI.list({ limit: 14 }).catch(() => []),
- weightAPI.stats().catch(() => null),
- userAPI.getSettings().catch(() => DEFAULT_SETTINGS),
+ // backend's max — Up Next must see every program
+ programAPI.list({ limit: 100 })
+ .catch(err => { absent['your programs'] = apiErrorMessage(err, FALLBACK); return [] }),
+ foodAPI.stats(format(TODAY, 'yyyy-MM-dd'))
+ // A 200 carrying the wrong shape never reaches the catch. Unchecked, the missing
+ // field went through Math.round and the ring read "NaN".
+ .then(fs => isDailyStats(fs) ? fs : Promise.reject(new Error('unreadable')))
+ .catch(err => { absent["today's food"] = apiErrorMessage(err, FALLBACK); return DEFAULT_FOOD }),
+ weightAPI.list({ limit: 14 })
+ .catch(err => { absent['your weight'] = apiErrorMessage(err, FALLBACK); return [] }),
+ weightAPI.stats()
+ .catch(err => { absent['your weight'] = apiErrorMessage(err, FALLBACK); return null }),
])
- .then(([ws, ps, fs, wl, wst, s]) => {
+ .then(([ws, ps, fs, wl, wst]) => {
setWorkouts(ws || [])
setPrograms(ps || [])
setFood(fs || DEFAULT_FOOD)
setWeightLogs(wl || [])
setWeightStats(wst)
- setSettings(s || DEFAULT_SETTINGS)
+ setMissing(absent)
})
- .catch(err => setError(err.message || 'Failed to load'))
+ .catch(err => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))
.finally(() => setLoading(false))
- }, [TODAY])
+ }, [TODAY, retryKey, fetchSettings])
if (loading) return <Loading />
+ // The dashboard is nothing but other requests' answers, so when the load fails there
+ // is no honest partial view to show — every tile would read 0, which states "you did
+ // nothing this week" rather than "we could not ask".
if (error) {
return (
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
- </div>
+ <ErrorState
+ size="page"
+ title="Couldn't load your dashboard"
+ message={error}
+ onRetry={() => { setError(null); setLoading(true); setRetryKey(k => k + 1) }}
+ />
)
}
@@ -323,12 +359,16 @@ export default function Dashboard() {
<span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">Cals</span>
<Flame className="w-3 h-3 text-tx-muted" />
</div>
- <p className="text-xl font-bold text-tx-primary leading-none">
- {Math.round(food.total_calories)}
- </p>
- <div className="progress-track">
- <div className="progress-bar" style={{ width: `${calPct}%`, background: '#00b8d9' }} />
- </div>
+ {foodMissing ? (
+ <StatFailure label="Couldn't load today's calories" />
+ ) : (
+ <>
+ <p className="text-xl font-bold text-tx-primary leading-none">{Math.round(food.total_calories)}</p>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${calPct}%`, background: '#00b8d9' }} />
+ </div>
+ </>
+ )}
</div>
<div className="card p-3 flex flex-col gap-1.5">
@@ -336,12 +376,18 @@ export default function Dashboard() {
<span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">Protein</span>
<Beef className="w-3 h-3 text-tx-muted" />
</div>
- <p className="text-xl font-bold text-tx-primary leading-none">
- {Math.round(food.total_protein)}<span className="text-xs text-tx-muted font-normal">g</span>
- </p>
- <div className="progress-track">
- <div className="progress-bar" style={{ width: `${protPct}%`, background: '#f59e0b' }} />
- </div>
+ {foodMissing ? (
+ <StatFailure label="Couldn't load today's protein" />
+ ) : (
+ <>
+ <p className="text-xl font-bold text-tx-primary leading-none">
+ {Math.round(food.total_protein)}<span className="text-xs text-tx-muted font-normal">g</span>
+ </p>
+ <div className="progress-track">
+ <div className="progress-bar" style={{ width: `${protPct}%`, background: '#f59e0b' }} />
+ </div>
+ </>
+ )}
</div>
</div>
@@ -577,6 +623,17 @@ export default function Dashboard() {
</Link>
</div>
+ {foodMissing ? (
+ // The KPI tiles above mirror these numbers with the bare failure mark; the
+ // sentence and the retry belong here, in the section that owns them.
+ <ErrorState
+ size="section"
+ title="Couldn't load today's food"
+ message={missing["today's food"]}
+ onRetry={retry}
+ />
+ ) : (
+ <>
{/* Calorie total */}
<div className="flex items-baseline gap-1.5 mb-3">
<span className="text-3xl font-bold text-tx-primary tabular-nums leading-none">
@@ -611,6 +668,8 @@ export default function Dashboard() {
</div>
))}
</div>
+ </>
+ )}
</div>
</div>
@@ -711,7 +770,17 @@ export default function Dashboard() {
className="mb-2"
/>
- {weightLogs.length === 0 ? (
+ {weightLogs.length === 0 && weightMissing ? (
+ // Not the "log your first weight" prompt: this reader may have years of them.
+ // Card-sized, so it gets the section treatment — mark, sentence and a button —
+ // rather than the bare mark a stat tile has room for.
+ <ErrorState
+ size="section"
+ title="Couldn't load your weight"
+ message={missing['your weight']}
+ onRetry={retry}
+ />
+ ) : weightLogs.length === 0 ? (
<button
type="button"
onClick={() => setSheetOpen(true)}
diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsx
index b5d5682..5cc7c8e 100644
--- a/web/src/pages/EditProgram.tsx
+++ b/web/src/pages/EditProgram.tsx
@@ -3,7 +3,8 @@ import { useNavigate, useParams } from 'react-router-dom'
import { ArrowLeft, AlertCircle, BookOpen, FileText, Dumbbell, CalendarDays } from 'lucide-react'
import { programAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'
-import { hasWorkoutExercises, types } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, hasWorkoutExercises, types } from '@lyftr/shared'
+import { ErrorState } from '../components/ui'
import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'
import type { DayDraft } from '../components/programs/types'
@@ -18,13 +19,19 @@ export default function EditProgram() {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
- const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
+ // `error` is for what the FORM can tell the user before anything is sent (a missing
+ // name, an empty day). What the SERVER says lives on the hook below — different
+ // questions, kept apart on purpose, and rendered in the same place.
const [error, setError] = useState('')
+ // Separate from `error`, which is this form's own validation. A load that never
+ // arrived is not a missing field: there is nothing to edit, and the header would
+ // otherwise assert "0 exercises" about a workout that has several.
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })
- useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
useEffect(() => {
const programId = Number(id)
@@ -55,43 +62,43 @@ export default function EditProgram() {
})),
})
})
- .catch(() => { setError('Failed to load program'); })
+ .catch(err => { setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")); })
.finally(() => setInitialLoading(false))
- }, [id])
+ }, [id, retryKey])
const cacheExercise = (ex: types.Exercise) => setPickerExercises(prev => ({ ...prev, [ex.id]: ex }))
- const handleSubmit = async (e: React.FormEvent) => {
+ const save = useAsyncAction(async () => {
+ const payload = {
+ name: formData.name,
+ notes: formData.notes,
+ // Declares this client round-trips day ids: without it, deleting every
+ // existing day and adding only new (id-less) ones is indistinguishable
+ // from a legacy payload and the server would positionally re-attribute
+ // the deleted days' workout history to the new days.
+ day_ids_known: true,
+ days: formData.days.map(d => ({
+ ...d,
+ exercises: d.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
+ })),
+ })),
+ }
+ await programAPI.update(Number(id), payload)
+ navigate('/programs')
+ }, 'Failed to update program')
+
+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])
+
+ const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Program name required'); return }
if (formData.days.length === 0) { setError('Add at least one day'); return }
const hasAnyExercise = hasWorkoutExercises(formData.days)
if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }
- setLoading(true)
- try {
- const payload = {
- name: formData.name,
- notes: formData.notes,
- // Declares this client round-trips day ids: without it, deleting every
- // existing day and adding only new (id-less) ones is indistinguishable
- // from a legacy payload and the server would positionally re-attribute
- // the deleted days' workout history to the new days.
- day_ids_known: true,
- days: formData.days.map(d => ({
- ...d,
- exercises: d.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, target_weight: displayToLbs(s.target_weight, settings.weight_unit) })),
- })),
- })),
- }
- await programAPI.update(Number(id), payload)
- navigate('/programs')
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to update program')
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
if (initialLoading) {
@@ -102,6 +109,18 @@ export default function EditProgram() {
)
}
+ if (loadError) {
+ return (
+ <ErrorState
+ size="page"
+ title="Couldn't load this program"
+ message={loadError}
+ onRetry={() => { setLoadError(null); setInitialLoading(true); setRetryKey(k => k + 1) }}
+ secondary={<button onClick={() => navigate('/programs')} className="btn-secondary btn-sm">Back to programs</button>}
+ />
+ )
+ }
+
const totalExercises = formData.days.reduce((s, d) => s + d.exercises.length, 0)
const totalSets = formData.days.reduce((s, d) => s + d.exercises.reduce((s2, ex) => s2 + ex.sets.length, 0), 0)
@@ -120,10 +139,10 @@ export default function EditProgram() {
</div>
<form onSubmit={handleSubmit} className="space-y-6">
- {error && (
+ {(error || save.error) && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -180,9 +199,9 @@ export default function EditProgram() {
<button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
Cancel
</button>
- <button type="submit" disabled={loading} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
+ <button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
<BookOpen className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Changes'}
+ {save.busy ? 'Saving…' : 'Save Changes'}
</button>
</div>
</form>
diff --git a/web/src/pages/EditWorkout.tsx b/web/src/pages/EditWorkout.tsx
index f94a12f..cf04bb2 100644
--- a/web/src/pages/EditWorkout.tsx
+++ b/web/src/pages/EditWorkout.tsx
@@ -5,7 +5,8 @@ import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'
import WeightInput from '../components/WeightInput'
import ExercisePicker from '../components/ExercisePicker'
-import { types } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, types } from '@lyftr/shared'
+import { ErrorState } from '../components/ui'
interface WorkoutFormData {
name: string
@@ -20,9 +21,16 @@ export default function EditWorkout() {
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
const [showPicker, setShowPicker] = useState(false)
- const [loading, setLoading] = useState(false)
const [initialLoading, setInitialLoading] = useState(true)
+ // `error` is for what the FORM can tell the user before anything is sent (a missing
+ // name, an empty day). What the SERVER says lives on the hook below — different
+ // questions, kept apart on purpose, and rendered in the same place.
const [error, setError] = useState('')
+ // Separate from `error`, which is this form's own validation. A load that never
+ // arrived is not a missing field: there is nothing to edit, and the header would
+ // otherwise assert "0 exercises" about a workout that has several.
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})
const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, exercises: [] })
const [originalStartedAt, setOriginalStartedAt] = useState('')
@@ -31,7 +39,6 @@ export default function EditWorkout() {
// timestamp would move the workout's day on a rep-count fix made from another zone.
const [originalTZOffset, setOriginalTZOffset] = useState<number | undefined>(undefined)
- useEffect(() => { if (error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error])
useEffect(() => {
const workoutId = Number(id)
@@ -54,9 +61,9 @@ export default function EditWorkout() {
})),
})
})
- .catch(() => setError('Failed to load workout'))
+ .catch(err => setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")))
.finally(() => setInitialLoading(false))
- }, [id])
+ }, [id, retryKey])
const addExercise = (exercise: types.Exercise) => {
setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))
@@ -91,29 +98,29 @@ export default function EditWorkout() {
})
}
- const handleSubmit = async (e: React.FormEvent) => {
+ const save = useAsyncAction(async () => {
+ const payload = {
+ ...formData,
+ duration: formData.duration * 60,
+ started_at: originalStartedAt || new Date().toISOString(),
+ tz_offset_minutes: originalTZOffset,
+ exercises: formData.exercises.map(ex => ({
+ ...ex,
+ sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
+ })),
+ }
+ await workoutAPI.update(Number(id), payload)
+ navigate('/workouts')
+ }, 'Failed to update workout')
+
+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])
+
+ const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!formData.name.trim()) { setError('Workout name required'); return }
if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }
- setLoading(true)
- try {
- const payload = {
- ...formData,
- duration: formData.duration * 60,
- started_at: originalStartedAt || new Date().toISOString(),
- tz_offset_minutes: originalTZOffset,
- exercises: formData.exercises.map(ex => ({
- ...ex,
- sets: ex.sets.map(s => ({ ...s, weight: displayToLbs(s.weight, settings.weight_unit) })),
- })),
- }
- await workoutAPI.update(Number(id), payload)
- navigate('/workouts')
- } catch (err: any) {
- setError(err.response?.data?.error || 'Failed to update workout')
- } finally {
- setLoading(false)
- }
+ setError('')
+ void save.run()
}
if (initialLoading) {
@@ -124,6 +131,18 @@ export default function EditWorkout() {
)
}
+ if (loadError) {
+ return (
+ <ErrorState
+ size="page"
+ title="Couldn't load this workout"
+ message={loadError}
+ onRetry={() => { setLoadError(null); setInitialLoading(true); setRetryKey(k => k + 1) }}
+ secondary={<button onClick={() => navigate('/workouts')} className="btn-secondary btn-sm">Back to workouts</button>}
+ />
+ )
+ }
+
const selectedIds = formData.exercises.map(e => e.exercise_id)
const totalSets = formData.exercises.reduce((sum, ex) => sum + ex.sets.length, 0)
const totalWeight = formData.exercises.reduce((sum, ex) => sum + ex.sets.reduce((s, set) => s + (set.weight || 0), 0), 0)
@@ -140,10 +159,10 @@ export default function EditWorkout() {
</div>
</div>
- {error && (
+ {(error || save.error) && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -264,9 +283,9 @@ export default function EditWorkout() {
<button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">
Cancel
</button>
- <button type="submit" disabled={loading} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
+ <button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2">
<Dumbbell className="w-4 h-4" />
- {loading ? 'Saving…' : 'Save Changes'}
+ {save.busy ? 'Saving…' : 'Save Changes'}
</button>
</div>
</form>
diff --git a/web/src/pages/ExerciseDetail.tsx b/web/src/pages/ExerciseDetail.tsx
index 6a5370a..c0af36b 100644
--- a/web/src/pages/ExerciseDetail.tsx
+++ b/web/src/pages/ExerciseDetail.tsx
@@ -9,7 +9,8 @@ import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore, weightShort, displayWeight } from '../stores/settings'
import { useTheme } from '../hooks/useTheme'
import PeriodSelector from '../components/PeriodSelector'
-import { types } from '@lyftr/shared'
+import { apiErrorMessage, isNotFound, types } from '@lyftr/shared'
+import { ErrorState } from '../components/ui'
import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'
const HISTORY_PERIODS = ['1m', '3m', '6m', 'All'] as const
@@ -45,6 +46,15 @@ export default function ExerciseDetail() {
const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('3m')
const [imgFailed, setImgFailed] = useState(false)
const [loading, setLoading] = useState(true)
+ const [error, setError] = useState<string | null>(null)
+ // A 404 is not a retryable failure: the row is gone, and a Try again button that
+ // cannot ever succeed is worse than no button. Tracked separately from the message
+ // because the message alone cannot say which kind of failure produced it.
+ const [gone, setGone] = useState(false)
+ // Bumping this re-runs the load effect. A lifted useCallback would be the tidier
+ // shape, but it would mean restructuring a working effect to gain a retry button;
+ // this does the same job in three lines.
+ const [retryKey, setRetryKey] = useState(0)
useEffect(() => {
const id = Number(exerciseId)
@@ -66,9 +76,12 @@ export default function ExerciseDetail() {
setPR(prData)
setHistory(histData || [])
})
- .catch(() => navigate(-1))
+ .catch(err => {
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
+ })
.finally(() => setLoading(false))
- }, [exerciseId])
+ }, [exerciseId, retryKey])
const filteredHistory = useMemo(() => {
const days = HISTORY_DAYS[historyPeriod]
@@ -80,6 +93,20 @@ export default function ExerciseDetail() {
const bodyColor = isDark ? '#162240' : '#e2e8f0'
const highlightColors = ['#0e7490', '#22d3ee'] // [secondary=cyan-700, primary=cyan-400]
+ // A dropped connection used to navigate(-1) — off the screen, no explanation, nothing to
+ // retry. Say what happened and leave them where they tapped.
+ if (error) {
+ return (
+ <ErrorState
+ size="page"
+ title="Couldn't load this exercise"
+ message={error}
+ onRetry={gone ? undefined : () => { setError(null); setRetryKey(k => k + 1) }}
+ secondary={<button onClick={() => navigate(-1)} className="btn-secondary btn-sm">Go back</button>}
+ />
+ )
+ }
+
if (loading || !exercise) {
return (
<div className="flex items-center justify-center py-20">
diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsx
index 6f3e2c1..c72f102 100644
--- a/web/src/pages/Food.tsx
+++ b/web/src/pages/Food.tsx
@@ -13,8 +13,10 @@ import {
} from 'recharts'
import Loading from '../components/Loading'
import PeriodSelector from '../components/PeriodSelector'
-import { foodAPI, userAPI } from '../services/api'
-import { todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay } from '@lyftr/shared'
+import { foodAPI } from '../services/api'
+import { useSettingsStore } from '../stores/settings'
+import { apiErrorMessage, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay } from '@lyftr/shared'
+import { ErrorState } from '../components/ui'
const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const
const MEAL_LABELS: Record<string, string> = {
@@ -70,9 +72,22 @@ export default function Food() {
const [selectedDate, setSelectedDate] = useState(todayStr())
const [logs, setLogs] = useState<types.FoodLog[]>([])
const [stats, setStats] = useState<types.DailyStats | null>(null)
- const [settings, setSettings] = useState<types.UserSettings | null>(null)
+ // The day's entries are the primary read and already fail the page. These two are
+ // caught so one of them cannot blank a working day — but caught silently they
+ // substituted zeros and an empty chart, which is what "ate nothing" looks like.
+ // Name -> what the server said, for the areas with room to show it.
+ const [missing, setMissing] = useState<Record<string, string>>({})
+ const [historyKey, setHistoryKey] = useState(0)
+ // From the store, not a page-local fetch: this page carried a fourth copy of the
+ // fallback settings literal, invisible to the store's loadFailed flag. The store
+ // fetch no-ops when loaded and retries when the last read fell back.
+ const { settings, fetch: fetchSettings } = useSettingsStore()
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // Separate from `error`, which reports a failed action (a delete) while the day's
+ // data is still on screen. This one means the day itself never arrived, so there is
+ // no ring, no total and no meal list worth drawing.
+ const [loadError, setLoadError] = useState<string | null>(null)
const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('30d')
const [historyData, setHistoryData] = useState<types.FoodHistoryPoint[]>([])
@@ -88,42 +103,66 @@ export default function Food() {
setLogs([])
setStats(null)
setError(null)
+ setLoadError(null)
try {
const defaultStats: types.DailyStats = {
date, total_calories: 0, total_protein: 0, total_carbs: 0,
total_fat: 0, total_fiber: 0, workout_count: 0,
}
- const [logData, statsData, settingsData] = await Promise.all([
+ let statsFailed = false
+ let statsMessage = ''
+ const [logData, statsData] = await Promise.all([
foodAPI.list(date),
- foodAPI.stats(date).catch(() => defaultStats),
- settings
- ? Promise.resolve(settings)
- : userAPI.getSettings().catch(() => ({
- user_id: 0, weight_unit: 'lbs' as const,
- calorie_target: 2000, protein_target: 150, carb_target: 250, fat_target: 65,
- })),
+ foodAPI.stats(date)
+ // Same as the dashboard: a readable 200 is the only kind that counts as data.
+ // Unchecked this rendered 0 kcal, which is what "hasn't eaten yet" looks like.
+ .then(st => isDailyStats(st) ? st : Promise.reject(new Error('unreadable')))
+ .catch(err => {
+ statsFailed = true
+ statsMessage = apiErrorMessage(err, "The server didn't say what went wrong.")
+ return defaultStats
+ }),
])
setLogs(logData || [])
setStats(statsData)
- if (!settings) setSettings(settingsData as types.UserSettings)
+ setMissing(m => {
+ const next = { ...m }
+ if (statsFailed) next["today's totals"] = statsMessage
+ else delete next["today's totals"]
+ return next
+ })
} catch (err: any) {
- setError(err.message || 'Failed to load food data')
+ setLoadError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
hasLoadedRef.current = true
setLoading(false)
}
- }, [settings])
+ }, [])
+ useEffect(() => { void fetchSettings() }, [fetchSettings])
useEffect(() => { loadDay(selectedDate) }, [selectedDate, location.key, loadDay])
useEffect(() => {
+ // Same race as the weight trend: 90d is a slower query than 7d, so without this a
+ // stale wide answer can overwrite the narrow one the user just asked for.
+ let cancelled = false
setHistoryLoading(true)
const days = historyPeriod === '7d' ? 7 : historyPeriod === '30d' ? 30 : 90
foodAPI.history(days)
- .then(data => setHistoryData(data || []))
- .catch(() => {})
- .finally(() => setHistoryLoading(false))
- }, [historyPeriod])
+ .then(data => {
+ if (cancelled) return
+ setHistoryData(data || [])
+ setMissing(m => { const next = { ...m }; delete next['your history']; return next })
+ })
+ .catch(err => {
+ if (cancelled) return
+ setMissing(m => ({
+ ...m, 'your history': apiErrorMessage(err, "The server didn't say what went wrong."),
+ }))
+ })
+ .finally(() => { if (!cancelled) setHistoryLoading(false) })
+ return () => { cancelled = true }
+ }, [historyPeriod, historyKey])
const openLog = (meal: types.FoodLog['meal']) => {
navigate(`/food/log?meal=${meal}&date=${selectedDate}`)
@@ -136,8 +175,8 @@ export default function Food() {
setLogs(prev => prev.filter(l => l.id !== id))
setDeleteConfirmId(null)
foodAPI.stats(selectedDate).then(setStats).catch(() => {})
- } catch {
- setError('Failed to delete entry')
+ } catch (err) {
+ setError(apiErrorMessage(err, "Couldn't delete that entry."))
} finally {
setDeletingId(null)
}
@@ -145,7 +184,25 @@ export default function Food() {
if (loading && !hasLoadedRef.current) return <Loading />
+ // Rings at 0 kcal and four empty meal sections say "you have eaten nothing today".
+ // That is a different sentence from "we could not ask", and only one of them is true.
+ if (loadError) {
+ return (
+ <div className="space-y-4 animate-slide-up">
+ <PageHeader title="Nutrition" subtitle="Macros & meals" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your food log"
+ message={loadError}
+ onRetry={() => loadDay(selectedDate)}
+ />
+ </div>
+ )
+ }
+
const s = stats
+ const statsMissing = "today's totals" in missing
+ const historyMissing = 'your history' in missing
const totalCals = s?.total_calories ?? 0
const calTarget = settings?.calorie_target ?? 2000
const remaining = calTarget - totalCals
@@ -220,7 +277,19 @@ export default function Food() {
</div>
{/* Macro summary card */}
- {settings && (
+ {settings && statsMissing && (
+ // The totals are this card's entire content, so the failure is stated here
+ // rather than as a dash with its explanation somewhere else on the page.
+ <div className="card p-5">
+ <ErrorState
+ size="section"
+ title="Couldn't load today's totals"
+ message="Something went wrong on our end."
+ onRetry={() => void loadDay(selectedDate)}
+ />
+ </div>
+ )}
+ {settings && !statsMissing && (
<div className="card p-5 space-y-5">
{/* Calorie hero */}
<div className="flex items-center justify-between">
@@ -399,8 +468,22 @@ export default function Food() {
<div className="flex items-center justify-center h-48 text-xs text-tx-muted">Loading…</div>
) : historyData.length === 0 ? (
<div className="flex flex-col items-center justify-center h-48 gap-2">
- <CalendarDays className="w-8 h-8 text-tx-muted opacity-40" />
- <p className="text-xs text-tx-muted">No data yet — start logging meals</p>
+ {historyMissing ? (
+ // Chart-sized, so it gets the section treatment. The calendar belongs to
+ // the empty state below, not here — stacked above this it read as two
+ // unrelated icons for one condition.
+ <ErrorState
+ size="section"
+ title="Couldn't load your history"
+ message={missing['your history']}
+ onRetry={() => setHistoryKey(k => k + 1)}
+ />
+ ) : (
+ <>
+ <CalendarDays className="w-8 h-8 text-tx-muted opacity-40" />
+ <p className="text-xs text-tx-muted">No data yet — start logging meals</p>
+ </>
+ )}
</div>
) : (
<ResponsiveContainer width="100%" height={220}>
diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsx
index 83f404b..e30fbf1 100644
--- a/web/src/pages/GymModeWorkout.tsx
+++ b/web/src/pages/GymModeWorkout.tsx
@@ -1,12 +1,11 @@
import { useState, useEffect, useRef } from 'react'
-import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router-dom'
import {
CheckCircle2, Plus, X, Dumbbell, Flag, ChevronRight, ChevronLeft, Play,
Minimize2, Trash2, Repeat, Check, Layers, Timer,
} from 'lucide-react'
import Model, { IExerciseData } from 'react-body-highlighter'
-import { types, PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange } from '@lyftr/shared'
+import { useAsyncAction, types, PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange } from '@lyftr/shared'
import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'
import { useTheme } from '../hooks/useTheme'
import { useWorkoutSession } from '../stores/workoutSession'
@@ -16,7 +15,7 @@ import RestTimerBanner from '../components/RestTimerBanner'
import { workoutAPI } from '../services/api'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
-import DiscardConfirm from '../components/DiscardConfirm'
+import { ConfirmSheet } from '../components/ui'
import { displayWeight, displayToLbs } from '../stores/settings'
function buildBodyData(exercise: types.Exercise): IExerciseData[] {
@@ -75,8 +74,6 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
const [imgFailed, setImgFailed] = useState(false)
const [confirmFinish, setConfirmFinish] = useState(false)
const [confirmCancel, setConfirmCancel] = useState(false)
- const [saving, setSaving] = useState(false)
- const [saveError, setSaveError] = useState('')
const setPhase = (p: typeof phase) => setGymState(p, activeIdx, activeSetIdx)
const onSetActiveIdx = (i: number) => setGymState(phase, i, 0)
@@ -95,24 +92,19 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
prevLenRef.current = exerciseCount
}, [exerciseCount])
+ // This used to set the message and then dismiss the sheet that displays it, so the
+ // explanation was rendered nowhere and a failed finish looked like a dead button.
+ // The sheet stays open now; the session is intact and the retry is one tap away.
+ const finish = useAsyncAction(async () => {
+ const saved = await workoutAPI.create(buildPayload())
+ cancelSession()
+ minimizeGym()
+ // Surface the routine auto-progression as a toast on the workouts list (#40).
+ navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
+ }, 'Failed to save workout')
+
if (!session) return null
- const handleFinish = async () => {
- setSaving(true)
- setSaveError('')
- try {
- const payload = buildPayload()
- const saved = await workoutAPI.create(payload)
- cancelSession()
- minimizeGym()
- // Surface the routine auto-progression as a toast on the workouts list (#40).
- navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)
- } catch (err: any) {
- setSaveError(err.response?.data?.error || 'Failed to save workout')
- setSaving(false)
- setConfirmFinish(false)
- }
- }
const handleMinimize = () => {
minimizeGym()
@@ -187,6 +179,38 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
)
}
+ // The two confirms, declared once. Each phase below returns its own tree, and all
+ // three ended with a byte-identical copy of this pair — nothing in it varies by
+ // phase, so it was three places to forget the same change.
+ const confirms = (
+ <>
+ <ConfirmSheet
+ open={confirmFinish}
+ icon={Flag}
+ title="Finish Workout?"
+ message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}
+ confirmLabel="Finish"
+ busyLabel="Saving…"
+ cancelLabel="Keep Going"
+ busy={finish.busy}
+ error={finish.error}
+ onConfirm={() => { void finish.run() }}
+ onCancel={() => { setConfirmFinish(false); finish.reset() }}
+ />
+ <ConfirmSheet
+ open={confirmCancel}
+ icon={Trash2}
+ destructive
+ title="Discard workout?"
+ message="This ends the workout without saving — all progress is lost."
+ confirmLabel="Discard"
+ cancelLabel="Keep Going"
+ onConfirm={() => { cancelSession(); handleMinimize() }}
+ onCancel={() => setConfirmCancel(false)}
+ />
+ </>
+ )
+
// ── Overview ──────────────────────────────────────────────────────────
if (phase === 'overview') {
return (
@@ -287,24 +311,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
)}
</div>
- {confirmFinish && createPortal(
- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Finish Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
- {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
- <div className="flex gap-3">
- <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>
- <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Flag className="w-3.5 h-3.5" />{saving ? 'Saving…' : 'Finish'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
- <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} />
+ {confirms}
</div>
)
}
@@ -461,24 +468,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
</button>
</div>
- {confirmFinish && createPortal(
- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Finish Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
- {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
- <div className="flex gap-3">
- <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">Keep Going</button>
- <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Flag className="w-3.5 h-3.5" />{saving ? 'Saving…' : 'Finish'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
- <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} />
+ {confirms}
</div>
)
}
@@ -744,30 +734,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {
content up instead of covering it. Renders null when no rest is active. */}
<RestTimerBanner docked />
- {/* ── Finish confirm ── */}
- {confirmFinish && createPortal(
- <div className="fixed inset-0 bg-black/60 z-[70] flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Finish Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">{completedSets} of {totalSets} sets completed. Workout will be saved.</p>
- {saveError && <p className="text-xs text-error-400 mb-3">{saveError}</p>}
- <div className="flex gap-3">
- <button onClick={() => setConfirmFinish(false)} disabled={saving} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 disabled:opacity-50 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
- Keep Going
- </button>
- <button onClick={handleFinish} disabled={saving} className="flex-1 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Flag className="w-3.5 h-3.5" />
- {saving ? 'Saving…' : 'Finish'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
-
- {/* ── Cancel confirm ── */}
- <DiscardConfirm open={confirmCancel} onKeep={() => setConfirmCancel(false)} onDiscard={() => { cancelSession(); handleMinimize() }} />
+ {confirms}
</div>
)
}
diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsx
index f11f9a1..e112cba 100644
--- a/web/src/pages/LogFood.tsx
+++ b/web/src/pages/LogFood.tsx
@@ -6,7 +6,8 @@ import {
Coffee, Sun, Moon, Cookie, ChevronRight,
} from 'lucide-react'
import { foodAPI, savedFoodsAPI } from '../services/api'
-import { todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, apiErrorMessage, findSavedFood } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, todayStr, dayToInstant, entryDay, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, findSavedFood } from '@lyftr/shared'
+import { ErrorState, ListError } from '../components/ui'
import BarcodeScanner from '../components/BarcodeScanner'
import IconButton from '../components/ui/IconButton'
import SegmentedControl from '../components/ui/SegmentedControl'
@@ -130,6 +131,12 @@ export default function LogFood() {
const [searchResults, setSearchResults] = useState<types.FoodSearchResult[]>([])
const [recentItems, setRecentItems] = useState<types.FoodSearchResult[]>([])
const [savedFoods, setSavedFoods] = useState<types.SavedFood[]>([])
+ // Each list's own failure. Kept separate from the page: one of these failing is not a
+ // reason to withhold search, and an empty list that failed to load must not draw the
+ // same "nothing here" as a list that really is empty.
+ const [recentError, setRecentError] = useState<string | null>(null)
+ const [savedError, setSavedError] = useState<string | null>(null)
+ const [listReload, setListReload] = useState(0)
const [searching, setSearching] = useState(false)
const [searchError, setSearchError] = useState<string | null>(null)
const [rateLimited, setRateLimited] = useState(false)
@@ -138,8 +145,6 @@ export default function LogFood() {
const [servings, setServings] = useState(1)
const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)
const [date, setDate] = useState(initDate)
- const [saving, setSaving] = useState(false)
- const [saveError, setSaveError] = useState<string | null>(null)
// Derived from the list rather than tracked, so a star clicked on any tab is reflected
// everywhere the same food appears — including the detail view.
@@ -201,6 +206,8 @@ export default function LogFood() {
const [togglingFavorite, setTogglingFavorite] = useState<Set<string>>(new Set())
const [favoriteError, setFavoriteError] = useState<string | null>(null)
+ const [editError, setEditError] = useState<string | null>(null)
+ const [editRetry, setEditRetry] = useState(0)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const searchInputRef = useRef<HTMLInputElement>(null)
@@ -213,8 +220,8 @@ export default function LogFood() {
setMeal(entry.meal)
setDate(entryDay(entry))
setPhase('detail')
- }).catch(() => navigate('/food', { replace: true }))
- }, [editId, navigate])
+ }).catch(err => setEditError(apiErrorMessage(err, "The server didn't say what went wrong.")))
+ }, [editId, navigate, editRetry])
useEffect(() => {
foodAPI.list(todayStr()).then(logs => {
@@ -229,9 +236,12 @@ export default function LogFood() {
}
}
setRecentItems(items)
- }).catch(() => {})
- savedFoodsAPI.list().then(setSavedFoods).catch(() => {})
- }, [])
+ setRecentError(null)
+ }).catch(err => setRecentError(apiErrorMessage(err, "Couldn't load what you logged today.")))
+ savedFoodsAPI.list()
+ .then(list => { setSavedFoods(list); setSavedError(null) })
+ .catch(err => setSavedError(apiErrorMessage(err, "Couldn't load your favourites.")))
+ }, [listReload])
useEffect(() => {
if (tab !== 'all') return
@@ -273,26 +283,23 @@ export default function LogFood() {
}
}
+ const save = useAsyncAction(async (item: types.FoodSearchResult) => {
+ const payload = {
+ ...scaleServing(item, servings),
+ meal,
+ logged_at: dayToInstant(date),
+ }
+ if (editId) {
+ await foodAPI.update(editId, payload)
+ } else {
+ await foodAPI.log(payload)
+ }
+ navigate('/food', { replace: true })
+ }, 'Failed to save')
+
const handleLog = async () => {
- if (!selected || saving) return
- setSaving(true)
- setSaveError(null)
- try {
- const payload = {
- ...scaleServing(selected, servings),
- meal,
- logged_at: dayToInstant(date),
- }
- if (editId) {
- await foodAPI.update(editId, payload)
- } else {
- await foodAPI.log(payload)
- }
- navigate('/food', { replace: true })
- } catch (err: any) {
- setSaveError(err?.response?.data?.error || 'Failed to save')
- setSaving(false)
- }
+ if (!selected || save.busy) return
+ void save.run(selected)
}
if (phase === 'scan') {
@@ -304,6 +311,20 @@ export default function LogFood() {
)
}
+ // The route exists to edit ONE entry; if that entry never arrived there is nothing
+ // to show but the search screen, which answers a question the user did not ask.
+ if (editId && editError) {
+ return (
+ <ErrorState
+ size="page"
+ title="Couldn't load this entry"
+ message={editError}
+ onRetry={() => { setEditError(null); setEditRetry(k => k + 1) }}
+ secondary={<button onClick={() => navigate('/food')} className="btn-secondary btn-sm">Back to food</button>}
+ />
+ )
+ }
+
const cal = selected ? Math.round(selected.calories * servings) : 0
const pro = selected ? +(selected.protein * servings).toFixed(1) : 0
const carb = selected ? +(selected.carbs * servings).toFixed(1) : 0
@@ -443,7 +464,9 @@ export default function LogFood() {
)}
{tab === 'recent' && (
- recentItems.length === 0
+ recentError
+ ? <ListError subject="what you logged today" message={recentError} onRetry={() => { setRecentError(null); setListReload(n => n + 1) }} />
+ : recentItems.length === 0
? (
<div className="px-4 py-14 text-center">
<Utensils className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />
@@ -464,7 +487,9 @@ export default function LogFood() {
)}
{tab === 'myfoods' && (
- savedFoods.length === 0
+ savedError
+ ? <ListError subject="your favourites" message={savedError} onRetry={() => { setSavedError(null); setListReload(n => n + 1) }} />
+ : savedFoods.length === 0
? (
<div className="px-4 py-14 text-center">
<Star className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />
@@ -525,10 +550,10 @@ export default function LogFood() {
{/* Detail phase */}
{phase === 'detail' && selected && (
<div className="space-y-4 pb-32">
- {saveError && (
+ {save.error && (
<div className="alert-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{saveError}</span>
+ <span>{save.error}</span>
</div>
)}
@@ -558,7 +583,11 @@ export default function LogFood() {
</div>
{selected.serving_size && (
<p className="text-xs text-tx-muted mt-1">
- per {servings === 1 ? '' : `${servings} × `}{selected.serving_size}
+ {/* The label comes from OpenFoodFacts, which is free text — and rows
+ logged before the backend stopped prefixing it still read "per
+ 100g". Supplying a second "per" gave "per per 100g". */}
+ per {servings === 1 ? '' : `${servings} × `}
+ {selected.serving_size.replace(/^per\s+/i, '')}
</p>
)}
</div>
@@ -665,10 +694,10 @@ export default function LogFood() {
<div className="fixed bottom-0 inset-x-0 p-4 bg-surface-base/95 backdrop-blur-sm border-t border-surface-border safe-area-bottom">
<button
onClick={handleLog}
- disabled={saving}
+ disabled={save.busy}
className="btn-primary btn-lg w-full"
>
- {saving ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}
+ {save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}
</button>
</div>
)}
diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsx
index 97c9b72..1fc93ca 100644
--- a/web/src/pages/Login.tsx
+++ b/web/src/pages/Login.tsx
@@ -39,7 +39,7 @@ export default function Login() {
await login('[email protected]', 'password123')
navigate('/')
} catch (err: any) {
- setError(apiErrorMessage(err, 'Demo login failed'))
+ setError(apiErrorMessage(err, "Couldn't sign in to the demo account."))
} finally {
setLoading(false)
}
diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsx
index 5c654d09..b116878 100644
--- a/web/src/pages/ProgramDetail.tsx
+++ b/web/src/pages/ProgramDetail.tsx
@@ -1,5 +1,5 @@
+import { ConfirmSheet, ErrorState } from '../components/ui'
import { useState, useEffect } from 'react'
-import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { format } from 'date-fns'
import {
@@ -9,7 +9,7 @@ import {
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { useSettingsStore, weightShort, displayWeight } from '../stores/settings'
-import { types, allExercises, activeSessionExercisesForDay, dayLabel, sessionNameForDay, targetWeightLabel, restLabel } from '@lyftr/shared'
+import { apiErrorMessage, isNotFound, useAsyncAction, types, allExercises, activeSessionExercisesForDay, dayLabel, sessionNameForDay, targetWeightLabel, restLabel } from '@lyftr/shared'
import { muscleColor } from '../utils/exerciseUtils'
// Rows shown before the review banner collapses behind a "Show all" toggle (#40).
@@ -25,9 +25,19 @@ export default function ProgramDetail() {
const [program, setProgram] = useState<types.Program | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // A 404 is not a retryable failure: the row is gone, and a Try again button that
+ // cannot ever succeed is worse than no button. Tracked separately from the message
+ // because the message alone cannot say which kind of failure produced it.
+ const [gone, setGone] = useState(false)
+ // Bumping this re-runs the load effect. A lifted useCallback would be the tidier
+ // shape, but it would mean restructuring a working effect on five pages to gain a
+ // retry button; this does the same job in three lines.
+ const [retryKey, setRetryKey] = useState(0)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
const [resolving, setResolving] = useState(false)
+ // Separate from `error`, which replaces the whole page: a failed resolve must leave the
+ // program on screen so the same buttons are still under the finger to retry.
+ const [resolveError, setResolveError] = useState<string | null>(null)
const [showAllSuggestions, setShowAllSuggestions] = useState(false)
const [selectedDayIdx, setSelectedDayIdx] = useState(0)
@@ -36,11 +46,12 @@ export default function ProgramDetail() {
const resolveSuggestions = async (accept: number[], dismiss: number[]) => {
if (!program || resolving) return
setResolving(true)
+ setResolveError(null)
try {
const updated = await programAPI.resolveSuggestions(program.id, { accept, dismiss })
setProgram(updated)
- } catch {
- /* leave the banner in place so the user can retry */
+ } catch (err) {
+ setResolveError(apiErrorMessage(err, "Couldn't save those targets."))
} finally {
setResolving(false)
}
@@ -53,13 +64,14 @@ export default function ProgramDetail() {
setProgram(data)
setSelectedDayIdx(data.current_day_index || 0)
} catch (err: any) {
- setError(err.message || 'Failed to load program')
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
setLoading(false)
}
}
load()
- }, [id])
+ }, [id, retryKey])
const days = program?.days ?? []
const selectedDay = days[selectedDayIdx]
@@ -72,17 +84,14 @@ export default function ProgramDetail() {
navigate('/workout/active')
}
- const handleDelete = async () => {
+ // Was `catch { setDeleting(false); setConfirming(false) }` — the confirm quietly
+ // closed and the user was left guessing whether the tap had registered. It stays
+ // up now and says why.
+ const remove = useAsyncAction(async () => {
if (!program) return
- setDeleting(true)
- try {
- await programAPI.delete(program.id)
- navigate('/programs', { replace: true })
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ await programAPI.delete(program.id)
+ navigate('/programs', { replace: true })
+ }, 'Failed to delete program')
if (loading) {
return (
@@ -94,15 +103,13 @@ export default function ProgramDetail() {
if (error || !program) {
return (
- <div className="space-y-4">
- <Link to="/programs" className="flex items-center gap-2 text-sm text-tx-muted hover:text-tx-primary transition-colors">
- <ArrowLeft className="w-4 h-4" /> Back
- </Link>
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error || 'Program not found'}</span>
- </div>
- </div>
+ <ErrorState
+ size="page"
+ title="Couldn't load this program"
+ message={error ?? 'That program no longer exists.'}
+ onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}
+ secondary={<Link to="/programs" className="btn-secondary btn-sm">Back to programs</Link>}
+ />
)
}
@@ -179,25 +186,19 @@ export default function ProgramDetail() {
</div>
{/* Delete confirm — bottom sheet */}
- {confirming && createPortal(
- <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Program?</h3>
- <p className="text-sm text-tx-muted mb-5">"{program.name}" will be permanently deleted.</p>
- <div className="flex gap-3">
- <button onClick={() => setConfirming(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
- Cancel
- </button>
- <button onClick={handleDelete} disabled={deleting} className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Trash2 className="w-3.5 h-3.5" />
- {deleting ? 'Deleting…' : 'Delete'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
+ <ConfirmSheet
+ open={confirming}
+ icon={Trash2}
+ destructive
+ title="Delete Program?"
+ message={`"${program.name}" will be permanently deleted.`}
+ confirmLabel="Delete"
+ busyLabel="Deleting…"
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
+ />
{/* Auto-progression review banner (#40) — approve the targets you beat last workout */}
{suggestions.length > 0 && (
@@ -250,6 +251,12 @@ export default function ProgramDetail() {
: <>Show all {suggestions.length} <ChevronDown className="w-3.5 h-3.5" /></>}
</button>
)}
+ {resolveError && (
+ <div className="flex items-start gap-2 px-4 py-2.5 border-t border-surface-border/60 text-sm text-error-400">
+ <AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />
+ <span className="flex-1">{resolveError}</span>
+ </div>
+ )}
<div className="flex gap-2 px-4 py-3 border-t border-surface-border/60">
<button
onClick={() => resolveSuggestions([], suggestedSetIds)}
diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsx
index e578737..473c1fc 100644
--- a/web/src/pages/Programs.tsx
+++ b/web/src/pages/Programs.tsx
@@ -6,9 +6,10 @@ import { useNavigate } from 'react-router-dom'
import Loading from '../components/Loading'
import PageHeader from '../components/ui/PageHeader'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
+import { ErrorState, ListError } from '../components/ui'
import { programAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
-import { types } from '@lyftr/shared'
+import { useAsyncAction, types } from '@lyftr/shared'
import {
todaysDay, dayLabel, isDayStartable, programExerciseCount, programSetCount, sessionNameForDay,
@@ -56,18 +57,14 @@ function ProgramCard({
navigate('/workout/active')
}
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await programAPI.delete(program.id)
- onDelete(program.id)
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // Was `catch { setDeleting(false); setConfirming(false) }` — the card quietly came
+ // back and the user was left guessing whether the tap had registered. The confirm
+ // stays up now and says why, which is the same rule the sheets follow.
+ const remove = useAsyncAction(async () => {
+ await programAPI.delete(program.id)
+ onDelete(program.id)
+ }, 'Failed to delete program')
if (confirming) {
return (
@@ -80,6 +77,7 @@ function ProgramCard({
<div>
<p className="text-sm font-semibold text-tx-primary">Delete "{program.name}"?</p>
<p className="text-xs text-tx-muted">This cannot be undone</p>
+ {remove.error && <p className="text-xs text-error-400 mt-1">{remove.error}</p>}
</div>
</div>
<div className="flex items-center gap-2">
@@ -90,12 +88,12 @@ function ProgramCard({
Cancel
</button>
<button
- onClick={handleDelete}
- disabled={deleting}
+ onClick={() => { void remove.run() }}
+ disabled={remove.busy}
className="px-3 py-1.5 text-xs bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-lg transition-colors font-medium flex items-center gap-1"
>
<Trash2 className="w-3 h-3" />
- {deleting ? 'Deleting…' : 'Delete'}
+ {remove.busy ? 'Deleting…' : 'Delete'}
</button>
</div>
</div>
@@ -249,13 +247,52 @@ export default function Programs() {
return () => clearTimeout(t)
}, [search])
- const { items: programs, sentinelRef, hasMore, loading, initialLoading, reload } = useServerInfiniteList<types.Program>({
+ const {
+ items: programs, sentinelRef, hasMore, loading, initialLoading, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<types.Program>({
fetcher: (offset, limit) => programAPI.list({ offset, limit, q: debouncedSearch || undefined }),
deps: [debouncedSearch],
})
if (initialLoading) return <Loading />
+ // Everything on this page is downstream of one request, so when it fails with nothing
+ // on screen the page failed — not a section of it. A section-sized error stranded among
+ // empty tiles and a search box that filters nothing is three dead regions and a note;
+ // one page-level error is the same information said once. The section-scoped ListError
+ // below stays for the case it is actually for: a later page failing under rows that
+ // did arrive.
+ if (listError && programs.length === 0) {
+ return (
+ <div className="space-y-5 animate-slide-up">
+ <PageHeader title="Programs" subtitle="Reusable workout templates" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your programs"
+ message={listError}
+ onRetry={retryList}
+ />
+ </div>
+ )
+ }
+
+ // Three separate claims these tiles used to make without having the numbers.
+ //
+ // `programs` is one page of an infinite list, so its length is what has loaded, not how
+ // many exist: with 25 programs on the server the Total tile read "20 programs" on a
+ // perfectly healthy connection. While more pages remain it is a lower bound, and says so.
+ //
+ // A failed read leaves the list empty too, and 0 then means "we never heard back"
+ // rather than "you have none" — indistinguishable from the empty account below it.
+ // No failure branch here on purpose: the early return above fires on exactly
+ // "listError and nothing loaded", so by this point either rows arrived or the page is
+ // already showing its own error. A tile-level failure state would be unreachable.
+ const totalLabel = hasMore ? `${programs.length}+` : programs.length.toString()
+ const avgLabel = programs.length === 0
+ ? '—'
+ : Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length).toString()
+
return (
<div className="space-y-5 animate-slide-up">
<PageHeader
@@ -270,8 +307,8 @@ export default function Programs() {
<div className="grid grid-cols-2 gap-3">
{[
- { label: 'Total', value: programs.length.toString(), unit: 'programs', icon: BookOpen },
- { label: 'Avg Exercises', value: programs.length > 0 ? Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length).toString() : '0', unit: 'per program', icon: Dumbbell },
+ { label: 'Total', value: totalLabel, unit: 'programs', icon: BookOpen },
+ { label: 'Avg Exercises', value: avgLabel, unit: 'per program', icon: Dumbbell },
].map(s => (
<div key={s.label} className="card p-4">
<div className="flex items-center gap-1.5 mb-2">
@@ -297,6 +334,8 @@ export default function Programs() {
<div className="space-y-2">
{programs.length === 0 && !loading ? (
+ // A failed first page never reaches here — the early return above renders it —
+ // so an empty list at this point really is empty.
<div className="empty-state">
<div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4">
<BookOpen className="w-6 h-6 text-tx-muted" />
@@ -315,6 +354,7 @@ export default function Programs() {
/>
))}
<div ref={sentinelRef} />
+ {listError && <ListError subject="your programs" message={listError} onRetry={retryList} />}
{hasMore && loading && (
<p className="text-center text-xs text-tx-muted py-2">Loading more…</p>
)}
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 55e1e53..9be14b3 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -1,12 +1,14 @@
import { useState, useEffect, useCallback } from 'react'
-import { memberSince } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, memberSince } from '@lyftr/shared'
import { useAuthStore } from '../stores/auth'
import { useServerStore } from '../stores/server'
import { useServerInfo } from '../hooks/useServerInfo'
import { useSettingsStore } from '../stores/settings'
import { useTheme } from '../hooks/useTheme'
-import { exerciseAPI } from '../services/api'
+import { exerciseAPI, userAPI } from '../services/api'
import PageHeader from '../components/ui/PageHeader'
+import { ErrorState } from '../components/ui'
+import { ConfirmSheet } from '../components/ui'
import ServerSettings from '../components/ServerSettings'
import { Link } from 'react-router-dom'
import {
@@ -31,12 +33,15 @@ import {
//
// The label keeps a `min-w` floor so wrapping actually triggers: with `min-w-0` alone it
// would shrink to nothing and the pair would stay jammed on one line forever.
-function SettingRow({ label, description, children }: { label: string; description?: string; children: React.ReactNode }) {
+// `descriptionTone` lets a row report its own failure in place of its description. A row
+// like the unit toggle sits far down a long page, and the page-level banner is at the very
+// top — measured at 809px above the control, off-screen, which is the same as saying nothing.
+function SettingRow({ label, description, descriptionTone, children }: { label: string; description?: string; descriptionTone?: 'error'; children: React.ReactNode }) {
return (
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-4">
<div className="min-w-[9rem] flex-1">
<p className="text-sm font-medium text-tx-primary">{label}</p>
- {description && <p className="text-xs text-tx-muted mt-0.5">{description}</p>}
+ {description && <p className={`text-xs mt-0.5 ${descriptionTone === 'error' ? 'text-error-400' : 'text-tx-muted'}`}>{description}</p>}
</div>
{/* break-words so a long unbroken value wraps instead of overflowing the card. */}
<div className="min-w-0 max-w-full flex-shrink-0 break-words">{children}</div>
@@ -63,15 +68,24 @@ export default function Settings() {
const serverInfo = useServerInfo()
const { theme, toggleTheme } = useTheme()
const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout, setRestEnabled, setRestSeconds } = useSettingsStore()
+ const settingsLoadFailed = useSettingsStore(s => s.loadFailed)
const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)
- const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const [showCustomRest, setShowCustomRest] = useState(false)
+ const [confirmDelete, setConfirmDelete] = useState(false)
+ // Not the page-level `error`: that renders in a banner at the very top, and the unit
+ // toggle sits ~800px down a long settings page. Measured in a browser — the toggle
+ // flicked back to lbs while the explanation was off-screen above, which is the
+ // "say it where the tap was" failure this whole branch exists to stop.
+ const [unitError, setUnitError] = useState<string | null>(null)
const [cacheStatus, setCacheStatus] = useState<{ count: number } | null>(null)
const [seedAction, setSeedAction] = useState<'refresh' | 'clear' | null>(null)
- const [seedMsg, setSeedMsg] = useState<string | null>(null)
+ // Carries whether it FAILED, not just what it said. Both outcomes used to land in
+ // one muted grey line, so "Refreshed 812 exercises" and "Can't reach the server
+ // right now." were the same small grey text — a failure that does not read as one.
+ const [seedMsg, setSeedMsg] = useState<{ text: string; failed: boolean } | null>(null)
const [formData, setFormData] = useState({
weight_unit: storedSettings.weight_unit,
@@ -89,27 +103,33 @@ export default function Settings() {
} catch { /* cache status is a best-effort probe; absence just hides the count */ }
}, [])
- useEffect(() => {
- const load = async () => {
- try {
- await fetchSettings()
- const s = useSettingsStore.getState().settings
- setFormData({
- weight_unit: s.weight_unit,
- calorie_target: s.calorie_target,
- protein_target: s.protein_target,
- carb_target: s.carb_target,
- fat_target: s.fat_target,
- })
- } catch (err: any) {
- setError(err.message || 'Failed to load settings')
- } finally {
- setLoading(false)
- }
+ // Lifted out of the effect so Retry runs the SAME routine. It did not, at first:
+ // the button called fetchSettings() alone, the store recovered the real targets, and
+ // the form went on showing the defaults it had been seeded with — so the next Save
+ // would have written them over the numbers that had just come back.
+ const load = useCallback(async () => {
+ setLoading(true)
+ try {
+ await fetchSettings()
+ const s = useSettingsStore.getState().settings
+ setFormData({
+ weight_unit: s.weight_unit,
+ calorie_target: s.calorie_target,
+ protein_target: s.protein_target,
+ carb_target: s.carb_target,
+ fat_target: s.fat_target,
+ })
+ } catch (err: any) {
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
+ } finally {
+ setLoading(false)
}
+ }, [fetchSettings])
+
+ useEffect(() => {
load()
loadCacheStatus()
- }, [loadCacheStatus])
+ }, [load, loadCacheStatus])
// No polling: nothing populates the cache in the background any more. It fills as
// a side-effect of reads, and these two actions are synchronous.
@@ -119,10 +139,10 @@ export default function Settings() {
setSeedMsg(null)
try {
const res = await exerciseAPI.refreshCache()
- setSeedMsg(`Refreshed ${res.refreshed.toLocaleString()} exercise${res.refreshed === 1 ? '' : 's'}`)
+ setSeedMsg({ text: `Refreshed ${res.refreshed.toLocaleString()} exercise${res.refreshed === 1 ? '' : 's'}`, failed: false })
loadCacheStatus()
} catch (err: any) {
- setSeedMsg(err.message || 'Refresh failed')
+ setSeedMsg({ text: apiErrorMessage(err, "Couldn't refresh the cache."), failed: true })
} finally {
setSeedAction(null)
}
@@ -133,36 +153,55 @@ export default function Settings() {
setSeedMsg(null)
try {
const res = await exerciseAPI.clearCacheOnServer()
- setSeedMsg(`Cleared ${res.cleared.toLocaleString()} unused exercises`)
+ setSeedMsg({ text: `Cleared ${res.cleared.toLocaleString()} unused exercises`, failed: false })
loadCacheStatus()
} catch (err) {
- setSeedMsg(err instanceof Error ? err.message : 'Clear failed')
+ setSeedMsg({ text: apiErrorMessage(err, "Couldn't clear the cache."), failed: true })
} finally {
setSeedAction(null)
}
}
+ // The store rolls its own optimistic patch back when the write fails, so the app no
+ // longer shows a unit the server never accepted. Saying so is still this page's job —
+ // a toggle that flips back on its own, silently, is its own small mystery.
const handleUnitChange = async (unit: 'lbs' | 'kg') => {
+ // Captured before the optimistic write. Negating `unit` only happened to be right when
+ // the user switched; tapping the unit already selected and failing flipped them over.
+ const previous = formData.weight_unit
setFormData(prev => ({ ...prev, weight_unit: unit }))
+ setUnitError(null)
try {
await updateSettings({ ...formData, weight_unit: unit })
- } catch { /* local state already switched; the next save retries the write */ }
+ } catch (err) {
+ setFormData(prev => ({ ...prev, weight_unit: previous }))
+ setUnitError(apiErrorMessage(err, "Couldn't change the weight unit."))
+ }
}
- const handleSave = async () => {
- setSaving(true)
- setError(null)
+ // `err.message` here was the raw JS message — for an axios failure that reads
+ // "Request failed with status code 400", which is true and tells the user nothing.
+ const save = useAsyncAction(async () => {
+ await updateSettings(formData)
+ setSuccess(true)
+ setTimeout(() => setSuccess(false), 3000)
+ }, 'Failed to save settings')
+
+ // Mobile has had this since it shipped; web rendered the button and wired nothing to
+ // it, so "Delete account" was a control that did nothing at all — worse than absent,
+ // because it reads as a feature that is simply broken.
+ //
+ // logout() is what moves the user out: it clears the tokens, which flips the route
+ // guard. Nothing navigates by hand, exactly as on mobile.
+ const deleteAccount = useAsyncAction(async () => {
+ await userAPI.deleteAccount()
+ await logout()
+ }, 'Could not delete account')
+
+ const handleSave = () => {
setSuccess(false)
- try {
- await updateSettings(formData)
- setSuccess(true)
- setTimeout(() => setSuccess(false), 3000)
- } catch (err: any) {
- setError(err.message || 'Failed to save settings')
- } finally {
- setSaving(false)
- }
+ void save.run()
}
if (loading) {
@@ -173,14 +212,16 @@ export default function Settings() {
)
}
+
+
return (
<div className="space-y-5 animate-slide-up max-w-2xl">
<PageHeader title="Settings" subtitle="Preferences and account configuration" />
- {error && (
+ {(error || save.error) && (
<div className="alert-error">
<AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || save.error}</span>
</div>
)}
@@ -312,9 +353,33 @@ export default function Settings() {
})()}
</Section>
- {/* Goals & Units */}
+ {/* Goals & Units — the only server-backed, editable block on this page.
+
+ Gated on its own rather than page-level, because almost nothing else here
+ needs the server: theme, workout layout and the rest timer are device prefs,
+ sign out is local, and the API server row is the very control someone needs
+ WHEN the server cannot be reached. Blanking the page took that away at
+ exactly the wrong moment.
+
+ What must not survive the failure is this section: the store falls back to
+ defaults, so the inputs showed 2000/150/250/65 and Save PUT them over real
+ targets of 3175/205/310/88. Measured, not theorised. */}
+ {settingsLoadFailed ? (
+ <Section title="Goals & Units">
+ <ErrorState
+ size="section"
+ title="Couldn't load your goals"
+ message="These are your saved targets and units, so we won't guess at them. Everything else on this page still works."
+ onRetry={() => { void load() }}
+ />
+ </Section>
+ ) : (
<Section title="Goals & Units">
- <SettingRow label="Weight unit" description="Changes apply immediately across the app">
+ <SettingRow
+ label="Weight unit"
+ description={unitError ?? 'Changes apply immediately across the app'}
+ descriptionTone={unitError ? 'error' : undefined}
+ >
<div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">
{(['lbs', 'kg'] as const).map(unit => (
<button
@@ -386,13 +451,14 @@ export default function Settings() {
<p className="text-xs text-tx-muted">Save calorie and macro targets</p>
<button
onClick={handleSave}
- disabled={saving}
+ disabled={save.busy}
className="btn-primary btn-sm"
>
- <Check className="w-3.5 h-3.5" /> {saving ? 'Saving...' : 'Save targets'}
+ <Check className="w-3.5 h-3.5" /> {save.busy ? 'Saving...' : 'Save targets'}
</button>
</div>
</Section>
+ )}
{/* Server info */}
<Section title="Self-Hosted Instance">
@@ -428,7 +494,9 @@ export default function Settings() {
{seedMsg && (
<div className="py-2 px-1">
- <p className="text-xs text-tx-muted">{seedMsg}</p>
+ <p className={`text-xs ${seedMsg.failed ? 'text-[color:var(--alert-error)]' : 'text-tx-muted'}`}>
+ {seedMsg.text}
+ </p>
</div>
)}
@@ -464,11 +532,27 @@ export default function Settings() {
</button>
</SettingRow>
<SettingRow label="Delete account" description="Permanently delete all your data">
- <button className="btn-danger btn-sm">
+ <button onClick={() => setConfirmDelete(true)} className="btn-danger btn-sm">
<Trash2 className="w-3.5 h-3.5" /> Delete
</button>
</SettingRow>
</Section>
+
+ {/* error stays on the sheet: a failed delete has to answer under the same finger
+ that pressed Delete, not as a banner at the top of a scrolled settings page. */}
+ <ConfirmSheet
+ open={confirmDelete}
+ icon={Trash2}
+ destructive
+ title="Delete account?"
+ message="This permanently deletes your account and all of your data. This can't be undone."
+ confirmLabel="Delete account"
+ busyLabel="Deleting…"
+ busy={deleteAccount.busy}
+ error={deleteAccount.error ?? undefined}
+ onConfirm={() => { void deleteAccount.run() }}
+ onCancel={() => { setConfirmDelete(false); deleteAccount.reset() }}
+ />
</div>
)
}
diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsx
index 136cced..5a82e07 100644
--- a/web/src/pages/Weight.tsx
+++ b/web/src/pages/Weight.tsx
@@ -9,8 +9,9 @@ import DateInput from '../components/ui/DateInput'
import PeriodSelector from '../components/PeriodSelector'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
-import { BODYWEIGHT_STEP, clampStep, todayStr, daysAgoStr, dayToInstant, entryDay, dayToLocalDate, types, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, useAsyncAction, BODYWEIGHT_STEP, clampStep, todayStr, daysAgoStr, dayToInstant, entryDay, dayToLocalDate, types, formatDay } from '@lyftr/shared'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
+import { ErrorState, ListError, StatFailure } from '../components/ui'
import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs, displayWeight, round1 , weightError, maxWeight } from '../stores/settings'
@@ -213,30 +214,60 @@ export default function Weight() {
const [error, setError] = useState<string | null>(null)
// Paginated history list
- const { items, sentinelRef, hasMore, loading: listLoading, initialLoading, reload } = useServerInfiniteList<types.WeightLog>({
+ const {
+ items, sentinelRef, hasMore, loading: listLoading, initialLoading, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<types.WeightLog>({
fetcher: (offset, limit) => weightAPI.list({ offset, limit }),
})
// Chart data — re-fetched when period changes
const [chartLogs, setChartLogs] = useState<types.WeightLog[]>([])
+ // 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)
+ const [statsError, setStatsError] = useState<string | null>(null)
+ const [retryKey, setRetryKey] = useState(0)
+
+ // `cancelled` is not tidiness, it is correctness. A wider window is a slower query, so
+ // tapping All and then 7d can land All's answer last — and the figures, the chart and
+ // the "over 7d" line would then all be describing a period the user is not looking at.
+ // Measured: 7d reads 182/181/183 and All reads 179/173/185, and without this the 7d
+ // view showed All's numbers.
useEffect(() => {
+ let cancelled = false
const days = PERIOD_DAYS[period]
const from = days != null ? daysAgoStr(days) : undefined
weightAPI.list({ limit: 1000, from })
- .then(data => setChartLogs(data || []))
- .catch(() => { /* chart keeps the previous series rather than blanking on a failed refetch */ })
- }, [period])
+ // 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) } })
+ .catch(err => { if (!cancelled) setChartError(apiErrorMessage(err, "Couldn't load your weight trend.")) })
+ return () => { cancelled = true }
+ }, [period, retryKey])
useEffect(() => {
- weightAPI.stats().then(setStats).catch(() => {})
- }, [])
+ let cancelled = false
+ weightAPI.stats()
+ .then(data => { if (!cancelled) { setStats(data); setStatsError(null) } })
+ .catch(err => { if (!cancelled) setStatsError(apiErrorMessage(err, "Couldn't load your weight stats.")) })
+ return () => { cancelled = true }
+ }, [retryKey])
+
+ // One control puts all three reads back, so a reader never has to work out which of
+ // them failed to know what to press.
+ const retryAll = () => {
+ setChartError(null)
+ setStatsError(null)
+ setRetryKey(k => k + 1)
+ retryList()
+ }
// Log form
const [newWeight, setNewWeight] = useState('')
const [newDate, setNewDate] = useState(todayStr())
const [newNotes, setNewNotes] = useState('')
- const [logging, setLogging] = useState(false)
const [showNotes, setShowNotes] = useState(false)
const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)
const duplicateWarningDismissedRef = useRef(false)
@@ -261,9 +292,27 @@ export default function Weight() {
})
}, [chartLogs, settings.weight_unit])
+ const log = useAsyncAction(async (w: number) => {
+ const real = await weightAPI.log({
+ weight: displayToLbs(w, settings.weight_unit),
+ notes: newNotes.trim(),
+ logged_at: dayToInstant(newDate),
+ })
+ setNewWeight(String(displayWeight(real.weight, settings.weight_unit)))
+ setNewNotes('')
+ setNewDate(todayStr())
+ setShowNotes(false)
+ duplicateWarningDismissedRef.current = false
+ reload()
+ weightAPI.stats().then(setStats).catch(() => {})
+ const days = PERIOD_DAYS[period]
+ const from = days != null ? daysAgoStr(days) : undefined
+ weightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => {})
+ }, 'Failed to log weight')
+
const handleLog = async (e: React.FormEvent) => {
e.preventDefault()
- if (logging) return
+ if (log.busy) return
const w = parseFloat(newWeight)
const wErr = weightError(w, settings.weight_unit)
if (wErr) {
@@ -276,50 +325,20 @@ export default function Weight() {
return
}
- setLogging(true)
setError(null)
setShowDuplicateWarning(false)
-
- try {
- const real = await weightAPI.log({
- weight: displayToLbs(w, settings.weight_unit),
- notes: newNotes.trim(),
- logged_at: dayToInstant(newDate),
- })
- setNewWeight(String(displayWeight(real.weight, settings.weight_unit)))
- setNewNotes('')
- setNewDate(todayStr())
- setShowNotes(false)
- duplicateWarningDismissedRef.current = false
- reload()
- weightAPI.stats().then(setStats).catch(() => {})
- const days = PERIOD_DAYS[period]
- const from = days != null ? daysAgoStr(days) : undefined
- weightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => {})
- } catch (err: any) {
- setError(err?.response?.data?.error || 'Failed to log weight')
- } finally {
- setLogging(false)
- }
+ void log.run(w)
}
if (initialLoading) return <Loading />
- if (error && items.length === 0) {
- return (
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
- </div>
- )
- }
// 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
const useServerAggregate = period === 'All' && stats != null
- const currentLbs = periodValues[0] ?? stats?.latest ?? 0
- const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? 0
+ const currentLbs = periodValues[0] ?? stats?.latest ?? items[0]?.weight ?? 0
+ const oldestLbs = periodValues[periodValues.length - 1] ?? stats?.starting ?? currentLbs
const changeLbs = currentLbs - oldestLbs
const avgLbs = useServerAggregate
? (stats!.avg ?? 0)
@@ -331,6 +350,36 @@ export default function Weight() {
? (stats!.max ?? 0)
: (periodValues.length > 0 ? Math.max(...periodValues) : 0)
+ // A number we never received is not zero, and neither is the average of nothing. With
+ // no values to aggregate the tiles read "—" whatever the reason: an outage otherwise
+ // renders "0 lb" in the same type as a real measurement, and a new account is told its
+ // lowest ever weight was zero. Which of the two it is, the hero and the chart say.
+ const loadFailed = chartError != null || statsError != null || listError != null
+
+ // Scope the error to the scope of the failure. Three sections failing separately is
+ // three problems and gets three errors; three sections failing because the server is
+ // down is ONE problem, and four retry buttons for it are four ways to say "reload".
+ const everythingFailed = chartError != null && statsError != null && listError != null
+ && items.length === 0 && periodValues.length === 0
+
+ // Nothing to aggregate. Two different reasons, and they are not the same sentence:
+ // an account with no entries yet reads "—", a section whose reads failed says so
+ // where the numbers would have been. A dash alone explains nothing, and the retry for
+ // it belongs beside it rather than in a banner at the top of the page.
+ // What the hero can honestly state. With the trend and stats reads both dead the old
+ // code fell through to 0 and rendered "0 lb · no change over 30d" — a measurement, in
+ // 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 > 0
+ const changeKnown = periodValues.length > 1
+ const noValues = periodValues.length === 0 && (stats == null || stats.total_entries === 0)
+ const figuresFailed = noValues && (chartError != null || statsError != null)
+ const 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 current = displayWeight(currentLbs, settings.weight_unit)
const change = displayWeight(changeLbs, settings.weight_unit)
const avg = displayWeight(avgLbs, settings.weight_unit)
@@ -347,6 +396,23 @@ export default function Weight() {
: 'bg-error-500/10 border-error-500/20 text-error-400'
const changeWord = change === 0 ? 'no change' : change < 0 ? 'lost' : 'gained'
+ // Title and subtitle stay, so the reader still knows where they are; the header's
+ // action does not. On an error screen the primary action is the retry, and a
+ // btn-primary beside it that leads to a save which cannot succeed outranks it.
+ if (everythingFailed) {
+ return (
+ <div className="space-y-5 animate-slide-up">
+ <PageHeader title="Weight" subtitle="Track your body weight over time" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your weight"
+ message={listError ?? chartError ?? statsError ?? ''}
+ onRetry={retryAll}
+ />
+ </div>
+ )
+ }
+
return (
<div className="space-y-5 animate-slide-up">
<PageHeader
@@ -355,10 +421,10 @@ export default function Weight() {
action={<span className="badge-brand"><Calendar className="w-3 h-3" /> {wUnit}</span>}
/>
- {error && (
+ {(error || log.error) && (
<div className="alert-error" role="alert" aria-live="polite">
<AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error}</span>
+ <span>{error || log.error}</span>
</div>
)}
@@ -449,10 +515,10 @@ export default function Weight() {
<button
type="submit"
- disabled={!(parseFloat(newWeight) > 0) || logging}
+ disabled={!(parseFloat(newWeight) > 0) || log.busy}
className="btn-primary btn-lg w-full"
>
- <Plus className="w-4 h-4" /> {logging ? 'Logging…' : 'Log Weight'}
+ <Plus className="w-4 h-4" /> {log.busy ? 'Logging…' : 'Log Weight'}
</button>
<p className="input-help flex items-center justify-center gap-1.5 text-center">
<Sunrise className="w-3.5 h-3.5 text-amber-400 flex-shrink-0" />
@@ -463,7 +529,17 @@ export default function Weight() {
{/* Current weight hero */}
<div className="card p-6 border-brand-500/20 bg-brand-500/5">
- {items.length === 0 ? (
+ {items.length === 0 && loadFailed ? (
+ // Empty and unreachable look identical from here, so the empty copy cannot be
+ // the default: it told someone with years of entries that they had never
+ // weighed themselves, and invited them to fix it against a server that was down.
+ <ErrorState
+ size="section"
+ title="Couldn't load your weight"
+ message={listError ?? chartError ?? statsError ?? ''}
+ onRetry={retryAll}
+ />
+ ) : items.length === 0 ? (
<div className="text-center py-2">
<p className="stat-label mb-1">Current Weight</p>
<p className="text-tx-muted text-sm">The scale doesn't know you exist yet. Fix that.</p>
@@ -474,18 +550,20 @@ export default function Weight() {
<div>
<p className="stat-label mb-2">Current Weight</p>
<div className="flex items-end gap-2">
- <span className="stat-value text-5xl">{current}</span>
- <span className="text-tx-muted text-lg mb-1">{wUnit}</span>
+ <span className="stat-value text-5xl">{currentKnown ? current : '—'}</span>
+ {currentKnown && <span className="text-tx-muted text-lg mb-1">{wUnit}</span>}
</div>
</div>
- <div className={`flex items-center gap-1.5 text-sm font-semibold px-3 py-1.5 rounded-lg border ${trendClass}`}>
+ <div className={`flex items-center gap-1.5 text-sm font-semibold px-3 py-1.5 rounded-lg border ${trendClass} ${changeKnown ? '' : 'hidden'}`}>
<TrendIcon className="w-4 h-4" />
{Math.abs(change)} {wUnit}
</div>
</div>
- <p className="text-xs text-tx-muted mt-3">
- {Math.abs(change)} {wUnit} {changeWord} over {period}
- </p>
+ {changeKnown && (
+ <p className="text-xs text-tx-muted mt-3">
+ {Math.abs(change)} {wUnit} {changeWord} over {period}
+ </p>
+ )}
</>
)}
</div>
@@ -503,12 +581,30 @@ export default function Weight() {
<span className="stat-label">{s.label}</span>
<HelpTip content={s.tip} />
</div>
- <span className="stat-value text-xl">{Math.round(s.value)}</span>
- <span className="text-xs text-tx-muted ml-1">{wUnit}</span>
+ {figuresFailed ? (
+ <StatFailure label={`Couldn't load ${s.label.toLowerCase()} weight`} />
+ ) : (
+ <>
+ <span className="stat-value text-xl">{aggregatesUnknown ? '—' : Math.round(s.value)}</span>
+ {!aggregatesUnknown && <span className="text-xs text-tx-muted ml-1">{wUnit}</span>}
+ </>
+ )}
</div>
))}
</div>
+ {/* Only the stale case earns a line here. When the figures never arrived the tiles
+ above are already showing the failure mark, and repeating it in words underneath
+ was the same thing said twice. Stale is different: the tiles are showing real
+ numbers, so nothing else on screen says they are out of date. */}
+ {figuresStale && (
+ <div className="flex items-center gap-2 px-1 text-xs text-tx-muted" role="status">
+ <AlertCircle className="w-3.5 h-3.5 flex-shrink-0 text-amber-400" />
+ <span>Couldn't refresh these — showing the last we loaded.</span>
+ <button onClick={retryAll} className="underline hover:text-tx-primary">Try again</button>
+ </div>
+ )}
+
{/* Chart + period selector */}
<div className="card p-5">
<div className="flex items-center justify-between mb-4 gap-2">
@@ -516,7 +612,9 @@ export default function Weight() {
<PeriodSelector options={PERIODS} value={period} onChange={setPeriod} />
</div>
- {chartPoints.length === 0 ? (
+ {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">
No data for this period
</div>
@@ -529,7 +627,10 @@ export default function Weight() {
)}
</div>
- {/* History */}
+ {/* History — the error sits outside the items guard on purpose: a failed first
+ page leaves items empty, and the guard alone rendered nothing whatsoever. */}
+ {listError && <ListError subject="your weight history" message={listError} onRetry={retryList} />}
+
{items.length > 0 && (
<>
<h2 className="section-title px-1">History</h2>
diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsx
index 0a88fde..06c78e5 100644
--- a/web/src/pages/WeightDetail.tsx
+++ b/web/src/pages/WeightDetail.tsx
@@ -1,12 +1,12 @@
+import { ConfirmSheet } from '../components/ui'
import { useState, useEffect } from 'react'
-import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import { ArrowLeft, Scale, Trash2, Edit2, Save, X, AlertCircle, Loader } from 'lucide-react'
import { weightAPI } from '../services/api'
import { useSettingsStore, weightShort, displayWeight, weightError, maxWeight, resolveWeightLbs } from '../stores/settings'
-import { useBodyScrollLock } from '../hooks/useBodyScrollLock'
import { useEscapeKey } from '../hooks/useEscapeKey'
-import { todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types, formatDay } from '@lyftr/shared'
+import { useAsyncAction, apiErrorMessage, isNotFound, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types, formatDay } from '@lyftr/shared'
+import { ErrorState } from '../components/ui'
import StepperTile from '../components/ui/StepperTile'
import NumberField from '../components/ui/NumberField'
@@ -19,34 +19,30 @@ export default function WeightDetail() {
const [log, setLog] = useState<types.WeightLog | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ const [gone, setGone] = useState(false)
+ const [retryKey, setRetryKey] = useState(0)
// Edit mode
const [editing, setEditing] = useState(false)
const [editWeight, setEditWeight] = useState('')
const [editDate, setEditDate] = useState('')
const [editNotes, setEditNotes] = useState('')
- const [saving, setSaving] = useState(false)
const [editError, setEditError] = useState('')
// Delete confirm
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
- useBodyScrollLock(confirming)
- useEscapeKey(confirming, () => setConfirming(false))
useEscapeKey(editing, () => { setEditing(false); setEditError('') })
useEffect(() => {
weightAPI.get(Number(id))
- .then(data => {
- setLog(data)
- setEditWeight(String(displayWeight(data.weight, settings.weight_unit)))
- setEditDate(entryDay(data))
- setEditNotes(data.notes ?? '')
+ .then(setLog)
+ .catch(err => {
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
})
- .catch(err => setError(err?.response?.data?.error || 'Failed to load entry'))
.finally(() => setLoading(false))
- }, [id])
+ }, [id, retryKey])
const startEdit = () => {
if (!log) return
@@ -57,43 +53,38 @@ export default function WeightDetail() {
setEditing(true)
}
- const handleSave = async (e: React.FormEvent) => {
+ const saveEdit = useAsyncAction(async (entry: types.WeightLog) => {
+ const updated = await weightAPI.update(entry.id, {
+ weight: resolveWeightLbs(editWeight, entry.weight, settings.weight_unit),
+ notes: editNotes.trim(),
+ logged_at: dayToInstant(editDate, entry.logged_at),
+ })
+ setLog(updated)
+ setEditing(false)
+ }, 'Failed to save')
+
+ // `editError` is what this page can say about the value in the box; the hook carries
+ // what the server said. The entry is passed to run() because the guard below is what
+ // proves it is not null.
+ const handleSave = (e: React.FormEvent) => {
e.preventDefault()
- if (!log || saving) return
+ if (!log || saveEdit.busy) return
const w = parseFloat(editWeight)
const wErr = weightError(w, settings.weight_unit)
if (wErr) {
setEditError(wErr)
return
}
- setSaving(true)
setEditError('')
- try {
- const updated = await weightAPI.update(log.id, {
- weight: resolveWeightLbs(editWeight, log.weight, settings.weight_unit),
- notes: editNotes.trim(),
- logged_at: dayToInstant(editDate, log.logged_at),
- })
- setLog(updated)
- setEditing(false)
- } catch (err: any) {
- setEditError(err?.response?.data?.error || 'Failed to save')
- } finally {
- setSaving(false)
- }
+ void saveEdit.run(log)
}
- const handleDelete = async () => {
- if (!log || deleting) return
- setDeleting(true)
- try {
- await weightAPI.delete(log.id)
- navigate('/weight', { replace: true })
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // Was a bare `catch` that closed the confirm and left the entry there — the same
+ // silent failure as every other delete in the app before this branch.
+ const remove = useAsyncAction(async (entry: types.WeightLog) => {
+ await weightAPI.delete(entry.id)
+ navigate('/weight', { replace: true })
+ }, 'Failed to delete entry')
if (loading) {
return (
@@ -105,15 +96,13 @@ export default function WeightDetail() {
if (error || !log) {
return (
- <div className="space-y-4">
- <Link to="/weight" className="flex items-center gap-2 text-sm text-tx-muted hover:text-tx-primary transition-colors">
- <ArrowLeft className="w-4 h-4" /> Weight
- </Link>
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error || 'Entry not found'}</span>
- </div>
- </div>
+ <ErrorState
+ size="page"
+ title="Couldn't load this entry"
+ message={error ?? 'That entry no longer exists.'}
+ onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}
+ secondary={<Link to="/weight" className="btn-secondary btn-sm">Back to weight</Link>}
+ />
)
}
@@ -177,10 +166,10 @@ export default function WeightDetail() {
<div className="card p-5">
<h2 className="section-title mb-4">Edit Entry</h2>
<form onSubmit={handleSave} className="space-y-4">
- {editError && (
+ {(editError || saveEdit.error) && (
<div className="alert-error" role="alert">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
- <span>{editError}</span>
+ <span>{editError || saveEdit.error}</span>
</div>
)}
@@ -227,11 +216,11 @@ export default function WeightDetail() {
</button>
<button
type="submit"
- disabled={!(parseFloat(editWeight) > 0) || saving}
+ disabled={!(parseFloat(editWeight) > 0) || saveEdit.busy}
className="flex-1 btn-primary py-2.5 rounded-xl flex items-center justify-center gap-1.5"
>
<Save className="w-4 h-4" />
- {saving ? 'Saving…' : 'Save'}
+ {saveEdit.busy ? 'Saving…' : 'Save'}
</button>
</div>
</form>
@@ -239,34 +228,19 @@ export default function WeightDetail() {
)}
{/* Delete confirm — bottom sheet */}
- {confirming && createPortal(
- <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Entry?</h3>
- <p className="text-sm text-tx-muted mb-5">
- {formatDay(entryDay(log), 'MMMM d, yyyy')} · {displayWeight(log.weight, settings.weight_unit)} {wUnit} will be permanently deleted.
- </p>
- <div className="flex gap-3">
- <button
- onClick={() => setConfirming(false)}
- className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm"
- >
- Cancel
- </button>
- <button
- onClick={handleDelete}
- disabled={deleting}
- className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5"
- >
- <Trash2 className="w-3.5 h-3.5" />
- {deleting ? 'Deleting…' : 'Delete'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
+ <ConfirmSheet
+ open={confirming}
+ icon={Trash2}
+ destructive
+ title="Delete Entry?"
+ message={`${formatDay(entryDay(log), 'MMMM d, yyyy')} · ${displayWeight(log.weight, settings.weight_unit)} ${wUnit} will be permanently deleted.`}
+ confirmLabel="Delete"
+ busyLabel="Deleting…"
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { if (!remove.busy) void remove.run(log) }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
+ />
</div>
)
}
diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsx
index f2d4047..1f721ce 100644
--- a/web/src/pages/WorkoutDetail.tsx
+++ b/web/src/pages/WorkoutDetail.tsx
@@ -1,12 +1,12 @@
+import { ConfirmSheet, ErrorState } from '../components/ui'
import { useState, useEffect } from 'react'
-import { createPortal } from 'react-dom'
import { useParams, useNavigate, Link } from 'react-router-dom'
import {
- ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, AlertCircle, Loader, Pause, TimerOff,
+ ArrowLeft, Clock, Dumbbell, TrendingUp, Edit2, Trash2, ChevronRight, Loader, Pause, TimerOff,
} from 'lucide-react'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'
-import { types, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, isNotFound, useAsyncAction, types, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'
import { muscleColor } from '../utils/exerciseUtils'
function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit: string }) {
@@ -30,8 +30,15 @@ export default function WorkoutDetail() {
const [workout, setWorkout] = useState<types.Workout | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
+ // A 404 is not a retryable failure: the row is gone, and a Try again button that
+ // cannot ever succeed is worse than no button. Tracked separately from the message
+ // because the message alone cannot say which kind of failure produced it.
+ const [gone, setGone] = useState(false)
+ // Bumping this re-runs the load effect. A lifted useCallback would be the tidier
+ // shape, but it would mean restructuring a working effect on five pages to gain a
+ // retry button; this does the same job in three lines.
+ const [retryKey, setRetryKey] = useState(0)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
useEffect(() => {
const load = async () => {
@@ -39,25 +46,23 @@ export default function WorkoutDetail() {
const data = await workoutAPI.get(Number(id))
setWorkout(data)
} catch (err: any) {
- setError(err.message || 'Failed to load workout')
+ setGone(isNotFound(err))
+ setError(apiErrorMessage(err, "The server didn't say what went wrong."))
} finally {
setLoading(false)
}
}
load()
- }, [id])
+ }, [id, retryKey])
- const handleDelete = async () => {
+ // Was `catch { setDeleting(false); setConfirming(false) }` — the confirm quietly
+ // closed and the user was left guessing whether the tap had registered. It stays
+ // up now and says why.
+ const remove = useAsyncAction(async () => {
if (!workout) return
- setDeleting(true)
- try {
- await workoutAPI.delete(workout.id)
- navigate('/workouts', { replace: true })
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ await workoutAPI.delete(workout.id)
+ navigate('/workouts', { replace: true })
+ }, 'Failed to delete workout')
if (loading) {
return (
@@ -69,15 +74,13 @@ export default function WorkoutDetail() {
if (error || !workout) {
return (
- <div className="space-y-4">
- <Link to="/workouts" className="flex items-center gap-2 text-sm text-tx-muted hover:text-tx-primary transition-colors">
- <ArrowLeft className="w-4 h-4" /> Back
- </Link>
- <div className="alert-error">
- <AlertCircle className="w-5 h-5 flex-shrink-0" />
- <span>{error || 'Workout not found'}</span>
- </div>
- </div>
+ <ErrorState
+ size="page"
+ title="Couldn't load this workout"
+ message={error ?? 'That workout no longer exists.'}
+ onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}
+ secondary={<Link to="/workouts" className="btn-secondary btn-sm">Back to workouts</Link>}
+ />
)
}
@@ -112,25 +115,19 @@ export default function WorkoutDetail() {
</div>
{/* Delete confirm — bottom sheet */}
- {confirming && createPortal(
- <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
- <div className="bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-sm p-6">
- <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mb-4 sm:hidden" />
- <h3 className="font-display font-bold text-lg text-tx-primary mb-1">Delete Workout?</h3>
- <p className="text-sm text-tx-muted mb-5">"{workout.name}" will be permanently deleted.</p>
- <div className="flex gap-3">
- <button onClick={() => setConfirming(false)} className="flex-1 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">
- Cancel
- </button>
- <button onClick={handleDelete} disabled={deleting} className="flex-1 py-3 bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-xl transition-colors font-semibold text-sm flex items-center justify-center gap-1.5">
- <Trash2 className="w-3.5 h-3.5" />
- {deleting ? 'Deleting…' : 'Delete'}
- </button>
- </div>
- </div>
- </div>,
- document.body
- )}
+ <ConfirmSheet
+ open={confirming}
+ icon={Trash2}
+ destructive
+ title="Delete Workout?"
+ message={`"${workout.name}" will be permanently deleted.`}
+ confirmLabel="Delete"
+ busyLabel="Deleting…"
+ busy={remove.busy}
+ error={remove.error}
+ onConfirm={() => { void remove.run() }}
+ onCancel={() => { setConfirming(false); remove.reset() }}
+ />
{/* Header */}
<div className="card p-4">
diff --git a/web/src/pages/WorkoutExercisePicker.tsx b/web/src/pages/WorkoutExercisePicker.tsx
index 28f1483..de30393 100644
--- a/web/src/pages/WorkoutExercisePicker.tsx
+++ b/web/src/pages/WorkoutExercisePicker.tsx
@@ -1,24 +1,26 @@
-import { useState, useEffect, useCallback, useRef } from 'react'
+import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowLeft, Search, Dumbbell } from 'lucide-react'
+import { useServerList, types } from '@lyftr/shared'
+import { ListError } from '../components/ui'
import { exerciseAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
-import { types } from '@lyftr/shared'
import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'
// Must match the server's default page size: a short page is what signals the end.
const PAGE_SIZE = 50
+const DEBOUNCE_MS = 250
export default function WorkoutExercisePicker() {
const navigate = useNavigate()
const { session, addExercise } = useWorkoutSession()
- const [exercises, setExercises] = useState<types.Exercise[]>([])
const [query, setQuery] = useState('')
- const [loading, setLoading] = useState(false)
- const [page, setPage] = useState(1)
- const [exhausted, setExhausted] = useState(false)
- // Identifies the newest request so a slow earlier one cannot overwrite it.
- const reqRef = useRef(0)
+ const [debouncedQuery, setDebouncedQuery] = useState('')
+
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)
+ return () => clearTimeout(t)
+ }, [query])
const selectedIds = session?.exercises.map(e => e.exercise_id) ?? []
@@ -26,30 +28,21 @@ export default function WorkoutExercisePicker() {
// into the browser to slice it here — this screen used to render the first 40 of
// whatever it had downloaded and tell the user to refine their search, which was
// a truncation dressed up as advice.
- const load = useCallback(async (q: string, nextPage: number, append = false) => {
- const id = ++reqRef.current
- setLoading(true)
- try {
- const data = await exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage }) || []
- // Typing faster than the network otherwise leaves the list showing results for
- // a query the user has already moved on from.
- if (reqRef.current !== id) return
- setExercises(prev => (append ? [...prev, ...data] : data))
- setExhausted(data.length < PAGE_SIZE)
- setPage(nextPage)
- } catch { /* a failed search keeps the previous list rather than blanking it */ }
- finally { if (reqRef.current === id) setLoading(false) }
- }, [])
+ const fetcher = useCallback(
+ (offset: number, limit: number) =>
+ exerciseAPI
+ .list({ ...(debouncedQuery ? { q: debouncedQuery } : {}), page: offset / limit + 1 })
+ .then(data => data ?? []),
+ [debouncedQuery]
+ )
- useEffect(() => { load('', 1) }, [load])
-
- useEffect(() => {
- const t = setTimeout(() => {
- setExhausted(false)
- load(query, 1)
- }, 250)
- return () => clearTimeout(t)
- }, [query, load])
+ const {
+ items: exercises, loadMore, hasMore, loading, initialLoading, error, retry,
+ } = useServerList<types.Exercise>({
+ fetcher,
+ pageSize: PAGE_SIZE,
+ deps: [debouncedQuery],
+ })
const handleSelect = (exercise: types.Exercise) => {
const newEx: types.ActiveSessionExercise = {
@@ -84,9 +77,15 @@ export default function WorkoutExercisePicker() {
</button>
<div>
<h1 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h1>
- <p className="text-xs text-tx-muted">
- {available.length} loaded{exhausted ? '' : '…'}
- </p>
+ {/* Derived from the rows we actually hold, so it is only true if the fetch
+ landed. On a failure `available` is empty and this read "0 loaded" directly
+ above a message saying we could not load anything — the same claim the
+ error state exists to stop. */}
+ {!error && (
+ <p className="text-xs text-tx-muted">
+ {available.length} loaded{hasMore ? '…' : ''}
+ </p>
+ )}
</div>
</div>
@@ -105,15 +104,23 @@ export default function WorkoutExercisePicker() {
{/* List */}
<div className="flex-1 overflow-y-auto -mx-4 px-4">
- {loading && exercises.length === 0 ? (
+ {initialLoading ? (
<div className="flex items-center justify-center py-12 text-tx-muted text-sm">
<Dumbbell className="w-5 h-5 mr-2 animate-pulse text-brand-500" />
Loading…
</div>
) : available.length === 0 ? (
- <div className="flex items-center justify-center py-12 text-tx-muted text-sm">
- No exercises found
- </div>
+ // "No exercises found" is only true if we heard back. On a failed fetch it
+ // reads as an empty catalogue rather than a connection that dropped.
+ error ? (
+ <div className="py-4">
+ <ListError subject="these exercises" message={error} onRetry={retry} />
+ </div>
+ ) : (
+ <div className="flex items-center justify-center py-12 text-tx-muted text-sm">
+ No exercises found
+ </div>
+ )
) : (
<div className="space-y-1">
{available.map(ex => (
@@ -150,10 +157,10 @@ export default function WorkoutExercisePicker() {
</div>
</button>
))}
- {!exhausted && (
+ {hasMore && (
<button
type="button"
- onClick={() => load(query, page + 1, true)}
+ onClick={loadMore}
disabled={loading}
className="btn-secondary btn-sm w-full my-3"
>
diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsx
index bf4bb42..09c2efa 100644
--- a/web/src/pages/Workouts.tsx
+++ b/web/src/pages/Workouts.tsx
@@ -5,19 +5,19 @@ import { Dumbbell, Plus, Clock, Search, Edit2, Trash2, TrendingUp, Award, Chevro
import { useNavigate, useLocation } from 'react-router-dom'
import Loading from '../components/Loading'
import EmptyState from '../components/ui/EmptyState'
+import { ErrorState, ListError } from '../components/ui'
import PageHeader from '../components/ui/PageHeader'
import { Toast } from '../components/ui'
import { useServerInfiniteList } from '../hooks/useServerInfiniteList'
import { workoutAPI } from '../services/api'
import { useSettingsStore, weightShort, displayVolume } from '../stores/settings'
-import { types, workoutDay, calcVolume, formatDay } from '@lyftr/shared'
+import { useAsyncAction, types, workoutDay, calcVolume, formatDay } from '@lyftr/shared'
function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onEdit: (id: number) => void; onDelete: (id: number) => void }) {
const navigate = useNavigate()
const { settings } = useSettingsStore()
const wUnit = weightShort(settings.weight_unit)
const [confirming, setConfirming] = useState(false)
- const [deleting, setDeleting] = useState(false)
const [menuOpen, setMenuOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
const portalRef = useRef<HTMLDivElement>(null)
@@ -34,16 +34,13 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on
const durationMin = Math.round(workout.duration / 60)
const totalVolume = displayVolume(calcVolume(workout), wUnit)
- const handleDelete = async () => {
- setDeleting(true)
- try {
- await workoutAPI.delete(workout.id)
- onDelete(workout.id)
- } catch {
- setDeleting(false)
- setConfirming(false)
- }
- }
+ // Was `catch { setDeleting(false); setConfirming(false) }` — the card quietly came
+ // back and the user was left guessing whether the tap had registered. The confirm
+ // stays up now and says why, which is the same rule the sheets follow.
+ const remove = useAsyncAction(async () => {
+ await workoutAPI.delete(workout.id)
+ onDelete(workout.id)
+ }, 'Failed to delete workout')
if (confirming) {
return (
@@ -56,15 +53,16 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on
<div>
<p className="text-sm font-semibold text-tx-primary">Delete "{workout.name}"?</p>
<p className="text-xs text-tx-muted">This cannot be undone</p>
+ {remove.error && <p className="text-xs text-error-400 mt-1">{remove.error}</p>}
</div>
</div>
<div className="flex items-center gap-2">
<button onClick={() => setConfirming(false)} className="btn-secondary btn-sm">
Cancel
</button>
- <button onClick={handleDelete} disabled={deleting} className="btn-danger-solid btn-sm disabled:opacity-50">
+ <button onClick={() => { void remove.run() }} disabled={remove.busy} className="btn-danger-solid btn-sm disabled:opacity-50">
<Trash2 className="w-3 h-3" />
- {deleting ? 'Deleting…' : 'Delete'}
+ {remove.busy ? 'Deleting…' : 'Delete'}
</button>
</div>
</div>
@@ -221,13 +219,36 @@ export default function Workouts() {
return () => clearTimeout(t)
}, [search])
- const { items: workouts, sentinelRef, hasMore, loading, initialLoading, reload } = useServerInfiniteList<types.Workout>({
+ const {
+ items: workouts, sentinelRef, hasMore, loading, initialLoading, reload,
+ error: listError, retry: retryList,
+ } = useServerInfiniteList<types.Workout>({
fetcher: (offset, limit) => workoutAPI.list({ offset, limit, q: debouncedSearch || undefined }),
deps: [debouncedSearch],
})
if (initialLoading) return <Loading />
+ // Everything on this page is downstream of one request, so when it fails with nothing
+ // on screen the page failed — not a section of it. A section-sized error stranded among
+ // empty tiles and a search box that filters nothing is three dead regions and a note;
+ // one page-level error is the same information said once. The section-scoped ListError
+ // below stays for the case it is actually for: a later page failing under rows that
+ // did arrive.
+ if (listError && workouts.length === 0) {
+ return (
+ <div className="space-y-5 animate-slide-up">
+ <PageHeader title="Workouts" subtitle="Track and review your training sessions" />
+ <ErrorState
+ size="page"
+ title="Couldn't load your workouts"
+ message={listError}
+ onRetry={retryList}
+ />
+ </div>
+ )
+ }
+
return (
<div className="space-y-5 animate-slide-up">
<PageHeader
@@ -240,14 +261,22 @@ export default function Workouts() {
}
/>
- {/* Summary */}
+ {/* Summary — derived from `workouts`, so it is only true if the list arrived.
+ On a failed load the array is empty and these read "0 logged · 0 sessions",
+ which is a claim about the user's training, not a blank. The search box and
+ Log Workout below still work, so they stay; only the derived numbers go. */}
+ {!listError && (
<div className="grid grid-cols-3 gap-3">
{[
- { label: 'Total', value: workouts.length.toString(), unit: 'logged' },
+ // One page of an infinite list, so this is what has loaded, not how many exist:
+ // with more pages outstanding it is a lower bound and says so, rather than
+ // reporting a page size as a training history.
+ { label: 'Total', value: hasMore ? `${workouts.length}+` : workouts.length.toString(), unit: 'logged' },
// The month the workout was logged in, not the month its UTC instant lands in —
// a session near a month boundary belongs to the month the lifter trained in.
{ label: 'This Month', value: workouts.filter(w => workoutDay(w).startsWith(format(new Date(), 'yyyy-MM'))).length.toString(), unit: 'sessions' },
- { label: 'Avg Time', value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '0', unit: 'min' },
+ // The mean of no sessions is not zero minutes.
+ { label: 'Avg Time', value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '—', unit: 'min' },
].map(s => (
<div key={s.label} className="card p-4">
<div className="flex items-center gap-1.5 mb-2">
@@ -260,6 +289,7 @@ export default function Workouts() {
</div>
))}
</div>
+ )}
{/* Search */}
<div className="relative">
@@ -275,6 +305,8 @@ export default function Workouts() {
{/* Workout list */}
<div className="space-y-2">
{workouts.length === 0 && !loading ? (
+ // A failed first page never reaches here — the early return above renders it —
+ // so an empty list at this point really is empty.
<EmptyState
icon={Dumbbell}
title="No workouts found"
@@ -287,6 +319,7 @@ export default function Workouts() {
onDelete={() => reload()}
/>)}
<div ref={sentinelRef} />
+ {listError && <ListError subject="your workouts" message={listError} onRetry={retryList} />}
{hasMore && loading && (
<p className="text-center text-xs text-tx-muted py-2">Loading more…</p>
)}
diff --git a/web/src/services/api.test.ts b/web/src/services/api.test.ts
index 5830aaa..e99cac6 100644
--- a/web/src/services/api.test.ts
+++ b/web/src/services/api.test.ts
@@ -1,15 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { apiUrl, apiErrorMessage } from './api'
-
-describe('apiUrl', () => {
- it('builds the same-origin path when no origin is given', () => {
- expect(apiUrl()).toBe('/api/v1')
- })
-
- it('prefixes an absolute origin', () => {
- expect(apiUrl('http://localhost:3000')).toBe('http://localhost:3000/api/v1')
- })
-})
+import { apiErrorMessage } from './api'
describe('apiErrorMessage', () => {
it('passes through a structured server error', () => {
@@ -25,24 +15,31 @@ describe('apiErrorMessage', () => {
expect(apiErrorMessage({ response: { status: 405, data: {} } }, 'fallback')).toMatch(/misconfigured/i)
})
- // 502/503/504 are the reverse proxy talking, not the backend: it accepted the
- // connection and could not reach the app behind it. "Server error" was true but
- // unhelpful — the answer is to wait, not to change anything.
- it('reads a gateway status as a restart, not a generic server error', () => {
+ // A proxy saying the backend is not answering IT is worth retrying in a moment; our own
+ // code failing will fail the same way until someone reads the logs. Self-hosted stacks
+ // produce the first one on every `docker compose up -d`.
+ it('tells a restarting proxy apart from our own code failing', () => {
for (const status of [502, 503, 504]) {
expect(apiErrorMessage({ response: { status, data: {} } }, 'fallback')).toMatch(/restarting or unreachable/i)
}
+ expect(apiErrorMessage({ response: { status: 500, data: {} } }, 'fallback')).toMatch(/server error/i)
})
- // Every reverse proxy serves its 502 as an HTML page, so a body sniff that ran first
- // diagnosed a restarting backend as "you typed the wrong address".
- it('reads an HTML-bodied 502 as a restart, not as a wrong address', () => {
+ // This asserted /web page/ for an HTML-bodied 502, which pinned the wrong answer:
+ // every reverse proxy serves its 502 as HTML, so the body sniff fired first and told
+ // a self-hoster to check Server settings while their backend was merely restarting.
+ // Status is the stronger signal and is now read first.
+ it('reads an HTML 502 from a proxy as a restart, not as a wrong address', () => {
const html = '<!DOCTYPE html><html><body>502 Bad Gateway</body></html>'
- expect(apiErrorMessage({ response: { status: 502, data: html } }, 'fallback')).toMatch(/restarting or unreachable/i)
+ const msg = apiErrorMessage({ response: { status: 502, data: html } }, 'Failed to save')
+ expect(msg).toMatch(/restarting or unreachable/i)
+ expect(msg).not.toBe('Failed to save')
})
- it('still maps a plain 500 to a server error', () => {
- expect(apiErrorMessage({ response: { status: 500, data: {} } }, 'fallback')).toMatch(/server error/i)
+ // The sniff still earns its keep where the status explains nothing on its own.
+ it('names an HTML body when the status does not already explain it', () => {
+ const html = '<html><body>Welcome to nginx</body></html>'
+ expect(apiErrorMessage({ response: { status: 500, data: html } }, 'x')).toMatch(/web page/i)
})
it('uses the fallback for other responses without a server error', () => {
diff --git a/web/src/services/api.ts b/web/src/services/api.ts
index 0b15dd0..bce8649 100644
--- a/web/src/services/api.ts
+++ b/web/src/services/api.ts
@@ -18,6 +18,4 @@ export const {
savedFoodsAPI,
} = client
-export { apiUrl, apiErrorMessage, testServerConnection, type ServerInfo } from '@lyftr/shared'
-
-export default client.api
+export { apiErrorMessage, testServerConnection, type ServerInfo } from '@lyftr/shared'