Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Add an exercise browser with generic filters, reachable from Workouts (#228)
Carter6658c495350d
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.goindex bc83883..b68a9d3 100644--- a/backend/controllers/exercises.go+++ b/backend/controllers/exercises.go@@ -5,6 +5,7 @@ import ("errors""log""strconv"+ "strings""github.com/Cawlumm/lyftr-backend/middleware""github.com/Cawlumm/lyftr-backend/stores"@@ -20,12 +21,19 @@ func requestLocale(c *gin.Context) string { return stores.NormalizeLocale(c.Quer// Open Food Facts that key their names by language alone.func requestLanguage(c *gin.Context) string { return stores.BaseLanguage(requestLocale(c)) }+// filterParam reads a catalogue filter. The values are lowercase slugs, and a filter that+// matches nothing is answered with an empty list rather than an error, so `muscle_group=Chest`+// used to look exactly like a muscle with no exercises.+func filterParam(c *gin.Context, key string) string {+ return strings.ToLower(strings.TrimSpace(c.Query(key)))+}+func (h *Handler) ListExercises(c *gin.Context) {f := stores.ExerciseFilter{Query: c.Query("q"),- MuscleGroup: c.Query("muscle_group"),- Category: c.Query("category"),- Equipment: c.Query("equipment"),+ MuscleGroup: filterParam(c, "muscle_group"),+ Category: filterParam(c, "category"),+ Equipment: filterParam(c, "equipment"),Locale: requestLocale(c),Limit: 100,}diff --git a/backend/controllers/exercises_test.go b/backend/controllers/exercises_test.goindex 333b114..a49b885 100644--- a/backend/controllers/exercises_test.go+++ b/backend/controllers/exercises_test.go@@ -386,3 +386,26 @@ func TestExercises_RemovedUpstreamHiddenFromListButResolvable(t *testing.T) {t.Errorf("logging a removed exercise = %d %s, want 201", w.Code, w.Body.String())}}++// A filter is a lowercase slug. Capitals or stray spaces used to match nothing, and the+// empty list that came back read as "no exercises for this muscle".+func TestListExercises_filtersAreNormalised(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ seedSpanishSquat(t, uid) // muscle_group 'legs', category 'strength'++ count := func(query string) int {+ c, w := newContext(uid, http.MethodGet, "/api/v1/exercises"+query, nil)+ th.ListExercises(c)+ return len(decodeResponse(t, w)["data"].([]any))+ }++ for _, query := range []string{"?muscle_group=legs", "?muscle_group=Legs", "?muscle_group=%20LEGS%20", "?category=STRENGTH"} {+ if got := count(query); got != 1 {+ t.Errorf("GET /exercises%s returned %d rows, want 1", query, got)+ }+ }+ if got := count("?muscle_group=bogus"); got != 0 {+ t.Errorf("an unknown muscle returned %d rows, want 0", got)+ }+}diff --git a/mobile/app/(tabs)/workouts/exercises.tsx b/mobile/app/(tabs)/workouts/exercises.tsxnew file mode 100644index 0000000..9e35a84--- /dev/null+++ b/mobile/app/(tabs)/workouts/exercises.tsx@@ -0,0 +1,7 @@+import { ExerciseBrowser } from '../../../src/components/workouts/ExerciseBrowser'++// Read-only exercise catalogue, opened from the Workouts list. Lives in the Workouts stack so+// a row opens workouts/exercise/[exerciseId] and back returns here.+export default function WorkoutsExercises() {+ return <ExerciseBrowser />+}diff --git a/mobile/app/(tabs)/workouts/index.tsx b/mobile/app/(tabs)/workouts/index.tsxindex d36f0dc..144b4b0 100644--- a/mobile/app/(tabs)/workouts/index.tsx+++ b/mobile/app/(tabs)/workouts/index.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useRef, useState } from 'react'-import { ActivityIndicator, FlatList, RefreshControl, View } from 'react-native'+import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from 'react-native'import { router, useFocusEffect, type Href } from 'expo-router'-import { Award, CheckCircle2, Dumbbell, Plus, RotateCcw, TrendingUp } from 'lucide-react-native'+import { Award, CheckCircle2, ChevronRight, Dumbbell, Library, Plus, RotateCcw, TrendingUp } from 'lucide-react-native'import { format } from 'date-fns'import { weightShort, workoutDay, useTranslation, type Workout } from '@lyftr/shared'import { AppText, Card, EmptyState, ErrorState, IconButton, StatFailure, Label, PageHeader, Screen, SearchField, Toast } from '../../../src/components/ui'@@ -21,7 +21,7 @@ export default function Workouts() {const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const unit = weightShort(settings.weight_unit)- const { accent } = useTheme()+ const { accent, colors } = useTheme()const [search, setSearch] = useState('')const [debouncedSearch, setDebouncedSearch] = useState('')@@ -226,6 +226,24 @@ export default function Workouts() {}/>+ {/* A labelled row, not a header icon: the exercise library is a place to go, and an+ unlabelled glyph beside the plus did not say where. */}+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t('workouts.list.browseExercises')}+ onPress={() => router.push('/workouts/exercises')}+ className="flex-row items-center gap-3 rounded-xl border border-surface-border bg-surface-raised p-3.5 active:bg-surface-muted"+ >+ <View className="h-10 w-10 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10">+ <Library size={20} color={accent} strokeWidth={2} />+ </View>+ <View className="flex-1">+ <AppText variant="bodySemibold">{t('workouts.list.browseExercises')}</AppText>+ <AppText variant="caption" color="muted" numberOfLines={1}>{t('exercises.browse.subtitle')}</AppText>+ </View>+ <ChevronRight size={16} color={colors.txMuted} />+ </Pressable>+{/* Summary — web's 3-card grid. Dimmed while a new search revalidates: thestats summarize the loaded items, so they're stale mid-search — fadingthem (and the rows below) signals "updating" without a blank flash. */}diff --git a/mobile/src/components/ui/ActiveFilters.tsx b/mobile/src/components/ui/ActiveFilters.tsxnew file mode 100644index 0000000..24cb63b--- /dev/null+++ b/mobile/src/components/ui/ActiveFilters.tsx@@ -0,0 +1,51 @@+import { Pressable, ScrollView } from 'react-native'+import Animated, { FadeIn, FadeOut, LinearTransition } from 'react-native-reanimated'+import { X } from 'lucide-react-native'+import { type FilterGroup, type FilterValues, activeFilters, useTranslation } from '@lyftr/shared'+import { useTheme } from '../../theme/useTheme'+import { AppText } from './Typography'++interface Props {+ groups: readonly FilterGroup[]+ values: FilterValues+ onRemove: (key: string) => void+}++// What is on, as removable chips under the search field, so a filter can be dropped in one+// tap without reopening the sheet. Renders nothing when nothing is on. Mirrors web+// ui/ActiveFilters.+export function ActiveFilters({ groups, values, onRemove }: Props) {+ const { t } = useTranslation()+ const { accent } = useTheme()+ const active = activeFilters(groups, values)+ if (active.length === 0) return null+ return (+ <ScrollView+ horizontal+ showsHorizontalScrollIndicator={false}+ accessibilityLabel={t('filters.active')}+ keyboardShouldPersistTaps="handled"+ contentContainerClassName="gap-1.5 px-4"+ >+ {active.map((f) => (+ <Animated.View+ key={f.key}+ entering={FadeIn.duration(150)}+ exiting={FadeOut.duration(120)}+ layout={LinearTransition}+ >+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t('filters.remove', { label: f.label })}+ onPress={() => onRemove(f.key)}+ hitSlop={6}+ className="flex-row items-center gap-1 rounded-full border border-brand-500/40 bg-brand-500/15 py-1.5 pl-3 pr-2 active:opacity-60"+ >+ <AppText variant="caption" color="brand" className="capitalize">{f.label}</AppText>+ <X size={12} color={accent} strokeWidth={2.4} />+ </Pressable>+ </Animated.View>+ ))}+ </ScrollView>+ )+}diff --git a/mobile/src/components/ui/FilterButton.tsx b/mobile/src/components/ui/FilterButton.tsxnew file mode 100644index 0000000..fda1c52--- /dev/null+++ b/mobile/src/components/ui/FilterButton.tsx@@ -0,0 +1,39 @@+import { Pressable, View } from 'react-native'+import { SlidersHorizontal } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'+import { useTheme } from '../../theme/useTheme'+import { AppText } from './Typography'++interface Props {+ /** How many filters are on. Zero is the plain button; more lights it up with the count. */+ active: number+ onPress: () => void+}++// The button beside a search field that opens a FilterSheet. The count is on the button+// itself so what is narrowing the list is visible without opening anything. Mirrors web+// ui/FilterButton.+export function FilterButton({ active, onPress }: Props) {+ const { t } = useTranslation()+ const { accent, colors } = useTheme()+ const on = active > 0+ return (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={on ? t('filters.buttonActive', { active }) : t('filters.button')}+ onPress={onPress}+ className={`h-11 w-11 items-center justify-center rounded-xl border active:scale-95 ${+ on ? 'border-brand-500/40 bg-brand-500/15' : 'border-surface-border bg-surface-muted'+ }`}+ >+ <SlidersHorizontal size={16} color={on ? accent : colors.txMuted} strokeWidth={2.2} />+ {on ? (+ <View className="absolute -right-1.5 -top-1.5 h-[18px] min-w-[18px] items-center justify-center rounded-full bg-brand-500 px-1">+ <AppText variant="caption" className="text-[11px] font-semibold" style={{ color: '#ffffff' }}>+ {active}+ </AppText>+ </View>+ ) : null}+ </Pressable>+ )+}diff --git a/mobile/src/components/ui/FilterSheet.test.tsx b/mobile/src/components/ui/FilterSheet.test.tsxnew file mode 100644index 0000000..16e8e56--- /dev/null+++ b/mobile/src/components/ui/FilterSheet.test.tsx@@ -0,0 +1,99 @@+import { fireEvent, render, screen } from '@testing-library/react-native'+import type { FilterGroup } from '@lyftr/shared'++jest.mock('@react-native-async-storage/async-storage', () =>+ require('@react-native-async-storage/async-storage/jest/async-storage-mock')+)+jest.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),+ SafeAreaProvider: ({ children }: { children: unknown }) => children,+}))++import { ActiveFilters } from './ActiveFilters'+import { FilterButton } from './FilterButton'+import { FilterSheet } from './FilterSheet'++// Deliberately not the exercise filters: the sheet is generic over whatever groups a screen+// declares, and a test that only used muscles would not notice if it quietly were not.+const groups: FilterGroup[] = [+ { key: 'meal', label: 'Meal', options: [{ value: 'lunch', label: 'Lunch' }, { value: 'dinner', label: 'Dinner' }] },+ { key: 'source', label: 'Source', options: [{ value: 'saved', label: 'Saved' }] },+]++const none = { meal: null, source: null } as Record<string, string | null>++describe('FilterSheet (mobile)', () => {+ it('renders every option of every group', async () => {+ await render(<FilterSheet open groups={groups} values={none} onChange={jest.fn()} onReset={jest.fn()} onClose={jest.fn()} />)+ expect(screen.getByText('Meal')).toBeTruthy()+ expect(screen.getByText('Source')).toBeTruthy()+ expect(screen.getByText('Dinner')).toBeTruthy()+ expect(screen.getByText('Saved')).toBeTruthy()+ })++ it('renders nothing when closed', async () => {+ await render(<FilterSheet open={false} groups={groups} values={none} onChange={jest.fn()} onReset={jest.fn()} onClose={jest.fn()} />)+ expect(screen.queryByText('Meal')).toBeNull()+ })++ it('reports the option picked, and null when the one that is on is picked again', async () => {+ const onChange = jest.fn()+ await render(+ <FilterSheet open groups={groups} values={{ meal: 'lunch', source: null }} onChange={onChange} onReset={jest.fn()} onClose={jest.fn()} />+ )+ await fireEvent.press(screen.getByText('Dinner'))+ expect(onChange).toHaveBeenLastCalledWith('meal', 'dinner')+ await fireEvent.press(screen.getByRole('button', { name: 'Lunch' }))+ expect(onChange).toHaveBeenLastCalledWith('meal', null)+ })++ it('closes from the close button', async () => {+ const onClose = jest.fn()+ await render(<FilterSheet open groups={groups} values={none} onChange={jest.fn()} onReset={jest.fn()} onClose={onClose} />)+ await fireEvent.press(screen.getByRole('button', { name: 'Close' }))+ expect(onClose).toHaveBeenCalled()+ })++ it('does not reset when nothing is on, and resets and closes when something is', async () => {+ const onReset = jest.fn()+ const onClose = jest.fn()+ const { rerender } = await render(+ <FilterSheet open groups={groups} values={none} onChange={jest.fn()} onReset={onReset} onClose={onClose} />+ )+ await fireEvent.press(screen.getByText('Reset'))+ expect(onReset).not.toHaveBeenCalled()++ await rerender(+ <FilterSheet open groups={groups} values={{ meal: 'lunch', source: null }} onChange={jest.fn()} onReset={onReset} onClose={onClose} />+ )+ await fireEvent.press(screen.getByText('Reset'))+ expect(onReset).toHaveBeenCalled()+ await fireEvent.press(screen.getByText('Done'))+ expect(onClose).toHaveBeenCalled()+ })+})++describe('FilterButton (mobile)', () => {+ it('is plain at zero and carries the count above it', async () => {+ const { rerender } = await render(<FilterButton active={0} onPress={jest.fn()} />)+ expect(screen.getByRole('button', { name: 'Filters' })).toBeTruthy()+ await rerender(<FilterButton active={2} onPress={jest.fn()} />)+ expect(screen.getByRole('button', { name: 'Filters, 2 active' })).toBeTruthy()+ expect(screen.getByText('2')).toBeTruthy()+ })+})++describe('ActiveFilters (mobile)', () => {+ it('lists what is on and removes by key', async () => {+ const onRemove = jest.fn()+ await render(<ActiveFilters groups={groups} values={{ source: 'saved', meal: 'dinner' }} onRemove={onRemove} />)+ expect(screen.getByText('Dinner')).toBeTruthy()+ await fireEvent.press(screen.getByRole('button', { name: 'Remove filter: Saved' }))+ expect(onRemove).toHaveBeenCalledWith('source')+ })++ it('renders nothing when nothing is on', async () => {+ await render(<ActiveFilters groups={groups} values={none} onRemove={jest.fn()} />)+ expect(screen.queryByText('Dinner')).toBeNull()+ })+})diff --git a/mobile/src/components/ui/FilterSheet.tsx b/mobile/src/components/ui/FilterSheet.tsxnew file mode 100644index 0000000..4c1b8f6--- /dev/null+++ b/mobile/src/components/ui/FilterSheet.tsx@@ -0,0 +1,98 @@+import { Pressable, ScrollView, View, useWindowDimensions } from 'react-native'+import { Check, X } from 'lucide-react-native'+import * as Haptics from 'expo-haptics'+import { type FilterGroup, type FilterValues, activeFilterCount, useTranslation } from '@lyftr/shared'+import { useTheme } from '../../theme/useTheme'+import { AppText } from './Typography'+import { Button } from './Button'+import { IconButton } from './IconButton'+import { Sheet } from './Sheet'++interface Props {+ open: boolean+ groups: readonly FilterGroup[]+ values: FilterValues+ /** Fires with the option picked, or null when the one already on is picked again. */+ onChange: (key: string, value: string | null) => void+ onReset: () => void+ onClose: () => void+}++// The panel behind a FilterButton: one section per group, every option visible at once+// instead of scrolled past. Generic over `groups`, so a screen with other filters brings its+// own list and nothing here changes. Changes apply as they are made (the list updates behind+// the scrim); Done only closes. Mirrors web ui/FilterSheet.+export function FilterSheet({ open, groups, values, onChange, onReset, onClose }: Props) {+ const { t } = useTranslation()+ const { height } = useWindowDimensions()+ const { accent } = useTheme()+ const count = activeFilterCount(groups, values)++ return (+ <Sheet open={open} onClose={onClose} haptic="selection">+ <View className="flex-row items-center justify-between border-b border-surface-border px-5 pb-3 pt-1">+ <AppText variant="title">{t('filters.title')}</AppText>+ <View className="flex-row items-center gap-3">+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t('filters.reset')}+ accessibilityState={{ disabled: count === 0 }}+ onPress={() => {+ Haptics.selectionAsync().catch(() => {})+ onReset()+ }}+ disabled={count === 0}+ hitSlop={10}+ className={`active:opacity-60 ${count === 0 ? 'opacity-40' : ''}`}+ >+ <AppText variant="label" color="brand">{t('filters.reset')}</AppText>+ </Pressable>+ <IconButton icon={X} label={t('common.close')} variant="ghost" size="md" onPress={onClose} />+ </View>+ </View>++ <ScrollView style={{ maxHeight: height * 0.6 }} contentContainerClassName="gap-6 px-5 py-4">+ {groups.map((group) => (+ <View key={group.key} accessibilityLabel={group.label}>+ <View className="mb-2.5 flex-row items-baseline justify-between">+ <AppText variant="subheading">{group.label}</AppText>+ {values[group.key] != null ? (+ <AppText variant="caption" color="brand" className="capitalize">+ {group.options.find((o) => o.value === values[group.key])?.label}+ </AppText>+ ) : null}+ </View>+ <View className="flex-row flex-wrap gap-2">+ {group.options.map((option) => {+ const on = values[group.key] === option.value+ return (+ <Pressable+ key={option.value}+ accessibilityRole="button"+ accessibilityState={{ selected: on }}+ onPress={() => {+ Haptics.selectionAsync().catch(() => {})+ onChange(group.key, on ? null : option.value)+ }}+ className={`flex-row items-center gap-1.5 rounded-full border px-3.5 py-2.5 active:scale-95 ${+ on ? 'border-brand-500/40 bg-brand-500/15' : 'border-surface-border bg-surface-muted'+ }`}+ >+ {on ? <Check size={14} color={accent} strokeWidth={2.6} /> : null}+ <AppText variant="caption" color={on ? 'brand' : 'muted'} className="capitalize">+ {option.label}+ </AppText>+ </Pressable>+ )+ })}+ </View>+ </View>+ ))}+ </ScrollView>++ <View className="border-t border-surface-border px-5 pt-3">+ <Button title={t('filters.done')} onPress={onClose} />+ </View>+ </Sheet>+ )+}diff --git a/mobile/src/components/ui/Sheet.tsx b/mobile/src/components/ui/Sheet.tsxindex de33b61..5043cc7 100644--- a/mobile/src/components/ui/Sheet.tsx+++ b/mobile/src/components/ui/Sheet.tsx@@ -1,5 +1,5 @@-import { useEffect, type ReactNode } from 'react'-import { Modal, Pressable, View } from 'react-native'+import { useEffect, useRef, type ReactNode } from 'react'+import { Animated as RNAnimated, Modal, PanResponder, Pressable, View } from 'react-native'import Animated, { Easing, SlideInDown } from 'react-native-reanimated'import { useSafeAreaInsets } from 'react-native-safe-area-context'import * as Haptics from 'expo-haptics'@@ -8,6 +8,10 @@ import * as Haptics from 'expo-haptics'// ActionSheet handing off to a ConfirmSheet) to start after this one dismisses.export const SHEET_ANIM_MS = 240+// How far, or how fast, a downward swipe on the grabber has to go to dismiss the sheet.+const DISMISS_DISTANCE = 90+const DISMISS_VELOCITY = 0.8+type SheetHaptic = 'selection' | 'warning' | 'none'interface Props {@@ -33,6 +37,39 @@ interface Props {export function Sheet({ open, onClose, children, bottomInset = 20, haptic = 'none' }: Props) {const insets = useSafeAreaInsets()+ // Swipe down on the grabber to dismiss. PanResponder rather than gesture-handler: a Modal is+ // its own native root, and gesture-handler needs a root view inside it to receive touches.+ // Only the grabber zone listens, so a ScrollView inside the sheet keeps its own scrolling.+ const dragY = useRef(new RNAnimated.Value(0)).current+ const onCloseRef = useRef(onClose)+ onCloseRef.current = onClose+ const pan = useRef(+ PanResponder.create({+ onStartShouldSetPanResponder: () => true,+ onMoveShouldSetPanResponder: (_, g) => Math.abs(g.dy) > 4,+ onPanResponderMove: (_, g) => dragY.setValue(Math.max(0, g.dy)),+ onPanResponderRelease: (_, g) => {+ if (g.dy > DISMISS_DISTANCE || g.vy > DISMISS_VELOCITY) {+ RNAnimated.timing(dragY, { toValue: 600, duration: 160, useNativeDriver: true }).start(() => {+ onCloseRef.current()+ // A sheet whose parent declines to close (a confirm that is mid-request) must come+ // back rather than sit invisible behind its scrim. A no-op when it did close.+ RNAnimated.spring(dragY, { toValue: 0, useNativeDriver: true, bounciness: 0 }).start()+ })+ } else {+ RNAnimated.spring(dragY, { toValue: 0, useNativeDriver: true, bounciness: 0 }).start()+ }+ },+ onPanResponderTerminate: () => {+ RNAnimated.spring(dragY, { toValue: 0, useNativeDriver: true, bounciness: 0 }).start()+ },+ }),+ ).current++ useEffect(() => {+ if (open) dragY.setValue(0)+ }, [open, dragY])+useEffect(() => {if (!open || haptic === 'none') returnconst fire = haptic === 'warning'@@ -47,15 +84,20 @@ export function Sheet({ open, onClose, children, bottomInset = 20, haptic = 'non<Modal visible transparent statusBarTranslucent animationType="fade" onRequestClose={onClose}><Pressable className="flex-1 justify-end bg-black/60" onPress={onClose}><Animated.View entering={SlideInDown.duration(SHEET_ANIM_MS).easing(Easing.out(Easing.cubic))}>- <Pressable- onPress={(e) => e.stopPropagation()}- style={{ paddingBottom: insets.bottom + bottomInset }}- className="rounded-t-3xl border border-surface-border bg-surface-base pt-3"- >- {/* Grabber — signals a dismissible sheet; matches the web handle. */}- <View className="mx-auto mb-3 h-1 w-10 rounded-full bg-surface-muted" />- {children}- </Pressable>+ <RNAnimated.View style={{ transform: [{ translateY: dragY }] }}>+ <Pressable+ onPress={(e) => e.stopPropagation()}+ style={{ paddingBottom: insets.bottom + bottomInset }}+ className="rounded-t-3xl border border-surface-border bg-surface-base pt-3"+ >+ {/* Grabber — signals a dismissible sheet, and is the handle you swipe down. The+ zone is taller than the bar so it is easy to hit; matches the web handle. */}+ <View {...pan.panHandlers} className="-mt-3 items-center pb-3 pt-3">+ <View className="h-1 w-10 rounded-full bg-surface-muted" />+ </View>+ {children}+ </Pressable>+ </RNAnimated.View></Animated.View></Pressable></Modal>diff --git a/mobile/src/components/ui/index.ts b/mobile/src/components/ui/index.tsindex c2fa8a7..452538f 100644--- a/mobile/src/components/ui/index.ts+++ b/mobile/src/components/ui/index.ts@@ -22,6 +22,9 @@ export { SectionHeader } from './SectionHeader'export { Button } from './Button'export { IconButton } from './IconButton'export { SegmentedControl } from './SegmentedControl'+export { FilterButton } from './FilterButton'+export { FilterSheet } from './FilterSheet'+export { ActiveFilters } from './ActiveFilters'// Inputsexport { Field } from './Field'diff --git a/mobile/src/components/workouts/ExerciseBrowser.test.tsx b/mobile/src/components/workouts/ExerciseBrowser.test.tsxnew file mode 100644index 0000000..4f8f1a4--- /dev/null+++ b/mobile/src/components/workouts/ExerciseBrowser.test.tsx@@ -0,0 +1,105 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react-native'+import type { Exercise } from '@lyftr/shared'++const mockPush = jest.fn()+jest.mock('expo-router', () => ({+ router: { push: (...a: unknown[]) => mockPush(...a), navigate: jest.fn(), replace: jest.fn(), back: jest.fn(), canGoBack: () => true },+}))+jest.mock('@react-native-async-storage/async-storage', () =>+ require('@react-native-async-storage/async-storage/jest/async-storage-mock')+)+jest.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),+ SafeAreaProvider: ({ children }: { children: unknown }) => children,+ SafeAreaView: ({ children }: { children: unknown }) => children,+}))++import { client } from '../../lib/lyftr'+import { ExerciseBrowser } from './ExerciseBrowser'++const bench: Exercise = {+ id: 1, name: 'Bench Press', muscle_group: 'chest', secondary_muscles: [],+ category: 'strength', equipment: 'barbell', description: '',+}++const renderBrowser = async () => await render(<ExerciseBrowser />)++afterEach(() => { jest.restoreAllMocks(); mockPush.mockReset() })++describe('ExerciseBrowser (mobile)', () => {+ it('asks for an unfiltered first page and opens a row on the exercise page', async () => {+ const list = jest.spyOn(client.exerciseAPI, 'list').mockResolvedValue([bench])+ await renderBrowser()++ await fireEvent.press(await screen.findByText('Bench Press'))++ expect(list).toHaveBeenCalledWith({ page: 1 })+ expect(mockPush).toHaveBeenCalledWith('/workouts/exercise/1')+ })++ const openFilters = async () => await fireEvent.press(screen.getByRole('button', { name: 'Filters' }))++ it('sends the sheet filters to the server and resets them', async () => {+ const list = jest.spyOn(client.exerciseAPI, 'list').mockResolvedValue([bench])+ await renderBrowser()+ await screen.findByText('Bench Press')+ await openFilters()++ await fireEvent.press(screen.getByRole('button', { name: 'chest', selected: false }))+ await waitFor(() => expect(list).toHaveBeenLastCalledWith({ muscle_group: 'chest', page: 1 }))++ await fireEvent.press(screen.getByText('Dumbbell'))+ await waitFor(() =>+ expect(list).toHaveBeenLastCalledWith({ muscle_group: 'chest', equipment: 'dumbbell', page: 1 }))++ await fireEvent.press(screen.getByText('Reset'))+ await waitFor(() => expect(list).toHaveBeenLastCalledWith({ page: 1 }))+ })++ it('counts the filters on the button and removes one from its chip', async () => {+ const list = jest.spyOn(client.exerciseAPI, 'list').mockResolvedValue([bench])+ await renderBrowser()+ await screen.findByText('Bench Press')+ await openFilters()+ await fireEvent.press(screen.getByRole('button', { name: 'chest', selected: false }))+ await fireEvent.press(screen.getByRole('button', { name: 'Barbell', selected: false }))+ await fireEvent.press(screen.getByText('Done'))++ expect(await screen.findByRole('button', { name: 'Filters, 2 active' })).toBeTruthy()+ await fireEvent.press(screen.getByRole('button', { name: 'Remove filter: chest' }))+ await waitFor(() => expect(list).toHaveBeenLastCalledWith({ equipment: 'barbell', page: 1 }))+ expect(screen.getByRole('button', { name: 'Filters, 1 active' })).toBeTruthy()+ })++ // An empty filter result must not read as an empty library: that answer offers "Try again"+ // and says the library is still loading, which is false when the server answered.+ it('says no exercise matches when a filter returns nothing, not that the library is empty', async () => {+ jest.spyOn(client.exerciseAPI, 'list').mockResolvedValueOnce([bench]).mockResolvedValue([])+ await renderBrowser()+ await screen.findByText('Bench Press')+ await openFilters()++ await fireEvent.press(screen.getByText('calves'))++ expect(await screen.findByText('No exercises match')).toBeTruthy()+ expect(screen.queryByText('The exercise library is still loading')).toBeNull()+ })++ it('shows the empty-library state when an unfiltered list is empty', async () => {+ jest.spyOn(client.exerciseAPI, 'list').mockResolvedValue([])+ await renderBrowser()++ expect(await screen.findByText('The exercise library is still loading')).toBeTruthy()+ expect(screen.queryByText('No exercises match')).toBeNull()+ })++ it('says the load failed instead of an empty catalogue', async () => {+ const err: any = new Error('timeout of 20000ms exceeded')+ err.code = 'ECONNABORTED'+ jest.spyOn(client.exerciseAPI, 'list').mockRejectedValue(err)+ await renderBrowser()++ expect(await screen.findByText("Couldn't load exercises")).toBeTruthy()+ expect(screen.queryByText('No exercises found')).toBeNull()+ })+})diff --git a/mobile/src/components/workouts/ExerciseBrowser.tsx b/mobile/src/components/workouts/ExerciseBrowser.tsxnew file mode 100644index 0000000..f3490d3--- /dev/null+++ b/mobile/src/components/workouts/ExerciseBrowser.tsx@@ -0,0 +1,217 @@+import { useCallback, useEffect, useState } from 'react'+import { ActivityIndicator, FlatList, Pressable, View } from 'react-native'+import { router, type Href } from 'expo-router'+import { SafeAreaView } from 'react-native-safe-area-context'+import { ArrowLeft, ChevronRight, Dumbbell, SearchX } from 'lucide-react-native'+import Animated, { useAnimatedStyle, withTiming } from 'react-native-reanimated'+import {+ EXERCISE_PAGE_SIZE, EXERCISE_SEARCH_DEBOUNCE_MS,+ activeFilterCount, emptyFilters, exerciseBrowseFiltered, exerciseBrowseParams, exerciseCatalogEmpty,+ exerciseFilterGroups, hasEquipmentToShow, setFilter, useTranslation,+ type Exercise, type FilterValues,+} from '@lyftr/shared'+import {+ ActiveFilters, AppText, Button, EmptyState, ErrorState, FilterButton, FilterSheet, IconButton,+ PageHeader, SearchField, Skeleton,+} from '../ui'+import { client } from '../../lib/lyftr'+import { useServerInfiniteList } from '../../hooks/useServerInfiniteList'+import { useTheme } from '../../theme/useTheme'+import { equipmentLabel, muscleLabel } from '../../utils/exerciseUtils'+import { ExerciseImage } from './ExerciseImage'++const exerciseHref = (id: number) => `/workouts/exercise/${id}` as unknown as Href++// Row-shaped placeholders for the first load, so the list fills in rather than popping in+// after a spinner. Same thumbnail size and two text lines as BrowseRow.+function BrowseSkeleton() {+ return (+ <View className="px-4 py-2">+ {Array.from({ length: 8 }, (_, i) => (+ <View key={i} className="flex-row items-center gap-3 px-3 py-3">+ <Skeleton width={44} height={44} radius={12} />+ <View className="flex-1 gap-2">+ <Skeleton width="65%" height={14} />+ <Skeleton width="35%" height={11} />+ </View>+ </View>+ ))}+ </View>+ )+}++function BrowseRow({ exercise }: { exercise: Exercise }) {+ useTranslation() // re-renders on a language switch: the labels below come from the catalog+ const { colors } = useTheme()+ return (+ <Pressable+ accessibilityRole="button"+ onPress={() => router.push(exerciseHref(exercise.id))}+ className="flex-row items-center gap-3 px-3 py-3 active:bg-surface-muted/60"+ >+ <ExerciseImage url={exercise.image_url} />+ <View className="flex-1">+ <AppText variant="subheading" numberOfLines={1}>{exercise.name}</AppText>+ <View className="mt-0.5 flex-row flex-wrap items-center gap-1.5">+ <View className="rounded border border-surface-border bg-surface-muted px-1.5 py-0.5">+ <AppText variant="caption" color="muted" className="capitalize">+ {muscleLabel(exercise.muscle_group)}+ </AppText>+ </View>+ {hasEquipmentToShow(exercise.equipment) ? (+ <AppText variant="caption" color="muted">{equipmentLabel(exercise.equipment)}</AppText>+ ) : null}+ </View>+ </View>+ <ChevronRight size={16} color={colors.txMuted} />+ </Pressable>+ )+}++// Read-only catalogue, reached from the Workouts tab: look an exercise up and open its page+// without starting a workout. Same server-paged list as the picker, minus the add step, plus+// the muscle and equipment filters the API already takes, behind a filter button.+export function ExerciseBrowser() {+ const { t } = useTranslation()+ const { accent } = useTheme()+ const [query, setQuery] = useState('')+ const [debouncedQuery, setDebouncedQuery] = useState('')+ const [filters, setFilters] = useState<FilterValues>(() => emptyFilters(exerciseFilterGroups()))+ const [sheetOpen, setSheetOpen] = useState(false)+ const groups = exerciseFilterGroups()+ const { muscle, equipment } = filters+ const count = activeFilterCount(groups, filters)++ useEffect(() => {+ const timer = setTimeout(() => setDebouncedQuery(query), EXERCISE_SEARCH_DEBOUNCE_MS)+ return () => clearTimeout(timer)+ }, [query])++ const filtered = exerciseBrowseFiltered({ query: debouncedQuery, muscle, equipment })++ const fetcher = useCallback(+ (offset: number, limit: number) =>+ client.exerciseAPI+ .list({ ...exerciseBrowseParams({ query: debouncedQuery, muscle, equipment }), page: offset / limit + 1 })+ .then((data) => data ?? []),+ [debouncedQuery, muscle, equipment]+ )++ const {+ items: exercises, loadMore, hasMore, loading, initialLoading, refreshing, staleResults,+ error: listError, retry: retryList, reload,+ } = useServerInfiniteList<Exercise>({+ fetcher,+ pageSize: EXERCISE_PAGE_SIZE,+ deps: [debouncedQuery, muscle, equipment],+ })++ // Eased rather than snapped, so a fresh query reads as the same list updating.+ const fade = useAnimatedStyle(+ () => ({ opacity: withTiming(refreshing ? 0.5 : 1, { duration: 150 }) }),+ [refreshing],+ )+ const resetFilters = () => setFilters(emptyFilters(groups))+ // The hook keeps the previous query's rows when a new query's first page fails; shown as they+ // are they read as its results, so the failure takes their place.+ const shown = staleResults ? [] : exercises+ const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))+ const changeFilter = (key: string, value: string | null) => setFilters((f) => setFilter(f, key, value))++ return (+ <SafeAreaView className="flex-1 bg-surface-base" edges={['top']}>+ <View className="flex-row items-center gap-3 px-4 pb-3 pt-3">+ <IconButton icon={ArrowLeft} label={t('exercises.browse.backToWorkouts')} variant="ghost" size="md" onPress={goBack} />+ <View className="flex-1">+ <PageHeader title={t('exercises.browse.title')} subtitle={t('exercises.browse.subtitle')} />+ </View>+ </View>++ <View className="flex-row items-center gap-2 px-4 pb-3">+ <View className="flex-1">+ <SearchField value={query} onChangeText={setQuery} placeholder={t('exercises.picker.search')} />+ </View>+ <FilterButton active={count} onPress={() => setSheetOpen(true)} />+ </View>++ {count > 0 ? (+ <View className="pb-2">+ <ActiveFilters groups={groups} values={filters} onRemove={(key) => changeFilter(key, null)} />+ </View>+ ) : null}++ <FilterSheet+ open={sheetOpen}+ groups={groups}+ values={filters}+ onChange={changeFilter}+ onReset={resetFilters}+ onClose={() => setSheetOpen(false)}+ />++ {initialLoading ? (+ <BrowseSkeleton />+ ) : (+ // Fade the stale rows while a new query or filter revalidates (they swap in place when+ // the fresh page lands); the search field and filters above stay interactive.+ <Animated.View className="flex-1" style={fade}>+ <FlatList+ data={shown}+ keyExtractor={(e) => String(e.id)}+ keyboardShouldPersistTaps="handled"+ keyboardDismissMode="on-drag"+ contentContainerStyle={{ paddingHorizontal: 16, paddingVertical: 8 }}+ ItemSeparatorComponent={() => <View className="ml-[56px] h-px bg-surface-border/60" />}+ renderItem={({ item }) => <BrowseRow exercise={item} />}+ onEndReached={loadMore}+ onEndReachedThreshold={0.5}+ ListEmptyComponent={+ // "No exercises found" is only true if we heard back; on a failed fetch it would+ // read as an empty catalogue rather than a connection that dropped.+ listError ? (+ <ErrorState title={t('exercises.picker.loadFailed')} message={listError} onRetry={retryList} />+ ) : exerciseCatalogEmpty(filtered, { items: exercises, hasMore, error: listError }) ? (+ <EmptyState+ compact+ icon={Dumbbell}+ title={t('exercises.picker.catalogEmpty.title')}+ subtitle={t('exercises.picker.catalogEmpty.body')}+ action={+ <Button+ variant="secondary"+ title={loading ? t('common.retrying') : t('common.tryAgain')}+ onPress={() => { void reload() }}+ loading={loading}+ />+ }+ />+ ) : (+ <EmptyState+ compact+ icon={SearchX}+ title={filtered ? t('exercises.browse.noMatchTitle') : t('exercises.picker.empty')}+ subtitle={filtered+ ? (count > 0 ? t('exercises.browse.noMatchBody') : t('common.tryDifferentSearch'))+ : undefined}+ action={count > 0+ ? <Button variant="secondary" title={t('filters.reset')} onPress={resetFilters} />+ : undefined}+ />+ )+ }+ ListFooterComponent={+ listError && shown.length > 0 ? (+ <ErrorState title={t('exercises.picker.loadMoreFailed')} message={listError} onRetry={retryList} />+ ) : hasMore && shown.length > 0 ? (+ <View className="flex-row items-center justify-center gap-2 py-4">+ <ActivityIndicator color={accent} />+ <AppText variant="caption" color="muted">{t('common.loadingMore')}</AppText>+ </View>+ ) : undefined+ }+ />+ </Animated.View>+ )}+ </SafeAreaView>+ )+}diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsxindex 4c20237..3339f6c 100644--- a/mobile/src/components/workouts/ExercisePicker.tsx+++ b/mobile/src/components/workouts/ExercisePicker.tsx@@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react'import { ActivityIndicator, FlatList, Modal, Pressable, TextInput, View } from 'react-native'import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'import { ArrowLeft, Dumbbell, Search } from 'lucide-react-native'-import { exerciseCatalogEmpty, useTranslation, type Exercise } from '@lyftr/shared'+import { exerciseCatalogEmpty, hasEquipmentToShow, EXERCISE_PAGE_SIZE, EXERCISE_SEARCH_DEBOUNCE_MS, useTranslation, type Exercise } from '@lyftr/shared'import { AppText, Button, EmptyState, ErrorState, IconButton } from '../ui'import { client } from '../../lib/lyftr'import { useServerInfiniteList } from '../../hooks/useServerInfiniteList'@@ -16,11 +16,6 @@ interface Props {onClose: () => void}-// Must match the server's default page size: a short page is what tells us there-// is nothing left for this query.-const PAGE_SIZE = 50-// Matches the search debounce used elsewhere on mobile (programs/workouts/weight).-const DEBOUNCE_MS = 250function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => void }) {useTranslation() // re-renders on a language switch: the labels below come from the catalog@@ -42,7 +37,7 @@ function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => v{muscleLabel(exercise.muscle_group)}</AppText></View>- {exercise.equipment && exercise.equipment !== 'other' ? (+ {hasEquipmentToShow(exercise.equipment) ? (<AppText variant="caption" color="muted">{equipmentLabel(exercise.equipment)}</AppText>@@ -64,7 +59,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {const [debouncedQuery, setDebouncedQuery] = useState('')useEffect(() => {- const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ const timer = setTimeout(() => setDebouncedQuery(query), EXERCISE_SEARCH_DEBOUNCE_MS)return () => clearTimeout(timer)}, [query])@@ -84,7 +79,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {items: exercises, loadMore, hasMore, loading, initialLoading, error: listError, retry: retryList, reload,} = useServerInfiniteList<Exercise>({fetcher,- pageSize: PAGE_SIZE,+ pageSize: EXERCISE_PAGE_SIZE,deps: [debouncedQuery],})diff --git a/mobile/src/lib/useServerList.test.ts b/mobile/src/lib/useServerList.test.tsindex ea2281e..56c2113 100644--- a/mobile/src/lib/useServerList.test.ts+++ b/mobile/src/lib/useServerList.test.ts@@ -46,6 +46,34 @@ describe('useServerList — a page that never arrived', () => {expect(result.current.hasMore).toBe(false)})+ // Rows from the previous query stay up when a new query's first page fails; a screen has to+ // be able to tell that apart from a later page failing, where the rows are still the answer.+ it('flags the rows as stale when a new query fails, and not when only a later page does', async () => {+ const fetcher = jest.fn()+ .mockResolvedValueOnce(page(0, 2))+ .mockRejectedValueOnce(timeout())+ .mockResolvedValueOnce(page(0, 2))+ .mockRejectedValueOnce(timeout())++ const { result, rerender } = await renderHook(+ ({ q }: { q: string }) => useServerList<number>({ fetcher, pageSize: 2, deps: [q] }),+ { initialProps: { q: 'a' } },+ )+ await waitFor(() => expect(result.current.items).toEqual([0, 1]))+ expect(result.current.staleResults).toBe(false)++ await act(async () => { result.current.loadMore() })+ await waitFor(() => expect(result.current.error).toBeTruthy())+ expect(result.current.staleResults).toBe(false)++ await rerender({ q: 'b' })+ await waitFor(() => expect(result.current.items).toEqual([0, 1]))+ await rerender({ q: 'c' })+ await waitFor(() => expect(result.current.error).toBeTruthy())+ expect(result.current.items).toEqual([0, 1])+ expect(result.current.staleResults).toBe(true)+ })+it('resumes from where it stopped, without discarding what loaded', async () => {const fetcher = jest.fn().mockResolvedValueOnce(page(0, 2))diff --git a/mobile/src/utils/exerciseUtils.ts b/mobile/src/utils/exerciseUtils.tsindex d060c8a..063ea66 100644--- a/mobile/src/utils/exerciseUtils.ts+++ b/mobile/src/utils/exerciseUtils.ts@@ -37,6 +37,11 @@ const MUSCLE_COLORS: Record<string, MuscleTint> = {forearms: { chip: 'bg-cyan-500/20', border: 'border-cyan-500/30', text: '#22d3ee' },traps: { chip: 'bg-indigo-500/20', border: 'border-indigo-500/30', text: '#818cf8' },lats: { chip: 'bg-sky-500/20', border: 'border-sky-500/30', text: '#38bdf8' },+ 'lower-back': { chip: 'bg-blue-500/20', border: 'border-blue-500/30', text: '#60a5fa' },+ 'middle-back': { chip: 'bg-blue-500/20', border: 'border-blue-500/30', text: '#60a5fa' },+ neck: { chip: 'bg-rose-500/20', border: 'border-rose-500/30', text: '#fb7185' },+ adductors: { chip: 'bg-emerald-500/20', border: 'border-emerald-500/30', text: '#34d399' },+ abductors: { chip: 'bg-violet-500/20', border: 'border-violet-500/30', text: '#a78bfa' },}// null → caller renders the muted fallback (bg-surface-muted chip + colors.txMuted).diff --git a/packages/shared/src/hooks/useServerList.ts b/packages/shared/src/hooks/useServerList.tsindex 048e5af..fffbe30 100644--- a/packages/shared/src/hooks/useServerList.ts+++ b/packages/shared/src/hooks/useServerList.ts@@ -54,6 +54,10 @@ interface Result<T> {// hasMore=false, so the list stopped exactly like a list that had reached its end —// the one shape a reader cannot tell from success. Render it, with retry().error: string | null+ // The rows on screen are from an earlier query: a new query's first page failed, and the old+ // rows are kept rather than blanked. Dim them and say so, or they read as the answer to the+ // search or filter just made. False when a later page failed (the rows are still the answer).+ staleResults: boolean// Resume from wherever we stopped. Keeps whatever already loaded.retry: () => void}@@ -72,7 +76,7 @@ export function useServerList<T>({// What failed, not what to say about it: the sentence is made at render so it follows a// language switch. `unreadable` is a 200 with a body that is not a list; `cause` is a// rejected fetch.- const [failure, setFailure] = useState<{ unreadable: true } | { cause: unknown } | null>(null)+ const [failure, setFailure] = useState<(({ unreadable: true } | { cause: unknown }) & { firstPage: boolean }) | null>(null)const offsetRef = useRef(0)// Tracks whether a fetch is in flight to prevent double-fetches (onEndReached can// fire repeatedly during momentum scrolling)@@ -105,7 +109,7 @@ export function useServerList<T>({if (!Array.isArray(page)) {if (myId === reqIdRef.current) {setHasMore(false)- setFailure({ unreadable: true })+ setFailure({ unreadable: true, firstPage: replace })}return}@@ -122,7 +126,7 @@ export function useServerList<T>({// all there is". Name it and let the screen offer retry().if (myId === reqIdRef.current) {setHasMore(false)- setFailure({ cause: err })+ setFailure({ cause: err, firstPage: replace })}} finally {// Only the latest fetch owns the shared flags — a stale response bows out without@@ -183,5 +187,6 @@ export function useServerList<T>({items, loadMore, hasMore: hasMore || depsPending, loading,initialLoading: loading && !initializedRef.current,refreshing, reload, error, retry,+ staleResults: failure !== null && failure.firstPage && items.length > 0,}}diff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.jsonindex f84bb08..e67ee4b 100644--- a/packages/shared/src/i18n/locales/en.json+++ b/packages/shared/src/i18n/locales/en.json@@ -207,6 +207,15 @@},"saveFailed": "Failed to save settings"},+ "filters": {+ "title": "Filters",+ "button": "Filters",+ "buttonActive": "Filters, {{active}} active",+ "reset": "Reset",+ "done": "Done",+ "active": "Active filters",+ "remove": "Remove filter: {{label}}"+ },"common": {"duration": {"seconds": "{{value}}s",@@ -967,6 +976,7 @@"title": "Workouts","subtitle": "Track and review your training sessions","logWorkout": "Log Workout",+ "browseExercises": "Browse exercises","searchPlaceholder": "Search workouts…","empty": {"title": "No workouts found",@@ -1260,8 +1270,8 @@"hamstrings": "hamstrings","lats": "lats","legs": "legs",- "lower-back": "lower-back",- "middle-back": "middle-back",+ "lower-back": "lower back",+ "middle-back": "middle back","neck": "neck","obliques": "obliques","other": "other",@@ -1270,6 +1280,15 @@"traps": "traps","triceps": "triceps"},+ "browse": {+ "title": "Exercises",+ "subtitle": "Look up any exercise and how it is done",+ "backToWorkouts": "Back to workouts",+ "muscle": "Muscle",+ "equipment": "Equipment",+ "noMatchTitle": "No exercises match",+ "noMatchBody": "Try another search or reset the filters."+ },"picker": {"catalogEmpty": { "title": "The exercise library is still loading", "body": "Try again in a moment." },"title": "Add Exercise",diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.jsonindex a9724a1..5d2bac3 100644--- a/packages/shared/src/i18n/locales/es.json+++ b/packages/shared/src/i18n/locales/es.json@@ -209,6 +209,15 @@},"saveFailed": "No se pudieron guardar los ajustes"},+ "filters": {+ "title": "Filtros",+ "button": "Filtros",+ "buttonActive": "Filtros, {{active}} activos",+ "reset": "Restablecer",+ "done": "Listo",+ "active": "Filtros activos",+ "remove": "Quitar filtro: {{label}}"+ },"common": {"duration": {"seconds": "{{value}} s",@@ -978,6 +987,7 @@"title": "Entrenamientos","subtitle": "Registra y revisa tus sesiones de entrenamiento","logWorkout": "Registrar entrenamiento",+ "browseExercises": "Explorar ejercicios","searchPlaceholder": "Buscar entrenamientos…","empty": {"title": "No se encontraron entrenamientos",@@ -1285,6 +1295,15 @@"traps": "trapecios","triceps": "tríceps"},+ "browse": {+ "title": "Ejercicios",+ "subtitle": "Consulta cualquier ejercicio y cómo se hace",+ "backToWorkouts": "Volver a entrenamientos",+ "muscle": "Músculo",+ "equipment": "Equipo",+ "noMatchTitle": "Ningún ejercicio coincide",+ "noMatchBody": "Prueba otra búsqueda o restablece los filtros."+ },"picker": {"catalogEmpty": { "title": "La biblioteca de ejercicios todavía se está cargando", "body": "Inténtalo de nuevo en un momento." },"title": "Agregar ejercicio",diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 8f4be50..b2dcb79 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -16,6 +16,7 @@ export * from './utils/number'export * from './utils/workoutSets'export * from './utils/macroColors'export * from './utils/exerciseUtils'+export * from './utils/filters'export * from './utils/workout'export * from './utils/programDrafts'export * from './utils/food'diff --git a/packages/shared/src/utils/exerciseUtils.test.ts b/packages/shared/src/utils/exerciseUtils.test.tsindex 9046d47..7af688c 100644--- a/packages/shared/src/utils/exerciseUtils.test.ts+++ b/packages/shared/src/utils/exerciseUtils.test.ts@@ -1,5 +1,5 @@import { i18n } from '../i18n'-import { catalogSyncLines, categoryLabel, equipmentLabel, exerciseCatalogEmpty, muscleLabel, resolveMuscleSlugs } from './exerciseUtils'+import { catalogSyncLines, categoryLabel, equipmentLabel, exerciseBrowseFiltered, exerciseBrowseParams, exerciseCatalogEmpty, EXERCISE_FILTER_EQUIPMENT, EXERCISE_FILTER_MUSCLES, hasEquipmentToShow, muscleLabel, resolveMuscleSlugs } from './exerciseUtils'// A stand-in for the per-platform tables — the rule under test is the lookup, not any// particular library's slug vocabulary.@@ -67,11 +67,17 @@ describe('equipmentLabel', () => {describe('muscleLabel', () => {it('gives the slug back unchanged in en, as the screens rendered it before the catalog', () => {- for (const slug of ['chest', 'lower-back', 'middle-back', 'full-body', 'quadriceps', 'abs']) {+ for (const slug of ['chest', 'full-body', 'quadriceps', 'abs']) {expect(muscleLabel(slug)).toBe(slug)}})+ // The two back slugs are hyphenated for the API, which reads as a typo on a chip.+ it('spaces the hyphenated back slugs in en', () => {+ expect(muscleLabel('lower-back')).toBe('lower back')+ expect(muscleLabel('middle-back')).toBe('middle back')+ })+it('passes an unknown or empty value through as it came', () => {expect(muscleLabel('rotator cuff')).toBe('rotator cuff')expect(muscleLabel('lower back')).toBe('lower back')@@ -190,3 +196,58 @@ describe('catalogSyncLines', () => {expect(text).toContain('Nuevo intento: 15:30.')})})++describe('exerciseBrowseParams', () => {+ const none = { query: '', muscle: null, equipment: null }++ it('omits every empty filter rather than sending an empty one', () => {+ expect(exerciseBrowseParams(none)).toEqual({})+ })++ it('trims the query and treats whitespace-only as no query', () => {+ expect(exerciseBrowseParams({ ...none, query: ' press ' })).toEqual({ q: 'press' })+ expect(exerciseBrowseParams({ ...none, query: ' ' })).toEqual({})+ })++ it('maps muscle and equipment to the server param names', () => {+ expect(exerciseBrowseParams({ query: 'curl', muscle: 'biceps', equipment: 'dumbbell' })).toEqual({+ q: 'curl', muscle_group: 'biceps', equipment: 'dumbbell',+ })+ })+})++describe('exerciseBrowseFiltered', () => {+ it('is false with nothing narrowing the list, true for any one filter', () => {+ expect(exerciseBrowseFiltered({ query: '', muscle: null, equipment: null })).toBe(false)+ expect(exerciseBrowseFiltered({ query: ' ', muscle: null, equipment: null })).toBe(false)+ expect(exerciseBrowseFiltered({ query: 'x', muscle: null, equipment: null })).toBe(true)+ expect(exerciseBrowseFiltered({ query: '', muscle: 'chest', equipment: null })).toBe(true)+ expect(exerciseBrowseFiltered({ query: '', muscle: null, equipment: 'cable' })).toBe(true)+ })+})++describe('exercise filter chips', () => {+ it('only offers slugs the label tables know, so no chip falls back to a raw slug', () => {+ for (const m of EXERCISE_FILTER_MUSCLES) expect(muscleLabel(m)).toBe(i18n.t(`exercises.muscle.${m}`))+ for (const e of EXERCISE_FILTER_EQUIPMENT) expect(equipmentLabel(e)).toBe(i18n.t(`exercises.equipment.${e}`))+ })+})++describe('hasEquipmentToShow', () => {+ it('hides the values the catalogue uses to say nothing', () => {+ for (const none of ['other', 'none', 'None', '', ' ', null, undefined]) expect(hasEquipmentToShow(none)).toBe(false)+ })++ it('shows real equipment, including the legacy spaced spelling', () => {+ for (const real of ['barbell', 'body-only', 'body only', 'e-z-curl-bar']) expect(hasEquipmentToShow(real)).toBe(true)+ })+})++describe('muscle filter chips', () => {+ it('offers no alias the catalogue never returns, and no duplicates', () => {+ for (const dead of ['back', 'abs', 'core', 'legs', 'obliques', 'full-body', 'other']) {+ expect(EXERCISE_FILTER_MUSCLES).not.toContain(dead)+ }+ expect(new Set(EXERCISE_FILTER_MUSCLES).size).toBe(EXERCISE_FILTER_MUSCLES.length)+ })+})diff --git a/packages/shared/src/utils/exerciseUtils.ts b/packages/shared/src/utils/exerciseUtils.tsindex 25126c8..f535372 100644--- a/packages/shared/src/utils/exerciseUtils.ts+++ b/packages/shared/src/utils/exerciseUtils.ts@@ -17,6 +17,7 @@import { i18n } from '../i18n'import type { ExerciseCacheStatus } from '../types'import { formatInstant } from './dateUtils'+import type { FilterGroup } from './filters'// Equipment and muscle names are read off exercises the server serves. Both vocabularies are// open-exercise-db's slugs, so a label is looked up by slug and anything outside the list@@ -70,10 +71,83 @@ export function categoryLabel(raw: string | undefined | null): string {// is a different answer from a search that matched nothing. hasMore is true until a page// settles and again on every query change, so this never claims it before an answer.export function exerciseCatalogEmpty(- query: string,+ narrowed: string | boolean,list: { items: readonly unknown[]; hasMore: boolean; error: string | null },): boolean {- return !query && !list.error && !list.hasMore && list.items.length === 0+ return !narrowed && !list.error && !list.hasMore && list.items.length === 0+}++// The Exercises browser's filters. A chip is only worth showing if the server can answer it, and+// MUSCLE_SLUGS / EQUIPMENT_SLUGS above are not that list: they are every spelling the labels+// know, including ones open-exercise-db never returns. `back`, `abs`, `core`, `legs`,+// `obliques` and `full-body` match nothing there, so a Back chip answered "No exercises" with+// the whole catalogue behind it. These are the muscle_group values the catalogue actually+// holds (checked against it: each returns rows), ordered head to toe. Equipment drops the+// catch-alls (other, none) and the long tail. Both apps import these, so the two browsers+// offer the same filters.+export const EXERCISE_FILTER_MUSCLES = [+ 'chest', 'shoulders', 'biceps', 'triceps', 'forearms', 'abdominals',+ 'lats', 'middle-back', 'lower-back', 'traps', 'glutes',+ 'quadriceps', 'hamstrings', 'calves', 'adductors', 'abductors', 'neck',+] as const++export const EXERCISE_FILTER_EQUIPMENT = [+ 'body-only', 'barbell', 'dumbbell', 'machine', 'cable', 'kettlebells', 'bands',+] as const++export interface ExerciseBrowseFilters {+ query: string+ muscle: string | null+ equipment: string | null+}++// The one place the browser's filter state becomes request params, so web and mobile cannot+// disagree on what "chest + dumbbell + 'press'" asks the server for. Empty means omitted:+// the server reads an absent param as "no filter", and an empty one as a filter on "".+export function exerciseBrowseParams(f: ExerciseBrowseFilters): { q?: string; muscle_group?: string; equipment?: string } {+ const q = f.query.trim()+ return {+ ...(q ? { q } : {}),+ ...(f.muscle ? { muscle_group: f.muscle } : {}),+ ...(f.equipment ? { equipment: f.equipment } : {}),+ }+}++// One screenful and change; the server caps a page at 100. Every exercise list pages by this, and+// a short page is what tells it there is nothing left, so it must match the server's default.+export const EXERCISE_PAGE_SIZE = 50+// How long typing pauses before an exercise search goes to the server.+export const EXERCISE_SEARCH_DEBOUNCE_MS = 250++// Whether an exercise's equipment is worth printing next to its name. `other` and `none` are+// the catalogue's way of saying nothing, and a row that reads "Chest · None" is noise.+// The browser's filters as a generic FilterGroup list, labelled in the active language. Built+// per render rather than held as a constant, since the labels change with the language.+export function exerciseFilterGroups(): FilterGroup[] {+ return [+ {+ key: 'muscle',+ label: i18n.t('exercises.browse.muscle'),+ options: EXERCISE_FILTER_MUSCLES.map((value) => ({ value, label: muscleLabel(value) })),+ },+ {+ key: 'equipment',+ label: i18n.t('exercises.browse.equipment'),+ options: EXERCISE_FILTER_EQUIPMENT.map((value) => ({ value, label: equipmentLabel(value) })),+ },+ ]+}++export function hasEquipmentToShow(raw: string | undefined | null): boolean {+ const slug = slugOf(raw)+ return slug !== '' && slug !== 'other' && slug !== 'none'+}++// Whether a result list is the answer to a narrowed question. exerciseCatalogEmpty takes a+// query to tell "the library is empty" from "nothing matched"; a chip narrows the question+// exactly as typed text does, so it must count, or an empty chip result reads as an empty library.+export function exerciseBrowseFiltered(f: ExerciseBrowseFilters): boolean {+ return Object.keys(exerciseBrowseParams(f)).length > 0}export interface CatalogSyncLine { text: string; warning: boolean }diff --git a/packages/shared/src/utils/filters.test.ts b/packages/shared/src/utils/filters.test.tsnew file mode 100644index 0000000..d64d517--- /dev/null+++ b/packages/shared/src/utils/filters.test.ts@@ -0,0 +1,52 @@+import {+ activeFilterCount, activeFilters, emptyFilters, parseFilters, setFilter,+ type FilterGroup,+} from './filters'++const groups: FilterGroup[] = [+ { key: 'muscle', label: 'Muscle', options: [{ value: 'chest', label: 'Chest' }, { value: 'lats', label: 'Lats' }] },+ { key: 'equipment', label: 'Equipment', options: [{ value: 'barbell', label: 'Barbell' }] },+]++describe('filters', () => {+ it('starts with every group on any', () => {+ expect(emptyFilters(groups)).toEqual({ muscle: null, equipment: null })+ })++ it('sets one group and leaves the others', () => {+ const chest = setFilter(emptyFilters(groups), 'muscle', 'chest')+ expect(chest).toEqual({ muscle: 'chest', equipment: null })+ expect(setFilter(chest, 'muscle', 'lats').muscle).toBe('lats')+ expect(setFilter(chest, 'muscle', null).muscle).toBeNull()+ })++ it('does not mutate what it was given', () => {+ const start = emptyFilters(groups)+ setFilter(start, 'equipment', 'barbell')+ expect(start).toEqual({ muscle: null, equipment: null })+ })++ it('lists active filters in group order with their labels', () => {+ const values = { equipment: 'barbell', muscle: 'lats' }+ expect(activeFilters(groups, values)).toEqual([+ { key: 'muscle', value: 'lats', label: 'Lats', groupLabel: 'Muscle' },+ { key: 'equipment', value: 'barbell', label: 'Barbell', groupLabel: 'Equipment' },+ ])+ expect(activeFilterCount(groups, values)).toBe(2)+ })++ it('does not count a value no option offers', () => {+ expect(activeFilters(groups, { muscle: 'bogus', equipment: null })).toEqual([])+ expect(activeFilterCount(groups, emptyFilters(groups))).toBe(0)+ })++ it('parses values from a reader and drops anything not offered', () => {+ const params = new URLSearchParams('muscle=chest&equipment=kettle')+ expect(parseFilters(groups, (k) => params.get(k))).toEqual({ muscle: 'chest', equipment: null })+ expect(parseFilters(groups, () => undefined)).toEqual({ muscle: null, equipment: null })+ })++ it('is case-sensitive, because the API values are slugs', () => {+ expect(parseFilters(groups, (k) => (k === 'muscle' ? 'Chest' : null)).muscle).toBeNull()+ })+})diff --git a/packages/shared/src/utils/filters.ts b/packages/shared/src/utils/filters.tsnew file mode 100644index 0000000..eb3a1e6--- /dev/null+++ b/packages/shared/src/utils/filters.ts@@ -0,0 +1,72 @@+// Filter state for any list that narrows by a few named choices (exercises by muscle and+// equipment today; anything else later). Platform-agnostic on purpose: the web and mobile+// filter sheets are different components over the same rules, so the rules live here once.+//+// A screen declares its filters as `FilterGroup[]` and holds a `FilterValues` map. Each+// group is single-select, because that is what the API takes (`muscle_group=chest`), and a+// null value means "any". Everything below returns new objects, so the result can go+// straight into `setState` or a URL.++export interface FilterOption {+ /** What goes to the API and into the URL. */+ value: string+ /** What the person reads. */+ label: string+}++export interface FilterGroup {+ /** Stable id: the key in `FilterValues` and the URL parameter name. */+ key: string+ label: string+ options: readonly FilterOption[]+}++export type FilterValues = Record<string, string | null>++export interface ActiveFilter {+ key: string+ value: string+ label: string+ groupLabel: string+}++export function emptyFilters(groups: readonly FilterGroup[]): FilterValues {+ return Object.fromEntries(groups.map((g) => [g.key, null]))+}++export function setFilter(values: FilterValues, key: string, value: string | null): FilterValues {+ return { ...values, [key]: value }+}++// In group order, so the summary row reads the same however the filters were picked. A value+// no option offers is skipped rather than shown: it would filter to nothing with no label to+// explain why.+export function activeFilters(groups: readonly FilterGroup[], values: FilterValues): ActiveFilter[] {+ const out: ActiveFilter[] = []+ for (const g of groups) {+ const value = values[g.key]+ if (value == null) continue+ const option = g.options.find((o) => o.value === value)+ if (option) out.push({ key: g.key, value, label: option.label, groupLabel: g.label })+ }+ return out+}++export function activeFilterCount(groups: readonly FilterGroup[], values: FilterValues): number {+ return activeFilters(groups, values).length+}++// Builds values from anything that can answer "what is set for this key" (a URLSearchParams,+// stored settings). A value is trusted only if the group offers it: a hand-edited+// `?muscle=bogus` would otherwise filter to nothing with no chip lit to explain why.+export function parseFilters(+ groups: readonly FilterGroup[],+ read: (key: string) => string | null | undefined,+): FilterValues {+ return Object.fromEntries(+ groups.map((g) => {+ const raw = read(g.key)+ return [g.key, raw != null && g.options.some((o) => o.value === raw) ? raw : null]+ }),+ )+}diff --git a/web/src/App.tsx b/web/src/App.tsxindex e682484..b248099 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -10,6 +10,7 @@ import ActiveWorkout from './pages/ActiveWorkout'import StartWorkout from './pages/StartWorkout'import WorkoutExercisePicker from './pages/WorkoutExercisePicker'import ExerciseDetail from './pages/ExerciseDetail'+import ExercisesBrowse from './pages/ExercisesBrowse'import AddProgram from './pages/AddProgram'import EditProgram from './pages/EditProgram'import AddWorkout from './pages/AddWorkout'@@ -61,6 +62,7 @@ function App() {<Route path="/workout/active" element={<ActiveWorkout />} /><Route path="/workout/active/add-exercise" element={<WorkoutExercisePicker />} /><Route path="/workout/active/exercise/:exerciseId" element={<ExerciseDetail />} />+ <Route path="/exercises" element={<ExercisesBrowse />} /><Route path="/exercises/:exerciseId" element={<ExerciseDetail />} /><Route path="/food" element={<Food />} /><Route path="/food/log" element={<LogFood />} />diff --git a/web/src/components/ExerciseListEmpty.tsx b/web/src/components/ExerciseListEmpty.tsxindex 3beef55..ed1c817 100644--- a/web/src/components/ExerciseListEmpty.tsx+++ b/web/src/components/ExerciseListEmpty.tsx@@ -1,9 +1,19 @@-import { Dumbbell } from 'lucide-react'+import type { ReactNode } from 'react'+import { Dumbbell, SearchX } from 'lucide-react'import { exerciseCatalogEmpty, types, useTranslation } from '@lyftr/shared'import { EmptyState, ListError } from './ui'interface Props {query: string+ // True when something other than typed text narrowed the list (a filter chip). Defaults+ // to whether there is a query, which is all the picker has.+ filtered?: boolean+ // What a narrowed list that matched nothing says, when "No exercises found" is too bare.+ // A title alone is enough; the body and action say what to try.+ emptyTitle?: string+ emptyBody?: string+ // What the person can do about a narrowed list that matched nothing (drop the filters).+ emptyAction?: ReactNodeitems: readonly types.Exercise[]hasMore: booleanerror: string | null@@ -14,7 +24,7 @@ interface Props {// What an exercise list shows when it has no rows: a failure, an empty library, or a// search that matched nothing. Each reads differently and only one is true.-export default function ExerciseListEmpty({ query, items, hasMore, error, loading, retry, reload }: Props) {+export default function ExerciseListEmpty({ query, filtered = query !== '', emptyTitle, emptyBody, emptyAction, items, hasMore, error, loading, retry, reload }: Props) {const { t } = useTranslation()if (error) {@@ -25,7 +35,7 @@ export default function ExerciseListEmpty({ query, items, hasMore, error, loadin)}- if (exerciseCatalogEmpty(query, { items, hasMore, error })) {+ if (exerciseCatalogEmpty(filtered, { items, hasMore, error })) {// reload, not retry: retry sets hasMore back to true, which would flip this to// "No exercises found" while the request is in flight.return (@@ -48,6 +58,10 @@ export default function ExerciseListEmpty({ query, items, hasMore, error, loadin)}+ if (emptyTitle) {+ return <EmptyState compact icon={SearchX} title={emptyTitle} subtitle={emptyBody} action={emptyAction} />+ }+return (<div className="flex items-center justify-center py-16 text-tx-muted text-sm">{t('exercises.picker.empty')}diff --git a/web/src/components/ExercisePicker.tsx b/web/src/components/ExercisePicker.tsxindex ae1bd8d..3613ab0 100644--- a/web/src/components/ExercisePicker.tsx+++ b/web/src/components/ExercisePicker.tsx@@ -2,18 +2,13 @@ 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, useTranslation } from '@lyftr/shared'+import { useServerList, types, useTranslation, hasEquipmentToShow, EXERCISE_PAGE_SIZE, EXERCISE_SEARCH_DEBOUNCE_MS } from '@lyftr/shared'import ExerciseListEmpty from './ExerciseListEmpty'import { exerciseAPI } from '../services/api'import { muscleColorBordered, muscleLabel, equipmentLabel } from '../utils/exerciseUtils'-// Must match the server's default page size, since a short page is what signals-// the end of the results.-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 = 250interface Props {selectedIds: number[]@@ -28,7 +23,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Propsconst scrollRef = useRef<HTMLDivElement>(null)useEffect(() => {- const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ const timer = setTimeout(() => setDebouncedQuery(query), EXERCISE_SEARCH_DEBOUNCE_MS)return () => clearTimeout(timer)}, [query])@@ -46,7 +41,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Propsconst list = useServerList<types.Exercise>({fetcher,- pageSize: PAGE_SIZE,+ pageSize: EXERCISE_PAGE_SIZE,deps: [debouncedQuery],})const { items: exercises, loadMore, hasMore, loading, initialLoading, error } = list@@ -162,7 +157,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(ex.muscle_group)}`}>{muscleLabel(ex.muscle_group)}</span>- {ex.equipment && ex.equipment !== 'other' && (+ {hasEquipmentToShow(ex.equipment) && (<span className="text-xs text-tx-muted">{equipmentLabel(ex.equipment)}</span>diff --git a/web/src/components/ui/ActiveFilters.tsx b/web/src/components/ui/ActiveFilters.tsxnew file mode 100644index 0000000..a78cf81--- /dev/null+++ b/web/src/components/ui/ActiveFilters.tsx@@ -0,0 +1,32 @@+import { X } from 'lucide-react'+import { type FilterGroup, type FilterValues, activeFilters, useTranslation } from '@lyftr/shared'++interface Props {+ groups: readonly FilterGroup[]+ values: FilterValues+ onRemove: (key: string) => void+}++// What is on, as removable chips under the search box, so a filter can be dropped in one tap+// without reopening the sheet. Renders nothing when nothing is on.+export default function ActiveFilters({ groups, values, onRemove }: Props) {+ const { t } = useTranslation()+ const active = activeFilters(groups, values)+ if (active.length === 0) return null+ return (+ <div role="group" aria-label={t('filters.active')} className="flex gap-1.5 overflow-x-auto -mx-4 px-4">+ {active.map(f => (+ <button+ key={f.key}+ type="button"+ onClick={() => onRemove(f.key)}+ aria-label={t('filters.remove', { label: f.label })}+ className="animate-slide-up flex-shrink-0 inline-flex items-center gap-1 pl-3 pr-2 py-1.5 rounded-full text-xs font-medium border capitalize bg-brand-500/15 border-brand-500/40 text-brand-500 hover:bg-brand-500/25 transition-colors"+ >+ {f.label}+ <X className="w-3 h-3" />+ </button>+ ))}+ </div>+ )+}diff --git a/web/src/components/ui/FilterButton.tsx b/web/src/components/ui/FilterButton.tsxnew file mode 100644index 0000000..0533f2c--- /dev/null+++ b/web/src/components/ui/FilterButton.tsx@@ -0,0 +1,35 @@+import { SlidersHorizontal } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'++interface Props {+ /** How many filters are on. Zero is the plain button; more lights it up with the count. */+ active: number+ onClick: () => void+}++// The button beside a search box that opens a FilterSheet. The count is on the button itself+// so what is narrowing the list is visible without opening anything.+export default function FilterButton({ active, onClick }: Props) {+ const { t } = useTranslation()+ const on = active > 0+ return (+ <button+ type="button"+ onClick={onClick}+ aria-label={on ? t('filters.buttonActive', { active }) : t('filters.button')}+ title={t('filters.button')}+ className={`relative flex-shrink-0 w-11 h-11 rounded-xl border flex items-center justify-center transition-colors ${+ on+ ? 'bg-brand-500/15 border-brand-500/40 text-brand-500'+ : 'bg-surface-muted border-surface-border text-tx-muted hover:text-tx-primary'+ }`}+ >+ <SlidersHorizontal className="w-4 h-4" />+ {on && (+ <span className="absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-brand-500 text-white text-[11px] font-semibold flex items-center justify-center">+ {active}+ </span>+ )}+ </button>+ )+}diff --git a/web/src/components/ui/FilterSheet.test.tsx b/web/src/components/ui/FilterSheet.test.tsxnew file mode 100644index 0000000..51c5f89--- /dev/null+++ b/web/src/components/ui/FilterSheet.test.tsx@@ -0,0 +1,136 @@+import { describe, it, expect, vi } from 'vitest'+import { render, screen, fireEvent } from '@testing-library/react'+import FilterSheet from './FilterSheet'+import FilterButton from './FilterButton'+import ActiveFilters from './ActiveFilters'+import type { FilterGroup } from '@lyftr/shared'++// Deliberately not the exercise filters: the sheet is generic over whatever groups a screen+// declares, and a test that only used muscles would not notice if it quietly were not.+const groups: FilterGroup[] = [+ { key: 'meal', label: 'Meal', options: [{ value: 'lunch', label: 'Lunch' }, { value: 'dinner', label: 'Dinner' }] },+ { key: 'source', label: 'Source', options: [{ value: 'saved', label: 'Saved' }] },+]++const renderSheet = (values = { meal: null, source: null } as Record<string, string | null>) => {+ const onChange = vi.fn()+ const onReset = vi.fn()+ const onClose = vi.fn()+ render(<FilterSheet open groups={groups} values={values} onChange={onChange} onReset={onReset} onClose={onClose} />)+ return { onChange, onReset, onClose }+}++describe('FilterSheet', () => {+ it('renders a section per group with every option, and nothing when closed', () => {+ renderSheet()+ expect(screen.getByRole('group', { name: 'Meal' })).toBeTruthy()+ expect(screen.getByRole('group', { name: 'Source' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Dinner' })).toBeTruthy()+ })++ it('renders nothing when closed', () => {+ render(<FilterSheet open={false} groups={groups} values={{}} onChange={() => {}} onReset={() => {}} onClose={() => {}} />)+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('reports the option picked, and null when the one that is on is picked again', () => {+ const { onChange } = renderSheet({ meal: 'lunch', source: null })+ fireEvent.click(screen.getByRole('button', { name: 'Dinner' }))+ expect(onChange).toHaveBeenLastCalledWith('meal', 'dinner')+ fireEvent.click(screen.getByRole('button', { name: 'Lunch' }))+ expect(onChange).toHaveBeenLastCalledWith('meal', null)+ })++ it('disables Reset until something is on, then reports it', () => {+ const none = renderSheet()+ expect((screen.getByRole('button', { name: 'Reset' }) as HTMLButtonElement).disabled).toBe(true)+ expect(none.onReset).not.toHaveBeenCalled()+ })++ it('resets and closes', () => {+ const { onReset, onClose } = renderSheet({ meal: 'lunch', source: null })+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))+ expect(onReset).toHaveBeenCalled()+ fireEvent.click(screen.getByRole('button', { name: 'Done' }))+ expect(onClose).toHaveBeenCalled()+ })++ it('closes from the close button', () => {+ const { onClose } = renderSheet()+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))+ expect(onClose).toHaveBeenCalled()+ })++ // Touch only: the grabber and header are the handle, so a swipe down past the threshold closes.+ const swipe = (to: number) => {+ const handle = screen.getByTestId('filter-sheet-handle')+ fireEvent.touchStart(handle, { touches: [{ clientY: 100 }] })+ fireEvent.touchMove(handle, { touches: [{ clientY: to }] })+ fireEvent.touchEnd(handle)+ }++ it('closes on a long swipe down and stays open on a short one', () => {+ const { onClose } = renderSheet()+ swipe(130)+ expect(onClose).not.toHaveBeenCalled()+ swipe(260)+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('does not close when the touch is cancelled partway', () => {+ const { onClose } = renderSheet()+ const handle = screen.getByTestId('filter-sheet-handle')+ fireEvent.touchStart(handle, { touches: [{ clientY: 100 }] })+ fireEvent.touchMove(handle, { touches: [{ clientY: 300 }] })+ fireEvent.touchCancel(handle)+ expect(onClose).not.toHaveBeenCalled()+ })++ it('closes on a click on the scrim but not on one that started inside the sheet', () => {+ const { onClose } = renderSheet()+ const dialog = screen.getByRole('dialog')+ const scrim = dialog.parentElement!+ fireEvent.mouseDown(dialog)+ fireEvent.click(scrim)+ expect(onClose).not.toHaveBeenCalled()+ fireEvent.mouseDown(scrim)+ fireEvent.click(scrim)+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('moves focus into the sheet', () => {+ renderSheet()+ expect(document.activeElement).toBe(screen.getByRole('dialog'))+ })++ it('closes on Escape', () => {+ const { onClose } = renderSheet()+ fireEvent.keyDown(document, { key: 'Escape' })+ expect(onClose).toHaveBeenCalled()+ })+})++describe('FilterButton', () => {+ it('is plain at zero and carries the count above it', () => {+ const { rerender } = render(<FilterButton active={0} onClick={() => {}} />)+ expect(screen.getByRole('button', { name: 'Filters' })).toBeTruthy()+ rerender(<FilterButton active={2} onClick={() => {}} />)+ expect(screen.getByRole('button', { name: 'Filters, 2 active' }).textContent).toBe('2')+ })+})++describe('ActiveFilters', () => {+ it('lists what is on in group order and removes by key', () => {+ const onRemove = vi.fn()+ render(<ActiveFilters groups={groups} values={{ source: 'saved', meal: 'dinner' }} onRemove={onRemove} />)+ const chips = screen.getAllByRole('button')+ expect(chips.map(c => c.textContent)).toEqual(['Dinner', 'Saved'])+ fireEvent.click(screen.getByRole('button', { name: 'Remove filter: Saved' }))+ expect(onRemove).toHaveBeenCalledWith('source')+ })++ it('renders nothing when nothing is on', () => {+ const { container } = render(<ActiveFilters groups={groups} values={{ meal: null, source: null }} onRemove={() => {}} />)+ expect(container.firstChild).toBeNull()+ })+})diff --git a/web/src/components/ui/FilterSheet.tsx b/web/src/components/ui/FilterSheet.tsxnew file mode 100644index 0000000..4a10e36--- /dev/null+++ b/web/src/components/ui/FilterSheet.tsx@@ -0,0 +1,133 @@+import { useEffect, useRef } from 'react'+import { createPortal } from 'react-dom'+import { Check, X } from 'lucide-react'+import { type FilterGroup, type FilterValues, activeFilterCount, useTranslation } from '@lyftr/shared'+import { useEscapeKey } from '../../hooks/useEscapeKey'+import { useBodyScrollLock } from '../../hooks/useBodyScrollLock'+import { useSheetDrag } from '../../hooks/useSheetDrag'++interface Props {+ open: boolean+ groups: readonly FilterGroup[]+ values: FilterValues+ /** Fires with the option picked, or null when the one already on is picked again. */+ onChange: (key: string, value: string | null) => void+ onReset: () => void+ onClose: () => void+}++// The panel behind a FilterButton: one section per group, every option visible at once+// instead of scrolled past. Generic over `groups`, so a screen with other filters brings its+// own list and nothing here changes. Changes apply as they are made (the list updates behind+// the scrim); Done only closes. Mirrors mobile's FilterSheet.+export default function FilterSheet({ open, groups, values, onChange, onReset, onClose }: Props) {+ const { t } = useTranslation()+ useBodyScrollLock(open)+ useEscapeKey(open, onClose)+ const drag = useSheetDrag(onClose)+ const dialogRef = useRef<HTMLDivElement>(null)+ const downOnScrim = useRef(false)++ // Move focus into the sheet when it opens and back to what opened it when it closes, so a+ // keyboard or screen-reader user is not left tabbing through the page behind the scrim.+ useEffect(() => {+ if (!open) return+ const opener = document.activeElement as HTMLElement | null+ dialogRef.current?.focus()+ return () => opener?.focus?.()+ }, [open])++ if (!open) return null++ const count = activeFilterCount(groups, values)++ 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"+ onMouseDown={e => { downOnScrim.current = e.target === e.currentTarget }}+ onClick={e => { if (downOnScrim.current && e.target === e.currentTarget) onClose() }}+ >+ <div+ ref={dialogRef}+ tabIndex={-1}+ role="dialog"+ aria-modal="true"+ aria-label={t('filters.title')}+ style={drag.style}+ className="outline-none animate-slide-up bg-surface-base border border-surface-border rounded-t-2xl sm:rounded-2xl w-full sm:max-w-md max-h-[85dvh] flex flex-col"+ >+ <div {...drag.handlers} style={drag.handleStyle} data-testid="filter-sheet-handle">+ <div className="mx-auto w-10 h-1 rounded-full bg-surface-muted mt-3 sm:hidden" />+ <div className="flex items-center justify-between px-5 pt-4 pb-3 border-b border-surface-border">+ <h3 className="font-display font-bold text-lg text-tx-primary">{t('filters.title')}</h3>+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={onReset}+ disabled={count === 0}+ className="px-2 py-1.5 rounded-lg text-sm font-medium text-brand-500 hover:bg-brand-500/10 transition-colors disabled:text-tx-muted disabled:opacity-50 disabled:hover:bg-transparent"+ >+ {t('filters.reset')}+ </button>+ <button+ type="button"+ onClick={onClose}+ aria-label={t('common.close')}+ className="p-2 -mr-2 rounded-lg text-tx-muted hover:text-tx-primary hover:bg-surface-muted transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ </div>+ </div>++ <div className="flex-1 overflow-y-auto px-5 py-4 space-y-6">+ {groups.map(group => (+ <div key={group.key} role="group" aria-label={group.label}>+ <div className="flex items-baseline justify-between mb-2.5">+ <p className="text-sm font-semibold text-tx-primary">{group.label}</p>+ {values[group.key] != null && (+ <p className="text-xs text-brand-500 capitalize">+ {group.options.find(o => o.value === values[group.key])?.label}+ </p>+ )}+ </div>+ <div className="flex flex-wrap gap-2">+ {group.options.map(option => {+ const on = values[group.key] === option.value+ return (+ <button+ key={option.value}+ type="button"+ aria-pressed={on}+ onClick={() => onChange(group.key, on ? null : option.value)}+ className={`inline-flex items-center gap-1.5 px-3.5 py-2 rounded-full text-sm font-medium border capitalize transition-colors ${+ on+ ? 'bg-brand-500/15 border-brand-500/40 text-brand-500'+ : 'bg-surface-muted border-surface-border text-tx-muted hover:text-tx-primary'+ }`}+ >+ {on && <Check className="w-3.5 h-3.5" strokeWidth={2.5} />}+ {option.label}+ </button>+ )+ })}+ </div>+ </div>+ ))}+ </div>++ <div className="p-5 pt-3 border-t border-surface-border">+ <button+ type="button"+ onClick={onClose}+ className="w-full py-3 bg-brand-500 hover:bg-brand-600 text-white rounded-xl font-semibold text-sm transition-colors"+ >+ {t('filters.done')}+ </button>+ </div>+ </div>+ </div>,+ document.body,+ )+}diff --git a/web/src/components/ui/index.ts b/web/src/components/ui/index.tsindex 5ef96a5..ef8f60e 100644--- a/web/src/components/ui/index.ts+++ b/web/src/components/ui/index.ts@@ -12,3 +12,6 @@ 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 FilterButton } from './FilterButton'+export { default as FilterSheet } from './FilterSheet'+export { default as ActiveFilters } from './ActiveFilters'diff --git a/web/src/hooks/useSheetDrag.ts b/web/src/hooks/useSheetDrag.tsnew file mode 100644index 0000000..41e1272--- /dev/null+++ b/web/src/hooks/useSheetDrag.ts@@ -0,0 +1,36 @@+import { useRef, useState, type TouchEvent } from 'react'++// Swipe a bottom sheet down to dismiss it. Attach `handlers` to the part that should act as the+// handle (the grabber and header), not the whole sheet, so the scrolling list inside keeps its own+// scrolling. Touch only: with a mouse the sheet has a close button and Escape.+export function useSheetDrag(onClose: () => void, threshold = 90) {+ const [dy, setDy] = useState(0)+ const startY = useRef<number | null>(null)+ // Read on release instead of the state: a flick whose last move has not re-rendered yet would+ // otherwise be judged on a stale distance and fail to dismiss.+ const lastDy = useRef(0)++ const handlers = {+ onTouchStart: (e: TouchEvent) => { startY.current = e.touches[0].clientY },+ onTouchMove: (e: TouchEvent) => {+ if (startY.current == null) return+ lastDy.current = Math.max(0, e.touches[0].clientY - startY.current)+ setDy(lastDy.current)+ },+ onTouchEnd: () => {+ if (lastDy.current > threshold) onClose()+ startY.current = null+ lastDy.current = 0+ setDy(0)+ },+ onTouchCancel: () => { startY.current = null; lastDy.current = 0; setDy(0) },+ }++ return {+ handlers,+ // Keeps the browser from starting its own vertical pan (or pull-to-refresh) on the handle.+ handleStyle: { touchAction: 'none' } as const,+ // No transition while the finger is down, so the sheet follows it; it springs back on release.+ style: dy > 0 ? { transform: `translateY(${dy}px)`, transition: 'none' } : undefined,+ }+}diff --git a/web/src/pages/ExercisesBrowse.test.tsx b/web/src/pages/ExercisesBrowse.test.tsxnew file mode 100644index 0000000..f8564a6--- /dev/null+++ b/web/src/pages/ExercisesBrowse.test.tsx@@ -0,0 +1,211 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'+import ExercisesBrowse from './ExercisesBrowse'+import { types } from '@lyftr/shared'++const listMock = vi.fn()+vi.mock('../services/api', () => ({+ exerciseAPI: { list: (params?: Record<string, unknown>) => listMock(params) },+}))++const exercise = (id: number, name: string, muscle = 'chest', equipment = 'barbell'): types.Exercise => ({+ id,+ name,+ muscle_group: muscle,+ secondary_muscles: [],+ category: 'strength',+ equipment,+ description: '',+})++function Where() {+ const loc = useLocation()+ return <output data-testid="where">{loc.pathname + loc.search}</output>+}++const renderPage = (url = '/exercises') => render(+ <MemoryRouter initialEntries={[url]}>+ <Routes>+ <Route path="/exercises" element={<ExercisesBrowse />} />+ <Route path="/exercises/:id" element={<div>detail page</div>} />+ </Routes>+ <Where />+ </MemoryRouter>+)++beforeEach(() => {+ listMock.mockReset()+ listMock.mockResolvedValue([exercise(1, 'Bench Press')])+})++describe('ExercisesBrowse', () => {+ it('lists exercises as links to their detail page, with no add-to-workout step', async () => {+ renderPage()+ const row = await screen.findByRole('link', { name: /bench press/i })+ expect(row.getAttribute('href')).toBe('/exercises/1')+ })++ it('asks for an unfiltered first page, sending no empty filter params', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ expect(listMock).toHaveBeenCalledWith({ page: 1 })+ })++ const openFilters = () => fireEvent.click(screen.getByRole('button', { name: /^filters/i }))++ it('sends the muscle and equipment filters to the server, and resets them', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ openFilters()++ fireEvent.click(screen.getByRole('button', { name: 'chest', pressed: false }))+ await waitFor(() => expect(listMock).toHaveBeenLastCalledWith({ muscle_group: 'chest', page: 1 }))++ fireEvent.click(screen.getByRole('button', { name: 'Dumbbell', pressed: false }))+ await waitFor(() =>+ expect(listMock).toHaveBeenLastCalledWith({ muscle_group: 'chest', equipment: 'dumbbell', page: 1 }))++ fireEvent.click(screen.getByRole('button', { name: /reset/i }))+ await waitFor(() => expect(listMock).toHaveBeenLastCalledWith({ page: 1 }))+ })++ it('picking the option that is on turns it off', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: 'chest' }))+ fireEvent.click(await screen.findByRole('button', { name: 'chest', pressed: true }))+ await waitFor(() => expect(listMock).toHaveBeenLastCalledWith({ page: 1 }))+ })++ it('counts the filters on the button and shows each as a chip that removes only itself', async () => {+ renderPage('/exercises?muscle=chest&equipment=barbell')+ await screen.findByText('Bench Press')+ expect(screen.getByRole('button', { name: 'Filters, 2 active' })).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Remove filter: chest' }))+ await waitFor(() => expect(screen.getByTestId('where').textContent).toBe('/exercises?equipment=barbell'))+ expect(screen.getByRole('button', { name: 'Filters, 1 active' })).toBeTruthy()+ expect(listMock).toHaveBeenLastCalledWith({ equipment: 'barbell', page: 1 })+ })++ it('shows no filter chips when nothing is on', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ expect(screen.queryByRole('group', { name: /active filters/i })).toBeNull()+ expect(screen.getByRole('button', { name: 'Filters' })).toBeTruthy()+ })++ // The stale rows stay up and dim while a new query is in flight, as on the other lists,+ // instead of blanking or jumping.+ it('fades the list while a new filter loads, then restores it', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ let release: (v: types.Exercise[]) => void = () => {}+ listMock.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: 'chest' }))++ const list = () => document.querySelector('.overflow-y-auto.flex-1') as HTMLElement+ await waitFor(() => expect(list().className).toContain('opacity-50'))+ expect(screen.getByText('Bench Press')).toBeTruthy()++ release([exercise(2, 'Cable Fly')])+ await screen.findByText('Cable Fly')+ await waitFor(() => expect(list().className).not.toContain('opacity-50'))+ })++ it('searches by name alongside the chips', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: 'chest' }))+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: 'press' } })+ await waitFor(() =>+ expect(listMock).toHaveBeenLastCalledWith({ q: 'press', muscle_group: 'chest', page: 1 }))+ })++ // An empty chip result must not read as an empty library: that answer offers "Try+ // again" and says the library is still loading, which is false when the server answered.+ it('says no exercise matches when a filter returns nothing, not that the library is empty', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ listMock.mockResolvedValue([])+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: 'calves' }))+ expect(await screen.findByText(/no exercises match/i)).toBeTruthy()+ expect(screen.queryByText(/still loading/i)).toBeNull()+ })++ it('says the library is still loading when an unfiltered list is empty', async () => {+ listMock.mockResolvedValue([])+ renderPage()+ expect(await screen.findByText(/still loading/i)).toBeTruthy()+ })++ it('shows the failure, not an empty list, when the request fails', async () => {+ listMock.mockRejectedValue(new Error('network'))+ renderPage()+ expect(await screen.findByRole('button', { name: /retry|try again/i })).toBeTruthy()+ expect(screen.queryByText(/no exercises/i)).toBeNull()+ })++ // Opening an exercise unmounts the page. The filters have to come back with it, or+ // looking at three chest exercises means re-picking Chest three times.+ it('restores search and chips from the URL, and asks the server for them on first load', async () => {+ renderPage('/exercises?q=press&muscle=chest&equipment=dumbbell')+ await screen.findByText('Bench Press')+ expect(listMock).toHaveBeenCalledWith({ q: 'press', muscle_group: 'chest', equipment: 'dumbbell', page: 1 })+ expect((screen.getByPlaceholderText(/search exercises/i) as HTMLInputElement).value).toBe('press')+ openFilters()+ expect(screen.getByRole('button', { name: 'chest', pressed: true })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Dumbbell', pressed: true })).toBeTruthy()+ })++ it('writes the chips and the search to the URL without piling up history entries', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: 'chest' }))+ fireEvent.click(screen.getByRole('button', { name: 'Barbell' }))+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: ' bench ' } })+ await waitFor(() =>+ expect(screen.getByTestId('where').textContent).toBe('/exercises?muscle=chest&equipment=barbell&q=bench'))+ })++ // Opening an exercise inside the debounce window used to drop the search: the URL only got+ // it once the timer fired, and the timer dies with the page.+ it('puts the search in the URL as it is typed, without waiting for the debounce', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: 'press' } })+ expect(screen.getByTestId('where').textContent).toBe('/exercises?q=press')+ })++ // The hook keeps the previous rows when a refresh fails; left up they read as the results for+ // the filter just chosen, so the failure replaces them.+ it('shows the failure instead of the old rows when a refresh fails', async () => {+ renderPage()+ await screen.findByText('Bench Press')+ listMock.mockRejectedValue(new Error('network'))+ fireEvent.click(screen.getByRole('button', { name: /^filters/i }))+ fireEvent.click(screen.getByRole('button', { name: 'calves' }))+ expect(await screen.findByRole('button', { name: /retry|try again/i })).toBeTruthy()+ expect(screen.queryByText('Bench Press')).toBeNull()+ })++ it('drops the filters from the URL on reset', async () => {+ renderPage('/exercises?muscle=chest&equipment=barbell')+ await screen.findByText('Bench Press')+ openFilters()+ fireEvent.click(screen.getByRole('button', { name: /reset/i }))+ await waitFor(() => expect(screen.getByTestId('where').textContent).toBe('/exercises'))+ })++ it('ignores a muscle that is not one of the chips rather than filtering to nothing', async () => {+ renderPage('/exercises?muscle=bogus&equipment=nonsense')+ await screen.findByText('Bench Press')+ expect(listMock).toHaveBeenCalledWith({ page: 1 })+ })+})diff --git a/web/src/pages/ExercisesBrowse.tsx b/web/src/pages/ExercisesBrowse.tsxnew file mode 100644index 0000000..00e6d07--- /dev/null+++ b/web/src/pages/ExercisesBrowse.tsx@@ -0,0 +1,208 @@+import { useState, useEffect, useCallback } from 'react'+import { Link, useNavigate, useSearchParams } from 'react-router-dom'+import { ArrowLeft, ChevronRight, Dumbbell, Search, X } from 'lucide-react'+import {+ useServerList, types, useTranslation,+ EXERCISE_PAGE_SIZE, EXERCISE_SEARCH_DEBOUNCE_MS,+ activeFilterCount, emptyFilters, exerciseBrowseFiltered, exerciseBrowseParams, exerciseFilterGroups,+ hasEquipmentToShow, parseFilters,+} from '@lyftr/shared'+import ExerciseListEmpty from '../components/ExerciseListEmpty'+import { ActiveFilters, FilterButton, FilterSheet, PageHeader } from '../components/ui'+import { exerciseAPI } from '../services/api'+import { muscleColorBordered, muscleLabel, equipmentLabel } from '../utils/exerciseUtils'++// Read-only catalogue: look an exercise up and open its page without starting a workout.+// The list is the picker's (server-paged, nothing downloaded to slice here) minus the+// add-to-workout step, plus the muscle and equipment filters the API already takes.+//+// The filters live in the URL (?q=&muscle=&equipment=), not in component state: opening an+// exercise unmounts this page, and coming back used to land on the unfiltered alphabet,+// so looking at three chest exercises meant re-picking Chest three times.+export default function ExercisesBrowse() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const [params, setParams] = useSearchParams()+ const [sheetOpen, setSheetOpen] = useState(false)+ const groups = exerciseFilterGroups()+ const values = parseFilters(groups, key => params.get(key))+ const muscle = values.muscle+ const equipment = values.equipment+ const [query, setQuery] = useState(params.get('q') ?? '')+ const [debouncedQuery, setDebouncedQuery] = useState(query)++ // replace, not push: every filter change in history would make Back step through filter+ // states instead of leaving the page.+ const setParam = useCallback((key: string, value: string | null) => {+ setParams(prev => {+ const next = new URLSearchParams(prev)+ if (value) next.set(key, value)+ else next.delete(key)+ return next+ }, { replace: true })+ }, [setParams])++ // The box and the URL change together; only the request waits out the debounce. Otherwise+ // opening an exercise inside that window drops the search, and Back lands on the full list.+ const changeQuery = (value: string) => {+ setQuery(value)+ setParam('q', value.trim() || null)+ }++ useEffect(() => {+ const timer = setTimeout(() => setDebouncedQuery(query), EXERCISE_SEARCH_DEBOUNCE_MS)+ return () => clearTimeout(timer)+ }, [query])++ const filtered = exerciseBrowseFiltered({ query: debouncedQuery, muscle, equipment })+ const count = activeFilterCount(groups, values)++ const fetcher = useCallback(+ (offset: number, limit: number) =>+ exerciseAPI+ .list({ ...exerciseBrowseParams({ query: debouncedQuery, muscle, equipment }), page: offset / limit + 1 })+ .then(data => data ?? []),+ [debouncedQuery, muscle, equipment]+ )++ const list = useServerList<types.Exercise>({+ fetcher,+ pageSize: EXERCISE_PAGE_SIZE,+ deps: [debouncedQuery, muscle, equipment],+ })+ const { items: exercises, loadMore, hasMore, loading, initialLoading, refreshing, staleResults } = list++ const resetFilters = () => {+ setParams(prev => {+ const next = new URLSearchParams(prev)+ for (const key of Object.keys(emptyFilters(groups))) next.delete(key)+ return next+ }, { replace: true })+ }++ return (+ <div className="flex flex-col h-[calc(100dvh-8rem)] animate-slide-up">+ <div className="flex-shrink-0 space-y-3 pb-3">+ <div className="flex items-center gap-3">+ <button+ aria-label={t('exercises.browse.backToWorkouts')}+ onClick={() => navigate('/workouts')}+ className="p-2 hover:bg-surface-muted rounded-lg transition-colors"+ >+ <ArrowLeft className="w-5 h-5 text-tx-muted" />+ </button>+ <div className="min-w-0 flex-1">+ <PageHeader title={t('exercises.browse.title')} subtitle={t('exercises.browse.subtitle')} />+ </div>+ </div>++ <div className="flex items-center gap-2">+ <div className="relative flex-1">+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-tx-muted pointer-events-none" />+ <input+ type="text"+ value={query}+ onChange={e => changeQuery(e.target.value)}+ placeholder={t('exercises.picker.search')}+ aria-label={t('exercises.picker.search')}+ className={`input pl-10 w-full ${query ? 'pr-10' : ''}`}+ />+ {query && (+ <button+ type="button"+ onClick={() => changeQuery('')}+ aria-label={t('common.clearSearch')}+ className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-lg text-tx-muted hover:text-tx-primary transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ )}+ </div>+ <FilterButton active={count} onClick={() => setSheetOpen(true)} />+ </div>++ <ActiveFilters groups={groups} values={values} onRemove={key => setParam(key, null)} />+ </div>++ <FilterSheet+ open={sheetOpen}+ groups={groups}+ values={values}+ onChange={setParam}+ onReset={resetFilters}+ onClose={() => setSheetOpen(false)}+ />++ {/* The header above stays put and only the list scrolls, as in the picker: a hundred+ rows in, changing a filter should not mean scrolling back to the top for it. The+ rows fade while a new query or filter revalidates and swap in place when it lands. */}+ <div className={`flex-1 overflow-y-auto -mx-4 px-4 transition-opacity ${refreshing ? 'opacity-50' : ''}`}>+ {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" />+ {t('exercises.picker.loadingShort')}+ </div>+ ) : exercises.length === 0 || staleResults ? (+ <ExerciseListEmpty+ query={debouncedQuery}+ filtered={filtered}+ emptyTitle={filtered ? t('exercises.browse.noMatchTitle') : undefined}+ emptyBody={filtered ? (count > 0 ? t('exercises.browse.noMatchBody') : t('common.tryDifferentSearch')) : undefined}+ emptyAction={count > 0 ? (+ <button type="button" onClick={resetFilters} className="btn-secondary btn-sm">+ {t('filters.reset')}+ </button>+ ) : undefined}+ {...list}+ />+ ) : (+ <div className="space-y-1">+ {exercises.map(ex => (+ <Link+ key={ex.id}+ to={`/exercises/${ex.id}`}+ className="w-full flex items-center gap-3 px-3 py-3 rounded-xl hover:bg-surface-muted transition-colors text-left"+ >+ {ex.image_url ? (+ <img+ src={ex.image_url}+ alt=""+ loading="lazy"+ className="w-10 h-10 rounded-lg object-cover flex-shrink-0 bg-surface-muted"+ onError={e => { (e.target as HTMLImageElement).style.display = 'none' }}+ />+ ) : (+ <div className="w-10 h-10 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Dumbbell className="w-4 h-4 text-brand-500" />+ </div>+ )}+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-tx-primary truncate">{ex.name}</p>+ <div className="flex items-center gap-1.5 mt-0.5 flex-wrap">+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium border capitalize ${muscleColorBordered(ex.muscle_group)}`}>+ {muscleLabel(ex.muscle_group)}+ </span>+ {hasEquipmentToShow(ex.equipment) && (+ <span className="text-xs text-tx-muted">{equipmentLabel(ex.equipment)}</span>+ )}+ </div>+ </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </Link>+ ))}+ {hasMore && (+ <button+ type="button"+ onClick={loadMore}+ disabled={loading}+ className="btn-secondary btn-sm w-full my-3"+ >+ {loading ? t('exercises.picker.loadingShort') : t('exercises.picker.loadMore')}+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/web/src/pages/WorkoutExercisePicker.tsx b/web/src/pages/WorkoutExercisePicker.tsxindex e3bcd61..962350e 100644--- a/web/src/pages/WorkoutExercisePicker.tsx+++ b/web/src/pages/WorkoutExercisePicker.tsx@@ -1,15 +1,12 @@import { useState, useEffect, useCallback } from 'react'import { useNavigate } from 'react-router-dom'import { ArrowLeft, Search, Dumbbell } from 'lucide-react'-import { useServerList, types, useTranslation } from '@lyftr/shared'+import { useServerList, types, useTranslation, hasEquipmentToShow, EXERCISE_PAGE_SIZE, EXERCISE_SEARCH_DEBOUNCE_MS } from '@lyftr/shared'import ExerciseListEmpty from '../components/ExerciseListEmpty'import { exerciseAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'import { muscleColorBordered, muscleLabel, equipmentLabel } 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 = 250export default function WorkoutExercisePicker() {const { t } = useTranslation()@@ -19,7 +16,7 @@ export default function WorkoutExercisePicker() {const [debouncedQuery, setDebouncedQuery] = useState('')useEffect(() => {- const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ const timer = setTimeout(() => setDebouncedQuery(query), EXERCISE_SEARCH_DEBOUNCE_MS)return () => clearTimeout(timer)}, [query])@@ -39,7 +36,7 @@ export default function WorkoutExercisePicker() {const list = useServerList<types.Exercise>({fetcher,- pageSize: PAGE_SIZE,+ pageSize: EXERCISE_PAGE_SIZE,deps: [debouncedQuery],})const { items: exercises, loadMore, hasMore, loading, initialLoading, error } = list@@ -138,7 +135,7 @@ export default function WorkoutExercisePicker() {<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(ex.muscle_group)}`}>{muscleLabel(ex.muscle_group)}</span>- {ex.equipment && ex.equipment !== 'other' && (+ {hasEquipmentToShow(ex.equipment) && (<span className="text-xs text-tx-muted">{equipmentLabel(ex.equipment)}</span>diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsxindex 66201ad..7619bf5 100644--- a/web/src/pages/Workouts.tsx+++ b/web/src/pages/Workouts.tsx@@ -1,7 +1,7 @@import { useState, useEffect, useRef } from 'react'import { createPortal } from 'react-dom'import { format } from 'date-fns'-import { Dumbbell, Plus, Clock, Search, Edit2, Trash2, TrendingUp, Award, ChevronRight, MoreVertical } from 'lucide-react'+import { Dumbbell, Library, Plus, Clock, Search, Edit2, Trash2, TrendingUp, Award, ChevronRight, MoreVertical } from 'lucide-react'import { useNavigate, useLocation } from 'react-router-dom'import Loading from '../components/Loading'import EmptyState from '../components/ui/EmptyState'@@ -263,6 +263,23 @@ export default function Workouts() {}/>+ {/* A labelled row, not a header icon: the exercise library is a place to go, and an+ unlabelled glyph beside Log Workout did not say where. */}+ <button+ type="button"+ onClick={() => navigate('/exercises')}+ className="card-interactive w-full flex items-center gap-3 p-3.5 text-left"+ >+ <div className="w-10 h-10 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0">+ <Library className="w-5 h-5 text-brand-500" />+ </div>+ <div className="flex-1 min-w-0">+ <p className="text-sm font-medium text-tx-primary">{t('workouts.list.browseExercises')}</p>+ <p className="text-xs text-tx-muted truncate">{t('exercises.browse.subtitle')}</p>+ </div>+ <ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />+ </button>+{/* 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 anddiff --git a/web/src/utils/exerciseUtils.ts b/web/src/utils/exerciseUtils.tsindex c421b6a..43c4cc7 100644--- a/web/src/utils/exerciseUtils.ts+++ b/web/src/utils/exerciseUtils.ts@@ -21,6 +21,11 @@ const MUSCLE_COLORS: Record<string, string> = {forearms: 'bg-cyan-500/20 text-cyan-400 border-cyan-500/30',traps: 'bg-indigo-500/20 text-indigo-400 border-indigo-500/30',lats: 'bg-sky-500/20 text-sky-400 border-sky-500/30',+ 'lower-back': 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ 'middle-back': 'bg-blue-500/20 text-blue-400 border-blue-500/30',+ neck: 'bg-rose-500/20 text-rose-400 border-rose-500/30',+ adductors: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',+ abductors: 'bg-violet-500/20 text-violet-400 border-violet-500/30',}export function muscleColor(m: string): string {