Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

Tell an empty exercise library apart from a search with no matches (#212)

Carteraf80033c19f2
diff --git a/mobile/src/components/workouts/ExercisePicker.test.tsx b/mobile/src/components/workouts/ExercisePicker.test.tsx
new file mode 100644
index 0000000..7bf2ffa
--- /dev/null
+++ b/mobile/src/components/workouts/ExercisePicker.test.tsx
@@ -0,0 +1,71 @@
+import { fireEvent, render, screen, waitFor } from '@testing-library/react-native'
+import type { Exercise } from '@lyftr/shared'
+
+jest.mock('expo-router', () => ({
+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },
+}))
+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 { ExercisePicker } from './ExercisePicker'
+
+const bench: Exercise = {
+ id: 1, name: 'Bench Press', muscle_group: 'chest', secondary_muscles: [],
+ category: 'strength', equipment: 'barbell', description: '',
+}
+
+const fullPage = (): Exercise[] =>
+ Array.from({ length: 50 }, (_, i) => ({ ...bench, id: i + 1, name: `Exercise ${i + 1}` }))
+
+const renderPicker = () =>
+ render(<ExercisePicker selectedIds={[]} onSelect={jest.fn()} onClose={jest.fn()} />)
+
+afterEach(() => { jest.restoreAllMocks() })
+
+describe('ExercisePicker (mobile)', () => {
+ it('shows the empty-library state with Try again when an unfiltered list is empty', async () => {
+ jest.spyOn(client.exerciseAPI, 'list')
+ .mockResolvedValueOnce([])
+ .mockResolvedValue([bench])
+ renderPicker()
+
+ expect(await screen.findByText('The exercise library is still loading')).toBeTruthy()
+ expect(screen.queryByText('No exercises found')).toBeNull()
+
+ fireEvent.press(screen.getByText('Try again'))
+
+ expect(await screen.findByText('Bench Press')).toBeTruthy()
+ })
+
+ 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)
+ renderPicker()
+
+ expect(await screen.findByText("Couldn't load exercises")).toBeTruthy()
+ expect(screen.getByText(/didn't respond in time/i)).toBeTruthy()
+ expect(screen.getByText('Try again')).toBeTruthy()
+ expect(screen.queryByText('The exercise library is still loading')).toBeNull()
+ expect(screen.queryByText('No exercises found')).toBeNull()
+ })
+
+ it('a search with no matches keeps No exercises found', async () => {
+ jest.spyOn(client.exerciseAPI, 'list').mockImplementation(((params?: { q?: string }) =>
+ Promise.resolve(params?.q ? [] : fullPage())) as never)
+ renderPicker()
+ await screen.findByText('Exercise 1')
+
+ fireEvent.changeText(screen.getByPlaceholderText('Search exercises…'), 'zzz')
+
+ await waitFor(() => expect(screen.getByText('No exercises found')).toBeTruthy(), { timeout: 2000 })
+ expect(screen.queryByText('The exercise library is still loading')).toBeNull()
+ })
+})
diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsx
index 7c14c06..84b07ed 100644
--- a/mobile/src/components/workouts/ExercisePicker.tsx
+++ b/mobile/src/components/workouts/ExercisePicker.tsx
@@ -1,9 +1,9 @@
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, Search } from 'lucide-react-native'
-import { useTranslation, type Exercise } from '@lyftr/shared'
-import { AppText, ErrorState, IconButton } from '../ui'
+import { ArrowLeft, Dumbbell, Search } from 'lucide-react-native'
+import { exerciseCatalogEmpty, useTranslation, type Exercise } from '@lyftr/shared'
+import { AppText, Button, EmptyState, ErrorState, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
import { useServerInfiniteList } from '../../hooks/useServerInfiniteList'
import { useTheme } from '../../theme/useTheme'
@@ -81,7 +81,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
)
const {
- items: exercises, loadMore, hasMore, initialLoading, error: listError, retry: retryList,
+ items: exercises, loadMore, hasMore, loading, initialLoading, error: listError, retry: retryList, reload,
} = useServerInfiniteList<Exercise>({
fetcher,
pageSize: PAGE_SIZE,
@@ -161,6 +161,21 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
// it reads as an empty catalogue rather than a connection that dropped.
listError ? (
<ErrorState title={t('exercises.picker.loadFailed')} message={listError} onRetry={retryList} />
+ ) : exerciseCatalogEmpty(debouncedQuery, { 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}
+ />
+ }
+ />
) : (
<View className="items-center py-16">
<AppText variant="body" color="muted">{t('exercises.picker.empty')}</AppText>
diff --git a/mobile/src/lib/useServerList.test.ts b/mobile/src/lib/useServerList.test.ts
index 1585304..57fe15b 100644
--- a/mobile/src/lib/useServerList.test.ts
+++ b/mobile/src/lib/useServerList.test.ts
@@ -94,3 +94,29 @@ describe('useServerList — a page that never arrived', () => {
await waitFor(() => expect(result.current.error).toBe('Database is locked'))
})
})
+
+describe('useServerList — a change of deps', () => {
+ it('is not settled on the render that sees the new deps', async () => {
+ const fetcher = jest.fn().mockResolvedValue([])
+ const seen: boolean[] = []
+
+ const { result, rerender } = renderHook(
+ ({ q }: { q: string }) => {
+ const list = useServerList<number>({ fetcher, pageSize: 2, deps: [q] })
+ seen.push(list.hasMore)
+ return list
+ },
+ { initialProps: { q: 'zzz' } },
+ )
+
+ await waitFor(() => expect(result.current.hasMore).toBe(false))
+ seen.length = 0
+
+ rerender({ q: '' })
+
+ // The first render after the change must already say "not settled"; the reset
+ // effect that sets the state itself runs only after it.
+ expect(seen[0]).toBe(true)
+ await waitFor(() => expect(result.current.hasMore).toBe(false))
+ })
+})
diff --git a/packages/shared/src/hooks/useServerList.ts b/packages/shared/src/hooks/useServerList.ts
index dc0816c..6c8c492 100644
--- a/packages/shared/src/hooks/useServerList.ts
+++ b/packages/shared/src/hooks/useServerList.ts
@@ -80,6 +80,7 @@ export function useServerList<T>({
// ignored, so a slow request for an old query (e.g. "a") can't overwrite the results
// of a newer one ("ab") when they resolve out of order — the classic search race.
const reqIdRef = useRef(0)
+ const appliedDepsRef = useRef(deps)
const fetchPage = useCallback(async (currentOffset: number, replace: boolean) => {
if (fetchingRef.current) return
@@ -136,6 +137,7 @@ export function useServerList<T>({
// revalidate) so the list/summary never flash to empty. `refreshing` drives the
// screen's "searching" cue over the stale list; it clears when the fetch settles.
useEffect(() => {
+ appliedDepsRef.current = deps
offsetRef.current = 0
setHasMore(true)
setFailure(null)
@@ -164,12 +166,18 @@ export function useServerList<T>({
fetchPage(offsetRef.current, offsetRef.current === 0)
}, [fetchPage])
+ // The reset above runs after the render that saw the new deps, so that one render
+ // still carries the previous query's hasMore. A caller reading "settled" from it
+ // would answer for a query nobody asked any more; a change of deps means unsettled.
+ const depsPending = deps.length !== appliedDepsRef.current.length
+ || deps.some((d, i) => !Object.is(d, appliedDepsRef.current[i]))
+
const error = failure === null ? null
: 'cause' in failure ? apiErrorMessage(failure.cause, errorFallback ?? t('errors.list.loadFailed'))
: t('errors.list.unreadable')
return {
- items, loadMore, hasMore, loading,
+ items, loadMore, hasMore: hasMore || depsPending, loading,
initialLoading: loading && !initializedRef.current,
refreshing, reload, error, retry,
}
diff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.json
index fa1f684..7d690ad 100644
--- a/packages/shared/src/i18n/locales/en.json
+++ b/packages/shared/src/i18n/locales/en.json
@@ -1261,6 +1261,7 @@
"triceps": "triceps"
},
"picker": {
+ "catalogEmpty": { "title": "The exercise library is still loading", "body": "Try again in a moment." },
"title": "Add Exercise",
"loaded_one": "{{count}} loaded",
"loaded_other": "{{count}} loaded",
diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.json
index d9b7ad1..879a376 100644
--- a/packages/shared/src/i18n/locales/es.json
+++ b/packages/shared/src/i18n/locales/es.json
@@ -1274,6 +1274,7 @@
"triceps": "tríceps"
},
"picker": {
+ "catalogEmpty": { "title": "La biblioteca de ejercicios todavía se está cargando", "body": "Inténtalo de nuevo en un momento." },
"title": "Agregar ejercicio",
"loaded_one": "{{count}} cargado",
"loaded_other": "{{count}} cargados",
diff --git a/packages/shared/src/utils/exerciseUtils.test.ts b/packages/shared/src/utils/exerciseUtils.test.ts
index 51ec80c..d6221e3 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 { categoryLabel, equipmentLabel, muscleLabel, resolveMuscleSlugs } from './exerciseUtils'
+import { categoryLabel, equipmentLabel, exerciseCatalogEmpty, 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.
@@ -113,3 +113,27 @@ describe('categoryLabel', () => {
expect(categoryLabel('flexibility')).toBe('flexibility')
})
})
+
+describe('exerciseCatalogEmpty (locale-independent)', () => {
+ const settled = { items: [], hasMore: false, error: null }
+
+ it('is true for an unfiltered page that settled empty', () => {
+ expect(exerciseCatalogEmpty('', settled)).toBe(true)
+ })
+
+ it('is false for a search that matched nothing', () => {
+ expect(exerciseCatalogEmpty('squat', settled)).toBe(false)
+ })
+
+ it('is false while a page is still expected', () => {
+ expect(exerciseCatalogEmpty('', { ...settled, hasMore: true })).toBe(false)
+ })
+
+ it('is false after a failure', () => {
+ expect(exerciseCatalogEmpty('', { ...settled, error: 'offline' })).toBe(false)
+ })
+
+ it('is false when rows arrived', () => {
+ expect(exerciseCatalogEmpty('', { ...settled, items: [{ id: 1 }] })).toBe(false)
+ })
+})
diff --git a/packages/shared/src/utils/exerciseUtils.ts b/packages/shared/src/utils/exerciseUtils.ts
index 5d4dca1..2096a61 100644
--- a/packages/shared/src/utils/exerciseUtils.ts
+++ b/packages/shared/src/utils/exerciseUtils.ts
@@ -64,6 +64,16 @@ export function categoryLabel(raw: string | undefined | null): string {
return label === slug ? (raw ?? '') : label
}
+// An unfiltered page that settled empty means the server holds no exercises yet, which
+// 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,
+ list: { items: readonly unknown[]; hasMore: boolean; error: string | null },
+): boolean {
+ return !query && !list.error && !list.hasMore && list.items.length === 0
+}
+
export function muscleLabel(raw: string | undefined | null): string {
const slug = raw ?? ''
return isOneOf(MUSCLE_SLUGS, slug) ? i18n.t(`exercises.muscle.${slug}`) : slug
diff --git a/web/src/components/ExerciseListEmpty.tsx b/web/src/components/ExerciseListEmpty.tsx
new file mode 100644
index 0000000..3beef55
--- /dev/null
+++ b/web/src/components/ExerciseListEmpty.tsx
@@ -0,0 +1,56 @@
+import { Dumbbell } from 'lucide-react'
+import { exerciseCatalogEmpty, types, useTranslation } from '@lyftr/shared'
+import { EmptyState, ListError } from './ui'
+
+interface Props {
+ query: string
+ items: readonly types.Exercise[]
+ hasMore: boolean
+ error: string | null
+ loading: boolean
+ retry: () => void
+ reload: () => Promise<void>
+}
+
+// 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) {
+ const { t } = useTranslation()
+
+ if (error) {
+ return (
+ <div className="p-4">
+ <ListError subject={t('exercises.picker.errorSubject')} message={error} onRetry={retry} />
+ </div>
+ )
+ }
+
+ if (exerciseCatalogEmpty(query, { 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 (
+ <EmptyState
+ compact
+ icon={Dumbbell}
+ title={t('exercises.picker.catalogEmpty.title')}
+ subtitle={t('exercises.picker.catalogEmpty.body')}
+ action={
+ <button
+ type="button"
+ onClick={() => { void reload() }}
+ disabled={loading}
+ className="btn-secondary btn-sm"
+ >
+ {loading ? t('common.retrying') : t('common.tryAgain')}
+ </button>
+ }
+ />
+ )
+ }
+
+ return (
+ <div className="flex items-center justify-center py-16 text-tx-muted text-sm">
+ {t('exercises.picker.empty')}
+ </div>
+ )
+}
diff --git a/web/src/components/ExercisePicker.test.tsx b/web/src/components/ExercisePicker.test.tsx
index 69226d1..43684e2 100644
--- a/web/src/components/ExercisePicker.test.tsx
+++ b/web/src/components/ExercisePicker.test.tsx
@@ -157,4 +157,60 @@ describe('ExercisePicker', () => {
expect(screen.getByText('Barra')).toBeTruthy()
expect(screen.getByPlaceholderText('Buscar ejercicios…')).toBeTruthy()
})
+
+ it('says the library is still loading when an unfiltered list comes back empty', async () => {
+ listMock.mockResolvedValue([])
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+
+ expect(await screen.findByText('The exercise library is still loading')).toBeTruthy()
+ expect(screen.getByText('Try again in a moment.')).toBeTruthy()
+ expect(screen.queryByText(/no exercises found/i)).toBeNull()
+ expect(screen.queryByRole('alert')).toBeNull()
+ })
+
+ it('Try again on an empty library re-requests and shows what arrives', async () => {
+ let release: (v: types.Exercise[]) => void = () => {}
+ listMock
+ .mockResolvedValueOnce([])
+ .mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+
+ fireEvent.click(await screen.findByRole('button', { name: /try again/i }))
+
+ const retrying = await screen.findByRole('button', { name: /retrying/i })
+ expect((retrying as HTMLButtonElement).disabled).toBe(true)
+ expect(screen.getByText('The exercise library is still loading')).toBeTruthy()
+ expect(screen.queryByText(/no exercises found/i)).toBeNull()
+
+ await act(async () => { release([exercise(1, 'Barbell Squat')]) })
+
+ expect(await screen.findByText('Barbell Squat')).toBeTruthy()
+ expect(screen.queryByText('The exercise library is still loading')).toBeNull()
+ const last = listMock.mock.calls[listMock.mock.calls.length - 1][0]
+ expect(last.page).toBe(1)
+ expect(last).not.toHaveProperty('q')
+ })
+
+ it('a search with no matches keeps No exercises found', async () => {
+ listMock.mockImplementation((params?: ListParams) =>
+ Promise.resolve(params?.q || params?.page !== 1 ? [] : fullPage('Exercise')))
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+ await screen.findByText('Exercise 1')
+
+ fireEvent.change(screen.getByPlaceholderText(/search exercises/i), { target: { value: 'zzz' } })
+
+ expect(await screen.findByText('No exercises found')).toBeTruthy()
+ expect(screen.queryByText('The exercise library is still loading')).toBeNull()
+ })
+
+ it('the empty-library state follows a switch to Spanish (es)', async () => {
+ listMock.mockResolvedValue([])
+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)
+ await screen.findByText('The exercise library is still loading')
+
+ await act(async () => { await i18n.changeLanguage('es') })
+
+ expect(screen.getByText('La biblioteca de ejercicios todavía se está cargando')).toBeTruthy()
+ expect(screen.getByText('Intentar de nuevo')).toBeTruthy()
+ })
})
diff --git a/web/src/components/ExercisePicker.tsx b/web/src/components/ExercisePicker.tsx
index 3da9c92..ae1bd8d 100644
--- a/web/src/components/ExercisePicker.tsx
+++ b/web/src/components/ExercisePicker.tsx
@@ -3,7 +3,7 @@ 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 { ListError } from './ui'
+import ExerciseListEmpty from './ExerciseListEmpty'
import { exerciseAPI } from '../services/api'
import { muscleColorBordered, muscleLabel, equipmentLabel } from '../utils/exerciseUtils'
@@ -44,13 +44,12 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
[debouncedQuery]
)
- const {
- items: exercises, loadMore, hasMore, loading, initialLoading, error, retry,
- } = useServerList<types.Exercise>({
+ const list = useServerList<types.Exercise>({
fetcher,
pageSize: PAGE_SIZE,
deps: [debouncedQuery],
})
+ const { items: exercises, loadMore, hasMore, loading, initialLoading, error } = list
const available = exercises.filter(e => !selectedIds.includes(e.id))
@@ -119,17 +118,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props
{t('exercises.picker.loading')}
</div>
) : available.length === 0 ? (
- // "No exercises found" is only true if we heard back. On a failed fetch it
- // reads as an empty catalogue rather than a connection that dropped.
- error ? (
- <div className="p-4">
- <ListError subject={t('exercises.picker.errorSubject')} message={error} onRetry={retry} />
- </div>
- ) : (
- <div className="flex items-center justify-center py-16 text-tx-muted text-sm">
- {t('exercises.picker.empty')}
- </div>
- )
+ <ExerciseListEmpty query={debouncedQuery} {...list} />
) : (
<div
className="px-4 py-2 relative"
diff --git a/web/src/pages/WorkoutExercisePicker.tsx b/web/src/pages/WorkoutExercisePicker.tsx
index fdb2908..e3bcd61 100644
--- a/web/src/pages/WorkoutExercisePicker.tsx
+++ b/web/src/pages/WorkoutExercisePicker.tsx
@@ -2,7 +2,7 @@ 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 { ListError } from '../components/ui'
+import ExerciseListEmpty from '../components/ExerciseListEmpty'
import { exerciseAPI } from '../services/api'
import { useWorkoutSession } from '../stores/workoutSession'
import { muscleColorBordered, muscleLabel, equipmentLabel } from '../utils/exerciseUtils'
@@ -37,13 +37,12 @@ export default function WorkoutExercisePicker() {
[debouncedQuery]
)
- const {
- items: exercises, loadMore, hasMore, loading, initialLoading, error, retry,
- } = useServerList<types.Exercise>({
+ const list = useServerList<types.Exercise>({
fetcher,
pageSize: PAGE_SIZE,
deps: [debouncedQuery],
})
+ const { items: exercises, loadMore, hasMore, loading, initialLoading, error } = list
const handleSelect = (exercise: types.Exercise) => {
const newEx: types.ActiveSessionExercise = {
@@ -111,17 +110,7 @@ export default function WorkoutExercisePicker() {
{t('exercises.picker.loadingShort')}
</div>
) : available.length === 0 ? (
- // "No exercises found" is only true if we heard back. On a failed fetch it
- // reads as an empty catalogue rather than a connection that dropped.
- error ? (
- <div className="py-4">
- <ListError subject={t('exercises.picker.errorSubject')} message={error} onRetry={retry} />
- </div>
- ) : (
- <div className="flex items-center justify-center py-12 text-tx-muted text-sm">
- {t('exercises.picker.empty')}
- </div>
- )
+ <ExerciseListEmpty query={debouncedQuery} {...list} />
) : (
<div className="space-y-1">
{available.map(ex => (