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.

Mobile: pickers on useServerList, one scanner, one inline confirm (#179)

Carter858706639d0f
diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsx
index 47da6fa..f9c2e7e 100644
--- a/mobile/app/(tabs)/index.tsx
+++ b/mobile/app/(tabs)/index.tsx
@@ -9,7 +9,7 @@ import {
import {
Activity, ArrowRight, BookOpen, ChevronRight, Dumbbell, Play, Plus, Scale, Timer, TrendingUp,
} from 'lucide-react-native'
-import { activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
+import { apiErrorMessage, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay } from '@lyftr/shared'
import { Alert, AppText, Card, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'
import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'
import {
@@ -117,7 +117,7 @@ export default function Dashboard() {
useEffect(() => {
fetchSettings()
load()
- .catch((err) => setError(err?.message || 'Failed to load'))
+ .catch((err) => setError(apiErrorMessage(err, 'Failed to load')))
.finally(() => setLoading(false))
}, [fetchSettings, load])
diff --git a/mobile/app/(tabs)/nutrition/index.tsx b/mobile/app/(tabs)/nutrition/index.tsx
index 6a8490f..95f0c91 100644
--- a/mobile/app/(tabs)/nutrition/index.tsx
+++ b/mobile/app/(tabs)/nutrition/index.tsx
@@ -6,7 +6,7 @@ import { format, subDays, addDays } from 'date-fns'
import {
AlertCircle, CalendarDays, CheckCircle2, ChevronLeft, ChevronRight, Flame, Plus, Utensils,
} from 'lucide-react-native'
-import { todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'
+import { apiErrorMessage, todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'
import {
AppText, Card, DateInput, IconButton, Label, PageHeader, Screen, SearchField, SectionHeader, SegmentedControl, Toast,
} from '../../../src/components/ui'
@@ -97,7 +97,7 @@ export default function Nutrition() {
setLogs(logData || [])
setStats(statsData)
} catch (err: any) {
- setError(err?.message || 'Failed to load food data')
+ setError(apiErrorMessage(err, 'Failed to load food data'))
} finally {
hasLoadedRef.current = true
}
diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsx
index 31bdf3e..2da3368 100644
--- a/mobile/app/(tabs)/weight/index.tsx
+++ b/mobile/app/(tabs)/weight/index.tsx
@@ -4,7 +4,7 @@ import { useFocusEffect } from 'expo-router'
import { format } from 'date-fns'
import * as Haptics from 'expo-haptics'
import {
- Activity, AlertCircle, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
+ Activity, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,
TrendingDown, TrendingUp, X,
} from 'lucide-react-native'
import { useAsyncAction, apiErrorMessage, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'
@@ -17,7 +17,6 @@ import { WeightEntryRow } from '../../../src/components/weight/WeightEntryRow'
import { WeightSkeleton } from '../../../src/components/weight/WeightSkeleton'
import { useServerInfiniteList } from '../../../src/hooks/useServerInfiniteList'
import { client, useSettingsStore } from '../../../src/lib/lyftr'
-import { semanticInk } from '../../../src/theme/theme'
import { useTheme } from '../../../src/theme/useTheme'
const PERIODS = ['7d', '30d', '90d', 'All'] as const
@@ -30,8 +29,7 @@ export default function Weight() {
const fetchSettings = useSettingsStore((s) => s.fetch)
const unit = settings.weight_unit
const wUnit = weightShort(unit)
- const { colors, accent, brand, isDark } = useTheme()
- const warningInk = semanticInk[isDark ? 'dark' : 'light'].warning
+ const { colors, accent, brand } = useTheme()
const [period, setPeriod] = useState<Period>('30d')
const [stats, setStats] = useState<WeightStats | null>(null)
@@ -59,14 +57,20 @@ export default function Weight() {
refetchStats()
}, [fetchSettings, refetchStats])
- // Pull-to-refresh: drive the native RefreshControl spinner off a full refresh of all
- // three sources (history list + stats + chart), same affordance as the Workouts list.
+ // Every screen refresh means "this screen's data is stale" across all three sources
+ // (history list + stats + chart) — one awaitable callback so they can't drift apart.
+ const refreshAll = useCallback(
+ () => Promise.all([reload(), refetchStats(), refetchChart()]),
+ [reload, refetchStats, refetchChart]
+ )
+
+ // Pull-to-refresh: drive the native RefreshControl spinner off a full refresh.
const [pulling, setPulling] = useState(false)
const onPullRefresh = useCallback(async () => {
setPulling(true)
- await Promise.all([reload(), refetchStats(), refetchChart()])
+ await refreshAll()
setPulling(false)
- }, [reload, refetchStats, refetchChart])
+ }, [refreshAll])
// Log form
const [newWeight, setNewWeight] = useState('')
@@ -96,10 +100,8 @@ export default function Weight() {
focusedOnce.current = true
return
}
- reload()
- refetchStats()
- refetchChart()
- }, [reload, refetchStats, refetchChart])
+ refreshAll()
+ }, [refreshAll])
)
// Oldest → newest for the chart. Weight in the display unit; `sub` feeds the tap bubble.
@@ -125,9 +127,7 @@ export default function Weight() {
setNewDate(todayStr())
setShowNotes(false)
duplicateWarningDismissedRef.current = false
- reload()
- refetchStats()
- refetchChart()
+ refreshAll()
}, 'Failed to log weight')
const handleLog = async () => {
@@ -280,32 +280,23 @@ export default function Weight() {
) : null}
{showDuplicateWarning && items.length > 0 ? (
- <View className="flex-row items-start gap-3 rounded-xl border border-warning-500/20 bg-warning-500/10 px-4 py-3">
- <AlertCircle size={16} color={warningInk} style={{ marginTop: 2 }} />
- <View className="min-w-0 flex-1">
- <Text className="font-sans-semibold text-sm" style={{ color: warningInk }}>
- Already logged on {formatDay(entryDay(items[0]), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
- </Text>
- <View className="mt-2 flex-row gap-2">
- <Pressable
- onPress={() => setShowDuplicateWarning(false)}
- className="rounded-lg border border-surface-border bg-surface-overlay px-3 py-1 active:opacity-70"
- >
- <AppText variant="caption" color="secondary">Cancel</AppText>
- </Pressable>
- <Pressable
- onPress={() => {
- duplicateWarningDismissedRef.current = true
- setShowDuplicateWarning(false)
- handleLog()
- }}
- className="rounded-lg bg-warning-500 px-3 py-1 active:opacity-80"
- >
- <Text className="font-sans-semibold text-xs" style={{ color: brand.warningText }}>Log Anyway</Text>
- </Pressable>
- </View>
- </View>
- </View>
+ <Alert
+ variant="warning"
+ actions={[
+ { label: 'Cancel', onPress: () => setShowDuplicateWarning(false) },
+ {
+ label: 'Log Anyway',
+ primary: true,
+ onPress: () => {
+ duplicateWarningDismissedRef.current = true
+ setShowDuplicateWarning(false)
+ handleLog()
+ },
+ },
+ ]}
+ >
+ Already logged on {formatDay(entryDay(items[0]), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?
+ </Alert>
) : null}
<Button
@@ -377,13 +368,11 @@ export default function Weight() {
</View>
</View>
<View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>
- {chartData.length === 0 ? (
- <View className="h-44 items-center justify-center">
- <AppText variant="body" color="muted">No data for this period</AppText>
- </View>
- ) : chartData.length === 1 ? (
+ {chartData.length < 2 ? (
<View className="h-44 items-center justify-center">
- <AppText variant="body" color="muted">Log another entry to see the trend</AppText>
+ <AppText variant="body" color="muted">
+ {chartData.length === 0 ? 'No data for this period' : 'Log another entry to see the trend'}
+ </AppText>
</View>
) : (
<ExerciseHistoryChart data={chartData} width={chartWidth} unit={wUnit} readoutNote="" height={180} />
@@ -399,7 +388,7 @@ export default function Weight() {
item={item}
next={items[index + 1]}
unit={unit}
- onDeleted={() => { reload(); refetchStats(); refetchChart() }}
+ onDeleted={refreshAll}
/>
)}
ListFooterComponent={
diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
index c6d1b13..5422911 100644
--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx
+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx
@@ -1,14 +1,13 @@
import { useEffect, useState } from 'react'
-import { Pressable, Text, View } from 'react-native'
+import { Pressable, View } from 'react-native'
import * as Haptics from 'expo-haptics'
-import { AlertCircle, Scale, X } from 'lucide-react-native'
+import { Scale, X } from 'lucide-react-native'
import { useAsyncAction, dayToInstant, displayToLbs, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep } from '@lyftr/shared'
import {
Alert, AppText, Button, DateInput, Field, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID,
Sheet, StepperTile,
} from '../ui'
import { client, useSettingsStore } from '../../lib/lyftr'
-import { semanticInk } from '@lyftr/shared'
import { useTheme } from '../../theme/useTheme'
interface Props {
@@ -28,8 +27,7 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
const settings = useSettingsStore((s) => s.settings)
const unit = settings.weight_unit
const wUnit = weightShort(unit)
- const { colors, accent, brand, isDark } = useTheme()
- const warningInk = semanticInk[isDark ? 'dark' : 'light'].warning
+ const { colors, accent } = useTheme()
const [value, setValue] = useState('')
const [date, setDate] = useState(todayStr())
@@ -101,24 +99,19 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess
) : null}
{showDuplicateWarning && lastLog ? (
- <View className="flex-row items-start gap-3 rounded-xl border border-warning-500/20 bg-warning-500/10 px-4 py-3">
- <AlertCircle size={16} color={warningInk} style={{ marginTop: 2 }} />
- <View className="min-w-0 flex-1">
- <AppText variant="bodySemibold" color="warning">
- Already logged today ({Math.round(lastValue ?? 0)} {wUnit}). Log again anyway?
- </AppText>
- <View className="mt-2 flex-row gap-2">
- <Pressable onPress={() => setShowDuplicateWarning(false)}
- className="rounded-lg border border-surface-border bg-surface-overlay px-3 py-1 active:opacity-70">
- <AppText variant="caption" color="secondary">Cancel</AppText>
- </Pressable>
- <Pressable onPress={() => { setDupDismissed(true); setShowDuplicateWarning(false); submit(true) }}
- className="rounded-lg bg-warning-500 px-3 py-1 active:opacity-80">
- <Text className="font-sans-semibold text-xs" style={{ color: brand.warningText }}>Log Anyway</Text>
- </Pressable>
- </View>
- </View>
- </View>
+ <Alert
+ variant="warning"
+ actions={[
+ { label: 'Cancel', onPress: () => setShowDuplicateWarning(false) },
+ {
+ label: 'Log Anyway',
+ primary: true,
+ onPress: () => { setDupDismissed(true); setShowDuplicateWarning(false); submit(true) },
+ },
+ ]}
+ >
+ Already logged today ({Math.round(lastValue ?? 0)} {wUnit}). Log again anyway?
+ </Alert>
) : null}
<StepperTile
diff --git a/mobile/src/components/numericFields.test.ts b/mobile/src/components/numericFields.test.ts
index 3c8c3f1..f176699 100644
--- a/mobile/src/components/numericFields.test.ts
+++ b/mobile/src/components/numericFields.test.ts
@@ -1,5 +1,4 @@
-import { readFileSync, readdirSync } from 'fs'
-import { join } from 'path'
+import { offenders } from '../testing/sourceScan'
// #141 was reported as "the weight field won't take a decimal", and the first fix
// corrected NumberField — while ActiveExerciseCard and ExerciseFormCard carried their
@@ -10,26 +9,11 @@ import { join } from 'path'
// @lyftr/shared and this asserts nobody grows a fourth. It reads the sources rather
// than rendering anything: the bug was never in what a component does with the value,
// it was in one component not asking the shared helper in the first place.
-const SRC = join(__dirname, '..', '..')
-const CODE = /\.tsx?$/
-const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])
// A character class that filters input down to digits — with or without a decimal
// point. This is the shape of the logic that must not be re-implemented.
const STRIP = /\[\^0-9\.?\]/
-function sources(dir: string): string[] {
- return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
- if (e.name.startsWith('.') || SKIP.has(e.name)) return []
- const p = join(dir, e.name)
- if (e.isDirectory()) return sources(p)
- return CODE.test(e.name) && !e.name.includes('.test.') ? [p] : []
- })
-}
-
it('has exactly one implementation of numeric input sanitizing', () => {
- const offenders = [...sources(join(SRC, 'src')), ...sources(join(SRC, 'app'))].filter((p) =>
- STRIP.test(readFileSync(p, 'utf8')),
- )
- expect(offenders.map((p) => p.slice(SRC.length + 1).replace(/\\/g, '/'))).toEqual([])
+ expect(offenders([STRIP])).toEqual([])
})
diff --git a/mobile/src/components/ui/Alert.tsx b/mobile/src/components/ui/Alert.tsx
index a73eace..17bdb92 100644
--- a/mobile/src/components/ui/Alert.tsx
+++ b/mobile/src/components/ui/Alert.tsx
@@ -1,46 +1,55 @@
import type { ReactNode } from 'react'
-import { View } from 'react-native'
+import { Pressable, Text, View } from 'react-native'
import { AlertCircle, CheckCircle2, Info, TriangleAlert } from 'lucide-react-native'
import { semanticInk } from '../../theme/theme'
+import type { SemanticTone } from '@lyftr/shared'
import { useTheme } from '../../theme/useTheme'
import { AppText } from './Typography'
-type Variant = 'error' | 'success' | 'warning' | 'info'
// Mirrors the web `.alert-*` primitives in web/src/index.css: tinted background at 10%,
// border at 20%, matching foreground, leading icon, same radius and padding.
//
-// Mobile had no equivalent, so form-level messages were hand-rolled per screen as a bare
-// icon-plus-text row — legible, but visibly lighter than the boxed alert the same message
-// gets on web. AuthError in components/authui.tsx is the sign-in screens' own copy of this
-// idea; screens built on the standard ui kit should use this one.
-// The `Soft` tokens are the 400s — web's alerts colour their text and icon at 400, not
-// the 500 used for the tint and border.
-const ICONS: Record<Variant, typeof AlertCircle> = {
+// Foreground comes from semanticInk, not a fixed shade: the 400s these classes were
+// written with fail WCAG AA on a light surface, and this app is light-first. See
+// packages/shared's alertContrast test, which holds every pairing to 4.5:1.
+const ICONS: Record<SemanticTone, typeof AlertCircle> = {
error: AlertCircle,
success: CheckCircle2,
warning: TriangleAlert,
info: Info,
}
-const SURFACES: Record<Variant, string> = {
+const SURFACES: Record<SemanticTone, string> = {
error: 'bg-error-500/10 border-error-500/20',
success: 'bg-success-500/10 border-success-500/20',
warning: 'bg-warning-500/10 border-warning-500/20',
info: 'bg-brand-500/10 border-brand-500/20',
}
+const FILLS: Record<SemanticTone, string> = {
+ error: 'bg-error-500',
+ success: 'bg-success-500',
+ warning: 'bg-warning-500',
+ info: 'bg-brand-500',
+}
+
interface Props {
- variant: Variant
+ variant: SemanticTone
children: ReactNode
className?: string
/** 'compact' for dense surfaces — inside a sheet, where a full-size alert outweighs
* the copy it is qualifying and pushes the buttons off a short screen. */
size?: 'default' | 'compact'
+ /** Turns the alert into an inline confirm. Both weight-logging surfaces ask "already
+ * logged today, log again anyway?" and both had hand-rolled this row — identically,
+ * including the amber-on-amber confirm that measured 1.4:1 and had to be fixed twice.
+ * `primary` is the one that commits: solid fill, so it reads as the answer, not a hint. */
+ actions?: { label: string; onPress: () => void; primary?: boolean }[]
}
-export function Alert({ variant, children, className = '', size = 'default' }: Props) {
- const { isDark } = useTheme()
+export function Alert({ variant, children, className = '', size = 'default', actions }: Props) {
+ const { isDark, brand } = useTheme()
const Icon = ICONS[variant]
const color = semanticInk[isDark ? 'dark' : 'light'][variant]
const compact = size === 'compact'
@@ -53,9 +62,37 @@ export function Alert({ variant, children, className = '', size = 'default' }: P
} ${SURFACES[variant]} ${className}`}
>
<Icon size={compact ? 15 : 18} color={color} strokeWidth={2.2} style={{ marginTop: compact ? 1.5 : 1 }} />
- <AppText variant={compact ? 'caption' : 'body'} className="flex-1" style={{ color }}>
- {children}
- </AppText>
+ <View className="min-w-0 flex-1">
+ <AppText variant={compact ? 'caption' : 'body'} style={{ color }}>
+ {children}
+ </AppText>
+ {actions?.length ? (
+ <View className="mt-2 flex-row gap-2">
+ {actions.map((a) => (
+ <Pressable
+ key={a.label}
+ accessibilityRole="button"
+ onPress={a.onPress}
+ className={`rounded-lg px-3 py-1 ${
+ a.primary
+ ? `${FILLS[variant]} active:opacity-80`
+ : 'border border-surface-border bg-surface-overlay active:opacity-70'
+ }`}
+ >
+ {a.primary ? (
+ // Near-black on a solid tint. The obvious `text-warning-400` here is the
+ // pairing that measured 1.4:1 — amber on amber.
+ <Text className="font-sans-semibold text-xs" style={{ color: brand.warningText }}>
+ {a.label}
+ </Text>
+ ) : (
+ <AppText variant="caption" color="secondary">{a.label}</AppText>
+ )}
+ </Pressable>
+ ))}
+ </View>
+ ) : null}
+ </View>
</View>
)
}
diff --git a/mobile/src/components/ui/semanticColor.guard.test.ts b/mobile/src/components/ui/semanticColor.guard.test.ts
index f2d8a01..58dcaf4 100644
--- a/mobile/src/components/ui/semanticColor.guard.test.ts
+++ b/mobile/src/components/ui/semanticColor.guard.test.ts
@@ -1,5 +1,4 @@
-import { readFileSync, readdirSync } from 'fs'
-import { join, sep } from 'path'
+import { offenders } from '../../testing/sourceScan'
// THE RULE: a semantic colour is chosen by the theme, never written as a fixed shade.
//
@@ -10,46 +9,18 @@ import { join, sep } from 'path'
// notice by looking, so a reviewer reading `text-error-400` sees the word "error" and
// moves on.
//
-// So the shade is not a call site's decision any more. `<AppText color="error">` and
+// So the shade is not a call site's decision. `<AppText color="error">` and
// `<Alert variant="error">` resolve through semanticInk, which packages/shared's
-// alertContrast test holds to AA in both themes. This fails if anyone writes the shade
-// by hand again — including in the tempting case, a one-off bit of red text.
-const MOBILE = join(__dirname, '..', '..', '..')
-const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])
+// alertContrast test holds to AA in both themes. This fails if anyone writes a shade by
+// hand again — including in the tempting case, a one-off bit of red text.
// Text utilities only. `bg-error-500/10` and `border-error-500/20` are the tint and edge
-// of the alert surface itself, which are fine — it is the FOREGROUND that has to react to
-// the theme.
+// of the surface itself; it is the FOREGROUND that has to react to the theme.
const FIXED_SEMANTIC_TEXT = /\btext-(error|warning|success|brand)-\d{3}\b/
// Where the mapping itself lives, and is supposed to name shades.
const ALLOWED = new Set(['src/components/ui/Typography.tsx', 'src/theme/theme.ts'])
-const stripComments = (src: string): string =>
- src
- // JSX block comments as well as line comments — a note ABOUT this rule is not a
- // violation of it, and ExerciseFormCard carries one.
- .replace(/\{\/\*[\s\S]*?\*\/\}/g, '')
- .split(/\r?\n/)
- .map((l) => l.replace(/\/\/.*/, ''))
- .filter((l) => !l.trim().startsWith('*'))
- .join('\n')
-
-function sources(dir: string): string[] {
- return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
- if (e.name.startsWith('.') || SKIP.has(e.name)) return []
- const p = join(dir, e.name)
- if (e.isDirectory()) return sources(p)
- const code = e.name.endsWith('.ts') || e.name.endsWith('.tsx')
- return code && !e.name.includes('.test.') ? [p] : []
- })
-}
-
it('never hard-codes a semantic text shade', () => {
- const offenders = [...sources(join(MOBILE, 'src')), ...sources(join(MOBILE, 'app'))]
- .filter((p) => FIXED_SEMANTIC_TEXT.test(stripComments(readFileSync(p, 'utf8'))))
- .map((p) => p.slice(MOBILE.length + 1).split(sep).join('/'))
- .filter((p) => !ALLOWED.has(p))
-
- expect(offenders).toEqual([])
+ expect(offenders([FIXED_SEMANTIC_TEXT], ALLOWED)).toEqual([])
})
diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsx
index 523f931..db1ca49 100644
--- a/mobile/src/components/workouts/ExercisePicker.tsx
+++ b/mobile/src/components/workouts/ExercisePicker.tsx
@@ -1,10 +1,11 @@
-import { useCallback, useEffect, useRef, useState } from 'react'
+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 type { Exercise } from '@lyftr/shared'
import { AppText, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
+import { useServerInfiniteList } from '../../hooks/useServerInfiniteList'
import { useTheme } from '../../theme/useTheme'
import { EQUIPMENT_LABEL } from '../../utils/exerciseUtils'
import { ExerciseImage } from './ExerciseImage'
@@ -18,6 +19,8 @@ interface Props {
// 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 = 250
function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => void }) {
return (
@@ -55,52 +58,31 @@ function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => v
// back to the form without a store detour, hence Modal).
export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
const { accent, colors } = useTheme()
- const [exercises, setExercises] = useState<Exercise[]>([])
const [query, setQuery] = useState('')
- const [loading, setLoading] = useState(false)
- const [page, setPage] = useState(1)
- const [exhausted, setExhausted] = useState(false)
- // FlatList fires onEndReached more than once near the boundary; this keeps those
- // repeats from each starting their own request for the same page.
- const loadingRef = useRef(false)
- // Identifies the newest request so a slow earlier one cannot overwrite it.
- const reqRef = useRef(0)
+ const [debouncedQuery, setDebouncedQuery] = useState('')
+
+ useEffect(() => {
+ const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)
+ return () => clearTimeout(t)
+ }, [query])
// Every page comes from the server, which queries open-exercise-db. The client
// used to cache the whole unfiltered catalog on first open and slice it locally;
// that made each install a copy of a database it does not own, and on a phone it
// is the difference between one 50-row response and ~873 rows of JSON.
- const load = useCallback(async (q: string, nextPage: number, append = false) => {
- // Only an append is skippable. Dropping a search because a page fetch is still
- // in flight leaves the user looking at the unfiltered first page while their
- // query appears to have done nothing.
- if (append && loadingRef.current) return
- const id = ++reqRef.current
- loadingRef.current = true
- setLoading(true)
- try {
- const data = (await client.exerciseAPI.list({ ...(q ? { q } : {}), page: nextPage })) || []
- if (reqRef.current !== id) return // a newer request has taken over
- setExercises((prev) => (append ? [...prev, ...data] : data))
- setExhausted(data.length < PAGE_SIZE)
- setPage(nextPage)
- } catch {
- // Web swallows picker fetch errors too — the empty state covers it.
- } finally {
- if (reqRef.current === id) {
- loadingRef.current = false
- setLoading(false)
- }
- }
- }, [])
+ const fetcher = useCallback(
+ (offset: number, limit: number) =>
+ client.exerciseAPI
+ .list({ ...(debouncedQuery ? { q: debouncedQuery } : {}), page: offset / limit + 1 })
+ .then((data) => data ?? []),
+ [debouncedQuery]
+ )
- useEffect(() => {
- const t = setTimeout(() => {
- setExhausted(false)
- load(query, 1)
- }, query ? 250 : 0)
- return () => clearTimeout(t)
- }, [query, load])
+ const { items: exercises, loadMore, hasMore, initialLoading } = useServerInfiniteList<Exercise>({
+ fetcher,
+ pageSize: PAGE_SIZE,
+ deps: [debouncedQuery],
+ })
const available = exercises.filter((e) => !selectedIds.includes(e.id))
@@ -120,7 +102,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
18px heading read undersized for a full-screen surface. */}
<AppText variant="title">Add Exercise</AppText>
<AppText variant="caption" color="muted">
- {available.length} loaded{exhausted ? '' : '…'}
+ {available.length} loaded{hasMore ? '…' : ''}
</AppText>
</View>
</View>
@@ -148,7 +130,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
</View>
{/* List */}
- {loading && exercises.length === 0 ? (
+ {initialLoading ? (
<View className="flex-row items-center justify-center gap-2 py-16">
<ActivityIndicator color={accent} />
<AppText variant="body" color="muted">Loading exercises…</AppText>
@@ -164,7 +146,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
// media so the thumbnails read as a column, not boxed cells.
ItemSeparatorComponent={() => <View className="ml-[56px] h-px bg-surface-border/60" />}
renderItem={({ item }) => <PickerRow exercise={item} onPress={() => onSelect(item)} />}
- onEndReached={() => { if (!exhausted && !loading) load(query, page + 1, true) }}
+ onEndReached={loadMore}
onEndReachedThreshold={0.5}
ListEmptyComponent={
<View className="items-center py-16">
@@ -172,7 +154,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {
</View>
}
ListFooterComponent={
- !exhausted && exercises.length > 0 ? (
+ hasMore && exercises.length > 0 ? (
<View className="flex-row items-center justify-center gap-2 py-4">
<ActivityIndicator color={accent} />
<AppText variant="caption" color="muted">Loading more…</AppText>
diff --git a/mobile/src/lib/authNavigation.guard.test.ts b/mobile/src/lib/authNavigation.guard.test.ts
index 58093cf..5106409 100644
--- a/mobile/src/lib/authNavigation.guard.test.ts
+++ b/mobile/src/lib/authNavigation.guard.test.ts
@@ -1,5 +1,4 @@
-import { readFileSync, readdirSync } from 'fs'
-import { join, sep } from 'path'
+import { offenders } from '../testing/sourceScan'
// #145 was not a wrong line, it was a second opinion: the API client navigated to /login on
// a failed refresh while the auth store still said the user was signed in, and the root gate
@@ -14,8 +13,6 @@ import { join, sep } from 'path'
//
// Only /login is policed. Navigating to '/' is ordinary (several back-button fallbacks do
// it) and cannot loop, because no guard sends an authed user away from the tabs.
-const MOBILE = join(__dirname, '..', '..')
-const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])
// The three ways to reach a route in expo-router. <Link href="/login"> is deliberately
// absent: a link the user has to press is not the app deciding to move them, and
@@ -26,36 +23,6 @@ const ROUTES_TO_LOGIN = [
/pathname\s*:\s*['"`]\/login/, // either, in object form
]
-// Comments talk about the bug; only code can cause it. Stripping can only remove text, so
-// it can hide a violation but never invent one.
-//
-// Split on /\r?\n/ rather than '\n': the repo checks out CRLF on Windows, and a trailing
-// \r is a line terminator that `.` will not match — so an end-anchored //.* silently
-// stripped nothing, and this file's own "router.replace('/login')" comment flagged it.
-const stripComments = (src: string): string =>
- src
- .split(/\r?\n/)
- .map((l) => l.replace(/\/\/.*/, ''))
- .filter((l) => !l.trim().startsWith('*'))
- .join('\n')
-
-function sources(dir: string): string[] {
- return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
- if (e.name.startsWith('.') || SKIP.has(e.name)) return []
- const p = join(dir, e.name)
- if (e.isDirectory()) return sources(p)
- const code = e.name.endsWith('.ts') || e.name.endsWith('.tsx')
- return code && !e.name.includes('.test.') ? [p] : []
- })
-}
-
it('never routes anyone to the sign-in screen', () => {
- const offenders = [...sources(join(MOBILE, 'src')), ...sources(join(MOBILE, 'app'))]
- .filter((p) => {
- const code = stripComments(readFileSync(p, 'utf8'))
- return ROUTES_TO_LOGIN.some((re) => re.test(code))
- })
- .map((p) => p.slice(MOBILE.length + 1).split(sep).join('/'))
-
- expect(offenders).toEqual([])
+ expect(offenders(ROUTES_TO_LOGIN)).toEqual([])
})
diff --git a/mobile/src/testing/sourceScan.ts b/mobile/src/testing/sourceScan.ts
new file mode 100644
index 0000000..1ec6ef8
--- /dev/null
+++ b/mobile/src/testing/sourceScan.ts
@@ -0,0 +1,42 @@
+import { readFileSync, readdirSync } from 'fs'
+import { join, sep } from 'path'
+
+// Shared by the structural guards (authNavigation, semanticColor, numericFields). They all
+// need to walk the app's source and read it without comments, and they had a copy each —
+// which had already drifted: only one of them stripped JSX block comments, so a note ABOUT
+// a rule read as a violation of it, and one matched raw source for the same reason.
+
+const MOBILE = join(__dirname, '..', '..')
+const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])
+
+const walk = (dir: string): string[] =>
+ readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
+ if (e.name.startsWith('.') || SKIP.has(e.name)) return []
+ const p = join(dir, e.name)
+ if (e.isDirectory()) return walk(p)
+ return /\.tsx?$/.test(e.name) && !e.name.includes('.test.') ? [p] : []
+ })
+
+// Comments describe the rules these guards enforce; only code can break them. Stripping
+// can only remove text, so it can hide a violation but never invent one.
+//
+// Splitting on /\r?\n/ rather than '\n' is load-bearing: the repo checks out CRLF, and a
+// trailing \r is a line terminator that `.` will not match, so an end-anchored //.*
+// silently strips nothing.
+const withoutComments = (src: string): string =>
+ src
+ .replace(/\{\/\*[\s\S]*?\*\/\}/g, '')
+ .split(/\r?\n/)
+ .map((l) => l.replace(/\/\/.*/, ''))
+ .filter((l) => !l.trim().startsWith('*'))
+ .join('\n')
+
+/** Files whose code (not comments) matches any of `patterns`, repo-relative. */
+export const offenders = (patterns: RegExp[], allowed: Set<string> = new Set()): string[] =>
+ [...walk(join(MOBILE, 'src')), ...walk(join(MOBILE, 'app'))]
+ .filter((p) => {
+ const code = withoutComments(readFileSync(p, 'utf8'))
+ return patterns.some((re) => re.test(code))
+ })
+ .map((p) => p.slice(MOBILE.length + 1).split(sep).join('/'))
+ .filter((p) => !allowed.has(p))