Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
Localize the whole UI: i18next in @lyftr/shared, a language picker, every screen translated (#199)
Carterdeaf334461b8
diff --git a/CLAUDE.md b/CLAUDE.mdindex c15a4f9..19b6ec9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -171,6 +171,23 @@ true of one file. Do not document it here before it lands.---+## UI Strings — read before adding screen copy++**The rule: screen copy goes through `t()`, with keys in `packages/shared/src/i18n/locales/en.json`.**++- Single points of truth: `i18n/index.ts` (init, language registry, `resolveLanguage`),+ `stores/language.ts` (the device-level preference), `i18n/catalog.test.ts` (key, placeholder+ and plural parity across locales).+- `i18n/index.ts` also owns the language picker's entries, order, current-choice label+ (`LANGUAGE_ORDER`, `languageChoiceLabel`).+ The OS per-app language list is `supportedLocales` in `mobile/app.json`, held to the registry+ by a mobile test, and only changes with an EAS build.+- Hermes has no `Intl.PluralRules`; `mobile/src/lib/polyfills.ts` imports the polyfill.+- Numbers and dates are never formatted through i18next (see Numbers & Locale).+- Details and key-naming rules: CONTRIBUTING.md, "Translations".++---+## Failing Requests — read before touching the API client**The rule: every request settles, and only the server may end a session.**diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a517e69..1b38219 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -110,6 +110,45 @@ git rebase origin/main---+## Translations++UI strings live in one catalog per language in `packages/shared/src/i18n/locales`, shared+by web and mobile. `en.json` is the source and the fallback. The languages the app ships+are listed in `locales/README.md`.++**Adding a language**+1. Copy `en.json` to `<code>.json` and translate the values.+2. Add it to `resources` and `LANGUAGE_NAMES` (its own name, untranslated) in+ `i18n/index.ts`; TypeScript flags a missing entry, and the picker's order follows+ automatically.+3. List it in `locales/README.md` (`catalog.test.ts` fails if the table and the registry+ disagree).+4. Add the code to both `supportedLocales` lists of the `expo-localization` plugin in+ `mobile/app.json`, so the language appears in the iOS/Android per-app language settings.+ Mobile's `supportedLocales.test.ts` fails until you do; it reaches phones only with the+ next EAS build.+5. Run `npm run shared:test` and `npm run test -w @lyftr/mobile -- --ci --maxWorkers=4`. `catalog.test.ts` fails by key name on a missing or extra key,+ a changed `{{placeholder}}`, or a missing plural form.++**Key rules**+- Semantic dotted keys by screen, section, item and role (`settings.account.name.label`).+ Never the English sentence as the key.+- One key per context. Do not reuse a key because the English happens to match; the other+ language may not.+- Never build a sentence by concatenation. Use `{{placeholders}}` and keep them verbatim in+ every language.+- Counts use plural keys (`key_one`, `key_other`, ...). Each language provides exactly the+ categories `Intl.PluralRules` gives it: Spanish needs `_one`, `_many` and `_other`.+- Numbers and dates never go through i18next. Format them with `utils/number.ts` /+ `dateUtils.ts` and pass the result in as a placeholder.++**Renaming keys.** A key's identity is its translation memory (the lesson from Jellyfin).+Renaming a key for tidiness throws away every translation of it and forces retranslation.+Fix a typo by editing the English value in place; change the key only when the meaning+changes, because that is exactly when you want it retranslated.++---+## Commit MessagesFollow conventional commits:diff --git a/mobile/app.json b/mobile/app.jsonindex 3be80e5..fb55b6c 100644--- a/mobile/app.json+++ b/mobile/app.json@@ -59,7 +59,13 @@],"expo-font","@react-native-community/datetimepicker",- "expo-localization",+ [+ "expo-localization",+ {+ "allowDynamicLocaleChangesAndroid": true,+ "supportedLocales": { "ios": ["en", "es"], "android": ["en", "es"] }+ }+ ],["expo-network-security-config",{diff --git a/mobile/app/(auth)/login.tsx b/mobile/app/(auth)/login.tsxindex 8010679..39811f7 100644--- a/mobile/app/(auth)/login.tsx+++ b/mobile/app/(auth)/login.tsx@@ -3,7 +3,7 @@ import { Text, View, Linking } from 'react-native'import { Link } from 'expo-router'import { AuthScaffold } from '../../src/components/AuthScaffold'import { IconInput, GradientButton, SecondaryButton, AuthDivider, AuthError, ServerRow, Footer } from '../../src/components/authui'-import { registrationOpen } from '@lyftr/shared'+import { registrationOpen, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { useAuthStore, useServerInfo } from '../../src/lib/lyftr'import { useTheme } from '../../src/theme/useTheme'@@ -15,9 +15,10 @@ const DEMO_URL = 'https://lyftr-demo.fly.dev'const EMAIL_RE = /^\S+@\S+\.\S+$/export default function Login() {+ const { t } = useTranslation()const [email, setEmail] = useState('')const [password, setPassword] = useState('')- const [localError, setLocalError] = useState<string | null>(null)+ const [localError, setLocalError] = useState<UiMessage | null>(null)const login = useAuthStore((s) => s.login)const loading = useAuthStore((s) => s.isLoading)const error = useAuthStore((s) => s.error)@@ -35,8 +36,8 @@ export default function Login() {// Validate only on submit (not while typing): the browser's `required`/`type=email`// equivalent, surfaced as an error after the user presses Sign in.const submit = async () => {- if (!EMAIL_RE.test(email.trim())) { setLocalError('Enter a valid email address'); return }- if (!password) { setLocalError('Enter your password'); return }+ if (!EMAIL_RE.test(email.trim())) { setLocalError({ key: 'auth.validation.emailInvalid' }); return }+ if (!password) { setLocalError({ key: 'auth.validation.passwordRequired' }); return }setLocalError(null)try { await login(email.trim(), password) } catch {}}@@ -47,42 +48,42 @@ export default function Login() {const shownError = localError || errorreturn (- <AuthScaffold heading="Welcome back" subtitle="Sign in to continue training.">+ <AuthScaffold heading={t('auth.login.heading')} subtitle={t('auth.login.subtitle')}><ServerRow /><IconInput- label="Email"+ label={t('auth.field.email')}icon="mail"value={email}onChangeText={onChange(setEmail)}keyboardType="email-address"- placeholder="[email protected]"+ placeholder={t('auth.field.emailPlaceholder')}/><IconInput- label="Password"+ label={t('auth.field.password')}icon="lock"passwordvalue={password}onChangeText={onChange(setPassword)}placeholder="••••••••"/>- {shownError ? <AuthError message={shownError} /> : null}- <GradientButton title="Sign in" onPress={submit} loading={loading} />+ {shownError ? <AuthError message={uiMessage(shownError)} /> : null}+ <GradientButton title={t('auth.login.submit')} onPress={submit} loading={loading} /><AuthDivider />- <SecondaryButton title="Try demo account" hint="no sign-up" onPress={demo} />+ <SecondaryButton title={t('auth.login.demo')} hint={t('auth.login.demoHint')} onPress={demo} />{/* A closed server says so instead of offering a link that 403s on submit — but itdoes still say so, rather than leaving someone who came to sign up hunting for abutton that is not there (mastodon/mastodon#21556). */}<Footer>{isOpen ? (<View style={{ flexDirection: 'row', gap: 5 }}>- <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>New here?</Text>+ <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>{t('auth.login.newHere')}</Text><Link href="/register" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>- Create account+ {t('auth.login.createAccountLink')}</Link></View>) : (<Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>- This server is not accepting new accounts.+ {t('auth.closed.notice')}</Text>)}</Footer>diff --git a/mobile/app/(auth)/register.tsx b/mobile/app/(auth)/register.tsxindex c30cc5e..51ca516 100644--- a/mobile/app/(auth)/register.tsx+++ b/mobile/app/(auth)/register.tsx@@ -4,7 +4,10 @@ import { Link } from 'expo-router'import { AuthScaffold } from '../../src/components/AuthScaffold'import { PasswordRule } from '../../src/components/ui'import { IconInput, GradientButton, AuthError, ServerRow, Footer } from '../../src/components/authui'-import { registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'+import {+ registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules,+ uiMessage, useTranslation, type UiMessage,+} from '@lyftr/shared'import { useAuthStore, useServerInfo } from '../../src/lib/lyftr'import { useTheme } from '../../src/theme/useTheme'@@ -13,13 +16,14 @@ import { useTheme } from '../../src/theme/useTheme'const EMAIL_RE = /^\S+@\S+\.\S+$/export default function Register() {+ const { t } = useTranslation()const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [passwordConfirm, setPasswordConfirm] = useState('')// Only the email check lands here now — the password rules render under their own// fields as the user types (see below), so this holds the one error that has nowhere// else to go, plus whatever the server says.- const [localError, setLocalError] = useState<string | null>(null)+ const [localError, setLocalError] = useState<UiMessage | null>(null)const register = useAuthStore((s) => s.register)const loading = useAuthStore((s) => s.isLoading)const error = useAuthStore((s) => s.error)@@ -38,7 +42,7 @@ export default function Register() {const rules = newPasswordRules({ password, confirm: passwordConfirm })const submit = async () => {- if (!EMAIL_RE.test(email.trim())) { setLocalError('Enter a valid email address'); return }+ if (!EMAIL_RE.test(email.trim())) { setLocalError({ key: 'auth.validation.emailInvalid' }); return }// Backstop — the button is disabled until the rules pass.if (!rules.ready) returnsetLocalError(null)@@ -52,7 +56,7 @@ export default function Register() {// meet a 403 on submit. ServerRow stays: they may just be pointed at the wrong server.if (!isOpen) {return (- <AuthScaffold heading="Registration closed" subtitle="This server is not accepting new accounts.">+ <AuthScaffold heading={t('auth.register.closedHeading')} subtitle={t('auth.closed.notice')}><ServerRow /><Textstyle={{@@ -63,12 +67,11 @@ export default function Register() {marginTop: 8,}}>- The owner of this Lyftr instance has turned off new signups. If you should have an- account here, ask them to create one for you.+ {t('auth.register.closedBody')}</Text><Footer><Link href="/login" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>- Back to sign in+ {t('auth.register.backToSignIn')}</Link></Footer></AuthScaffold>@@ -76,18 +79,18 @@ export default function Register() {}return (- <AuthScaffold heading="Create account" subtitle="Start your training log.">+ <AuthScaffold heading={t('auth.register.heading')} subtitle={t('auth.register.subtitleNative')}><ServerRow /><IconInput- label="Email"+ label={t('auth.field.email')}icon="mail"value={email}onChangeText={onChange(setEmail)}keyboardType="email-address"- placeholder="[email protected]"+ placeholder={t('auth.field.emailPlaceholder')}/><IconInput- label="Password"+ label={t('auth.field.password')}icon="lock"passwordvalue={password}@@ -98,7 +101,7 @@ export default function Register() {<PasswordRule state={rules.length}>{lengthRuleLabel(password)}</PasswordRule></View><IconInput- label="Confirm password"+ label={t('auth.field.confirmPassword')}icon="lock"passwordvalue={passwordConfirm}@@ -108,13 +111,13 @@ export default function Register() {<View className="gap-1.5 mt-2"><PasswordRule state={rules.match}>{matchRuleLabel(rules.match)}</PasswordRule></View>- {shownError ? <AuthError message={shownError} /> : null}- <GradientButton title="Create account" onPress={submit} loading={loading} disabled={!rules.ready} />+ {shownError ? <AuthError message={uiMessage(shownError)} /> : null}+ <GradientButton title={t('auth.register.submit')} onPress={submit} loading={loading} disabled={!rules.ready} /><Footer><View style={{ flexDirection: 'row', gap: 5 }}>- <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>Have an account?</Text>+ <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>{t('auth.register.haveAccountShort')}</Text><Link href="/login" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>- Sign in+ {t('auth.register.signInLink')}</Link></View></Footer>diff --git a/mobile/app/(tabs)/_layout.tsx b/mobile/app/(tabs)/_layout.tsxindex 0c11dbf..ff60655 100644--- a/mobile/app/(tabs)/_layout.tsx+++ b/mobile/app/(tabs)/_layout.tsx@@ -1,8 +1,10 @@import { Tabs } from 'expo-router'import { House, Dumbbell, BookOpen, Apple, Scale } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../src/theme/useTheme'export default function TabsLayout() {+ const { t } = useTranslation()const { colors, brand } = useTheme()return (<Tabs@@ -18,23 +20,23 @@ export default function TabsLayout() {><Tabs.Screenname="index"- options={{ title: 'Home', tabBarIcon: ({ color, size }) => <House color={color} size={size} /> }}+ options={{ title: t('nav.home'), tabBarIcon: ({ color, size }) => <House color={color} size={size} /> }}/><Tabs.Screenname="workouts"- options={{ title: 'Workouts', tabBarIcon: ({ color, size }) => <Dumbbell color={color} size={size} /> }}+ options={{ title: t('nav.workouts'), tabBarIcon: ({ color, size }) => <Dumbbell color={color} size={size} /> }}/><Tabs.Screenname="programs"- options={{ title: 'Programs', tabBarIcon: ({ color, size }) => <BookOpen color={color} size={size} /> }}+ options={{ title: t('nav.programs'), tabBarIcon: ({ color, size }) => <BookOpen color={color} size={size} /> }}/><Tabs.Screenname="nutrition"- options={{ title: 'Nutrition', tabBarIcon: ({ color, size }) => <Apple color={color} size={size} /> }}+ options={{ title: t('nav.nutrition'), tabBarIcon: ({ color, size }) => <Apple color={color} size={size} /> }}/><Tabs.Screenname="weight"- options={{ title: 'Weight', tabBarIcon: ({ color, size }) => <Scale color={color} size={size} /> }}+ options={{ title: t('nav.weight'), tabBarIcon: ({ color, size }) => <Scale color={color} size={size} /> }}/>{/* Settings lives off the footer now — reached via the avatar in the Home header.href:null keeps /settings routable while hiding it from the tab bar. */}diff --git a/mobile/app/(tabs)/index.tsx b/mobile/app/(tabs)/index.tsxindex 994b17a..5466a1f 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 { apiErrorMessage, isDailyStats, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, nameInitial, lifterQuip } from '@lyftr/shared'+import { isDailyStats, activeSessionExercisesForDay, dayLabel, displayVolume, displayWeight, sessionNameForDay, weightShort, type DailyStats, type Program, type WeightLog, type WeightStats, type Workout, workoutDay, entryDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, nameInitial, lifterQuip, formatDate, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { AppText, Card, ErrorState, IconButton, Label, Screen, SectionHeader, SegmentedControl } from '../../src/components/ui'import { ExerciseImage } from '../../src/components/workouts/ExerciseImage'import {@@ -18,7 +18,7 @@ import {import { QuickWeighInSheet } from '../../src/components/dashboard/QuickWeighInSheet'import { DashboardSkeleton } from '../../src/components/dashboard/DashboardSkeleton'import { client, useAuthStore, useDisplayName, useSettingsStore, useWorkoutSession } from '../../src/lib/lyftr'-import { muscleColor } from '../../src/utils/exerciseUtils'+import { muscleColor, muscleLabel } from '../../src/utils/exerciseUtils'import { useTheme } from '../../src/theme/useTheme'// Native tap feedback (matches the rest of the app): selection tick for navigations /@@ -30,6 +30,9 @@ const DEFAULT_FOOD: DailyStats = {date: '', total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,}+// The seven weekday rows of the heatmap; every other one carries a letter.+const WEEKDAY_ROWS = [0, 1, 2, 3, 4, 5, 6] as const+const VOL_OPTIONS = [{ value: '7' as const, label: '7' }, { value: '14' as const, label: '14' }, { value: '30' as const, label: '30' },]@@ -44,11 +47,13 @@ function ProgressBar({ pct, color, opacity = 1, className = '' }: { pct: number;}function MuscleBadge({ muscle }: { muscle: string }) {+ // Re-renders on a language switch: the badge names the muscle from the catalog.+ useTranslation()const { colors } = useTheme()const tint = muscleColor(muscle)return (<View className={`self-start rounded px-1.5 py-0.5 ${tint?.chip ?? 'bg-surface-muted'}`}>- <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscle}</AppText>+ <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscleLabel(muscle)}</AppText></View>)}@@ -65,6 +70,7 @@ function LinkRow({ label, onPress }: { label: string; onPress: () => void }) {}export default function Dashboard() {+ const { t } = useTranslation()// Re-read on every load rather than once at mount: this tab stays mounted for the// life of the process, so an app left open overnight kept yesterday's header, week// boundary and "today" dot while load() fetched the real today's food.@@ -95,12 +101,14 @@ export default function Dashboard() {const [weightLogs, setWeightLogs] = useState<WeightLog[]>([])const [weightStats, setWeightStats] = useState<WeightStats | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // Failures are kept as a UiMessage (a key and the failure that caused it), not as a sentence,+ // so a banner already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)// The secondary reads are caught so one dead endpoint cannot blank a working dashboard.// What they must not do is then say nothing: a failed /food/stats rendered today as// 0 kcal, which is what "hasn't eaten yet" looks like. Name -> what the server said,// so the card that never loaded can say why.- const [missing, setMissing] = useState<Record<string, string>>({})+ const [missing, setMissing] = useState<Record<string, UiMessage>>({})const foodMissing = "today's food" in missingconst weightMissing = 'your weight' in missingconst programsMissing = 'your programs' in missing@@ -120,9 +128,9 @@ export default function Dashboard() {if (!Array.isArray(v)) throw new Error('unreadable')return v}- const absent: Record<string, string> = {}+ const absent: Record<string, UiMessage> = {}const note = (what: string, err: unknown) => {- absent[what] = apiErrorMessage(err, "The server didn't say what went wrong.")+ absent[what] = { key: 'settings.unknownError', cause: err }}const [ws, ps, fs, wl, wst] = await Promise.all([// Uncaught on purpose, mirroring web: this is the primary request, and it is@@ -150,7 +158,7 @@ export default function Dashboard() {useEffect(() => {fetchSettings()load()- .catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ .catch((err) => setError({ key: 'settings.unknownError', cause: err })).finally(() => setLoading(false))}, [fetchSettings, load])@@ -188,12 +196,12 @@ export default function Dashboard() {<Screen><ErrorStatesize="page"- title="Couldn't load your dashboard"- message={error}+ title={t('home.loadFailed')}+ message={uiMessage(error)}onRetry={() => {setError(null)setLoading(true)- load().catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong."))).finally(() => setLoading(false))+ load().catch((err) => setError({ key: 'settings.unknownError', cause: err })).finally(() => setLoading(false))}}/></Screen>@@ -223,7 +231,7 @@ export default function Dashboard() {}const chartData = workouts.slice(0, Number(volumePeriod)).reverse().map((w) => ({- date: formatDay(workoutDay(w), 'M/d'),+ date: formatDay(workoutDay(w), 'numericMonthDay'),volume: displayVolume(calcVolume(w), unit),name: w.name,}))@@ -242,9 +250,9 @@ export default function Dashboard() {const heatmapWeeks: Date[][] = []for (let i = 0; i < heatmapDays.length; i += 7) heatmapWeeks.push(heatmapDays.slice(i, i + 7))const monthLabels: (string | null)[] = heatmapWeeks.map((week, i) => {- const m = format(week[0], 'MMM')+ const m = formatDate(week[0], 'monthShort')if (i === 0) return m- return m !== format(heatmapWeeks[i - 1][0], 'MMM') ? m : null+ return m !== formatDate(heatmapWeeks[i - 1][0], 'monthShort') ? m : null})const muscleMap = new Map<string, number>()@@ -277,7 +285,7 @@ export default function Dashboard() {const fatPct = Math.min(100, (food.total_fat / settings.fat_target) * 100) || 0const sparkData = [...weightLogs].reverse().map((l) => ({- date: formatDay(entryDay(l), 'M/d'),+ date: formatDay(entryDay(l), 'numericMonthDay'),weight: displayWeight(l.weight, unit),}))@@ -295,10 +303,10 @@ export default function Dashboard() {<View className="flex-row items-start justify-between gap-3"><View className="min-w-0 flex-1"><Text className="font-sans-medium text-[11px] uppercase text-tx-muted" style={{ letterSpacing: 1 }}>- {format(now, 'EEEE, MMMM d')}+ {formatDate(now, 'weekdayMonthDayLong')}</Text>{/* No numberOfLines: a name is never clipped — see web's Dashboard. */}- <AppText variant="title" className="mt-0.5">{greeting(now)}, {username}</AppText>+ <AppText variant="title" className="mt-0.5">{greeting(now, username)}</AppText></View><View className="flex-row items-center gap-2"><Pressable@@ -306,12 +314,12 @@ export default function Dashboard() {className="flex-row items-center gap-1.5 rounded-xl bg-brand-500 px-4 py-2.5 active:scale-95"><Play size={15} color="#fff" />- <Text className="font-sans-bold text-sm text-white">{session ? 'Resume' : 'Start'}</Text>+ <Text className="font-sans-bold text-sm text-white">{t(session ? 'home.header.resume' : 'home.header.start')}</Text></Pressable>{/* Avatar → Settings. Settings moved off the footer; this is its entry point. */}<PressableaccessibilityRole="button"- accessibilityLabel="Settings"+ accessibilityLabel={t('nav.settings')}onPress={() => { hSelect(); router.navigate('/settings') }}hitSlop={6}className="active:scale-95"@@ -342,8 +350,8 @@ export default function Dashboard() {<Timer size={18} color={brand.warningSoft} /></View><View>- <AppText variant="bodySemibold" color="warning">Workout in progress</AppText>- <Text className="text-xs" style={{ color: brand.warningSoft, opacity: 0.7 }}>{session.name} — tap to resume</Text>+ <AppText variant="bodySemibold" color="warning">{t('home.activeSession.title')}</AppText>+ <Text className="text-xs" style={{ color: brand.warningSoft, opacity: 0.7 }}>{t('home.activeSession.tapToResume', { name: session.name })}</Text></View></View><ArrowRight size={18} color={brand.warningSoft} />@@ -362,25 +370,25 @@ export default function Dashboard() {<Card className="flex-row items-center gap-3"><PressableaccessibilityRole="button"- accessibilityLabel={`View ${upNext.program.name} routine`}+ accessibilityLabel={t('home.upNext.viewRoutine', { name: upNext.program.name })}onPress={() => { hSelect(); router.navigate(`/programs/${upNext.program.id}`) }}className="min-w-0 flex-1 flex-row items-center gap-3 active:opacity-70"><ExerciseImage url={upNext.day.exercises?.[0]?.exercise?.image_url} fallbackIcon={BookOpen} /><View className="min-w-0 flex-1">- <Label>Up next · {upNext.program.name}</Label>+ <Label>{t('home.upNext.label', { name: upNext.program.name })}</Label><Text className="mt-0.5 font-sans-semibold text-sm text-tx-primary" numberOfLines={1}>{dayLabel(upNext.day, upNext.day.order_index)}</Text><AppText variant="caption" color="muted" className="mt-0.5">- {(upNext.day.exercises ?? []).length} exercise{(upNext.day.exercises ?? []).length === 1 ? '' : 's'}+ {t('home.upNext.exercises', { count: (upNext.day.exercises ?? []).length })}</AppText></View><ChevronRight size={16} color={colors.txMuted} /></Pressable><IconButtonicon={Play}- label={`Start ${dayLabel(upNext.day, upNext.day.order_index)}`}+ label={t('home.upNext.start', { name: dayLabel(upNext.day, upNext.day.order_index) })}variant="solid"size="sm"onPress={startUpNext}@@ -391,7 +399,7 @@ export default function Dashboard() {// here the screen reads as an account with no routine, which is a claim we// cannot make from a request that never answered.<Card>- <ErrorState title="Couldn't load your programs" message={missing['your programs']} onRetry={onRefresh} />+ <ErrorState title={t('home.upNext.loadFailed')} message={uiMessage(missing['your programs'])} onRetry={onRefresh} /></Card>) : null}@@ -399,10 +407,10 @@ export default function Dashboard() {<Card><View className="flex-row items-start justify-between"><View>- <Label>This Week</Label>+ <Label>{t('home.thisWeek.title')}</Label><View className="mt-1 flex-row items-end gap-1.5"><AppText variant="display" style={{ fontSize: 34, lineHeight: 38, fontVariant: ['tabular-nums'] }}>{weekWorkouts.length}</AppText>- <AppText variant="caption" color="muted" className="mb-2">{weekWorkouts.length === 1 ? 'session' : 'sessions'}</AppText>+ <AppText variant="caption" color="muted" className="mb-2">{t('home.thisWeek.unit', { count: weekWorkouts.length })}</AppText></View></View><View className="h-9 w-9 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10">@@ -416,7 +424,7 @@ export default function Dashboard() {const isFuture = day > nowreturn (<View key={i} className="items-center gap-1.5">- <AppText variant="label" color={isToday ? 'brand' : 'muted'} className="text-[10px]">{format(day, 'EEEEE')}</AppText>+ <AppText variant="label" color={isToday ? 'brand' : 'muted'} className="text-[10px]">{formatDate(day, 'weekdayNarrow')}</AppText><View className={`h-3.5 w-3.5 rounded-full ${hasWorkout ? 'bg-brand-500' : isToday ? 'border-2 border-brand-500/60' : isFuture ? 'bg-surface-border/20' : 'bg-surface-border/60'}`} />@@ -430,14 +438,14 @@ export default function Dashboard() {<Card><SectionHeadericon={TrendingUp}- title="Volume Trend"+ title={t('home.volume.title')}right={<View style={{ width: 132 }}><SegmentedControl size="sm" options={VOL_OPTIONS} value={volumePeriod} onChange={setVolumePeriod} /></View>}className="mb-3"/>{chartData.length === 0 ? (<View className="items-center justify-center gap-2 py-10"><Dumbbell size={26} color={colors.txMuted} style={{ opacity: 0.4 }} />- <AppText variant="caption" color="muted">Log workouts to see trends</AppText>+ <AppText variant="caption" color="muted">{t('home.volume.empty')}</AppText></View>) : (<View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>@@ -450,13 +458,13 @@ export default function Dashboard() {<Card><SectionHeadericon={Activity}- title="Consistency"- right={<AppText variant="caption" color="muted">12 weeks</AppText>}+ title={t('home.consistency.title')}+ right={<AppText variant="caption" color="muted">{t('home.consistency.range')}</AppText>}className="mb-3"/>{workouts.length === 0 ? (<View className="items-center justify-center gap-2 py-6">- <AppText variant="caption" color="muted">Start working out to build your streak</AppText>+ <AppText variant="caption" color="muted">{t('home.consistency.empty')}</AppText></View>) : (<>@@ -470,9 +478,9 @@ export default function Dashboard() {</View><View className="flex-row" style={{ gap: 2 }}><View style={{ width: 14, gap: 2 }}>- {(['M', '', 'W', '', 'F', '', 'S'] as const).map((lbl, di) => (+ {WEEKDAY_ROWS.map((di) => (<View key={di} className="h-3 justify-center">- <Text className="text-[9px] text-tx-muted/60">{lbl}</Text>+ <Text className="text-[9px] text-tx-muted/60">{di % 2 === 0 ? formatDate(heatmapWeeks[0][di], 'weekdayNarrow') : ''}</Text></View>))}</View>@@ -502,15 +510,15 @@ export default function Dashboard() {</View>{heatSel ? (<AppText variant="caption" color="muted" className="mt-1.5">- {format(heatSel.day, 'MMM d')}{heatSel.count > 0 ? ` · ${heatSel.count} workout${heatSel.count > 1 ? 's' : ''}` : ' · rest day'}+ {heatSel.count > 0 ? t('home.heatmap.workouts', { date: formatDate(heatSel.day, 'monthDay'), count: heatSel.count }) : t('home.heatmap.restDay', { date: formatDate(heatSel.day, 'monthDay') })}</AppText>) : null}<View className="mt-2 flex-row items-center justify-end gap-1.5">- <Text className="text-[9px] text-tx-muted">Less</Text>+ <Text className="text-[9px] text-tx-muted">{t('home.heatmap.less')}</Text>{[colors.border, isDark ? brand.cyanEdge : brand.cyan, isDark ? brand.cyanLight : brand.cyanEdge].map((c, i) => (<View key={i} style={{ width: 12, height: 12, borderRadius: 3, backgroundColor: c }} />))}- <Text className="text-[9px] text-tx-muted">More</Text>+ <Text className="text-[9px] text-tx-muted">{t('home.heatmap.more')}</Text></View></>)}@@ -527,16 +535,18 @@ export default function Dashboard() {<Card><View className="mb-3 flex-row items-start justify-between gap-2"><View className="min-w-0 flex-1">- <Label className="mb-1">Last workout</Label>+ <Label className="mb-1">{t('home.lastWorkout.title')}</Label><Text className="font-sans-semibold text-base text-tx-primary" numberOfLines={1}>{lastWorkout.name}</Text><AppText variant="caption" color="muted" className="mt-0.5">- {formatDay(workoutDay(lastWorkout), 'MMM d')}- {mins > 0 ? ` · ${mins} min` : ''}- {totalSets > 0 ? ` · ${totalSets} sets` : ''}- {totalVolume > 0 ? ` · ${totalVolume.toLocaleString()} ${wUnit}` : ''}+ {[+ formatDay(workoutDay(lastWorkout), 'monthDay'),+ mins > 0 && t('home.lastWorkout.minutes', { mins }),+ totalSets > 0 && t('home.lastWorkout.sets', { count: totalSets }),+ totalVolume > 0 && `${totalVolume.toLocaleString()} ${wUnit}`,+ ].filter(Boolean).join(' · ')}</AppText></View>- <LinkRow label="All" onPress={() => router.navigate('/workouts')} />+ <LinkRow label={t('home.lastWorkout.all')} onPress={() => router.navigate('/workouts')} /></View><View className="gap-2.5">{exs.slice(0, 4).map((ex, i) => {@@ -551,7 +561,7 @@ export default function Dashboard() {</View>{best ? (<Text className="text-xs text-tx-muted" style={{ fontVariant: ['tabular-nums'] }}>- {sets.length}×{best.weight > 0 ? ` ${displayWeight(best.weight, unit)}${wUnit}` : ' BW'}+ {sets.length}×{best.weight > 0 ? ` ${displayWeight(best.weight, unit)}${wUnit}` : ` ${t('weight.bodyweightShort')}`}</Text>) : null}</View>@@ -559,7 +569,7 @@ export default function Dashboard() {})}</View>{exs.length > 4 ? (- <AppText variant="caption" color="muted" className="pt-2 text-center">+{exs.length - 4} more exercises</AppText>+ <AppText variant="caption" color="muted" className="pt-2 text-center">{t('home.lastWorkout.moreExercises', { count: exs.length - 4 })}</AppText>) : null}</Card></Pressable>@@ -567,14 +577,14 @@ export default function Dashboard() {})() : (<Card className="items-center justify-center gap-2" style={{ minHeight: 148 }}><Dumbbell size={30} color={colors.txMuted} style={{ opacity: 0.4 }} />- <AppText variant="body" color="muted">No workouts logged yet</AppText>+ <AppText variant="body" color="muted">{t('home.lastWorkout.empty')}</AppText>{/* Suppressed when the Up Next card is already showing above — thatcard is its own "start something" CTA, and stacking a second"start your first workout" link right under it is the exactredundant-buttons clutter this card exists to avoid. */}{!upNext ? (<Pressable onPress={() => { hSelect(); router.navigate('/workouts/start') }} hitSlop={6} className="active:opacity-60">- <AppText variant="caption" color="brand">Start your first workout →</AppText>+ <AppText variant="caption" color="brand">{t('home.lastWorkout.startFirst')}</AppText></Pressable>) : null}</Card>@@ -584,19 +594,19 @@ export default function Dashboard() {<Card><SectionHeadericon={Dumbbell}- title="Muscle Balance"- right={<AppText variant="caption" color="muted">{workouts.length} workouts</AppText>}+ title={t('home.muscle.title')}+ right={<AppText variant="caption" color="muted">{t('home.muscle.workouts', { count: workouts.length })}</AppText>}className="mb-1"/>{topMuscle ? (<AppText variant="caption" color="muted" className="mb-3 italic">{muscleRoast(topMuscle)}</AppText>) : (- <AppText variant="caption" color="muted" className="mb-3">Log workouts to see which muscles you train most.</AppText>+ <AppText variant="caption" color="muted" className="mb-3">{t('home.muscle.empty')}</AppText>)}{muscleData.length === 0 ? (<View className="items-center justify-center gap-2 py-6"><Dumbbell size={26} color={colors.txMuted} style={{ opacity: 0.3 }} />- <AppText variant="caption" color="muted">No workout data yet</AppText>+ <AppText variant="caption" color="muted">{t('home.muscle.noData')}</AppText></View>) : (<View className="items-center gap-4">@@ -612,7 +622,7 @@ export default function Dashboard() {<View className="mb-0.5 flex-row items-center gap-2"><View className="h-2 w-2 rounded-full" style={{ backgroundColor: color }} /><Text className={`flex-1 text-xs capitalize ${isTop ? 'font-sans-semibold text-tx-primary' : 'text-tx-secondary'}`} numberOfLines={1}>- {d.name}{isTop ? <Text className="text-[9px] uppercase text-tx-muted"> top</Text> : null}+ {muscleLabel(d.name)}{isTop ? <Text className="text-[9px] uppercase text-tx-muted">{` ${t('home.muscle.top')}`}</Text> : null}</Text><MuscleSparkline values={values} color={color} isTop={isTop} /><Text className="w-16 text-right text-xs text-tx-muted" style={{ fontVariant: ['tabular-nums'] }}>{d.value} · {pct}%</Text>@@ -629,9 +639,9 @@ export default function Dashboard() {{/* ── Today's Nutrition (also covers the Cals/Protein once in the KPI strip) ── */}<Card>{/* Web links "Log →" to /food; hidden on mobile until a Food page exists. */}- <AppText variant="subheading" className="mb-3">Today's Nutrition</AppText>+ <AppText variant="subheading" className="mb-3">{t('home.nutrition.title')}</AppText>{foodMissing ? (- <ErrorState title="Couldn't load today's food" message={missing["today's food"]} onRetry={onRefresh} />+ <ErrorState title={t('home.nutrition.loadFailed')} message={uiMessage(missing["today's food"])} onRetry={onRefresh} />) : (<><View className="mb-3 flex-row items-baseline gap-1.5">@@ -643,11 +653,11 @@ export default function Dashboard() {<ProgressBar pct={calPct} color="#00b8d9" className="mb-4" /><View className="gap-3">{[- { label: 'Protein', val: food.total_protein, target: settings.protein_target, pct: protPct, color: '#3b82f6' },- { label: 'Carbs', val: food.total_carbs, target: settings.carb_target, pct: carbsPct, color: '#f59e0b' },- { label: 'Fat', val: food.total_fat, target: settings.fat_target, pct: fatPct, color: '#8b5cf6' },+ { id: 'protein', label: t('home.macro.protein'), val: food.total_protein, target: settings.protein_target, pct: protPct, color: '#3b82f6' },+ { id: 'carbs', label: t('home.macro.carbs'), val: food.total_carbs, target: settings.carb_target, pct: carbsPct, color: '#f59e0b' },+ { id: 'fat', label: t('home.macro.fat'), val: food.total_fat, target: settings.fat_target, pct: fatPct, color: '#8b5cf6' },].map((m) => (- <View key={m.label}>+ <View key={m.id}><View className="mb-1 flex-row items-center justify-between"><AppText variant="caption" color="muted">{m.label}</AppText><Text className="text-xs font-sans-semibold text-tx-primary" style={{ fontVariant: ['tabular-nums'] }}>@@ -666,13 +676,13 @@ export default function Dashboard() {<Card><SectionHeadericon={Scale}- title="Weight"- right={<LinkRow label="View" onPress={() => router.navigate('/weight')} />}+ title={t('home.weight.title')}+ right={<LinkRow label={t('home.weight.view')} onPress={() => router.navigate('/weight')} />}className="mb-2"/>{weightLogs.length === 0 && weightMissing ? (// Not the "log your first weight" prompt: this reader may have years of them.- <ErrorState title="Couldn't load your weight" message={missing['your weight']} onRetry={onRefresh} />+ <ErrorState title={t('home.weight.loadFailed')} message={uiMessage(missing['your weight'])} onRetry={onRefresh} />) : weightLogs.length === 0 ? (<PressableonPress={() => { hSelect(); setSheetOpen(true) }}@@ -682,12 +692,12 @@ export default function Dashboard() {<Plus size={18} color={accent} /></View><View>- <Text className="text-sm font-sans-semibold text-tx-primary">Log your first weight</Text>- <AppText variant="caption" color="muted">Tap to start tracking</AppText>+ <Text className="text-sm font-sans-semibold text-tx-primary">{t('home.weight.logFirst')}</Text>+ <AppText variant="caption" color="muted">{t('home.weight.logFirstHint')}</AppText></View></Pressable>) : (- <Pressable onPress={() => { hSelect(); setSheetOpen(true) }} className="active:scale-[0.99]" accessibilityLabel="Log weight">+ <Pressable onPress={() => { hSelect(); setSheetOpen(true) }} className="active:scale-[0.99]" accessibilityLabel={t('home.weight.logAria')}><View className="mb-2 flex-row items-center justify-between"><View className="flex-row items-baseline gap-1.5"><AppText variant="display" style={{ fontSize: 30, lineHeight: 34, fontVariant: ['tabular-nums'] }}>{displayWeight(weightLogs[0].weight, unit)}</AppText>@@ -699,10 +709,10 @@ export default function Dashboard() {// never got — and a null or absent delta is no stats at all, not 0.const delta = weightStats?.change_7dif (typeof delta !== 'number' || !Number.isFinite(delta)) return null- if (delta === 0) return <AppText variant="caption" color="muted">7d · no change</AppText>+ if (delta === 0) return <AppText variant="caption" color="muted">{t('home.weight.noChange7d')}</AppText>return (<Text className="text-xs" style={{ color: delta < 0 ? brand.successSoft : brand.errorSoft, fontVariant: ['tabular-nums'] }}>- 7d · {delta < 0 ? '↓' : '↑'}{Math.abs(displayWeight(delta, unit))} {wUnit}+ {t(delta < 0 ? 'home.weight.trendDown' : 'home.weight.trendUp', { amount: Math.abs(displayWeight(delta, unit)), unit: wUnit })}</Text>)})()}diff --git a/mobile/app/(tabs)/nutrition/[id].tsx b/mobile/app/(tabs)/nutrition/[id].tsxindex 00934fa..1309828 100644--- a/mobile/app/(tabs)/nutrition/[id].tsx+++ b/mobile/app/(tabs)/nutrition/[id].tsx@@ -3,12 +3,12 @@ import { Image, Pressable, ScrollView, View } from 'react-native'import { router, useLocalSearchParams } from 'expo-router'import * as Haptics from 'expo-haptics'import { AlertCircle, ArrowLeft, Edit2, Flame, Trash2 } from 'lucide-react-native'-import { apiErrorMessage, entryToResult, formatLoggedAmount, isNotFound, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay } from '@lyftr/shared'+import { entryToResult, formatLoggedAmount, isNotFound, uiMessage, useAsyncAction, useFavorites, entryDay, type FoodLog, formatDay, useTranslation, type UiMessage } from '@lyftr/shared'import {AppText, Button, Card, ConfirmSheet, ErrorState, Loading, Screen, Toast, deleteConfirmProps,} from '../../../src/components/ui'import {- MACRO_COLORS, MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,+ MACRO_COLORS, MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, mealLabel, type Meal,} from '../../../src/components/nutrition/nutritionMeta'import { FavoriteStar } from '../../../src/components/nutrition/FoodResultRow'import { client } from '../../../src/lib/lyftr'@@ -19,12 +19,13 @@ import { useTheme } from '../../../src/theme/useTheme'// the shared log flow in edit mode; Delete routes through the ConfirmSheet. The dashboard// refetches on focus, so a delete/edit here is reflected when we pop back.export default function NutritionDetail() {+ const { t } = useTranslation()const { id } = useLocalSearchParams<{ id: string }>()const { colors, accent } = useTheme()const [entry, setEntry] = useState<FoodLog | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<UiMessage | null>(null)const [gone, setGone] = useState(false)const [retryKey, setRetryKey] = useState(0)const [confirming, setConfirming] = useState(false)@@ -41,7 +42,7 @@ export default function NutritionDetail() {.then(setEntry).catch((err) => {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })}).finally(() => setLoading(false))}, [id, retryKey])@@ -58,7 +59,7 @@ export default function NutritionDetail() {if (!entry) returnawait client.foodAPI.delete(entry.id)goBack() // the dashboard refetches on focus- }, 'Failed to delete entry')+ }, t('food.entry.deleteFailed'))if (loading) return <Loading />@@ -68,10 +69,10 @@ export default function NutritionDetail() {<View className="flex-1 py-4"><ErrorStatesize="page"- title="Couldn't load this entry"- message={error ?? 'That entry no longer exists.'}+ title={t('food.entry.loadFailed')}+ message={error ? uiMessage(error) : t('food.entry.gone')}onRetry={error && !gone ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}- secondary={<Button title="Back to nutrition" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('food.entry.backToNutrition')} variant="secondary" onPress={goBack} />}/></View></Screen>@@ -92,10 +93,10 @@ export default function NutritionDetail() {const MealIcon = MEAL_ICONS[meal]const mealColor = MEAL_COLORS[meal]const macros = [- { label: 'Protein', value: entry.protein, color: MACRO_TEXT.protein, bar: MACRO_COLORS.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },- { label: 'Carbs', value: entry.carbs, color: MACRO_TEXT.carbs, bar: MACRO_COLORS.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },- { label: 'Fat', value: entry.fat, color: MACRO_TEXT.fat, bar: MACRO_COLORS.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },- { label: 'Fiber', value: entry.fiber ?? 0, color: colors.txSecondary, bar: colors.txMuted, bg: colors.muted, border: colors.border },+ { label: t('food.macro.protein'), value: entry.protein, color: MACRO_TEXT.protein, bar: MACRO_COLORS.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },+ { label: t('food.macro.carbs'), value: entry.carbs, color: MACRO_TEXT.carbs, bar: MACRO_COLORS.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },+ { label: t('food.macro.fat'), value: entry.fat, color: MACRO_TEXT.fat, bar: MACRO_COLORS.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },+ { label: t('food.macro.fiber'), value: entry.fiber ?? 0, color: colors.txSecondary, bar: colors.txMuted, bg: colors.muted, border: colors.border },]// Calorie contribution per macro (4/4/9 kcal per g) → the composition bar + % split.@@ -105,11 +106,11 @@ export default function NutritionDetail() {// Spec-list rows (MFP / Lose It convention): serving size, amount, meal, logged.const specRows: { label: string; value: string; tabular?: boolean }[] = [- ...(entry.serving_size ? [{ label: 'Serving size', value: entry.serving_size }] : []),+ ...(entry.serving_size ? [{ label: t('food.entry.servingSize'), value: entry.serving_size }] : []),// In the unit it was logged in — "15 ml", not "0.15 servings" (#171).- { label: 'Amount', value: formatLoggedAmount(entry), tabular: true },- { label: 'Meal', value: MEAL_LABELS[meal] },- { label: 'Logged', value: formatDay(entryDay(entry), 'EEE, MMM d, yyyy') },+ { label: t('food.entry.amount'), value: formatLoggedAmount(entry), tabular: true },+ { label: t('food.entry.meal'), value: mealLabel(meal) },+ { label: t('food.entry.logged'), value: formatDay(entryDay(entry), 'weekdayMonthDayYear') },]return (@@ -120,7 +121,7 @@ export default function NutritionDetail() {<View className="flex-row items-center justify-between"><Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-1.5 active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Nutrition</AppText>+ <AppText variant="body" color="muted">{t('food.entry.back')}</AppText></Pressable><View className="flex-row items-center gap-2">{favoritesLoaded ? (@@ -134,17 +135,17 @@ export default function NutritionDetail() {) : null}<PressableaccessibilityRole="button"- accessibilityLabel="Edit entry"+ accessibilityLabel={t('food.entry.editLabel')}onPress={() => router.push(`/nutrition/log?edit=${entry.id}`)}hitSlop={6}className="h-9 flex-row items-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 px-3 active:scale-95"><Edit2 size={15} color={accent} strokeWidth={2.2} />- <AppText variant="label" style={{ color: accent }}>Edit</AppText>+ <AppText variant="label" style={{ color: accent }}>{t('common.edit')}</AppText></Pressable><PressableaccessibilityRole="button"- accessibilityLabel="Delete entry"+ accessibilityLabel={t('food.entry.deleteLabel')}onPress={() => setConfirming(true)}disabled={remove.busy}hitSlop={6}@@ -164,7 +165,7 @@ export default function NutritionDetail() {{/* Meal chip */}<View className="flex-row items-center gap-1.5 self-start rounded-full border px-2.5 py-1" style={{ backgroundColor: `${mealColor}1A`, borderColor: `${mealColor}40` }}><MealIcon size={13} color={mealColor} />- <AppText variant="caption" style={{ color: mealColor, fontWeight: '700' }}>{MEAL_LABELS[meal]}</AppText>+ <AppText variant="caption" style={{ color: mealColor, fontWeight: '700' }}>{mealLabel(meal)}</AppText></View>{/* Name + calorie hero */}@@ -184,7 +185,7 @@ export default function NutritionDetail() {<View style={{ width: `${pctCal(cals.fat)}%`, backgroundColor: MACRO_COLORS.fat }} /></View><View className="mt-2.5 flex-row justify-between">- {([['Protein', cals.protein, MACRO_COLORS.protein], ['Carbs', cals.carbs, MACRO_COLORS.carbs], ['Fat', cals.fat, MACRO_COLORS.fat]] as const).map(([label, v, color]) => (+ {([[t('food.macro.protein'), cals.protein, MACRO_COLORS.protein], [t('food.macro.carbs'), cals.carbs, MACRO_COLORS.carbs], [t('food.macro.fat'), cals.fat, MACRO_COLORS.fat]] as const).map(([label, v, color]) => (<View key={label} className="flex-row items-center gap-1.5"><View style={{ width: 8, height: 8, borderRadius: 2, backgroundColor: color }} /><AppText variant="caption" color="muted">{label}</AppText>@@ -220,7 +221,7 @@ export default function NutritionDetail() {</ScrollView><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete entry?', subject: `"${entry.name}"` })}+ {...deleteConfirmProps({ title: t('food.entry.deleteTitle'), subject: `"${entry.name}"` })}open={confirming}busy={remove.busy}error={remove.error}diff --git a/mobile/app/(tabs)/nutrition/index.tsx b/mobile/app/(tabs)/nutrition/index.tsxindex 67bfb1e..68cce05 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 {CalendarDays, CheckCircle2, ChevronLeft, ChevronRight, Flame, Plus, Utensils,} from 'lucide-react-native'-import { apiErrorMessage, isDailyStats, todayStr, type DailyStats, type FoodLog, dayToLocalDate} from '@lyftr/shared'+import { isDailyStats, todayStr, type DailyStats, type FoodLog, dayToLocalDate, formatDate, relativeDayLabel, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import {AppText, Card, DateInput, ErrorState, IconButton, Label, PageHeader, Screen, SearchField, SectionHeader, SegmentedControl, Skeleton, SkeletonList, StatFailure, Toast,} from '../../../src/components/ui'@@ -30,11 +30,8 @@ const FOOD_PAGE = 12// Top-level split: "Diary" is the per-day summary + food log; "Trends" is the multi-day// macro history. Keeps the per-day view a food-log-first surface (summary → list) while// the analytical chart lives one tap away instead of pushing the list down the page.-const VIEW_OPTIONS = [- { value: 'diary', label: 'Diary' },- { value: 'trends', label: 'Trends' },-] as const-type NutritionView = typeof VIEW_OPTIONS[number]['value']+const VIEW_VALUES = ['diary', 'trends'] as const+type NutritionView = typeof VIEW_VALUES[number]// Port of web/pages/Food.tsx — the daily Nutrition dashboard, mobile-polished: date// navigator + haptics, calorie hero + macro rings, four meal cards with entries whose@@ -51,23 +48,24 @@ const mealForNow = (): Meal => {}export default function Nutrition() {+ const { t } = useTranslation()const { colors, brand, accent } = useTheme()const { width: windowWidth } = useWindowDimensions()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)// One-shot courier from the log flow: ?logged=<meal label> | 'Updated' → success toast.const params = useLocalSearchParams<{ logged?: string }>()- const [toast, setToast] = useState<string | null>(null)+ const [toast, setToast] = useState<UiMessage | null>(null)const [selectedDate, setSelectedDate] = useState(todayStr())const [logs, setLogs] = useState<FoodLog[]>([])const [stats, setStats] = useState<DailyStats | null>(null)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<UiMessage | null>(null)// The totals and the history are caught so either can fail without blanking the diary.// Caught is not the same as silent: each keeps what the server said, and the card it// belongs to says so instead of rendering 0 kcal.- const [statsError, setStatsError] = useState<string | null>(null)- const [historyError, setHistoryError] = useState<string | null>(null)+ const [statsError, setStatsError] = useState<UiMessage | null>(null)+ const [historyError, setHistoryError] = useState<UiMessage | null>(null)const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('30d')const [historyData, setHistoryData] = useState<MacroHistoryPoint[]>([])@@ -108,7 +106,7 @@ export default function Nutrition() {const defaultStats: DailyStats = {date, total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0, total_fiber: 0, workout_count: 0,}- let statsMessage: string | null = null+ let statsMessage: UiMessage | null = nullconst [logData, statsData] = await Promise.all([// Same rule as the totals beside it: a reply we cannot read is a failure, not a// day with no food in it.@@ -121,7 +119,7 @@ export default function Nutrition() {// rendered as 0 kcal, which is what "hasn't eaten yet" looks like..then((st) => (isDailyStats(st) ? st : Promise.reject(new Error('unreadable')))).catch((err) => {- statsMessage = apiErrorMessage(err, "The server didn't say what went wrong.")+ statsMessage = { key: 'settings.unknownError', cause: err }return defaultStats}),])@@ -132,7 +130,7 @@ export default function Nutrition() {setLoadedDate(date)} catch (err: any) {if (id !== dayRequest.current) return- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })} finally {if (id === dayRequest.current) hasLoadedRef.current = true}@@ -156,7 +154,7 @@ export default function Nutrition() {setHistoryDataPeriod(historyPeriod)setHistoryError(null)})- .catch((err) => { if (id === historyRequest.current) setHistoryError(apiErrorMessage(err, "The server didn't say what went wrong.")) })+ .catch((err) => { if (id === historyRequest.current) setHistoryError({ key: 'settings.unknownError', cause: err }) }).finally(() => { if (id === historyRequest.current) setHistoryLoading(false) })}, [historyPeriod])useEffect(() => { loadHistory() }, [loadHistory])@@ -182,7 +180,7 @@ export default function Nutrition() {// Show the arrival toast once, then strip the param so it doesn't re-fire on re-render.useEffect(() => {if (params.logged) {- setToast(params.logged === 'Updated' ? 'Entry updated' : `Added to ${params.logged}`)+ setToast(params.logged === 'Updated' ? { key: 'food.diary.entryUpdated' } : { key: 'food.diary.addedTo', params: { meal: params.logged } })router.setParams({ logged: undefined })}}, [params.logged])@@ -207,14 +205,14 @@ export default function Nutrition() {}).catch((err) => {if (day !== selectedDateRef.current) return- setStatsError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setStatsError({ key: 'settings.unknownError', cause: err })})}, [selectedDate])if (!hasLoadedRef.current) return <NutritionSkeleton />const toastView = toast ? (- <Toast variant="success" icon={CheckCircle2} title={toast} onDismiss={() => setToast(null)} />+ <Toast variant="success" icon={CheckCircle2} title={uiMessage(toast)} onDismiss={() => setToast(null)} />) : null// Rings at 0 kcal and four empty meal sections say "you have eaten nothing today",@@ -225,11 +223,11 @@ export default function Nutrition() {return (<Screen><View className="flex-1 gap-4 pt-4">- <PageHeader title="Nutrition" subtitle="Macros & meals" />+ <PageHeader title={t('food.page.title')} subtitle={t('food.page.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your food log"- message={error}+ title={t('food.diary.loadFailed')}+ message={uiMessage(error)}onRetry={() => { void loadDay(selectedDate) }}/></View>@@ -264,6 +262,7 @@ export default function Nutrition() {const avgMacro = (key: 'protein' | 'carbs' | 'fat') =>histDays ? String(Math.round(historyPoints.reduce((s, d) => s + (d[key] || 0), 0) / histDays)) : '—'const isDiary = view === 'diary'+ const viewOptions = VIEW_VALUES.map((v) => ({ value: v, label: t(`food.view.${v}`) }))// Chart width: prefer the measured value, but seed a computed fallback (window − Screen// px-5 − Card p-4 = 72) so the chart renders immediately on first switch to Trends// instead of waiting for an onLayout that doesn't reliably fire on the view-swap.@@ -274,11 +273,7 @@ export default function Nutrition() {const prevDate = format(subDays(selectedDateObj, 1), 'yyyy-MM-dd')const nextDate = format(addDays(selectedDateObj, 1), 'yyyy-MM-dd')const canGoNext = selectedDate < todayStr()- const dayLabel = isToday- ? 'Today'- : selectedDate === format(subDays(new Date(), 1), 'yyyy-MM-dd')- ? 'Yesterday'- : format(selectedDateObj, 'EEE, MMM d')+ const dayLabel = relativeDayLabel(selectedDate)// The whole screen is a single FlatList so the food rows virtualize (only on-screen// rows mount, and their thumbnails load lazily) instead of every entry — plus its@@ -322,20 +317,20 @@ export default function Nutrition() {<View className="pt-4"><View className="gap-4"><PageHeader- title="Nutrition"- subtitle="Macros & meals"- action={<IconButton icon={Plus} variant="solid" size="md" label="Log Food" onPress={() => openLog(mealForNow())} />}+ title={t('food.page.title')}+ subtitle={t('food.page.subtitle')}+ action={<IconButton icon={Plus} variant="solid" size="md" label={t('food.diary.logFood')} onPress={() => openLog(mealForNow())} />}/>{/* Diary (per-day log) vs Trends (multi-day chart) */}- <SegmentedControl options={VIEW_OPTIONS} value={view} onChange={setView} />+ <SegmentedControl options={viewOptions} value={view} onChange={setView} />{isDiary ? (<>{/* Date navigator */}<View className="flex-row items-center gap-2"><Pressable- accessibilityLabel="Previous day"+ accessibilityLabel={t('food.diary.previousDay')}onPress={() => goDay(prevDate)}className="items-center justify-center rounded-xl p-3 active:scale-95">@@ -344,13 +339,13 @@ export default function Nutrition() {<View className="flex-1"><DateNavCenterdayLabel={dayLabel}- yearLabel={!isToday ? format(selectedDateObj, 'yyyy') : undefined}+ yearLabel={!isToday ? formatDate(selectedDateObj, 'year') : undefined}value={selectedDate}onChange={goDay}/></View><Pressable- accessibilityLabel="Next day"+ accessibilityLabel={t('food.diary.nextDay')}disabled={!canGoNext}onPress={() => goDay(nextDate)}className={`items-center justify-center rounded-xl p-3 active:scale-95 ${canGoNext ? '' : 'opacity-30'}`}@@ -374,14 +369,14 @@ export default function Nutrition() {</Card>) : statsError ? (<Card>- <ErrorState title="Couldn't load today's totals" message={statsError} onRetry={() => { void loadDay(selectedDate) }} />+ <ErrorState title={t('food.diary.totalsFailed')} message={uiMessage(statsError)} onRetry={() => { void loadDay(selectedDate) }} /></Card>) : (<Card className="gap-5">{/* Calorie hero */}<View className="flex-row items-center justify-between"><View>- <AppText variant="caption" color="muted" className="mb-1 uppercase" style={{ letterSpacing: 0.5 }}>Calories</AppText>+ <AppText variant="caption" color="muted" className="mb-1 uppercase" style={{ letterSpacing: 0.5 }}>{t('food.diary.calories')}</AppText><View className="flex-row items-baseline gap-1.5"><AppText variant="display" style={{ fontSize: 34, lineHeight: 38, fontVariant: ['tabular-nums'] }}>{Math.round(totalCals)}</AppText><AppText variant="body" color="muted">/ {calTarget}</AppText>@@ -396,7 +391,7 @@ export default function Nutrition() {><Flame size={16} color={isOver ? '#fbbf24' : '#34d399'} /><AppText variant="bodySemibold" style={{ fontSize: 13, color: isOver ? '#fbbf24' : '#34d399' }}>- {isOver ? `${Math.round(Math.abs(remaining))} over` : `${Math.round(remaining)} left`}+ {isOver ? t('food.diary.over', { amount: Math.round(Math.abs(remaining)) }) : t('food.diary.left', { amount: Math.round(remaining) })}</AppText></View></View>@@ -409,7 +404,7 @@ export default function Nutrition() {</View><View className="flex-row justify-between"><AppText variant="caption" color="muted" style={{ fontSize: 10 }}>0</AppText>- <AppText variant="caption" color="muted" style={{ fontSize: 10 }}>{calTarget} kcal goal</AppText>+ <AppText variant="caption" color="muted" style={{ fontSize: 10 }}>{t('food.diary.goal', { amount: calTarget })}</AppText></View></View>@@ -419,13 +414,13 @@ export default function Nutrition() {uneven.) */}<View className="flex-row"><View className="flex-1 items-center">- <MacroRing value={stats?.total_protein ?? 0} target={settings.protein_target} color={MACRO_COLORS.protein} label="Protein" />+ <MacroRing value={stats?.total_protein ?? 0} target={settings.protein_target} color={MACRO_COLORS.protein} label={t('food.macro.protein')} /></View><View className="flex-1 items-center">- <MacroRing value={stats?.total_carbs ?? 0} target={settings.carb_target} color={MACRO_COLORS.carbs} label="Carbs" />+ <MacroRing value={stats?.total_carbs ?? 0} target={settings.carb_target} color={MACRO_COLORS.carbs} label={t('food.macro.carbs')} /></View><View className="flex-1 items-center">- <MacroRing value={stats?.total_fat ?? 0} target={settings.fat_target} color={MACRO_COLORS.fat} label="Fat" />+ <MacroRing value={stats?.total_fat ?? 0} target={settings.fat_target} color={MACRO_COLORS.fat} label={t('food.macro.fat')} /></View></View></Card>@@ -435,12 +430,12 @@ export default function Nutrition() {<>{/* Daily-average macros over the selected history window */}<View className="gap-2">- <Label className="px-1">Daily average · {historyPeriod}</Label>+ <Label className="px-1">{t('food.trends.dailyAverage', { period: historyPeriod })}</Label><View className="flex-row gap-3">{([- ['Protein', 'protein', MACRO_COLORS.protein],- ['Carbs', 'carbs', MACRO_COLORS.carbs],- ['Fat', 'fat', MACRO_COLORS.fat],+ [t('food.macro.protein'), 'protein', MACRO_COLORS.protein],+ [t('food.macro.carbs'), 'carbs', MACRO_COLORS.carbs],+ [t('food.macro.fat'), 'fat', MACRO_COLORS.fat],] as const).map(([label, key, color]) => (<Card key={key} className="flex-1" style={{ paddingHorizontal: 12 }}><View className="mb-2 flex-row items-center gap-1.5">@@ -448,7 +443,7 @@ export default function Nutrition() {<Label numberOfLines={1}>{label}</Label></View>{histDays === 0 && historyError ? (- <StatFailure label={`Couldn't load average ${label.toLowerCase()}`} />+ <StatFailure label={t('food.trends.averageFailed', { macro: label.toLowerCase() })} />) : (<View className="flex-row items-end gap-1"><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{avgMacro(key)}</AppText>@@ -463,21 +458,21 @@ export default function Nutrition() {{/* Macro history */}<Card><SectionHeader- title="Macro History"+ title={t('food.history.title')}right={<View style={{ width: 150 }}><SegmentedControl size="sm" options={HISTORY_OPTIONS} value={historyPeriod} onChange={setHistoryPeriod} /></View>}className="mb-4"/><View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>{historyLoading ? (<View className="h-48 items-center justify-center">- <AppText variant="caption" color="muted">Loading…</AppText>+ <AppText variant="caption" color="muted">{t('food.history.loading')}</AppText></View>) : historyPoints.length === 0 && historyError ? (- <ErrorState title="Couldn't load your history" message={historyError} onRetry={() => { void loadHistory() }} />+ <ErrorState title={t('food.history.loadFailed')} message={uiMessage(historyError)} onRetry={() => { void loadHistory() }} />) : historyPoints.length === 0 ? (<View className="h-48 items-center justify-center gap-2"><CalendarDays size={32} color={colors.txMuted} style={{ opacity: 0.4 }} />- <AppText variant="caption" color="muted">No data yet — start logging meals</AppText>+ <AppText variant="caption" color="muted">{t('food.history.empty')}</AppText></View>) : (<MacroHistoryChart data={historyPoints} width={chartW} height={220} />@@ -486,9 +481,9 @@ export default function Nutrition() {{/* Legend */}<View className="mt-4 flex-row justify-center gap-4">{[- { color: MACRO_COLORS.protein, label: 'Protein' },- { color: MACRO_COLORS.carbs, label: 'Carbs' },- { color: MACRO_COLORS.fat, label: 'Fat' },+ { color: MACRO_COLORS.protein, label: t('food.macro.protein') },+ { color: MACRO_COLORS.carbs, label: t('food.macro.carbs') },+ { color: MACRO_COLORS.fat, label: t('food.macro.fat') },].map((m) => (<View key={m.label} className="flex-row items-center gap-1.5"><View style={{ width: 10, height: 10, borderRadius: 2, backgroundColor: m.color }} />@@ -506,15 +501,15 @@ export default function Nutrition() {{isDiary ? (<View className="mt-8 gap-3 pb-3"><View className="flex-row items-center justify-between px-1">- <Label>{isToday ? "Today's Food" : 'Food'}</Label>+ <Label>{isToday ? t('food.diary.titleToday') : t('food.diary.title')}</Label>{dayEntries.length > 0 && !dayPending ? (<AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>- {q ? `${filteredEntries.length} of ${dayEntries.length}` : `${dayEntries.length} ${dayEntries.length === 1 ? 'item' : 'items'}`}+ {q ? t('food.diary.filteredCount', { shown: filteredEntries.length, total: dayEntries.length }) : t('food.diary.items', { count: dayEntries.length })}</AppText>) : null}</View>{dayEntries.length > 0 && !dayPending ? (- <SearchField value={foodQuery} onChangeText={setFoodQuery} placeholder="Search this day's food…" />+ <SearchField value={foodQuery} onChangeText={setFoodQuery} placeholder={t('food.diary.searchPlaceholder')} />) : null}</View>) : null}@@ -526,14 +521,14 @@ export default function Nutrition() {) : q ? (<View className="items-center px-4 py-8"><Utensils size={28} color={colors.txMuted} style={{ opacity: 0.4 }} />- <AppText variant="body" color="muted" className="mt-2">No matches for “{foodQuery.trim()}”</AppText>+ <AppText variant="body" color="muted" className="mt-2">{t('food.diary.noMatches', { query: foodQuery.trim() })}</AppText></View>) : (<Card className="overflow-hidden p-0"><Pressable onPress={() => openLog(mealForNow())} className="items-center px-4 py-10 active:opacity-70"><Utensils size={32} color={colors.txMuted} style={{ opacity: 0.4 }} />- <AppText variant="body" color="muted" className="mt-2">No food logged yet</AppText>- <AppText variant="caption" color="muted" className="mt-1">Tap to log your first meal</AppText>+ <AppText variant="body" color="muted" className="mt-2">{t('food.diary.empty.title')}</AppText>+ <AppText variant="caption" color="muted" className="mt-1">{t('food.diary.empty.hint')}</AppText></Pressable></Card>)diff --git a/mobile/app/(tabs)/nutrition/log.tsx b/mobile/app/(tabs)/nutrition/log.tsxindex 8f76106..b72885b 100644--- a/mobile/app/(tabs)/nutrition/log.tsx+++ b/mobile/app/(tabs)/nutrition/log.tsx@@ -6,8 +6,8 @@ import {AlertCircle, ArrowLeft, ChevronRight, Minus, Plus, Scan, Star, Utensils, Zap,} from 'lucide-react-native'import {- useAsyncAction, dayToInstant, entryDay, todayStr,- type FoodSearchResult,+ useAsyncAction, useTranslation, uiMessage, dayToInstant, entryDay, todayStr,+ type FoodSearchResult, type UiMessage,} from '@lyftr/shared'import {Alert, AppText, Button, Card, DateInput, ErrorState, IconButton, Label, NumberField, Toast,@@ -18,25 +18,20 @@ import { BarcodeLookup } from '../../../src/components/nutrition/BarcodeLookup'import { FoodHero } from '../../../src/components/nutrition/FoodImage'import { FavoriteStar, FoodResultRow } from '../../../src/components/nutrition/FoodResultRow'import {- MACRO_COLORS, MACRO_TEXT, MEALS, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal,+ MACRO_COLORS, MACRO_TEXT, MEALS, MEAL_COLORS, MEAL_ICONS, mealLabel, type Meal,} from '../../../src/components/nutrition/nutritionMeta'import { client } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'-import { apiErrorMessage, entryToResult, foodResultKey, isNotFound, savedToResult, scaleServing, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'+import { entryToResult, foodResultKey, isNotFound, savedToResult, scaleServing, storedServingSize, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'type Phase = 'search' | 'detail' | 'scan'type SearchTab = 'recent' | 'myfoods' | 'all'const hSelect = () => Haptics.selectionAsync().catch(() => {})-const TAB_OPTIONS = [- { value: 'recent', label: 'Recent' },- { value: 'myfoods', label: 'Favorites' },- { value: 'all', label: 'Search' },-] as const-// Port of web/pages/LogFood.tsx — the search / detail / scan food-logging flow.export default function LogFood() {+ const { t } = useTranslation()const { colors, brand, accent, isDark } = useTheme()const params = useLocalSearchParams<{ meal?: string; date?: string; edit?: string }>()const editId = params.edit ? Number(params.edit) : null@@ -53,13 +48,13 @@ export default function LogFood() {// Bumped by every star/unstar; a list load drops its result if a toggle landed meanwhile.const listEpoch = favorites.epochconst [searching, setSearching] = useState(false)- const [searchError, setSearchError] = useState<string | null>(null)+ const [searchError, setSearchError] = useState<UiMessage | null>(null)const [rateLimited, setRateLimited] = useState(false)// A barcode lookup goes through Open Food Facts and routinely takes seconds (the// server allows it 5). The scanner closes the moment it reads a code, so without// this the screen sat unchanged and people rescanned, thinking it had failed (#164).// null: no lookup. error null: in flight. error set: failed, in the server's words.- const [lookup, setLookup] = useState<{ code: string; error: string | null } | null>(null)+ const [lookup, setLookup] = useState<{ code: string; error: UiMessage | null } | null>(null)const lookingUp = lookup !== null && lookup.error === nullconst [selected, setSelected] = useState<FoodSearchResult | null>(null)@@ -71,7 +66,7 @@ export default function LogFood() {// search index answers with per-100g figures and no serving at all, so a hit has to// be read again through the product endpoint before it can be trusted (#171).const [upgrading, setUpgrading] = useState<string | null>(null)- const [staleServing, setStaleServing] = useState<string | null>(null)+ const [staleServing, setStaleServing] = useState<UiMessage | null>(null)const [meal, setMeal] = useState<Meal>(initMeal)const [date, setDate] = useState(initDate)const [pulling, setPulling] = useState(false)@@ -84,7 +79,7 @@ export default function LogFood() {else if (done === 'removed') Haptics.selectionAsync().catch(() => {})}- const [editError, setEditError] = useState<string | null>(null)+ const [editError, setEditError] = useState<UiMessage | null>(null)const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)@@ -98,7 +93,7 @@ export default function LogFood() {setMeal(entry.meal)setDate(entryDay(entry))setPhase('detail')- }).catch((err) => setEditError(apiErrorMessage(err, "Couldn't load that entry.")))+ }).catch((err) => setEditError({ key: 'food.log.editLoadFailed', cause: err }))}, [editId, openOnEntry])// Recent (today, deduped ≤10) + favourites.@@ -149,7 +144,7 @@ export default function LogFood() {setSearchResults((await client.foodAPI.search(query.trim())) ?? [])} catch (err: any) {if (err?.response?.status === 429) setRateLimited(true)- else setSearchError('Food search unavailable — enter details manually')+ else setSearchError({ key: 'food.log.searchUnavailable' })setSearchResults([])} finally {setSearching(false)@@ -158,7 +153,7 @@ export default function LogFood() {return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }}, [query, tab])- const selectResult = (result: FoodSearchResult, note: string | null = null) => {+ const selectResult = (result: FoodSearchResult, note: UiMessage | null = null) => {hSelect()setSelected(result)amount.openOn(result)@@ -178,7 +173,7 @@ export default function LogFood() {} catch (err) {// The search row is still real data, so log against it rather than dead-ending —// but say which figures these are, because they are the ones that read wrong.- selectResult(result, apiErrorMessage(err, "Couldn't re-read this product."))+ selectResult(result, { key: 'food.log.rereadFailed', cause: err })} finally {setUpgrading(null)}@@ -186,7 +181,7 @@ export default function LogFood() {const enterManually = () => {setLookup(null)- selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })+ selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'manual' })}const lookUpBarcode = async (code: string) => {@@ -200,7 +195,7 @@ export default function LogFood() {// unreachable upstream is not an answer, and saying "not found" for it sent// people to type in a product that does exist.if (isNotFound(err)) enterManually()- else setLookup({ code, error: apiErrorMessage(err, "Couldn't look up that barcode.") })+ else setLookup({ code, error: { key: 'food.log.lookupFailed', cause: err } })}}@@ -222,8 +217,8 @@ export default function LogFood() {}Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})// Courier the confirmation to the dashboard toast: which meal (new) or 'Updated'.- router.replace(`/nutrition?logged=${editId ? 'Updated' : encodeURIComponent(MEAL_LABELS[meal])}`)- }, 'Failed to save')+ router.replace(`/nutrition?logged=${editId ? 'Updated' : encodeURIComponent(mealLabel(meal))}`)+ }, t('food.log.saveFailed'))const handleLog = async () => {if (!selected || save.busy) return@@ -250,22 +245,22 @@ export default function LogFood() {<Screen>{/* Header */}<View className="flex-row items-center gap-3 py-4">- <Pressable onPress={goBack} className="h-10 w-10 items-center justify-center rounded-xl active:scale-95" accessibilityLabel="Back">+ <Pressable onPress={goBack} className="h-10 w-10 items-center justify-center rounded-xl active:scale-95" accessibilityLabel={t('common.back')}><ArrowLeft size={20} color={colors.txMuted} /></Pressable><View className="min-w-0 flex-1">{phase === 'detail' && selected ? (<><View className="flex-row items-center gap-1.5">- <AppText variant="caption" color="muted">{editId ? 'Edit Food' : 'Log Food'}</AppText>+ <AppText variant="caption" color="muted">{editId ? t('food.log.editTitle') : t('food.log.title')}</AppText><ChevronRight size={12} color={colors.txMuted} />- <AppText variant="caption" color="secondary">Details</AppText>+ <AppText variant="caption" color="secondary">{t('food.log.details')}</AppText></View>- <AppText variant="title" numberOfLines={1}>{selected.name || 'New Entry'}</AppText>+ <AppText variant="title" numberOfLines={1}>{selected.name || t('food.log.newEntry')}</AppText>{selected.brand ? <AppText variant="caption" color="muted">{selected.brand}</AppText> : null}</>) : (- <AppText variant="title">Log Food</AppText>+ <AppText variant="title">{t('food.log.title')}</AppText>)}</View>{/* Favouriting is decoupled from logging, so the star lives beside the food@@ -292,7 +287,7 @@ export default function LogFood() {the user opened. */}{editError ? (<View className="pb-3">- <Alert variant="error">{editError}</Alert>+ <Alert variant="error">{uiMessage(editError)}</Alert></View>) : null}@@ -311,38 +306,46 @@ export default function LogFood() {<SearchFieldautoFocusloading={tab === 'all' && searching}- placeholder="Search food…"+ placeholder={t('food.log.searchPlaceholder')}value={query}- onChangeText={(t) => { setQuery(t); if (t.trim()) setTab('all'); if (lookup?.error) setLookup(null) }}+ onChangeText={(text) => { setQuery(text); if (text.trim()) setTab('all'); if (lookup?.error) setLookup(null) }}/></View><PressableonPress={() => { hSelect(); setPhase('scan') }}disabled={lookingUp}- accessibilityLabel="Scan barcode"+ accessibilityLabel={t('food.log.scanLabel')}accessibilityState={{ disabled: lookingUp }}className={`h-12 flex-row items-center gap-1.5 rounded-xl border border-surface-border bg-surface-muted px-3.5 active:opacity-70 ${lookingUp ? 'opacity-40' : ''}`}><Scan size={20} color={colors.txSecondary} />- <AppText variant="caption" color="secondary" style={{ fontWeight: '600' }}>Scan</AppText>+ <AppText variant="caption" color="secondary" style={{ fontWeight: '600' }}>{t('food.log.scan')}</AppText></Pressable></View>{/* Tabs */}- <SegmentedControl options={TAB_OPTIONS} value={tab} onChange={(t) => { setTab(t); if (lookup?.error) setLookup(null) }} />+ <SegmentedControl+ options={[+ { value: 'recent', label: t('food.log.tab.recent') },+ { value: 'myfoods', label: t('food.log.tab.favorites') },+ { value: 'all', label: t('food.log.tab.search') },+ ] as const}+ value={tab}+ onChange={(v) => { setTab(v); if (lookup?.error) setLookup(null) }}+ />{/* Above the tab content, not inside one branch: the star is on every tab, soa failure starring a search result has to be visible on the search tab. */}{rateLimited ? (<View className="flex-row items-center gap-2 rounded-xl border border-warning-500/20 bg-warning-500/10 px-3.5 py-3"><AlertCircle size={16} color={isDark ? brand.warningSoft : brand.warning} />- <AppText variant="caption" style={{ color: isDark ? brand.warningSoft : brand.warning }}>Too many requests — wait a moment and try again</AppText>+ <AppText variant="caption" style={{ color: isDark ? brand.warningSoft : brand.warning }}>{t('food.log.rateLimited')}</AppText></View>) : null}{searchError ? (<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 px-3.5 py-3"><AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />- <AppText variant="caption" color="error">{searchError}</AppText>+ <AppText variant="caption" color="error">{uiMessage(searchError)}</AppText></View>) : null}@@ -354,25 +357,25 @@ export default function LogFood() {// what failed, and both ways forward keep the code already scanned.<Card><ErrorState- title="Couldn't look up this barcode"- message={lookup.error}+ title={t('food.log.lookupFailedTitle')}+ message={uiMessage(lookup.error)}onRetry={() => lookUpBarcode(lookup.code)}- secondary={<Button title="Enter it manually" variant="secondary" onPress={enterManually} />}+ secondary={<Button title={t('food.log.enterManually')} variant="secondary" onPress={enterManually} />}/></Card>) : (<Card className="overflow-hidden p-0">{tab === 'all' && quickAddCals !== null ? (<Pressable- onPress={() => selectResult({ name: `${quickAddCals} kcal`, calories: quickAddCals, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ onPress={() => selectResult({ name: `${quickAddCals} kcal`, calories: quickAddCals, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'off' })}className="w-full flex-row items-center gap-3 border-b border-surface-border px-4 py-3.5 active:bg-surface-muted"><View className="h-11 w-11 items-center justify-center rounded-xl border border-brand-500/20 bg-brand-500/10"><Zap size={20} color={accent} /></View><View className="min-w-0 flex-1">- <AppText variant="bodySemibold">Quick add {quickAddCals} kcal</AppText>- <AppText variant="caption" color="muted" className="mt-0.5">No macro breakdown</AppText>+ <AppText variant="bodySemibold">{t('food.log.quickAdd', { kcal: quickAddCals })}</AppText>+ <AppText variant="caption" color="muted" className="mt-0.5">{t('food.log.noMacroBreakdown')}</AppText></View><ChevronRight size={16} color={colors.txMuted} /></Pressable>@@ -380,7 +383,7 @@ export default function LogFood() {{tab === 'recent' ? (recentItems.length === 0 ? (- <EmptyBlock icon={Utensils} title="No recent items today" subtitle="Search or scan to log food" />+ <EmptyBlock icon={Utensils} title={t('food.log.recent.empty.title')} subtitle={t('food.log.recent.empty.hint')} />) : (recentItems.map((item, i) => (<FoodResultRow@@ -397,7 +400,7 @@ export default function LogFood() {{tab === 'myfoods' ? (savedFoods.length === 0 ? (- <EmptyBlock icon={Star} title="No favorites yet" subtitle="Star foods while logging to find them here" />+ <EmptyBlock icon={Star} title={t('food.favorites.empty.title')} subtitle={t('food.favorites.empty.hint')} />) : (<>{savedFoods.map((sf) => (@@ -415,19 +418,19 @@ export default function LogFood() {) : null}{tab === 'all' && !query.trim() ? (- <EmptyBlock icon={Utensils} title="Search millions of foods" subtitle="Or scan a barcode" />+ <EmptyBlock icon={Utensils} title={t('food.log.search.emptyTitle')} subtitle={t('food.log.search.emptyHint')} />) : null}{tab === 'all' && query.trim() && searching ? (- <View className="px-4 py-14"><AppText variant="body" color="muted" className="text-center">Searching…</AppText></View>+ <View className="px-4 py-14"><AppText variant="body" color="muted" className="text-center">{t('food.log.search.searching')}</AppText></View>) : null}{tab === 'all' && query.trim() && !searching && searchResults.length === 0 && !searchError && !rateLimited ? (<View className="items-center gap-3 px-4 py-14">- <AppText variant="body" color="muted">No results for "{query}"</AppText>+ <AppText variant="body" color="muted">{t('food.log.search.noResults', { query })}</AppText><Pressable- onPress={() => selectResult({ name: query.trim(), calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ onPress={() => selectResult({ name: query.trim(), calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'off' })}className="rounded-lg border border-surface-border bg-surface-overlay px-3 py-2 active:opacity-70">- <AppText variant="caption" color="secondary">+ Enter "{query.trim()}" manually</AppText>+ <AppText variant="caption" color="secondary">{t('food.log.search.manualEntryWide', { query: query.trim() })}</AppText></Pressable></View>) : null}@@ -465,7 +468,7 @@ export default function LogFood() {than let them read as a serving — that is the whole of #171. */}{staleServing ? (<Alert variant="warning">- {staleServing} Showing search results, which are always per {selected.serving_size}.+ {t('food.log.staleServing', { note: uiMessage(staleServing), serving: selected.serving_size })}</Alert>) : null}@@ -481,21 +484,21 @@ export default function LogFood() {<AppText variant="body" color="muted">kcal</AppText></View>{selected.serving_size ? (- <AppText variant="caption" color="muted" className="mt-1">per {servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}{selected.serving_size}</AppText>+ <AppText variant="caption" color="muted" className="mt-1">{t('food.log.per', { serving: `${servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}${selected.serving_size}` })}</AppText>) : null}</View>{pro + carb + fat_ > 0 ? (<View className="w-24 flex-col items-end gap-1">- {[- { label: 'P', value: pro, color: MACRO_COLORS.protein },- { label: 'C', value: carb, color: MACRO_COLORS.carbs },- { label: 'F', value: fat_, color: MACRO_COLORS.fat },- ].map((m) => {+ {([+ { key: 'protein', value: pro, color: MACRO_COLORS.protein },+ { key: 'carbs', value: carb, color: MACRO_COLORS.carbs },+ { key: 'fat', value: fat_, color: MACRO_COLORS.fat },+ ] as const).map((m) => {const total = pro + carb + fat_const pct = total > 0 ? Math.round((m.value / total) * 100) : 0return (- <View key={m.label} className="w-full flex-row items-center gap-1.5">- <AppText variant="caption" color="muted" style={{ fontSize: 10, width: 10, textAlign: 'right' }}>{m.label}</AppText>+ <View key={m.key} className="w-full flex-row items-center gap-1.5">+ <AppText variant="caption" color="muted" style={{ fontSize: 10, width: 10, textAlign: 'right' }}>{t(`food.macro.${m.key}Initial`)}</AppText><View className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-muted">{/* inline height:'100%' — the h-full class expands on native (see index.tsx) */}<View style={{ width: `${pct}%`, height: '100%', borderRadius: 999, backgroundColor: m.color }} />@@ -510,15 +513,15 @@ export default function LogFood() {{/* Macro grid */}<View className="flex-row gap-2">- {[- { label: 'Protein', value: figures ? `${pro}g` : '—', color: MACRO_TEXT.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },- { label: 'Carbs', value: figures ? `${carb}g` : '—', color: MACRO_TEXT.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },- { label: 'Fat', value: figures ? `${fat_}g` : '—', color: MACRO_TEXT.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },- { label: 'Fiber', value: figures ? `${figures.fiber}g` : '—', color: colors.txSecondary, bg: colors.muted, border: colors.border },- ].map((m) => (- <View key={m.label} className="flex-1 items-center rounded-xl border p-2.5" style={{ backgroundColor: m.bg, borderColor: m.border }}>+ {([+ { key: 'protein', value: figures ? `${pro}g` : '—', color: MACRO_TEXT.protein, bg: 'rgba(16,185,129,0.10)', border: 'rgba(16,185,129,0.20)' },+ { key: 'carbs', value: figures ? `${carb}g` : '—', color: MACRO_TEXT.carbs, bg: 'rgba(245,158,11,0.10)', border: 'rgba(245,158,11,0.20)' },+ { key: 'fat', value: figures ? `${fat_}g` : '—', color: MACRO_TEXT.fat, bg: 'rgba(139,92,246,0.10)', border: 'rgba(139,92,246,0.20)' },+ { key: 'fiber', value: figures ? `${figures.fiber}g` : '—', color: colors.txSecondary, bg: colors.muted, border: colors.border },+ ] as const).map((m) => (+ <View key={m.key} className="flex-1 items-center rounded-xl border p-2.5" style={{ backgroundColor: m.bg, borderColor: m.border }}><AppText variant="bodySemibold" style={{ color: m.color, fontVariant: ['tabular-nums'] }}>{m.value}</AppText>- <AppText variant="caption" color="muted" style={{ fontSize: 10 }} className="mt-0.5">{m.label}</AppText>+ <AppText variant="caption" color="muted" style={{ fontSize: 10 }} className="mt-0.5">{t(`food.macro.${m.key}`)}</AppText></View>))}</View>@@ -528,26 +531,26 @@ export default function LogFood() {{/* Amount */}<Card className="gap-3"><View className="flex-row items-baseline gap-2">- <Label>{basis ? 'Amount' : 'Servings'}</Label>+ <Label>{basis ? t('food.entry.amount') : t('food.log.servings')}</Label>{selected.serving_size && !basis- ? <AppText variant="caption" color="muted">({selected.serving_size} each)</AppText>+ ? <AppText variant="caption" color="muted">{t('food.log.servingEach', { serving: selected.serving_size })}</AppText>: null}</View><View className="flex-row items-center gap-3">- <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? 'Decrease amount' : 'Decrease servings'} onPress={() => stepAmount(-1)} />+ <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? t('food.log.decreaseAmount') : t('food.log.decreaseServings')} onPress={() => stepAmount(-1)} /><View className="flex-1 flex-row items-center justify-center"><View className="flex-1"><NumberFieldinputMode="decimal"value={amount.text}onChange={amount.setText}- accessibilityLabel={basis ? `Amount in ${basis.unit}` : 'Servings'}+ accessibilityLabel={basis ? t('food.log.amountIn', { unit: basis.unit }) : t('food.log.servings')}inputAccessoryViewID={NUMERIC_ACCESSORY_ID}/></View>{basis ? <AppText variant="caption" color="muted" className="ml-1">{basis.unit}</AppText> : null}</View>- <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? 'Increase amount' : 'Increase servings'} onPress={() => stepAmount(1)} />+ <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? t('food.log.increaseAmount') : t('food.log.increaseServings')} onPress={() => stepAmount(1)} /></View>{/* The readout doubles as the reason the Log button is disabled. Deletingthe 0.5-serving floor made an empty or nonsense amount reachable for the@@ -556,10 +559,10 @@ export default function LogFood() {{basis || servings <= 0 || limitHint ? (<AppText variant="caption" color={limitHint ? 'warning' : 'muted'} className="text-center">{servings <= 0- ? `Enter an amount${basis ? ` in ${basis.unit}` : ''} to log this`+ ? (basis ? t('food.log.enterAmountIn', { unit: basis.unit }) : t('food.log.enterAmount')): limitHint? limitHint- : `${servingsLabel} ${servingsLabel === 1 ? 'serving' : 'servings'} of ${selected.serving_size}`}+ : t('food.log.servingsOf', { count: servingsLabel, serving: selected.serving_size })}</AppText>) : null}</Card>@@ -567,7 +570,7 @@ export default function LogFood() {{/* Meal + when */}<Card className="gap-5"><View className="gap-3">- <Label>Meal</Label>+ <Label>{t('food.entry.meal')}</Label><View className="flex-row flex-wrap gap-2">{MEALS.map((m) => {const MealIcon = MEAL_ICONS[m]@@ -580,7 +583,7 @@ export default function LogFood() {className={`flex-row items-center gap-2.5 rounded-xl border px-3.5 py-3 ${active ? 'border-brand-500/40 bg-brand-500/10' : 'border-surface-border bg-surface-muted'}`}><MealIcon size={16} color={active ? MEAL_COLORS[m] : colors.txMuted} />- <AppText variant="bodySemibold" style={{ fontSize: 13 }} color={active ? 'primary' : 'secondary'}>{MEAL_LABELS[m]}</AppText>+ <AppText variant="bodySemibold" style={{ fontSize: 13 }} color={active ? 'primary' : 'secondary'}>{mealLabel(m)}</AppText></Pressable>)})}@@ -589,7 +592,7 @@ export default function LogFood() {<View className="h-px bg-surface-border" />- <DateInput label="When" value={date} onChange={setDate} maximumDate={new Date()} />+ <DateInput label={t('food.log.when')} value={date} onChange={setDate} maximumDate={new Date()} /></Card></View>@@ -598,7 +601,7 @@ export default function LogFood() {{/* Sticky log button */}<View className="border-t border-surface-border bg-surface-base pb-6 pt-3"><Button- title={save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}+ title={save.busy ? t('common.saving') : editId ? t('food.log.saveChanges') : t('food.log.submit')}onPress={handleLog}loading={save.busy}// An empty or zero amount would log a row of zeroes.diff --git a/mobile/app/(tabs)/programs/[id].tsx b/mobile/app/(tabs)/programs/[id].tsxindex 3953828..753e7eb 100644--- a/mobile/app/(tabs)/programs/[id].tsx+++ b/mobile/app/(tabs)/programs/[id].tsx@@ -1,20 +1,19 @@import { useCallback, useEffect, useRef, useState } from 'react'import { Pressable, ScrollView, View } from 'react-native'import { router, useFocusEffect, useLocalSearchParams, type Href } from 'expo-router'-import { format } from 'date-fns'import {AlertCircle, ArrowLeft, Award, BookOpen, CalendarDays, Check, ChevronDown, ChevronRight, ChevronUp, Dumbbell,Edit2, Layers, Moon, Pause, Play, TimerOff, TrendingUp, Trash2, X,} from 'lucide-react-native'import { useAsyncAction,- activeSessionExercisesForDay, allExercises, apiErrorMessage, dayLabel, displayWeight, sessionNameForDay,- weightShort, type Program, type ProgramSet,+ activeSessionExercisesForDay, allExercises, dayLabel, displayWeight, sessionNameForDay,+ weightShort, type Program, type ProgramSet, formatDate, uiMessage, useTranslation, type UiMessage} from '@lyftr/shared'import { AppText, Button, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'import { client, useSettingsStore, useWorkoutSession } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'-import { muscleColor } from '../../../src/utils/exerciseUtils'+import { muscleColor, muscleLabel } from '../../../src/utils/exerciseUtils'import { targetWeightLabel, restLabel } from '@lyftr/shared'// Exercise-detail leaf, routed INSIDE the Programs stack (programs/exercise/[exerciseId])@@ -29,6 +28,7 @@ const activeHref = '/workouts/active' as unknown as Hrefconst SUGGESTION_CAP = 3function SetChip({ set, isBest, hasSuggestion, unit }: { set: ProgramSet; isBest: boolean; hasSuggestion: boolean; unit: string }) {+ const { t } = useTranslation()return (<ViewclassName={`px-2.5 py-1.5 rounded-lg border ${@@ -38,7 +38,7 @@ function SetChip({ set, isBest, hasSuggestion, unit }: { set: ProgramSet; isBest><AppText variant="caption" color={hasSuggestion ? 'secondary' : isBest ? 'brand' : 'secondary'} style={{ fontVariant: ['tabular-nums'] }}>{set.target_reps > 0 ? set.target_reps : '—'} ×{' '}- {set.target_weight > 0 ? `${displayWeight(set.target_weight, unit)} ${unit}` : 'BW'}+ {set.target_weight > 0 ? `${displayWeight(set.target_weight, unit)} ${unit}` : t('weight.bodyweightShort')}</AppText></View>)@@ -59,12 +59,13 @@ function MuscleBadge({ muscle }: { muscle: string }) {const tint = muscleColor(muscle)return (<View className={`px-1.5 py-0.5 rounded ${tint?.chip ?? 'bg-surface-muted'}`}>- <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscle}</AppText>+ <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscleLabel(muscle)}</AppText></View>)}export default function ProgramDetail() {+ const { t } = useTranslation()const { id } = useLocalSearchParams<{ id: string }>()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)@@ -75,7 +76,8 @@ export default function ProgramDetail() {const [program, setProgram] = useState<Program | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // UiMessages, not their sentences, so the banners follow a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Bumping this re-runs the load effect — three lines, rather than restructuring a// working effect to gain a retry button.const [retryKey, setRetryKey] = useState(0)@@ -83,7 +85,7 @@ export default function ProgramDetail() {const [resolving, setResolving] = useState(false)// Separate from `error`, which replaces the whole screen: a failed resolve must leave the// program on screen so the same buttons are still under the thumb to retry.- const [resolveError, setResolveError] = useState<string | null>(null)+ const [resolveError, setResolveError] = useState<UiMessage | null>(null)const [showAllSuggestions, setShowAllSuggestions] = useState(false)const [selectedDayIdx, setSelectedDayIdx] = useState(0)@@ -113,7 +115,7 @@ export default function ProgramDetail() {const updated = await client.programAPI.resolveSuggestions(program.id, { accept, dismiss })setProgram(updated)} catch (err) {- setResolveError(apiErrorMessage(err, "Couldn't save those targets."))+ setResolveError({ key: 'programs.detail.suggestions.saveFailed', cause: err })} finally {// Invalidate any focus refetch still in flight from before this point — its// response can't be trusted to reflect this write, whichever order it lands in.@@ -150,7 +152,7 @@ export default function ProgramDetail() {loadedRef.current = true}} catch (err) {- if (!cancelled && !loadedRef.current) setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ if (!cancelled && !loadedRef.current) setError({ key: 'settings.unknownError', cause: err })} finally {if (!cancelled) setLoading(false)}@@ -183,7 +185,7 @@ export default function ProgramDetail() {if (!program) returnawait client.programAPI.delete(program.id)goBack() // list refetches on focus- }, 'Failed to delete program')+ }, t('programs.deleteFailed'))if (loading) return <Loading />@@ -193,10 +195,10 @@ export default function ProgramDetail() {<View className="flex-1 py-4"><ErrorStatesize="page"- title="Couldn't load this program"- message={error ?? 'That program no longer exists.'}+ title={t('programs.detail.loadFailed')}+ message={error ? uiMessage(error) : t('programs.detail.gone')}onRetry={error ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}- secondary={<Button title="Back to programs" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('programs.detail.backToPrograms')} variant="secondary" onPress={goBack} />}/></View></Screen>@@ -227,11 +229,11 @@ export default function ProgramDetail() {newLabel = targetWeightLabel(sw, wUnit)} else {oldLabel = `${s.target_reps}`- newLabel = `${sr} reps`+ newLabel = t('programs.count.reps', { count: sr })}return {setId: s.id as number,- exName: ex.exercise?.name ?? 'Exercise',+ exName: ex.exercise?.name ?? t('programs.detail.suggestions.exerciseFallback'),setNumber: s.set_number,isPR: !!s.suggested_is_pr,oldLabel,@@ -250,35 +252,35 @@ export default function ProgramDetail() {<View className="flex-row items-center justify-between"><Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-1.5 active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Programs</AppText>+ <AppText variant="body" color="muted">{t('programs.detail.back')}</AppText></Pressable><View className="flex-row items-center gap-2">{/* Start is the primary action → filled brand pill; Edit brand outline;Delete a quiet ghost glyph that only reddens at the confirm step. */}<PressableaccessibilityRole="button"- accessibilityLabel="Start workout"+ accessibilityLabel={t('programs.detail.startLabel')}onPress={handleStart}disabled={!selectedDay || selectedDay.is_rest_day}hitSlop={6}className={`h-9 flex-row items-center gap-1.5 rounded-lg bg-brand-500 px-3 active:scale-95 ${!selectedDay || selectedDay.is_rest_day ? 'opacity-40' : ''}`}><Play size={14} color="#ffffff" strokeWidth={2.2} />- <AppText variant="label" color="white">Start</AppText>+ <AppText variant="label" color="white">{t('programs.detail.start')}</AppText></Pressable><PressableaccessibilityRole="button"- accessibilityLabel="Edit program"+ accessibilityLabel={t('programs.detail.editLabel')}onPress={() => router.push(`/programs/${program.id}/edit`)}hitSlop={6}className="h-9 flex-row items-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 px-3 active:scale-95"><Edit2 size={15} color={accent} strokeWidth={2.2} />- <AppText variant="label" style={{ color: accent }}>Edit</AppText>+ <AppText variant="label" style={{ color: accent }}>{t('common.edit')}</AppText></Pressable><PressableaccessibilityRole="button"- accessibilityLabel="Delete program"+ accessibilityLabel={t('programs.detail.deleteLabel')}onPress={() => setConfirming(true)}disabled={remove.busy}hitSlop={6}@@ -290,7 +292,7 @@ export default function ProgramDetail() {</View><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete Program?', subject: `"${program.name}"` })}+ {...deleteConfirmProps({ title: t('programs.deleteConfirmTitle'), subject: `"${program.name}"` })}open={confirming}busy={remove.busy}error={remove.error}@@ -305,7 +307,7 @@ export default function ProgramDetail() {{suggestions.some((s) => s.isPR)? <Award size={16} color={warningColor} />: <TrendingUp size={16} color={warningColor} />}- <AppText variant="bodySemibold" className="flex-1">New targets from your last workout</AppText>+ <AppText variant="bodySemibold" className="flex-1">{t('programs.detail.suggestions.title')}</AppText><View className="bg-warning-500/15 rounded-full px-2 py-0.5"><AppText variant="caption" style={{ color: warningColor, fontWeight: 'bold' }}>{suggestions.length}</AppText></View>@@ -315,7 +317,7 @@ export default function ProgramDetail() {<View className="flex-1 flex-row items-center gap-1.5 min-w-0">{sg.isPR ? <Award size={14} color={warningColor} /> : null}<AppText variant="caption" color="secondary" numberOfLines={1} className="flex-1">- <AppText variant="caption" color="primary" style={{ fontWeight: '600' }}>{sg.exName}</AppText> · Set {sg.setNumber}+ <AppText variant="caption" color="primary" style={{ fontWeight: '600' }}>{sg.exName}</AppText> · {t('programs.detail.suggestions.set', { number: sg.setNumber })}</AppText></View><View className="flex-row items-center flex-shrink-0">@@ -327,7 +329,7 @@ export default function ProgramDetail() {<PressableonPress={() => resolveSuggestions([sg.setId], [])}disabled={resolving}- accessibilityLabel={`Accept ${sg.exName} set ${sg.setNumber}`}+ accessibilityLabel={t('programs.detail.suggestions.accept', { name: sg.exName, number: sg.setNumber })}className={`w-7 h-7 rounded-lg bg-success-500/15 items-center justify-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}><Check size={14} color={isDark ? brand.successSoft : brand.success} strokeWidth={3} />@@ -335,7 +337,7 @@ export default function ProgramDetail() {<PressableonPress={() => resolveSuggestions([], [sg.setId])}disabled={resolving}- accessibilityLabel={`Dismiss ${sg.exName} set ${sg.setNumber}`}+ accessibilityLabel={t('programs.detail.suggestions.dismiss', { name: sg.exName, number: sg.setNumber })}className={`w-7 h-7 rounded-lg bg-surface-muted items-center justify-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}><X size={14} color={colors.txMuted} strokeWidth={3} />@@ -349,7 +351,7 @@ export default function ProgramDetail() {className="flex-row items-center justify-center gap-1.5 py-2 border-t border-surface-border/60 active:opacity-60"><AppText variant="caption" style={{ color: warningColor, fontWeight: '600' }}>- {showAllSuggestions ? 'Show less' : `Show all ${suggestions.length}`}+ {showAllSuggestions ? t('programs.detail.suggestions.showLess') : t('programs.detail.suggestions.showAll', { total: suggestions.length })}</AppText>{showAllSuggestions ? <ChevronUp size={14} color={warningColor} /> : <ChevronDown size={14} color={warningColor} />}</Pressable>@@ -357,7 +359,7 @@ export default function ProgramDetail() {{resolveError && (<View className="flex-row items-start gap-2 px-4 py-2.5 border-t border-surface-border/60"><AlertCircle size={16} color={brand.error} />- <AppText variant="caption" color="error" className="flex-1">{resolveError}</AppText>+ <AppText variant="caption" color="error" className="flex-1">{uiMessage(resolveError)}</AppText></View>)}<View className="flex-row gap-2 px-4 py-3 border-t border-surface-border/60">@@ -366,14 +368,14 @@ export default function ProgramDetail() {disabled={resolving}className={`flex-1 py-2 rounded-lg bg-surface-muted border border-surface-border items-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}>- <AppText variant="bodySemibold" color="secondary">Dismiss all</AppText>+ <AppText variant="bodySemibold" color="secondary">{t('programs.detail.suggestions.dismissAll')}</AppText></Pressable><PressableonPress={() => resolveSuggestions(suggestedSetIds, [])}disabled={resolving}className={`flex-1 py-2 rounded-lg bg-warning-500 items-center active:scale-95 ${resolving ? 'opacity-50' : ''}`}>- <AppText variant="bodySemibold" style={{ color: brand.warningText }}>Apply all ({suggestions.length})</AppText>+ <AppText variant="bodySemibold" style={{ color: brand.warningText }}>{t('programs.detail.suggestions.applyAll', { total: suggestions.length })}</AppText></Pressable></View></View>@@ -386,7 +388,7 @@ export default function ProgramDetail() {<View className="flex-1"><AppText variant="heading">{program.name}</AppText><AppText variant="body" color="muted" className="mt-0.5">- Created {format(new Date(program.created_at), 'MMMM d, yyyy')}+ {t('programs.createdOn', { date: formatDate(new Date(program.created_at), 'longDate') })}</AppText></View></View>@@ -396,21 +398,21 @@ export default function ProgramDetail() {<View className="flex-1 items-center"><View className="flex-row items-center gap-1 mb-0.5"><CalendarDays size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Cycle</AppText>+ <AppText variant="caption" color="muted">{t('programs.detail.stats.cycle')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{days.length || '—'}</AppText></View><View className="flex-1 items-center border-l border-surface-border"><View className="flex-row items-center gap-1 mb-0.5"><Dumbbell size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Exercises</AppText>+ <AppText variant="caption" color="muted">{t('programs.detail.stats.exercises')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{allExs.length}</AppText></View><View className="flex-1 items-center border-l border-surface-border"><View className="flex-row items-center gap-1 mb-0.5"><Layers size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Total Sets</AppText>+ <AppText variant="caption" color="muted">{t('programs.detail.stats.totalSets')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{totalSets}</AppText></View>@@ -429,9 +431,9 @@ export default function ProgramDetail() {{days.length === 0 ? (<View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-6"><CalendarDays size={28} color={colors.txMuted} style={{ opacity: 0.5 }} />- <AppText variant="body" color="muted" className="mt-2">No days yet</AppText>+ <AppText variant="body" color="muted" className="mt-2">{t('programs.detail.noDays')}</AppText><Pressable onPress={() => router.push(`/programs/${program.id}/edit`)} className="mt-2 active:opacity-60">- <AppText variant="caption" style={{ color: accent }}>Add a day →</AppText>+ <AppText variant="caption" style={{ color: accent }}>{t('programs.detail.addDay')}</AppText></Pressable></View>) : (@@ -461,7 +463,7 @@ export default function ProgramDetail() {distinguishable by shape/text (a11y) and reads as decoration. */}{isToday ? (<View className={`rounded-full px-1.5 py-0.5 ${isSelected ? 'bg-white/20' : 'bg-brand-500/15'}`}>- <AppText variant="caption" style={{ color: isSelected ? '#ffffff' : accent, letterSpacing: 0.5 }}>TODAY</AppText>+ <AppText variant="caption" style={{ color: isSelected ? '#ffffff' : accent, letterSpacing: 0.5 }}>{t('programs.detail.todayChip')}</AppText></View>) : null}</Pressable>@@ -474,9 +476,9 @@ export default function ProgramDetail() {{selectedDay?.is_rest_day ? (<View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-10"><Moon size={28} color={colors.txMuted} style={{ opacity: 0.6 }} />- <AppText variant="bodySemibold" className="mt-2">Rest Day</AppText>+ <AppText variant="bodySemibold" className="mt-2">{t('programs.day.rest')}</AppText><AppText variant="caption" color="muted" className="mt-1 text-center px-6">- No exercises scheduled — recover and come back stronger.+ {t('programs.detail.restDayHint')}</AppText></View>) : selectedDay ? (@@ -484,19 +486,23 @@ export default function ProgramDetail() {{!restOn && (<View className="flex-row items-center gap-1.5 px-1"><TimerOff size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Rest timer is off — turn it on in Settings</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.restOff')}</AppText></View>)}<View className="gap-3">{(selectedDay.exercises ?? []).length === 0 ? (<View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-8"><Dumbbell size={28} color={colors.txMuted} style={{ opacity: 0.5 }} />- <AppText variant="body" color="muted" className="mt-2">No exercises on this day yet</AppText>+ <AppText variant="body" color="muted" className="mt-2">{t('programs.detail.noExercises')}</AppText></View>) : (selectedDay.exercises ?? []).map((ex) => {const sets = ex.sets ?? []const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map((s) => s.target_weight || 0)) : 0const maxTarget = displayWeight(maxTargetLbs, wUnit)+ const setsSummary = [+ t('programs.count.sets', { count: sets.length }),+ ...(maxTarget > 0 ? [t('programs.detail.target', { weight: maxTarget, unit: wUnit })] : []),+ ].join(' · ')return (<Pressable@@ -512,7 +518,7 @@ export default function ProgramDetail() {<View className="flex-row items-center gap-2 mt-0.5">{ex.exercise?.muscle_group ? <MuscleBadge muscle={ex.exercise.muscle_group} /> : null}<AppText variant="caption" color="muted" numberOfLines={1} className="flex-shrink">- {sets.length} set{sets.length === 1 ? '' : 's'}{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}+ {setsSummary}</AppText></View></View>@@ -528,7 +534,7 @@ export default function ProgramDetail() {</View>{restOn && (ex.rest_seconds === 0 ? (- <AppText variant="caption" color="muted">No rest</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.noRest')}</AppText>) : (<View className="flex-row items-center gap-1"><Pause size={13} color={colors.txMuted} />diff --git a/mobile/app/(tabs)/programs/[id]/edit.tsx b/mobile/app/(tabs)/programs/[id]/edit.tsxindex b2d5609..d46d027 100644--- a/mobile/app/(tabs)/programs/[id]/edit.tsx+++ b/mobile/app/(tabs)/programs/[id]/edit.tsx@@ -3,7 +3,7 @@ import { Platform, ScrollView, View } from 'react-native'import { router, useLocalSearchParams } from 'expo-router'import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { apiErrorMessage, useAsyncAction, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, type Exercise } from '@lyftr/shared'+import { useAsyncAction, displayToLbs, hasWorkoutExercises, lbsToDisplay, weightShort, uiMessage, useTranslation, type Exercise, type UiMessage } from '@lyftr/shared'import { AppText, Button, ErrorState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'import { KeyboardDoneBar } from '../../../../src/components/workouts/KeyboardDoneBar'import { ProgramDaysEditor } from '../../../../src/components/programs/ProgramDaysEditor'@@ -31,6 +31,7 @@ function FieldHeader({ icon: Icon, label }: { icon: LucideIcon; label: string })export default function EditProgram() {const { id } = useLocalSearchParams<{ id: string }>()+ const { t } = useTranslation()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const wUnit = weightShort(settings.weight_unit)@@ -39,10 +40,10 @@ export default function EditProgram() {const [initialLoading, setInitialLoading] = useState(true)// Only what the FORM can say before anything is sent. What the SERVER says lives// on `save` below; both render in the same alert.- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)// Separate from `error`, which is this form's own validation. A load that never// arrived is not a missing field — there is nothing to edit.- const [loadError, setLoadError] = useState<string | null>(null)+ const [loadError, setLoadError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })@@ -85,7 +86,7 @@ export default function EditProgram() {})),})})- .catch((err) => { if (!cancelled) setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")) })+ .catch((err) => { if (!cancelled) setLoadError({ key: 'settings.unknownError', cause: err }) }).finally(() => { if (!cancelled) setInitialLoading(false) })return () => { cancelled = true }// eslint-disable-next-line react-hooks/exhaustive-deps@@ -123,18 +124,18 @@ export default function EditProgram() {}await client.programAPI.update(Number(id), payload)router.dismissTo('/programs')- }, 'Failed to update program')+ }, t('programs.form.updateFailed'))useEffect(() => {if (error || save.error) scrollRef.current?.scrollTo({ y: 0, animated: true })- }, [error, save.error])+ }, [error, save.failureKey])const handleSubmit = async () => {- if (!formData.name.trim()) { setError('Program name required'); return }- if (formData.days.length === 0) { setError('Add at least one day'); return }+ if (!formData.name.trim()) { setError({ key: 'programs.form.errors.nameRequired' }); return }+ if (formData.days.length === 0) { setError({ key: 'programs.form.errors.noDays' }); return }const hasAnyExercise = hasWorkoutExercises(formData.days)- if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }- setError('')+ if (!hasAnyExercise) { setError({ key: 'programs.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -143,10 +144,10 @@ export default function EditProgram() {<Screen><ErrorStatesize="page"- title="Couldn't load this program"- message={loadError}+ title={t('programs.detail.loadFailed')}+ message={uiMessage(loadError)}onRetry={() => { setLoadError(null); setRetryKey((k) => k + 1) }}- secondary={<Button title="Back to programs" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('programs.detail.backToPrograms')} variant="secondary" onPress={goBack} />}/></Screen>)@@ -169,11 +170,11 @@ export default function EditProgram() {><View className="gap-6 py-4"><View className="flex-row items-center gap-3">- <IconButton icon={ArrowLeft} label="Back" variant="ghost" size="md" onPress={goBack} />+ <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} /><View>- <AppText variant="title">Edit Program</AppText>+ <AppText variant="title">{t('programs.form.editTitle')}</AppText><AppText variant="caption" color="muted">- {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}+ {t('programs.form.summary', { days: t('programs.count.days', { count: formData.days.length }), exercises: t('programs.count.exercises', { count: totalExercises }), sets: t('programs.count.sets', { count: totalSets }) })}</AppText></View></View>@@ -181,24 +182,24 @@ export default function EditProgram() {{error || save.error ? (<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4"><AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />- <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>+ <AppText variant="body" color="error" className="flex-1">{error ? uiMessage(error) : save.error}</AppText></View>) : null}<View>- <FieldHeader icon={BookOpen} label="Program Name" />+ <FieldHeader icon={BookOpen} label={t('programs.form.name')} /><Fieldvalue={formData.name}- onChangeText={(t) => setFormData((prev) => ({ ...prev, name: t }))}+ onChangeText={(text) => setFormData((prev) => ({ ...prev, name: text }))}/></View><View>- <FieldHeader icon={FileText} label="Notes" />+ <FieldHeader icon={FileText} label={t('workouts.form.notes')} /><Fieldvalue={formData.notes}- onChangeText={(t) => setFormData((prev) => ({ ...prev, notes: t }))}- placeholder="Program description or goals…"+ onChangeText={(text) => setFormData((prev) => ({ ...prev, notes: text }))}+ placeholder={t('programs.form.notesPlaceholder')}multiline/></View>@@ -206,8 +207,8 @@ export default function EditProgram() {<View><View className="mb-3 flex-row items-center gap-2"><CalendarDays size={14} color={brand.cyan} strokeWidth={2.2} />- <Label>Days</Label>- <AppText variant="caption" color="muted">(repeats in this order)</AppText>+ <Label>{t('programs.form.days')}</Label>+ <AppText variant="caption" color="muted">{t('programs.form.daysHintEdit')}</AppText></View><ProgramDaysEditordays={formData.days}@@ -223,8 +224,8 @@ export default function EditProgram() {</ScrollView><View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">- <Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />- <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={save.busy} />+ <Button title={t('common.cancel')} variant="secondary" className="flex-1" onPress={goBack} />+ <Button title={t('workouts.form.saveChanges')} className="flex-1" onPress={handleSubmit} loading={save.busy} /></View><KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />diff --git a/mobile/app/(tabs)/programs/index.tsx b/mobile/app/(tabs)/programs/index.tsxindex 1d40d06..0e84a01 100644--- a/mobile/app/(tabs)/programs/index.tsx+++ b/mobile/app/(tabs)/programs/index.tsx@@ -3,7 +3,7 @@ import { ActivityIndicator, FlatList, RefreshControl, View } from 'react-native'import { router, useFocusEffect } from 'expo-router'import { BookOpen, Plus } from 'lucide-react-native'import type { Program } from '@lyftr/shared'-import { programExerciseCount } from '@lyftr/shared'+import { programExerciseCount, useTranslation } from '@lyftr/shared'import { AppText, Card, EmptyState, ErrorState, IconButton, Label, PageHeader, Screen, SearchField, StatFailure } from '../../../src/components/ui'import { ProgramCard } from '../../../src/components/programs/ProgramCard'import { ProgramsSkeleton } from '../../../src/components/programs/ProgramsSkeleton'@@ -12,6 +12,7 @@ import { client } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'export default function Programs() {+ const { t } = useTranslation()const { accent } = useTheme()const [search, setSearch] = useState('')@@ -82,8 +83,8 @@ export default function Programs() {return (<Screen><View className="flex-1 gap-5 py-4">- <PageHeader title="Programs" subtitle="Reusable workout templates" />- <ErrorState size="page" title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />+ <PageHeader title={t('programs.title')} subtitle={t('programs.subtitle')} />+ <ErrorState size="page" title={t('programs.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} /></View></Screen>)@@ -100,14 +101,15 @@ export default function Programs() {const stats = [// `programs` is what has loaded, not how many exist: while pages remain it is a lower// bound. A failed page is also "pages remain" — the hook drops hasMore on error.- { label: 'Total', value: hasMore || listError != null ? `${programs.length}+` : String(programs.length), unit: 'programs' },+ { label: t('programs.stats.total'), failed: t('programs.stats.totalFailed'), value: hasMore || listError != null ? `${programs.length}+` : String(programs.length), unit: t('programs.stats.totalUnit') },{- label: 'Avg Exercises',+ label: t('programs.stats.avgExercises'),+ failed: t('programs.stats.avgExercisesFailed'),value:programs.length > 0? String(Math.round(programs.reduce((s, p) => s + programExerciseCount(p), 0) / programs.length)): '—',- unit: 'per program',+ unit: t('programs.stats.perProgram'),},]@@ -129,12 +131,12 @@ export default function Programs() {ListHeaderComponent={<View className="gap-5 py-4"><PageHeader- title="Programs"- subtitle="Reusable workout templates"+ title={t('programs.title')}+ subtitle={t('programs.subtitle')}action={<IconButtonicon={Plus}- label="New Program"+ label={t('programs.newProgram')}variant="solid"size="md"onPress={() => router.push('/programs/new')}@@ -148,7 +150,7 @@ export default function Programs() {<Card key={s.label} className="flex-1 rounded-2xl"><Label className="mb-2" numberOfLines={1}>{s.label}</Label>{countsUnknown ? (- <StatFailure label={`Couldn't load ${s.label.toLowerCase()}`} />+ <StatFailure label={s.failed} />) : (<View className="flex-row items-end gap-1"><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{s.value}</AppText>@@ -163,7 +165,7 @@ export default function Programs() {value={search}onChangeText={setSearch}loading={refreshing}- placeholder="Search programs…"+ placeholder={t('programs.list.searchPlaceholder')}/></View>}@@ -180,12 +182,12 @@ export default function Programs() {loading ? null : listError ? (// Reached only with a search on screen; "No programs found" would blame the// query for a request that never landed.- <ErrorState title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />+ <ErrorState title={t('programs.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />) : (<EmptyStateicon={BookOpen}- title="No programs found"- subtitle={search ? 'Try a different search' : 'Create a program to get started'}+ title={t('programs.list.empty.title')}+ subtitle={search ? t('programs.list.empty.searchHint') : t('programs.list.empty.startHint')}/>)}@@ -194,7 +196,7 @@ export default function Programs() {// (re)load — there the content is already grayed, so a footer spinner// would read as an unwanted "loading" in the middle.listError && programs.length > 0 ? (- <ErrorState title="Couldn't load your programs" message={listError} onRetry={retryList} retrying={loading} />+ <ErrorState title={t('programs.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />) : hasMore && loading && !dim && programs.length > 0 ? (<View className="items-center py-3"><ActivityIndicator size="small" color={accent} />diff --git a/mobile/app/(tabs)/programs/new.tsx b/mobile/app/(tabs)/programs/new.tsxindex 1da34af..2c0d19e 100644--- a/mobile/app/(tabs)/programs/new.tsx+++ b/mobile/app/(tabs)/programs/new.tsx@@ -3,7 +3,7 @@ import { Platform, ScrollView, View } from 'react-native'import { router } from 'expo-router'import { AlertCircle, ArrowLeft, BookOpen, CalendarDays, FileText } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { useAsyncAction, displayToLbs, hasWorkoutExercises, weightShort, type Exercise } from '@lyftr/shared'+import { useAsyncAction, displayToLbs, hasWorkoutExercises, weightShort, uiMessage, useTranslation, type Exercise, type UiMessage } from '@lyftr/shared'import { AppText, Button, Field, IconButton, Label, Screen } from '../../../src/components/ui'import { KeyboardDoneBar } from '../../../src/components/workouts/KeyboardDoneBar'import { ProgramDaysEditor } from '../../../src/components/programs/ProgramDaysEditor'@@ -34,6 +34,7 @@ function FieldHeader({ icon: Icon, label, hint }: { icon: LucideIcon; label: str}export default function AddProgram() {+ const { t } = useTranslation()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const wUnit = weightShort(settings.weight_unit)@@ -41,7 +42,7 @@ export default function AddProgram() {// Only what the FORM can say before anything is sent. What the SERVER says lives// on `save` below; both render in the same alert.- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })const scrollRef = useRef<ScrollView>(null)@@ -77,18 +78,18 @@ export default function AddProgram() {}await client.programAPI.create(payload)router.dismissTo('/programs')- }, 'Failed to create program')+ }, t('programs.form.createFailed'))useEffect(() => {if (error || save.error) scrollRef.current?.scrollTo({ y: 0, animated: true })- }, [error, save.error])+ }, [error, save.failureKey])const handleSubmit = async () => {- if (!formData.name.trim()) { setError('Program name required'); return }- if (formData.days.length === 0) { setError('Add at least one day'); return }+ if (!formData.name.trim()) { setError({ key: 'programs.form.errors.nameRequired' }); return }+ if (formData.days.length === 0) { setError({ key: 'programs.form.errors.noDays' }); return }const hasAnyExercise = hasWorkoutExercises(formData.days)- if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }- setError('')+ if (!hasAnyExercise) { setError({ key: 'programs.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -107,11 +108,11 @@ export default function AddProgram() {><View className="gap-6 py-4"><View className="flex-row items-center gap-3">- <IconButton icon={ArrowLeft} label="Back" variant="ghost" size="md" onPress={goBack} />+ <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} /><View>- <AppText variant="title">New Program</AppText>+ <AppText variant="title">{t('programs.form.newTitle')}</AppText><AppText variant="caption" color="muted">- {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}+ {t('programs.form.summary', { days: t('programs.count.days', { count: formData.days.length }), exercises: t('programs.count.exercises', { count: totalExercises }), sets: t('programs.count.sets', { count: totalSets }) })}</AppText></View></View>@@ -119,25 +120,25 @@ export default function AddProgram() {{error || save.error ? (<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4"><AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />- <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>+ <AppText variant="body" color="error" className="flex-1">{error ? uiMessage(error) : save.error}</AppText></View>) : null}<View>- <FieldHeader icon={BookOpen} label="Program Name" hint="(required)" />+ <FieldHeader icon={BookOpen} label={t('programs.form.name')} hint={t('programs.form.required')} /><Fieldvalue={formData.name}- onChangeText={(t) => setFormData((prev) => ({ ...prev, name: t }))}- placeholder="e.g., Push Pull Legs, Upper Lower"+ onChangeText={(text) => setFormData((prev) => ({ ...prev, name: text }))}+ placeholder={t('programs.form.namePlaceholder')}/></View><View>- <FieldHeader icon={FileText} label="Notes" />+ <FieldHeader icon={FileText} label={t('workouts.form.notes')} /><Fieldvalue={formData.notes}- onChangeText={(t) => setFormData((prev) => ({ ...prev, notes: t }))}- placeholder="Program description or goals…"+ onChangeText={(text) => setFormData((prev) => ({ ...prev, notes: text }))}+ placeholder={t('programs.form.notesPlaceholder')}multiline/></View>@@ -145,8 +146,8 @@ export default function AddProgram() {<View><View className="mb-3 flex-row items-center gap-2"><CalendarDays size={14} color={brand.cyan} strokeWidth={2.2} />- <Label>Days</Label>- <AppText variant="caption" color="muted">(required — repeats in this order)</AppText>+ <Label>{t('programs.form.days')}</Label>+ <AppText variant="caption" color="muted">{t('programs.form.daysHintNew')}</AppText></View><ProgramDaysEditordays={formData.days}@@ -162,8 +163,8 @@ export default function AddProgram() {</ScrollView><View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">- <Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />- <Button title="Save Program" className="flex-1" onPress={handleSubmit} loading={save.busy} />+ <Button title={t('common.cancel')} variant="secondary" className="flex-1" onPress={goBack} />+ <Button title={t('programs.form.saveProgram')} className="flex-1" onPress={handleSubmit} loading={save.busy} /></View><KeyboardDoneBar nativeID={KEYPAD_DONE_ID} />diff --git a/mobile/app/(tabs)/settings/email.tsx b/mobile/app/(tabs)/settings/email.tsxindex 9dbb99f..f262d02 100644--- a/mobile/app/(tabs)/settings/email.tsx+++ b/mobile/app/(tabs)/settings/email.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { Pressable, ScrollView, View } from 'react-native'import { router } from 'expo-router'import { ArrowLeft, MailCheck } from 'lucide-react-native'-import { useAsyncAction, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'+import { useAsyncAction, useTranslation, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'import {Alert,AppText,@@ -21,6 +21,7 @@ import { useTheme } from '../../../src/theme/useTheme'// card rather than popping back because the sign-in identifier changed: a consequence the// person has to be told about.export default function ChangeEmailScreen() {+ const { t } = useTranslation()const { colors, brand } = useTheme()const user = useAuthStore((s) => s.user)const changeEmail = useAuthStore((s) => s.changeEmail)@@ -38,7 +39,7 @@ export default function ChangeEmailScreen() {setCurrent('')setCaseOnly(onlyCase)setChangedTo(updated.email)- }, "Couldn't change your email. Please try again.")+ }, t('settings.account.email.failedFallback'))const ready = emailChanged(email, user?.email) && !!current@@ -54,7 +55,7 @@ export default function ChangeEmailScreen() {className="flex-row items-center gap-1.5 self-start active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Settings</AppText>+ <AppText variant="body" color="muted">{t('settings.account.backLink')}</AppText></Pressable>)@@ -69,15 +70,15 @@ export default function ChangeEmailScreen() {<MailCheck size={24} color={brand.successSoft} strokeWidth={2.2} /></View><View className="gap-1">- <AppText variant="title" className="text-center">Email changed</AppText>+ <AppText variant="title" className="text-center">{t('settings.account.email.changedTitle')}</AppText><AppText variant="body" color="muted" className="text-center">- Sign in with {changedTo} from now on.{' '}+ {t('settings.account.email.signInWithPlain', { email: changedTo })}{' '}{caseOnly- ? 'Only the letter case changed, so your other devices stay signed in.'- : 'You stay signed in here; your other devices are signed out.'}+ ? t('settings.account.email.caseOnly')+ : t('settings.account.email.signedOutElsewhere')}</AppText></View>- <Button title="Back to settings" variant="secondary" onPress={back} className="mt-1" />+ <Button title={t('settings.account.backToSettings')} variant="secondary" onPress={back} className="mt-1" /></Card></View></ScrollView>@@ -91,18 +92,18 @@ export default function ChangeEmailScreen() {<View className="gap-5 py-4">{backLink}<PageHeader- title="Change email"- subtitle="You will sign in with the new address. Changing more than the letter case signs out your other devices."+ title={t('settings.account.email.pageTitle')}+ subtitle={t('settings.account.email.pageSubtitle')}/><Card className="gap-4"><View className="gap-1">- <AppText variant="caption" color="muted">Current email</AppText>+ <AppText variant="caption" color="muted">{t('settings.account.email.current')}</AppText><AppText variant="body">{user?.email ?? '—'}</AppText></View><Field- label="New email"+ label={t('settings.account.email.new')}value={email}onChangeText={setEmail}keyboardType="email-address"@@ -113,7 +114,7 @@ export default function ChangeEmailScreen() {autoFocus/><PasswordField- label="Current password"+ label={t('settings.account.password.current')}value={current}onChangeText={setCurrent}textContentType="password"@@ -123,14 +124,14 @@ export default function ChangeEmailScreen() {<View className="flex-row gap-2"><Button- title="Update email"+ title={t('settings.account.email.submit')}onPress={submit}loading={save.busy}disabled={!ready}className="flex-1"/><Button- title="Cancel"+ title={t('common.cancel')}variant="secondary"onPress={back}disabled={save.busy}diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsxindex 3aea259..48beb9e 100644--- a/mobile/app/(tabs)/settings/index.tsx+++ b/mobile/app/(tabs)/settings/index.tsx@@ -8,6 +8,7 @@ import {AlertTriangle,Dumbbell,KeyRound,+ Languages,LogOut,Mail,Minus,@@ -20,11 +21,14 @@ import {User,} from 'lucide-react-native'import { useAsyncAction,+ useTranslation,+ languageChoiceLabel,memberSince,normalizeServerUrl,testServerConnection,+ uiMessage,+ type UiMessage,isInsecureServerUrl,- INSECURE_SERVER_WARNING,sanitizeNumericInput,} from '@lyftr/shared'import {@@ -46,14 +50,21 @@ import {Toggle,type ToastVariant,} from '../../../src/components/ui'-import { client, useAuthStore, useDisplayName, useServerStore, useSettingsStore } from '../../../src/lib/lyftr'+import { client, useAuthStore, useDisplayName, useLanguageStore, useServerStore, useSettingsStore } from '../../../src/lib/lyftr'+import { LanguageSheet } from '../../../src/components/settings/LanguageSheet'import { useTheme } from '../../../src/theme/useTheme'const REST_PRESETS = [60, 90, 120, 180]-type ToastState = { variant: ToastVariant; title: string; description?: string }+// Which toast is up, not its words: the title and the failure sentence are made at render, so a+// toast on screen follows a live language switch.+type ToastState = 'saved' | 'saveTargets' | 'changeUnit' | 'deleteAccount'export default function SettingsScreen() {+ const { t } = useTranslation()+ const preference = useLanguageStore((s) => s.preference)+ const setPreference = useLanguageStore((s) => s.setPreference)+ const [languageOpen, setLanguageOpen] = useState(false)const user = useAuthStore((s) => s.user)const name = useDisplayName()const logout = useAuthStore((s) => s.logout)@@ -86,7 +97,12 @@ export default function SettingsScreen() {// Server repoint (same warn-but-save flow as the sign-in screens / web ServerSettings).const [urlInput, setUrlInput] = useState(serverUrl)const insecureServer = isInsecureServerUrl(serverUrl)- const [serverMsg, setServerMsg] = useState<string | null>(null)+ const [serverResult, setServerResult] = useState<+ | { kind: 'invalid' }+ | { kind: 'connected'; name: string; version: string }+ | { kind: 'saved'; failure: UiMessage }+ | null+ >(null)const [testing, setTesting] = useState(false)const [confirmDelete, setConfirmDelete] = useState(false)@@ -125,8 +141,8 @@ export default function SettingsScreen() {carb_target: parseInt(targets.carb_target) || 0,fat_target: parseInt(targets.fat_target) || 0,})- setToast({ variant: 'success', title: 'Targets saved' })- }, 'Could not save targets')+ setToast('saved')+ }, t('settings.targets.saveFailed'))const handleSaveTargets = () => { void saveTargets.run() }@@ -136,21 +152,23 @@ export default function SettingsScreen() {// back now; this is what says why.const changeUnit = useAsyncAction(async (unit: 'lbs' | 'kg') => {await updateSettings({ weight_unit: unit })- }, 'Could not change the weight unit')+ }, t('settings.targets.weightUnit.changeFailedFallback'))const saveServer = async () => {setTesting(true)- setServerMsg(null)+ setServerResult(null)const base = normalizeServerUrl(urlInput)if (urlInput.trim() && !base) {- setServerMsg('Enter a full URL including http:// or https://')+ setServerResult({ kind: 'invalid' })setTesting(false)return}// Warn-but-save: the choice is authoritative right away; the probe is advisory.await setServerUrl(base)const result = await testServerConnection(base)- setServerMsg(result.ok ? `Connected · ${result.info.name} v${result.info.version}` : `Saved — ${result.message}`)+ setServerResult(result.ok+ ? { kind: 'connected', name: result.info.name, version: result.info.version }+ : { kind: 'saved', failure: result.failure })setTesting(false)}@@ -159,25 +177,32 @@ export default function SettingsScreen() {// logout flips isAuthenticated; the root layout's Stack.Protected guard then makes// (tabs) unreachable and expo-router moves the user to sign-in. Nothing routes by hand.await logout()- }, 'Could not delete account')+ }, t('settings.deleteAccount.failed'))// These two report through the toast rather than an inline alert, so the message is// read off the hook when it changes. It used to be `err?.message`, which for an axios// error is the string "Request failed with status code 400" - true, and useless.useEffect(() => {- if (saveTargets.error) setToast({ variant: 'error', title: 'Could not save targets', description: saveTargets.error })- }, [saveTargets.error])+ if (saveTargets.failureKey) setToast('saveTargets')+ }, [saveTargets.failureKey])useEffect(() => {- if (changeUnit.error) setToast({ variant: 'error', title: 'Could not change units', description: changeUnit.error })- }, [changeUnit.error])+ if (changeUnit.failureKey) setToast('changeUnit')+ }, [changeUnit.failureKey])useEffect(() => {- if (deleteAccount.error) {+ if (deleteAccount.failureKey) {setConfirmDelete(false)- setToast({ variant: 'error', title: 'Could not delete account', description: deleteAccount.error })+ setToast('deleteAccount')}- }, [deleteAccount.error])+ }, [deleteAccount.failureKey])++ const toastView: { variant: ToastVariant; title: string; description?: string } | null =+ toast === 'saved' ? { variant: 'success', title: t('settings.unitsTargets.saved') }+ : toast === 'saveTargets' ? { variant: 'error', title: t('settings.targets.saveFailed'), description: saveTargets.error }+ : toast === 'changeUnit' ? { variant: 'error', title: t('settings.unitsTargets.changeUnitFailedTitle'), description: changeUnit.error }+ : toast === 'deleteAccount' ? { variant: 'error', title: t('settings.deleteAccount.failed'), description: deleteAccount.error }+ : nullif (!loaded) return <Loading />@@ -193,13 +218,13 @@ export default function SettingsScreen() {className="flex-row items-center gap-1.5 self-start active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Home</AppText>+ <AppText variant="body" color="muted">{t('settings.back')}</AppText></Pressable>- <PageHeader title="Settings" subtitle="Preferences and account configuration" />+ <PageHeader title={t('settings.title')} subtitle={t('settings.subtitle')} /></View>{/* Account */}- <SettingsGroup title="Account">+ <SettingsGroup title={t('settings.account.title')}>{/* Shows what the greeting will actually say, so the fallback is visiblewithout opening anything: the email's local part until a name is set.SettingsRow truncates its value to one line, which the dashboard heading@@ -207,24 +232,24 @@ export default function SettingsScreen() {full name is one tap away, where the heading IS the content. */}<SettingsRowicon={User}- label="Name"+ label={t('settings.account.name.label')}value={name}chevrononPress={() => router.push('/settings/name')}/><SettingsRowicon={Mail}- label="Email"+ label={t('settings.account.email.label')}value={user?.email ?? '—'}dividerchevrononPress={() => router.push('/settings/email')}/>- <SettingsRow icon={CalendarDays} label="Member since" value={memberSince(user?.created_at)} divider />+ <SettingsRow icon={CalendarDays} label={t('settings.account.memberSince.label')} value={memberSince(user?.created_at)} divider /><SettingsRowicon={KeyRound}- label="Password"- description="Changing it signs you out on your other devices"+ label={t('settings.account.password.label')}+ description={t('settings.account.password.description')}dividerchevrononPress={() => router.push('/settings/password')}@@ -232,44 +257,52 @@ export default function SettingsScreen() {</SettingsGroup>{/* Appearance */}- <SettingsGroup title="Appearance">+ <SettingsGroup title={t('settings.appearance.title')}><SettingsRowicon={Moon}- label="Dark mode"- description="Use the dark color scheme"+ label={t('settings.appearance.darkMode.label')}+ description={t('settings.appearance.darkMode.description')}right={<Togglevalue={mode === 'dark'}onValueChange={(on) => setMode(on ? 'dark' : 'light')}- accessibilityLabel="Dark mode"+ accessibilityLabel={t('settings.appearance.darkMode.label')}/>}/>+ <SettingsRow+ icon={Languages}+ label={t('settings.language.label')}+ value={languageChoiceLabel(preference)}+ chevron+ onPress={() => setLanguageOpen(true)}+ divider+ /></SettingsGroup>{/* Workout */}- <SettingsGroup title="Workout" footnote="Default rest seeds new exercises · a per-exercise rest overrides it.">+ <SettingsGroup title={t('settings.workout.title')} footnote={t('settings.workout.footnote')}><SettingsRowicon={Dumbbell}- label="Default workout view"+ label={t('settings.workout.defaultView.label')}below={<SegmentedControlvalue={settings.workout_layout ?? 'list'}onChange={setWorkoutLayout}options={[- { value: 'list', label: 'List' },- { value: 'gym', label: 'Gym Mode' },+ { value: 'list', label: t('settings.workout.layout.list') },+ { value: 'gym', label: t('settings.workout.layout.gym') },]}/>}/><SettingsRowicon={Timer}- label="Rest timer"- description="Auto-start a countdown between sets"+ label={t('settings.workout.restTimer.label')}+ description={t('settings.workout.restTimer.description')}dividerright={- <Toggle value={restEnabled} onValueChange={setRestEnabled} accessibilityLabel="Rest timer" />+ <Toggle value={restEnabled} onValueChange={setRestEnabled} accessibilityLabel={t('settings.workout.restTimer.label')} />}/>{/* Dependent sub-setting: shown but dimmed + inert when the timer is off (the value@@ -277,7 +310,7 @@ export default function SettingsScreen() {<View pointerEvents={restEnabled ? 'auto' : 'none'} style={{ opacity: restEnabled ? 1 : 0.4 }}><SettingsRowicon={Clock}- label="Default rest"+ label={t('settings.workout.defaultRest.label')}dividerbelow={<View className="gap-3">@@ -292,15 +325,15 @@ export default function SettingsScreen() {}}}options={[- ...REST_PRESETS.map((s) => ({ value: String(s), label: `${s}s` })),- { value: 'custom', label: restIsCustom ? `${restCur}s` : 'Custom' },+ ...REST_PRESETS.map((s) => ({ value: String(s), label: t('settings.workout.defaultRest.preset', { seconds: s }) })),+ { value: 'custom', label: restIsCustom ? t('settings.workout.defaultRest.preset', { seconds: restCur }) : t('settings.workout.defaultRest.custom') },]}/>{restCustomActive ? (<View className="flex-row items-center justify-center gap-3"><IconButtonicon={Minus}- label="Decrease rest by 5 seconds"+ label={t('settings.workout.defaultRest.decrease')}variant="secondary"size="md"onPress={() => setRestSeconds(Math.max(0, restCur - 5))}@@ -312,13 +345,13 @@ export default function SettingsScreen() {value={String(restCur)}onChange={(v) => setRestSeconds(Math.max(0, Math.min(3600, Number(v) || 0)))}inputMode="numeric"- accessibilityLabel="Custom rest seconds"+ accessibilityLabel={t('settings.workout.defaultRest.customLabel')}/></View></View><IconButtonicon={Plus}- label="Increase rest by 5 seconds"+ label={t('settings.workout.defaultRest.increase')}variant="secondary"size="md"onPress={() => setRestSeconds(Math.min(3600, restCur + 5))}@@ -337,19 +370,19 @@ export default function SettingsScreen() {2000/150/250/65 so the rest of the app keeps working, and Save would PUTthose straight over the user's real targets. */}{settingsLoadFailed ? (- <SettingsGroup title="Units & Targets">+ <SettingsGroup title={t('settings.unitsTargets.title')}><ErrorStatesize="section"- title="Couldn't load your goals"- message="These are your saved targets and units, so we won't guess at them. Everything else here still works."+ title={t('settings.targets.loadFailedTitle')}+ message={t('settings.unitsTargets.loadFailedMessage')}onRetry={() => { void fetchSettings() }}/></SettingsGroup>) : (- <SettingsGroup title="Units & Targets" footnote="Weight unit applies instantly across the app. Nutrition targets power the dashboard rings.">+ <SettingsGroup title={t('settings.unitsTargets.title')} footnote={t('settings.unitsTargets.footnote')}><SettingsRowicon={Scale}- label="Weight unit"+ label={t('settings.targets.weightUnit.label')}below={<SegmentedControlvalue={settings.weight_unit}@@ -363,43 +396,43 @@ export default function SettingsScreen() {/><View className="gap-3 border-t border-surface-border py-4"><Field- label="Calorie target"+ label={t('settings.targets.calorie.label')}keyboardType="number-pad"value={targets.calorie_target}onChangeText={onDigits('calorie_target')}rightSlot={<Muted className="text-xs">kcal</Muted>}/><Field- label="Protein target"+ label={t('settings.targets.protein.label')}keyboardType="number-pad"value={targets.protein_target}onChangeText={onDigits('protein_target')}rightSlot={<Muted className="text-xs">g</Muted>}/><Field- label="Carb target"+ label={t('settings.targets.carb.label')}keyboardType="number-pad"value={targets.carb_target}onChangeText={onDigits('carb_target')}rightSlot={<Muted className="text-xs">g</Muted>}/><Field- label="Fat target"+ label={t('settings.targets.fat.label')}keyboardType="number-pad"value={targets.fat_target}onChangeText={onDigits('fat_target')}rightSlot={<Muted className="text-xs">g</Muted>}/>- <Button title="Save targets" onPress={handleSaveTargets} loading={saveTargets.busy} className="mt-1" />+ <Button title={t('settings.targets.save')} onPress={handleSaveTargets} loading={saveTargets.busy} className="mt-1" /></View></SettingsGroup>)}{/* Server */}- <SettingsGroup title="Server" footnote="The self-hosted backend this app talks to. Leave the URL blank to use the default.">+ <SettingsGroup title={t('settings.server.title')} footnote={t('settings.server.footnote')}><SettingsRowicon={Server}- label="Backend"+ label={t('settings.server.backend.label')}right={<View className="max-w-[60%] flex-row items-center gap-2">{/* Amber, not green, whenever traffic leaves the device unencrypted (#79). */}@@ -407,41 +440,49 @@ export default function SettingsScreen() {? <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} />: <View className="h-1.5 w-1.5 rounded-full bg-success-500" />}<AppText variant="body" color={insecureServer ? 'warning' : 'muted'} numberOfLines={1}>- {serverUrl || 'Default backend'}+ {serverUrl || t('settings.server.backend.default')}</AppText></View>}/><View className="border-t border-surface-border py-4"><Field- label="Server URL"+ label={t('settings.server.url.label')}value={urlInput}onChangeText={setUrlInput}autoCapitalize="none"autoCorrect={false}keyboardType="url"- placeholder="https://your-server.example.com"+ placeholder={t('settings.server.url.placeholder')}/>- {serverMsg ? <AppText variant="caption" color="brand" className="mt-2">{serverMsg}</AppText> : null}+ {serverResult ? (+ <AppText variant="caption" color="brand" className="mt-2">+ {serverResult.kind === 'invalid'+ ? t('settings.server.url.invalid')+ : serverResult.kind === 'connected'+ ? t('settings.server.connected', { name: serverResult.name, version: serverResult.version })+ : t('settings.server.savedWithWarning', { message: uiMessage(serverResult.failure) })}+ </AppText>+ ) : null}{insecureServer ? (<View className="mt-2 flex-row items-start gap-1.5"><AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} style={{ marginTop: 1 }} /><AppText variant="caption" color="warning" className="flex-1">- {INSECURE_SERVER_WARNING}+ {t('server.insecureWarning')}</AppText></View>) : null}- <Button title="Test & save" variant="secondary" onPress={saveServer} loading={testing} className="mt-3" />+ <Button title={t('settings.server.url.testAndSave')} variant="secondary" onPress={saveServer} loading={testing} className="mt-3" /></View></SettingsGroup>{/* Account actions */}- <SettingsGroup title="Account actions">- <SettingsRow icon={LogOut} tint="muted" label="Sign out" onPress={() => logout()} chevron />+ <SettingsGroup title={t('settings.danger.actionsTitle')}>+ <SettingsRow icon={LogOut} tint="muted" label={t('settings.signOut.label')} onPress={() => logout()} chevron /><SettingsRowicon={Trash2}- label="Delete account"- description="Permanently delete all your data"+ label={t('settings.deleteAccount.label')}+ description={t('settings.deleteAccount.description')}destructivedivideronPress={() => setConfirmDelete(true)}@@ -450,23 +491,29 @@ export default function SettingsScreen() {</View></ScrollView>- {toast ? (+ {toastView ? (<Toast- variant={toast.variant}- title={toast.title}- description={toast.description}+ variant={toastView.variant}+ title={toastView.title}+ description={toastView.description}onDismiss={() => setToast(null)}/>) : null}+ <LanguageSheet+ open={languageOpen}+ value={preference}+ onSelect={(p) => { void setPreference(p) }}+ onClose={() => setLanguageOpen(false)}+ /><ConfirmSheetopen={confirmDelete}icon={Trash2}destructive- title="Delete account?"- message="This permanently deletes your account and all of your data. This can't be undone."- confirmLabel="Delete account"- busyLabel="Deleting…"+ title={t('settings.deleteAccount.sheetTitle')}+ message={t('settings.deleteAccount.sheetMessage')}+ confirmLabel={t('settings.deleteAccount.confirm')}+ busyLabel={t('settings.deleteAccount.busy')}busy={deleteAccount.busy}onConfirm={() => { void deleteAccount.run() }}onCancel={() => setConfirmDelete(false)}diff --git a/mobile/app/(tabs)/settings/name.tsx b/mobile/app/(tabs)/settings/name.tsxindex 6148a7a..56b9058 100644--- a/mobile/app/(tabs)/settings/name.tsx+++ b/mobile/app/(tabs)/settings/name.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { Pressable, ScrollView, View } from 'react-native'import { router } from 'expo-router'import { ArrowLeft } from 'lucide-react-native'-import { useAsyncAction, displayName, MAX_DISPLAY_NAME_LEN } from '@lyftr/shared'+import { useAsyncAction, useTranslation, displayName, MAX_DISPLAY_NAME_LEN } from '@lyftr/shared'import {Alert,AppText,@@ -20,6 +20,7 @@ import { useTheme } from '../../../src/theme/useTheme'// beside Cancel. Account rows are icon + label + value, so an editor belongs here rather// than as a form wedged into that group.export default function ChangeNameScreen() {+ const { t } = useTranslation()const { colors } = useTheme()const user = useAuthStore((s) => s.user)const settings = useSettingsStore((s) => s.settings)@@ -48,7 +49,7 @@ export default function ChangeNameScreen() {const save = useAsyncAction(async () => {await updateSettings({ display_name: name.trim() })back()- }, "Couldn't save your name. Please try again.")+ }, t('settings.account.name.saveFailedFallback'))return (<Screen>@@ -60,12 +61,12 @@ export default function ChangeNameScreen() {className="flex-row items-center gap-1.5 self-start active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Settings</AppText>+ <AppText variant="body" color="muted">{t('settings.account.backLink')}</AppText></Pressable><PageHeader- title="Name"- subtitle="The name the app greets you by."+ title={t('settings.account.name.title')}+ subtitle={t('settings.account.name.subtitle')}/><Card className="gap-4">@@ -73,7 +74,7 @@ export default function ChangeNameScreen() {needs an accessible one, or a screen reader announces only the emailplaceholder, as if that were the current value. */}<Field- accessibilityLabel="Name"+ accessibilityLabel={t('settings.account.name.label')}placeholder={displayName('', user?.email)}value={name}onChangeText={setName}@@ -85,21 +86,21 @@ export default function ChangeNameScreen() {onSubmitEditing={() => { if (!save.busy) void save.run() }}/><Muted className="text-xs">- Leave it empty and we'll use your email instead.+ {t('settings.account.name.emptyHint')}</Muted>{save.error ? <Alert variant="error">{save.error}</Alert> : null}<View className="flex-row gap-2"><Button- title="Save"+ title={t('settings.account.name.save')}onPress={() => void save.run()}loading={save.busy}disabled={name.trim() === (settings.display_name ?? '')}className="flex-1"/><Button- title="Cancel"+ title={t('common.cancel')}variant="secondary"onPress={back}disabled={save.busy}diff --git a/mobile/app/(tabs)/settings/password.tsx b/mobile/app/(tabs)/settings/password.tsxindex 109949b..b6dc4c1 100644--- a/mobile/app/(tabs)/settings/password.tsx+++ b/mobile/app/(tabs)/settings/password.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { Pressable, ScrollView, View } from 'react-native'import { router } from 'expo-router'import { ArrowLeft, ShieldCheck } from 'lucide-react-native'-import { useAsyncAction, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'+import { useAsyncAction, useTranslation, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'import {Alert,AppText,@@ -25,6 +25,7 @@ import { useTheme } from '../../../src/theme/useTheme'// centred confirmation card on success — so the two do not merely do the same thing, they// read as the same screen.export default function ChangePasswordScreen() {+ const { t } = useTranslation()const { colors, brand } = useTheme()const [current, setCurrent] = useState('')@@ -42,7 +43,7 @@ export default function ChangePasswordScreen() {await client.userAPI.changePassword({ current_password: current, new_password: next })setCurrent(''); setNext(''); setConfirm('')setDone(true)- }, "Couldn't change your password. Please try again.")+ }, t('settings.account.password.failedFallback'))const submit = async () => {// The rules render under the fields as the user types and the button stays disabled@@ -60,7 +61,7 @@ export default function ChangePasswordScreen() {className="flex-row items-center gap-1.5 self-start active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Settings</AppText>+ <AppText variant="body" color="muted">{t('settings.account.backLink')}</AppText></Pressable>)@@ -79,13 +80,12 @@ export default function ChangePasswordScreen() {<ShieldCheck size={24} color={brand.successSoft} strokeWidth={2.2} /></View><View className="gap-1">- <AppText variant="title" className="text-center">Password changed</AppText>+ <AppText variant="title" className="text-center">{t('settings.account.password.changedTitle')}</AppText><AppText variant="body" color="muted" className="text-center">- You are still signed in here. Every other device has been signed out and- will need the new password.+ {t('settings.account.password.changedBody')}</AppText></View>- <Button title="Back to settings" variant="secondary" onPress={back} className="mt-1" />+ <Button title={t('settings.account.backToSettings')} variant="secondary" onPress={back} className="mt-1" /></Card></View></ScrollView>@@ -99,13 +99,13 @@ export default function ChangePasswordScreen() {<View className="gap-5 py-4">{backLink}<PageHeader- title="Change password"- subtitle="You will stay signed in here. Every other device is signed out."+ title={t('settings.account.password.pageTitle')}+ subtitle={t('settings.account.password.pageSubtitle')}/><Card className="gap-4"><PasswordField- label="Current password"+ label={t('settings.account.password.current')}value={current}onChangeText={setCurrent}textContentType="password"@@ -113,7 +113,7 @@ export default function ChangePasswordScreen() {{/* newPassword lets the OS keychain offer to generate and save one, and stopsit filing the new value under the old password's entry. */}<PasswordField- label="New password"+ label={t('settings.account.password.new')}value={next}onChangeText={setNext}textContentType="newPassword"@@ -122,7 +122,7 @@ export default function ChangePasswordScreen() {<PasswordRule state={rules.different}>{differentRuleLabel()}</PasswordRule></PasswordField><PasswordField- label="Confirm new password"+ label={t('settings.account.password.confirmNew')}value={confirm}onChangeText={setConfirm}textContentType="newPassword"@@ -137,14 +137,14 @@ export default function ChangePasswordScreen() {<View className="flex-row gap-2"><Button- title="Update password"+ title={t('settings.account.password.submit')}onPress={submit}loading={save.busy}disabled={!rules.ready}className="flex-1"/><Button- title="Cancel"+ title={t('common.cancel')}variant="secondary"onPress={back}disabled={save.busy}diff --git a/mobile/app/(tabs)/weight/[id].tsx b/mobile/app/(tabs)/weight/[id].tsxindex 7870585..30507a3 100644--- a/mobile/app/(tabs)/weight/[id].tsx+++ b/mobile/app/(tabs)/weight/[id].tsx@@ -3,7 +3,7 @@ import { Pressable, ScrollView, View } from 'react-native'import { router, useLocalSearchParams } from 'expo-router'import * as Haptics from 'expo-haptics'import { ArrowLeft, Edit2, Scale, Trash2 } from 'lucide-react-native'-import { useAsyncAction, apiErrorMessage, isNotFound, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'+import { useAsyncAction, uiMessage, isNotFound, dayToInstant, displayWeight, maxWeight, resolveWeightLbs, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, formatDay, useTranslation, type UiMessage } from '@lyftr/shared'import { Alert,AppText, Button, Card, ConfirmSheet, DateInput, ErrorState, Field, Label, Loading, NumberField,NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, Screen, StepperTile, deleteConfirmProps,@@ -12,6 +12,7 @@ import { client, useSettingsStore } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'export default function WeightDetail() {+ const { t } = useTranslation()const { id, edit } = useLocalSearchParams<{ id: string; edit?: string }>()const settings = useSettingsStore((s) => s.settings)const unit = settings.weight_unit@@ -20,7 +21,7 @@ export default function WeightDetail() {const [log, setLog] = useState<WeightLog | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<UiMessage | null>(null)const [gone, setGone] = useState(false)const [retryKey, setRetryKey] = useState(0)@@ -29,7 +30,8 @@ export default function WeightDetail() {const [editWeight, setEditWeight] = useState('')const [editDate, setEditDate] = useState('')const [editNotes, setEditNotes] = useState('')- const [editError, setEditError] = useState('')+ // The value the box was rejected for, not the sentence, so the banner follows a language switch.+ const [badWeight, setBadWeight] = useState<number | null>(null)// Delete confirmconst [confirming, setConfirming] = useState(false)@@ -48,7 +50,7 @@ export default function WeightDetail() {}).catch((err) => {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })}).finally(() => setLoading(false))// eslint-disable-next-line react-hooks/exhaustive-deps@@ -59,7 +61,7 @@ export default function WeightDetail() {setEditWeight(String(displayWeight(log.weight, unit)))setEditDate(entryDay(log))setEditNotes(log.notes ?? '')- setEditError('')+ setBadWeight(null)setEditing(true)}@@ -74,9 +76,9 @@ export default function WeightDetail() {Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})setLog(updated)setEditing(false)- }, 'Failed to save')+ }, t('weight.detail.saveFailed'))- // `editError` is what this screen can say about the value in the box; the hook carries+ // `badWeight` is what this screen can say about the value in the box; the hook carries// what the server said. The entry is passed to run() because the guard above is what// proves it is not null.const handleSave = () => {@@ -84,10 +86,10 @@ export default function WeightDetail() {const w = parseFloat(editWeight)const wErr = weightError(w, unit)if (wErr) {- setEditError(wErr)+ setBadWeight(w)return}- setEditError('')+ setBadWeight(null)void saveEdit.run(log)}@@ -97,7 +99,9 @@ export default function WeightDetail() {if (!log) returnawait client.weightAPI.delete(log.id)goBack() // the list refetches on focus- }, 'Failed to delete entry')+ }, t('weight.deleteFailed'))++ const editError = badWeight == null ? '' : weightError(badWeight, unit) ?? ''if (loading) return <Loading />@@ -107,10 +111,10 @@ export default function WeightDetail() {<View className="flex-1 py-4"><ErrorStatesize="page"- title="Couldn't load this entry"- message={error ?? 'That entry no longer exists.'}+ title={t('weight.detail.loadFailed')}+ message={error ? uiMessage(error) : t('weight.detail.gone')}onRetry={error && !gone ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}- secondary={<Button title="Back to weight" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('weight.detail.backToWeight')} variant="secondary" onPress={goBack} />}/></View></Screen>@@ -125,23 +129,23 @@ export default function WeightDetail() {<View className="flex-row items-center justify-between"><Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-1.5 active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Weight</AppText>+ <AppText variant="body" color="muted">{t('weight.detail.back')}</AppText></Pressable>{!editing ? (<View className="flex-row items-center gap-2"><PressableaccessibilityRole="button"- accessibilityLabel="Edit entry"+ accessibilityLabel={t('weight.detail.editLabel')}onPress={startEdit}hitSlop={6}className="h-9 flex-row items-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 px-3 active:scale-95"><Edit2 size={15} color={accent} strokeWidth={2.2} />- <AppText variant="label" style={{ color: accent }}>Edit</AppText>+ <AppText variant="label" style={{ color: accent }}>{t('common.edit')}</AppText></Pressable><PressableaccessibilityRole="button"- accessibilityLabel="Delete entry"+ accessibilityLabel={t('weight.detail.deleteLabel')}onPress={() => setConfirming(true)}disabled={remove.busy}hitSlop={6}@@ -160,9 +164,9 @@ export default function WeightDetail() {<Scale size={28} color={accent} /></View><View className="min-w-0 flex-1">- <Label className="mb-1">Weight Entry</Label>+ <Label className="mb-1">{t('weight.detail.entryLabel')}</Label>{editing ? (- <AppText variant="bodySemibold" color="brand">Editing…</AppText>+ <AppText variant="bodySemibold" color="brand">{t('weight.detail.editing')}</AppText>) : (<><View className="flex-row items-end gap-2">@@ -170,7 +174,7 @@ export default function WeightDetail() {<AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText></View><AppText variant="body" color="muted" className="mt-1">- {formatDay(entryDay(log), 'EEEE, MMMM d, yyyy')}+ {formatDay(entryDay(log), 'weekdayDate')}</AppText>{log.notes ? (<AppText variant="body" color="secondary" className="mt-2 italic">"{log.notes}"</AppText>@@ -184,7 +188,7 @@ export default function WeightDetail() {{/* Edit form */}{editing ? (<Card>- <AppText variant="heading" className="mb-4">Edit Entry</AppText>+ <AppText variant="heading" className="mb-4">{t('weight.detail.editTitle')}</AppText><View className="gap-4">{editError || saveEdit.error ? (<Alert variant="error" size="compact">{editError || saveEdit.error}</Alert>@@ -192,8 +196,8 @@ export default function WeightDetail() {<StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('weight.log.weightLabel', { unit: wUnit })}+ name={t('weight.log.weightName')}step={BODYWEIGHT_STEP}onStep={(d) => setEditWeight(String(clampStep(parseFloat(editWeight) || 0, d, { min: 0, max: maxWeight(unit) })))}>@@ -202,27 +206,27 @@ export default function WeightDetail() {value={editWeight}onChange={setEditWeight}placeholder="0"- accessibilityLabel="Weight"+ accessibilityLabel={t('weight.log.weightField')}inputAccessoryViewID={NUMERIC_ACCESSORY_ID}/></StepperTile>- <DateInput label="Date" value={editDate} onChange={setEditDate} maximumDate={new Date()} />+ <DateInput label={t('weight.detail.date')} value={editDate} onChange={setEditDate} maximumDate={new Date()} /><Field- label="Notes (optional)"+ label={t('weight.detail.notesOptionalPlain')}value={editNotes}onChangeText={setEditNotes}- placeholder="e.g., morning, post-workout"+ placeholder={t('weight.detail.notePlaceholder')}maxLength={200}/><View className="flex-row items-center gap-2 pt-1"><View className="flex-1">- <Button title="Cancel" variant="secondary" onPress={() => { setEditing(false); setEditError('') }} />+ <Button title={t('common.cancel')} variant="secondary" onPress={() => { setEditing(false); setBadWeight(null) }} /></View><View className="flex-1">- <Button title={saveEdit.busy ? 'Saving…' : 'Save'} onPress={handleSave} loading={saveEdit.busy} disabled={!(parseFloat(editWeight) > 0) || saveEdit.busy} />+ <Button title={saveEdit.busy ? t('common.saving') : t('common.save')} onPress={handleSave} loading={saveEdit.busy} disabled={!(parseFloat(editWeight) > 0) || saveEdit.busy} /></View></View></View>@@ -233,8 +237,8 @@ export default function WeightDetail() {<ConfirmSheet{...deleteConfirmProps({- title: 'Delete Entry?',- subject: `${formatDay(entryDay(log), 'MMMM d, yyyy')} · ${displayWeight(log.weight, unit)} ${wUnit}`,+ title: t('weight.deleteTitle'),+ subject: t('weight.deleteSubject', { date: formatDay(entryDay(log), 'longDate'), weight: displayWeight(log.weight, unit), unit: wUnit }),})}open={confirming}busy={remove.busy}diff --git a/mobile/app/(tabs)/weight/index.tsx b/mobile/app/(tabs)/weight/index.tsxindex da37562..70a2b93 100644--- a/mobile/app/(tabs)/weight/index.tsx+++ b/mobile/app/(tabs)/weight/index.tsx@@ -1,13 +1,12 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { ActivityIndicator, FlatList, Pressable, RefreshControl, Text, View } from 'react-native'import { useFocusEffect } from 'expo-router'-import { format } from 'date-fns'import * as Haptics from 'expo-haptics'import {Activity, ArrowDown, ArrowUp, Calendar, Minus, Scale, Sunrise,TrendingDown, TrendingUp, X,} from 'lucide-react-native'-import { apiErrorMessage, useAsyncAction, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay } from '@lyftr/shared'+import { uiMessage, useAsyncAction, dayToInstant, daysAgoStr, displayToLbs, displayWeight, maxWeight, todayStr, weightError, weightShort, type WeightLog, type WeightStats, entryDay, dayToLocalDate, BODYWEIGHT_STEP, clampStep, formatDay, formatDate, useTranslation, type UiMessage } from '@lyftr/shared'import { Alert,AppText, BarbellBroken, Button, Card, DateInput, ErrorState, Field, Label, NumberField, NumericKeyboardAccessory,NUMERIC_ACCESSORY_ID, PageHeader, Screen, SegmentedControl, Skeleton, StatFailure, StepperTile,@@ -23,9 +22,9 @@ import { useTheme } from '../../../src/theme/useTheme'const PERIODS = ['7d', '30d', '90d', 'All'] as consttype Period = typeof PERIODS[number]const PERIOD_DAYS: Record<Period, number | null> = { '7d': 7, '30d': 30, '90d': 90, 'All': null }-const PERIOD_OPTIONS = PERIODS.map((p) => ({ value: p, label: p }))export default function Weight() {+ const { t, i18n } = useTranslation()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const unit = settings.weight_unit@@ -34,7 +33,9 @@ export default function Weight() {const [period, setPeriod] = useState<Period>('30d')const [stats, setStats] = useState<WeightStats | null>(null)- const [error, setError] = useState<string | null>(null)+ // The value the weight box was rejected for, not the sentence: the sentence is made at+ // render, so a banner already on screen follows a language switch.+ const [badWeight, setBadWeight] = useState<number | null>(null)// Paginated history list (newest-first) — the FlatList data.const fetcher = useCallback((offset: number, limit: number) => client.weightAPI.list({ offset, limit }), [])@@ -58,8 +59,8 @@ export default function Weight() {// Both reads used to swallow their failure, so the figures below fell back to 0 and// the screen rendered measurements it had never received.- const [chartError, setChartError] = useState<string | null>(null)- const [statsError, setStatsError] = useState<string | null>(null)+ const [chartError, setChartError] = useState<UiMessage | null>(null)+ const [statsError, setStatsError] = useState<UiMessage | null>(null)// Only the latest request may write. A wider window is a slower query, so tapping All// then 7d can land All's answer last, and every figure would then describe a period@@ -79,7 +80,7 @@ export default function Weight() {setChartPeriod(period)setChartError(null)})- .catch((err) => { if (id === chartRequest.current) setChartError(apiErrorMessage(err, "Couldn't load your weight trend.")) })+ .catch((err) => { if (id === chartRequest.current) setChartError({ key: 'weight.errors.trendFailed', cause: err }) }).finally(() => { if (id === chartRequest.current) setChartLoading(false) })}, [period])useEffect(() => { refetchChart() }, [refetchChart])@@ -89,7 +90,7 @@ export default function Weight() {const id = ++statsRequest.currentreturn client.weightAPI.stats().then((data) => { if (id === statsRequest.current) { setStats(data); setStatsError(null) } })- .catch((err) => { if (id === statsRequest.current) setStatsError(apiErrorMessage(err, "Couldn't load your weight stats.")) })+ .catch((err) => { if (id === statsRequest.current) setStatsError({ key: 'weight.errors.statsFailed', cause: err }) })}, [])useEffect(() => {fetchSettings()@@ -168,9 +169,9 @@ export default function Weight() {// this window's trend, however recent it is.(chartPeriod === period ? [...chartLogs] : []).reverse().map((l) => {const d = dayToLocalDate(entryDay(l))- return { date: format(d, 'M/d'), weight: displayWeight(l.weight, unit), sub: format(d, 'MMM d, yyyy') }+ return { date: formatDate(d, 'numericMonthDay'), weight: displayWeight(l.weight, unit), sub: formatDate(d, 'monthDayYear') }}),- [chartLogs, chartPeriod, period, unit]+ [chartLogs, chartPeriod, period, unit, i18n.language])const [chartWidth, setChartWidth] = useState(0)@@ -187,14 +188,14 @@ export default function Weight() {setShowNotes(false)duplicateWarningDismissedRef.current = falserefreshAll()- }, 'Failed to log weight')+ }, t('weight.log.failed'))const handleLog = async () => {if (log.busy) returnconst w = parseFloat(newWeight)const wErr = weightError(w, unit)if (wErr) {- setError(wErr)+ setBadWeight(w)return}@@ -204,7 +205,7 @@ export default function Weight() {return}- setError(null)+ setBadWeight(null)setShowDuplicateWarning(false)void log.run(w)}@@ -239,7 +240,7 @@ export default function Weight() {// called, so without this the screen tore itself down into a half-broken one for as// long as the requests took, then rebuilt the same error.const pageError = everythingFailed- ? (listError ?? chartError ?? statsError ?? '')+ ? (listError ?? (chartError ? uiMessage(chartError) : statsError ? uiMessage(statsError) : '')): retrying? heldPageError: null@@ -275,13 +276,15 @@ export default function Weight() {? 'bg-success-500/10 border-success-500/20': 'bg-error-500/10 border-error-500/20'const trendText = change === 0 ? colors.txMuted : change < 0 ? brand.successSoft : brand.errorSoft- const changeWord = change === 0 ? 'no change' : change < 0 ? 'lost' : 'gained'+ const changeKey = change === 0 ? 'weight.hero.changeNone' : change < 0 ? 'weight.hero.changeLost' : 'weight.hero.changeGained'const statCards = [- { label: 'Avg', value: avg, icon: Activity, color: accent },- { label: 'Low', value: min, icon: ArrowDown, color: brand.successSoft },- { label: 'High', value: max, icon: ArrowUp, color: brand.errorSoft },+ { id: 'avg' as const, value: avg, icon: Activity, color: accent },+ { id: 'low' as const, value: min, icon: ArrowDown, color: brand.successSoft },+ { id: 'high' as const, value: max, icon: ArrowUp, color: brand.errorSoft },]+ const periodOptions = PERIODS.map((p) => ({ value: p, label: t(`weight.period.chip.${p}`) }))+ const error = badWeight == null ? null : weightError(badWeight, unit)// Title and subtitle stay so the reader knows where they are; the unit chip does not,// and neither does the log form — a save that cannot succeed would outrank the retry.@@ -289,10 +292,10 @@ export default function Weight() {return (<Screen><View className="flex-1 gap-5 py-4">- <PageHeader title="Weight" subtitle="Track your body weight over time" />+ <PageHeader title={t('weight.title')} subtitle={t('weight.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your weight"+ title={t('weight.loadFailed')}message={pageError}onRetry={retryAll}retrying={retrying}@@ -319,8 +322,8 @@ export default function Weight() {ListHeaderComponent={<View className="gap-5 py-4"><PageHeader- title="Weight"- subtitle="Track your body weight over time"+ title={t('weight.title')}+ subtitle={t('weight.subtitle')}action={<View className="flex-row items-center gap-1.5 rounded-full border border-brand-500/25 bg-brand-500/10 px-3 py-1"><Calendar size={12} color={accent} />@@ -334,11 +337,11 @@ export default function Weight() {<View className="mb-3 flex-row items-center justify-between"><View className="flex-row items-center gap-2"><Scale size={16} color={accent} />- <AppText variant="bodySemibold">Log Weight</AppText>+ <AppText variant="bodySemibold">{t('weight.log.title')}</AppText></View>{items.length > 0 ? (<AppText variant="caption" color="muted">- last: {displayWeight(items[0].weight, unit)} {wUnit}+ {t('weight.log.last', { weight: displayWeight(items[0].weight, unit), unit: wUnit })}</AppText>) : null}</View>@@ -346,8 +349,8 @@ export default function Weight() {<View className="gap-3"><StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('weight.log.weightLabel', { unit: wUnit })}+ name={t('weight.log.weightName')}step={BODYWEIGHT_STEP}onStep={(d) => setNewWeight(String(clampStep(parseFloat(newWeight) || 0, d, { min: 0, max: maxWeight(unit) })))}>@@ -356,7 +359,7 @@ export default function Weight() {value={newWeight}onChange={setNewWeight}placeholder="0"- accessibilityLabel="Weight"+ accessibilityLabel={t('weight.log.weightField')}inputAccessoryViewID={NUMERIC_ACCESSORY_ID}/></StepperTile>@@ -364,8 +367,8 @@ export default function Weight() {{showNotes ? (<View className="gap-2 rounded-xl border border-surface-border bg-surface-overlay p-3"><View className="mb-1 flex-row items-center justify-between">- <AppText variant="caption" color="secondary">Date & note</AppText>- <Pressable onPress={() => setShowNotes(false)} hitSlop={8} className="p-1 active:opacity-60" accessibilityLabel="Collapse">+ <AppText variant="caption" color="secondary">{t('weight.log.dateAndNote')}</AppText>+ <Pressable onPress={() => setShowNotes(false)} hitSlop={8} className="p-1 active:opacity-60" accessibilityLabel={t('weight.log.collapse')}><X size={14} color={colors.txMuted} /></Pressable></View>@@ -373,7 +376,7 @@ export default function Weight() {<Fieldvalue={newNotes}onChangeText={setNewNotes}- placeholder="Note — e.g. morning, post-run"+ placeholder={t('weight.log.notePlaceholder')}maxLength={200}/></View>@@ -383,7 +386,7 @@ export default function Weight() {className="h-11 flex-row items-center justify-center gap-2 rounded-xl border border-surface-border bg-surface-overlay active:scale-[0.99]"><Calendar size={16} color={colors.txMuted} />- <AppText variant="body" color="secondary">Add date & note</AppText>+ <AppText variant="body" color="secondary">{t('weight.log.addDateAndNote')}</AppText></Pressable>)}@@ -395,9 +398,9 @@ export default function Weight() {<Alertvariant="warning"actions={[- { label: 'Cancel', onPress: () => setShowDuplicateWarning(false) },+ { label: t('common.cancel'), onPress: () => setShowDuplicateWarning(false) },{- label: 'Log Anyway',+ label: t('weight.log.logAnyway'),primary: true,onPress: () => {duplicateWarningDismissedRef.current = true@@ -407,19 +410,19 @@ export default function Weight() {},]}>- Already logged on {formatDay(entryDay(items[0]), 'MMM d')} ({displayWeight(items[0].weight, unit)} {wUnit}). Log again anyway?+ {t('weight.duplicateWarning', { date: formatDay(entryDay(items[0]), 'monthDay'), weight: displayWeight(items[0].weight, unit), unit: wUnit })}</Alert>) : null}<Button- title={log.busy ? 'Logging…' : 'Log Weight'}+ title={log.busy ? t('weight.log.submitting') : t('weight.log.submit')}onPress={handleLog}loading={log.busy}disabled={!(parseFloat(newWeight) > 0) || log.busy}/><View className="flex-row items-center justify-center gap-1.5"><Sunrise size={14} color={brand.warningSoft} />- <AppText variant="caption" color="muted">Best logged in the morning, after the bathroom</AppText>+ <AppText variant="caption" color="muted">{t('weight.log.tip')}</AppText></View></View></Card>@@ -431,21 +434,21 @@ export default function Weight() {// cannot be the default: it told someone with years of entries they had// never weighed themselves.<ErrorState- title="Couldn't load your weight"- message={listError ?? chartError ?? statsError ?? ''}+ title={t('weight.loadFailed')}+ message={listError ?? (chartError ? uiMessage(chartError) : statsError ? uiMessage(statsError) : '')}onRetry={retryAll}retrying={retrying}/>) : items.length === 0 ? (<View className="items-center py-2">- <Label className="mb-1">Current Weight</Label>- <AppText variant="body" color="muted">The scale doesn't know you exist yet. Fix that.</AppText>+ <Label className="mb-1">{t('weight.hero.current')}</Label>+ <AppText variant="body" color="muted">{t('weight.hero.empty')}</AppText></View>) : (<><View className="flex-row items-start justify-between"><View>- <Label className="mb-2">Current Weight</Label>+ <Label className="mb-2">{t('weight.hero.current')}</Label><View className="flex-row items-end gap-2"><AppText variant="display" style={{ fontSize: 40, lineHeight: 44, fontVariant: ['tabular-nums'] }}>{currentKnown ? current : '—'}</AppText>{currentKnown ? <AppText variant="body" color="muted" className="mb-1.5">{wUnit}</AppText> : null}@@ -462,7 +465,7 @@ export default function Weight() {</View>{changeKnown ? (<AppText variant="caption" color="muted" className="mt-3">- {Math.abs(change)} {wUnit} {changeWord} over {period}+ {t(changeKey, { amount: Math.abs(change), unit: wUnit, period: t(`weight.period.span.${period}`) })}</AppText>) : null}</>@@ -472,15 +475,15 @@ export default function Weight() {{/* Stats row */}<View className="flex-row gap-3">{statCards.map((s) => (- <Card key={s.label} className="flex-1" style={{ paddingHorizontal: 12 }}>+ <Card key={s.id} className="flex-1" style={{ paddingHorizontal: 12 }}><View className="mb-2 flex-row items-center gap-1.5"><s.icon size={14} color={s.color} />- <Label numberOfLines={1}>{s.label}</Label>+ <Label numberOfLines={1}>{t(`weight.stats.${s.id}.label`)}</Label></View>{chartPending ? (<Skeleton width={56} height={22} />) : figuresFailed ? (- <StatFailure label={`Couldn't load ${s.label.toLowerCase()} weight`} />+ <StatFailure label={t(`weight.stats.${s.id}.failed`)} />) : (<View className="flex-row items-end gap-1"><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{aggregatesUnknown ? '—' : Math.round(s.value)}</AppText>@@ -496,9 +499,9 @@ export default function Weight() {{/* The same mark every other failure on this screen uses, in warning inkrather than error: these numbers are real, just not fresh. */}<BarbellBroken size={20} color={semanticInk[isDark ? 'dark' : 'light'].warning} />- <AppText variant="caption" color="muted">Couldn't refresh these — showing the last we loaded.</AppText>+ <AppText variant="caption" color="muted">{t('weight.stale')}</AppText><Pressable onPress={retryAll} hitSlop={8} accessibilityRole="button" className="active:opacity-60">- <AppText variant="caption" color="secondary" className="underline">Try again</AppText>+ <AppText variant="caption" color="secondary" className="underline">{t('common.tryAgain')}</AppText></Pressable></View>) : null}@@ -506,9 +509,9 @@ export default function Weight() {{/* Chart + period selector */}<Card><View className="mb-3 flex-row items-center justify-between gap-2">- <AppText variant="bodySemibold">Trend</AppText>+ <AppText variant="bodySemibold">{t('weight.trend.title')}</AppText><View className="flex-1 max-w-[220px]">- <SegmentedControl size="sm" options={PERIOD_OPTIONS} value={period} onChange={setPeriod} />+ <SegmentedControl size="sm" options={periodOptions} value={period} onChange={setPeriod} /></View></View><View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>@@ -517,11 +520,11 @@ export default function Weight() {<Skeleton width="100%" height={120} radius={12} /></View>) : chartData.length === 0 && chartError ? (- <ErrorState title="Couldn't load your trend" message={chartError} onRetry={retryAll} retrying={retrying} />+ <ErrorState title={t('weight.trend.loadFailed')} message={uiMessage(chartError)} onRetry={retryAll} retrying={retrying} />) : chartData.length < 2 ? (<View className="h-44 items-center justify-center"><AppText variant="body" color="muted">- {chartData.length === 0 ? 'No data for this period' : 'Log another entry to see the trend'}+ {chartData.length === 0 ? t('weight.trend.noData') : t('weight.trend.needMore')}</AppText></View>) : (@@ -530,7 +533,7 @@ export default function Weight() {</View></Card>- {items.length > 0 ? <Label className="px-1">History</Label> : null}+ {items.length > 0 ? <Label className="px-1">{t('weight.history.title')}</Label> : null}</View>}renderItem={({ item, index }) => (@@ -545,7 +548,7 @@ export default function Weight() {// Only under rows that arrived: with none, the hero above already carries the// failure, and saying it twice is two retries for one problem.listError && items.length > 0 ? (- <ErrorState title="Couldn't load more entries" message={listError} onRetry={retryList} />+ <ErrorState title={t('weight.history.loadMoreFailed')} message={listError} onRetry={retryList} />) : hasMore && loading && items.length > 0 ? (<View className="items-center py-3"><ActivityIndicator size="small" color={accent} />diff --git a/mobile/app/(tabs)/workouts/[id].tsx b/mobile/app/(tabs)/workouts/[id].tsxindex 5d8527a..f4373b6 100644--- a/mobile/app/(tabs)/workouts/[id].tsx+++ b/mobile/app/(tabs)/workouts/[id].tsx@@ -4,18 +4,19 @@ import { router, useLocalSearchParams, type Href } from 'expo-router'import {ArrowLeft, ChevronRight, Clock, Edit2, Layers, Pause, TimerOff, Trash2, TrendingUp,} from 'lucide-react-native'-import { useAsyncAction, apiErrorMessage, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'+import { useAsyncAction, displayVolume, displayWeight, weightShort, type Workout, type Set as WorkoutSet, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { AppText, Button, ConfirmSheet, ErrorState, Loading, Screen, deleteConfirmProps } from '../../../src/components/ui'import { ExerciseImage } from '../../../src/components/workouts/ExerciseImage'import { client, useSettingsStore } from '../../../src/lib/lyftr'import { useTheme } from '../../../src/theme/useTheme'-import { muscleColor } from '../../../src/utils/exerciseUtils'+import { muscleColor, muscleLabel } from '../../../src/utils/exerciseUtils'// Exercise-detail leaf (workouts/exercise/[exerciseId]) — 1:1 port of web ExerciseDetail.const exerciseHref = (exerciseId: number) => `/workouts/exercise/${exerciseId}` as unknown as Hreffunction SetChip({ set, isBest, unit }: { set: WorkoutSet; isBest: boolean; unit: string }) {+ const { t } = useTranslation()return (// Web's ring-1 → a real border; non-best chips get border-transparent so both// states are the same size (RN borders take layout space, rings don't).@@ -29,7 +30,7 @@ function SetChip({ set, isBest, unit }: { set: WorkoutSet; isBest: boolean; unitcolor={isBest ? 'brand' : 'secondary'}style={{ fontVariant: ['tabular-nums'] }}>- {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${displayWeight(set.weight, unit)} ${unit}` : 'BW'}+ {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${displayWeight(set.weight, unit)} ${unit}` : t('weight.bodyweightShort')}</AppText></View>)@@ -42,13 +43,14 @@ function MuscleBadge({ muscle }: { muscle: string }) {<View className={`px-1.5 py-0.5 rounded ${tint?.chip ?? 'bg-surface-muted'}`}>{/* Tint via inline style — see exerciseUtils.ts for why not a className. */}<AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>- {muscle}+ {muscleLabel(muscle)}</AppText></View>)}export default function WorkoutDetail() {+ const { t } = useTranslation()const { id } = useLocalSearchParams<{ id: string }>()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)@@ -58,7 +60,8 @@ export default function WorkoutDetail() {const [workout, setWorkout] = useState<Workout | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // A UiMessage, not its sentence, so the banner follows a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Bumping this re-runs the load effect — three lines, rather than restructuring a// working effect to gain a retry button.const [retryKey, setRetryKey] = useState(0)@@ -75,7 +78,7 @@ export default function WorkoutDetail() {const data = await client.workoutAPI.get(Number(id))if (!cancelled) setWorkout(data)} catch (err) {- if (!cancelled) setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ if (!cancelled) setError({ key: 'settings.unknownError', cause: err })} finally {if (!cancelled) setLoading(false)}@@ -95,7 +98,7 @@ export default function WorkoutDetail() {if (!workout) returnawait client.workoutAPI.delete(workout.id)goBack() // list refetches on focus- }, 'Failed to delete workout')+ }, t('workouts.deleteFailed'))if (loading) return <Loading />@@ -106,10 +109,10 @@ export default function WorkoutDetail() {<View className="flex-1 py-4"><ErrorStatesize="page"- title="Couldn't load this workout"- message={error ?? 'That workout no longer exists.'}+ title={t('workouts.detail.loadFailed')}+ message={error ? uiMessage(error) : t('workouts.detail.gone')}onRetry={error ? () => { setError(null); setRetryKey((k) => k + 1) } : undefined}- secondary={<Button title="Back to workouts" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('workouts.detail.backToWorkouts')} variant="secondary" onPress={goBack} />}/></View></Screen>@@ -129,7 +132,7 @@ export default function WorkoutDetail() {<View className="flex-row items-center justify-between"><Pressable onPress={goBack} hitSlop={8} className="flex-row items-center gap-1.5 active:opacity-60"><ArrowLeft size={16} color={colors.txMuted} />- <AppText variant="body" color="muted">Workouts</AppText>+ <AppText variant="body" color="muted">{t('workouts.detail.back')}</AppText></Pressable><View className="flex-row items-center gap-2">{/* Clear hierarchy over two competing colored squares: Edit is the@@ -138,17 +141,17 @@ export default function WorkoutDetail() {Both are h-9 so they read as a matched pair. */}<PressableaccessibilityRole="button"- accessibilityLabel="Edit workout"+ accessibilityLabel={t('workouts.detail.editLabel')}onPress={() => router.push(`/workouts/${workout.id}/edit`)}hitSlop={6}className="h-9 flex-row items-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 px-3 active:scale-95"><Edit2 size={15} color={accent} strokeWidth={2.2} />- <AppText variant="label" style={{ color: accent }}>Edit</AppText>+ <AppText variant="label" style={{ color: accent }}>{t('common.edit')}</AppText></Pressable><PressableaccessibilityRole="button"- accessibilityLabel="Delete workout"+ accessibilityLabel={t('workouts.detail.deleteLabel')}onPress={() => setConfirming(true)}disabled={remove.busy}hitSlop={6}@@ -161,7 +164,7 @@ export default function WorkoutDetail() {{/* Delete confirm — slide-up bottom sheet (mirrors web's portal sheet). */}<ConfirmSheet- {...deleteConfirmProps({ title: 'Delete Workout?', subject: `"${workout.name}"` })}+ {...deleteConfirmProps({ title: t('workouts.deleteConfirmTitle'), subject: `"${workout.name}"` })}open={confirming}busy={remove.busy}error={remove.error}@@ -176,7 +179,7 @@ export default function WorkoutDetail() {<View className="flex-1"><AppText variant="heading">{workout.name}</AppText><AppText variant="body" color="muted" className="mt-0.5">- {formatDay(workoutDay(workout), 'EEEE, MMMM d, yyyy')}+ {formatDay(workoutDay(workout), 'weekdayDate')}</AppText></View></View>@@ -186,24 +189,24 @@ export default function WorkoutDetail() {<View className="flex-1 items-center"><View className="flex-row items-center gap-1 mb-0.5"><Clock size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Duration</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.duration')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{durationMin}- <AppText variant="caption" color="muted"> min</AppText>+ <AppText variant="caption" color="muted"> {t('workouts.detail.minutesUnit')}</AppText></AppText></View><View className="flex-1 items-center border-x border-surface-border"><View className="flex-row items-center gap-1 mb-0.5"><Layers size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Sets</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.sets')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{totalSets}</AppText></View><View className="flex-1 items-center"><View className="flex-row items-center gap-1 mb-0.5"><TrendingUp size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Volume</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.volume')}</AppText></View><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>{totalVolume > 0 ? totalVolume.toLocaleString() : '—'}@@ -223,7 +226,7 @@ export default function WorkoutDetail() {{!restOn && (<View className="flex-row items-center gap-1.5 px-1"><TimerOff size={13} color={colors.txMuted} />- <AppText variant="caption" color="muted">Rest timer is off — turn it on in Settings</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.restOff')}</AppText></View>)}<View className="gap-3">@@ -232,6 +235,10 @@ export default function WorkoutDetail() {const maxWeightLbs = sets.length > 0 ? Math.max(...sets.map((s) => s.weight || 0)) : 0const maxWeight = displayWeight(maxWeightLbs, wUnit)const exVol = displayVolume(exerciseVolume(sets), wUnit)+ const setsSummary = [+ t('workouts.detail.setCount', { count: sets.length }),+ ...(exVol > 0 ? [`${exVol.toLocaleString()} ${wUnit}`] : []),+ ].join(' · ')return (<Pressable@@ -250,13 +257,13 @@ export default function WorkoutDetail() {<View className="flex-row items-center gap-2 mt-0.5">{ex.exercise?.muscle_group ? <MuscleBadge muscle={ex.exercise.muscle_group} /> : null}<AppText variant="caption" color="muted" numberOfLines={1} className="flex-shrink">- {sets.length} sets{exVol > 0 ? ` · ${exVol.toLocaleString()} ${wUnit}` : ''}+ {setsSummary}</AppText></View></View>{maxWeight > 0 && (<View className="items-end mr-1">- <AppText variant="label" color="muted">best</AppText>+ <AppText variant="label" color="muted">{t('workouts.detail.best')}</AppText><AppText variant="subheading" color="brand" style={{ fontVariant: ['tabular-nums'] }}>{maxWeight} {wUnit}</AppText>@@ -274,7 +281,7 @@ export default function WorkoutDetail() {</View>{restOn && (ex.rest_seconds === 0 ? (- <AppText variant="caption" color="muted">No rest</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.noRest')}</AppText>) : (<View className="flex-row items-center gap-1"><Pause size={13} color={colors.txMuted} />diff --git a/mobile/app/(tabs)/workouts/[id]/edit.tsx b/mobile/app/(tabs)/workouts/[id]/edit.tsxindex 016de9a..d2f7360 100644--- a/mobile/app/(tabs)/workouts/[id]/edit.tsx+++ b/mobile/app/(tabs)/workouts/[id]/edit.tsx@@ -5,7 +5,7 @@ import {AlertCircle, ArrowLeft, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,} from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { apiErrorMessage, useAsyncAction, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay } from '@lyftr/shared'+import { useAsyncAction, dayToInstant, displayToLbs, lbsToDisplay, weightShort, type Exercise, workoutDay, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { AppText, Button, DateInput, EmptyState, ErrorState, Field, IconButton, Label, Loading, Screen } from '../../../../src/components/ui'import { ExerciseFormCard } from '../../../../src/components/workouts/ExerciseFormCard'import { DurationField } from '../../../../src/components/workouts/DurationField'@@ -51,6 +51,7 @@ function FieldHeader({ icon: Icon, label, hint }: { icon: LucideIcon; label: str}export default function EditWorkout() {+ const { t } = useTranslation()const { id } = useLocalSearchParams<{ id: string }>()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)@@ -60,11 +61,12 @@ export default function EditWorkout() {const [showPicker, setShowPicker] = useState(false)const [initialLoading, setInitialLoading] = useState(true)// Only what the FORM can say before anything is sent. What the SERVER says lives- // on `save` below; both render in the same alert.- const [error, setError] = useState('')+ // on `save` below; both render in the same alert. Both messages here are a UiMessage+ // rather than a sentence, so they follow a language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Separate from `error`, which is this form's own validation. A load that never// arrived is not a missing field — there is nothing to edit.- const [loadError, setLoadError] = useState<string | null>(null)+ const [loadError, setLoadError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', date: '', duration: 0, exercises: [] })@@ -112,7 +114,7 @@ export default function EditWorkout() {})),})})- .catch((err) => setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ .catch((err) => setLoadError({ key: 'settings.unknownError', cause: err })).finally(() => setInitialLoading(false))// Web effect deps: [id] only — settings are fetched before a user can navigate here.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -135,7 +137,7 @@ export default function EditWorkout() {],}))setShowPicker(false)- setError('')+ setError(null)}// Stable + immutable so the memoized ExerciseFormCard only re-renders the edited card,@@ -201,16 +203,16 @@ export default function EditWorkout() {// Web navigates to /workouts. Pop past the (stale) detail screen back to the// list — the detail refetches on next visit; the list reloads on focus.router.dismissTo('/workouts')- }, 'Failed to update workout')+ }, t('workouts.form.updateFailed'))useEffect(() => {if (error || save.error) scrollRef.current?.scrollTo({ y: 0, animated: true })- }, [error, save.error])+ }, [error, save.failureKey])const handleSubmit = async () => {- if (!formData.name.trim()) { setError('Workout name required'); return }- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }- setError('')+ if (!formData.name.trim()) { setError({ key: 'workouts.form.errors.nameRequired' }); return }+ if (formData.exercises.length === 0) { setError({ key: 'workouts.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -219,10 +221,10 @@ export default function EditWorkout() {<Screen><ErrorStatesize="page"- title="Couldn't load this workout"- message={loadError}+ title={t('workouts.detail.loadFailed')}+ message={uiMessage(loadError)}onRetry={() => { setLoadError(null); setRetryKey((k) => k + 1) }}- secondary={<Button title="Back to workouts" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('workouts.detail.backToWorkouts')} variant="secondary" onPress={goBack} />}/></Screen>)@@ -237,6 +239,13 @@ export default function EditWorkout() {(sum, ex) => sum + ex.sets.reduce((s, set) => s + (set.weight || 0), 0),0)+ const counts = {+ exercises: t('workouts.form.exerciseCount', { count: formData.exercises.length }),+ sets: t('workouts.form.setCount', { count: totalSets }),+ }+ const summary = totalWeight > 0+ ? t('workouts.form.summaryWithWeight', { ...counts, weight: Math.round(totalWeight), unit: wUnit })+ : t('workouts.form.summary', counts)return (<Screen>@@ -252,28 +261,25 @@ export default function EditWorkout() {><View className="gap-6 py-4"><View className="flex-row items-center gap-3">- <IconButton icon={ArrowLeft} label="Back" variant="ghost" size="md" onPress={goBack} />+ <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} /><View>- <AppText variant="title">Edit Workout</AppText>- <AppText variant="caption" color="muted">- {formData.exercises.length} exercises • {totalSets} sets- {totalWeight > 0 ? ` • ${Math.round(totalWeight)} ${wUnit}` : ''}- </AppText>+ <AppText variant="title">{t('workouts.form.editTitle')}</AppText>+ <AppText variant="caption" color="muted">{summary}</AppText></View></View>{error || save.error ? (<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4"><AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />- <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>+ <AppText variant="body" color="error" className="flex-1">{error ? uiMessage(error) : save.error}</AppText></View>) : null}<View>- <FieldHeader icon={Dumbbell} label="Workout Name" />+ <FieldHeader icon={Dumbbell} label={t('workouts.form.name')} /><Fieldvalue={formData.name}- onChangeText={(t) => setFormData((prev) => ({ ...prev, name: t }))}+ onChangeText={(text) => setFormData((prev) => ({ ...prev, name: text }))}/></View>@@ -281,7 +287,7 @@ export default function EditWorkout() {shifts the day; the original time-of-day is preserved on submit. */}<View className="flex-row gap-3"><View className="flex-[2]">- <FieldHeader icon={CalendarDays} label="Date" />+ <FieldHeader icon={CalendarDays} label={t('workouts.form.date')} /><DateInputvalue={formData.date}onChange={(d) => setFormData((prev) => ({ ...prev, date: d }))}@@ -290,7 +296,7 @@ export default function EditWorkout() {</View><View className="flex-1">{/* "min" already rides the value, so the label stays just "Duration". */}- <FieldHeader icon={Clock} label="Duration" />+ <FieldHeader icon={Clock} label={t('workouts.form.duration')} /><DurationFieldvalue={formData.duration}onChange={(m) => setFormData((prev) => ({ ...prev, duration: m }))}@@ -300,10 +306,10 @@ export default function EditWorkout() {</View><View>- <FieldHeader icon={FileText} label="Notes" />+ <FieldHeader icon={FileText} label={t('workouts.form.notes')} /><Fieldvalue={formData.notes}- onChangeText={(t) => setFormData((prev) => ({ ...prev, notes: t }))}+ onChangeText={(text) => setFormData((prev) => ({ ...prev, notes: text }))}multiline/></View>@@ -313,7 +319,7 @@ export default function EditWorkout() {<View className="mb-3 flex-row items-center justify-between"><View className="flex-row items-center gap-2"><Zap size={14} color={accent} strokeWidth={2.2} />- <Label>Exercises</Label>+ <Label>{t('workouts.form.exercises')}</Label></View><PressableaccessibilityRole="button"@@ -321,7 +327,7 @@ export default function EditWorkout() {className="flex-row items-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2 active:scale-95"><Plus size={13} color="#ffffff" />- <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>+ <Text className="font-sans-semibold text-xs text-white">{t('workouts.form.addExercise')}</Text></Pressable></View>@@ -330,8 +336,8 @@ export default function EditWorkout() {<EmptyStatecompacticon={Dumbbell}- title="No exercises"- subtitle="Add an exercise to this workout"+ title={t('workouts.form.empty.editTitle')}+ subtitle={t('workouts.form.empty.editHint')}/></View>)}@@ -361,12 +367,12 @@ export default function EditWorkout() {{formData.exercises.length > 0 && (<PressableaccessibilityRole="button"- accessibilityLabel="Add exercise"+ accessibilityLabel={t('workouts.form.addExerciseLabel')}onPress={() => setShowPicker(true)}className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"><Plus size={14} color={accent} />- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>+ <Text className="font-sans-semibold text-xs" style={{ color: accent }}>{t('workouts.form.addExercise')}</Text></Pressable>)}</View>@@ -378,8 +384,8 @@ export default function EditWorkout() {{/* Sticky footer actions — Save stays reachable however long the form grows.-mx-5 lets the divider span edge-to-edge past Screen's px-5. */}<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">- <Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />- <Button title="Save Changes" className="flex-1" onPress={handleSubmit} loading={save.busy} />+ <Button title={t('common.cancel')} variant="secondary" className="flex-1" onPress={goBack} />+ <Button title={t('workouts.form.saveChanges')} className="flex-1" onPress={handleSubmit} loading={save.busy} /></View>{/* iOS-only Done bar docked above the numeric keypads (they have no return key). */}diff --git a/mobile/app/(tabs)/workouts/active.tsx b/mobile/app/(tabs)/workouts/active.tsxindex 0d299d8..577b26e 100644--- a/mobile/app/(tabs)/workouts/active.tsx+++ b/mobile/app/(tabs)/workouts/active.tsx@@ -3,7 +3,7 @@ import { Keyboard, Pressable, ScrollView, Text, View } from 'react-native'import * as Haptics from 'expo-haptics'import { router } from 'expo-router'import { CheckCircle2, Dumbbell, Flag, Plus, Timer, X } from 'lucide-react-native'-import { useAsyncAction, weightShort, type Exercise, formatElapsed, useElapsedSeconds } from '@lyftr/shared'+import { useAsyncAction, weightShort, type Exercise, formatElapsed, useElapsedSeconds, useTranslation } from '@lyftr/shared'import { AppText, ConfirmSheet, NumericKeyboardAccessory, Screen } from '../../../src/components/ui'import { ActiveExerciseCard } from '../../../src/components/workouts/ActiveExerciseCard'import { ExercisePicker } from '../../../src/components/workouts/ExercisePicker'@@ -14,6 +14,7 @@ import { useWorkoutOutcome } from '../../../src/lib/workoutOutcome'import { useTheme } from '../../../src/theme/useTheme'export default function ActiveWorkout() {+ const { t } = useTranslation()const session = useWorkoutSession((s) => s.session)const updateSet = useWorkoutSession((s) => s.updateSet)const updateExerciseNotes = useWorkoutSession((s) => s.updateExerciseNotes)@@ -62,7 +63,7 @@ export default function ActiveWorkout() {setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })cancelSession()router.replace('/workouts')- }, 'Failed to save workout')+ }, t('workouts.active.saveFailed'))const jumpToExercise = useCallback((idx: number) => {setActiveExIdx(idx)@@ -118,10 +119,10 @@ export default function ActiveWorkout() {<View className="h-12 w-12 items-center justify-center rounded-xl border border-surface-border bg-surface-muted"><Dumbbell size={24} color={colors.txMuted} /></View>- <AppText variant="bodySemibold">No active workout</AppText>- <AppText variant="caption" color="muted">Start one from the Workouts tab</AppText>+ <AppText variant="bodySemibold">{t('workouts.active.noWorkout.title')}</AppText>+ <AppText variant="caption" color="muted">{t('workouts.active.noWorkout.hintTab')}</AppText><Pressable onPress={goHome} className="mt-2 rounded-xl bg-brand-500 px-4 py-2.5 active:scale-95">- <AppText variant="bodySemibold" color="white">Go to Workouts</AppText>+ <AppText variant="bodySemibold" color="white">{t('workouts.active.noWorkout.goWorkouts')}</AppText></Pressable></View></Screen>@@ -144,7 +145,7 @@ export default function ActiveWorkout() {<Timer size={14} color={accent} /><Text className="font-sans text-sm" style={{ color: accent, fontVariant: ['tabular-nums'] }}>{formatElapsed(elapsed)}</Text></View>- <AppText variant="caption" color="muted">{completedSets}/{totalSets} sets done</AppText>+ <AppText variant="caption" color="muted">{t('workouts.active.setsDone', { done: completedSets, total: totalSets })}</AppText></View></View><Pressable@@ -152,7 +153,7 @@ export default function ActiveWorkout() {className={`flex-row items-center gap-2 rounded-xl px-5 py-2.5 active:scale-95 ${allComplete ? 'bg-brand-500' : 'border border-brand-500/30 bg-brand-500/10'}`}><Flag size={16} color={allComplete ? '#ffffff' : accent} />- <Text className={`font-sans-bold text-sm ${allComplete ? 'text-white' : ''}`} style={allComplete ? undefined : { color: accent }}>Finish</Text>+ <Text className={`font-sans-bold text-sm ${allComplete ? 'text-white' : ''}`} style={allComplete ? undefined : { color: accent }}>{t('workouts.active.finish')}</Text></Pressable></View>{/* progress bar */}@@ -198,8 +199,8 @@ export default function ActiveWorkout() {{session.exercises.length === 0 ? (<View className="items-center gap-1 py-16"><Dumbbell size={28} color={colors.txMuted} />- <AppText variant="bodySemibold" className="mt-2">No exercises yet</AppText>- <AppText variant="caption" color="muted">Add exercises below</AppText>+ <AppText variant="bodySemibold" className="mt-2">{t('workouts.active.empty.title')}</AppText>+ <AppText variant="caption" color="muted">{t('workouts.active.empty.hint')}</AppText></View>) : (session.exercises.map((ex, exIdx) => (@@ -228,10 +229,10 @@ export default function ActiveWorkout() {<View className="mt-2 gap-2"><Pressable onPress={() => setShowPicker(true)} className="flex-row items-center justify-center gap-2 rounded-2xl border border-surface-border bg-surface-muted py-3.5 active:scale-95"><Plus size={16} color={colors.txSecondary} />- <Text className="font-sans-semibold text-sm text-tx-secondary">Add Exercise</Text>+ <Text className="font-sans-semibold text-sm text-tx-secondary">{t('workouts.active.addExercise')}</Text></Pressable><Pressable onPress={() => setConfirmCancel(true)} className="items-center py-2.5 active:opacity-60">- <Text className="font-sans text-xs text-tx-muted">Cancel Workout</Text>+ <Text className="font-sans text-xs text-tx-muted">{t('workouts.active.cancelWorkout')}</Text></Pressable></View></ScrollView>@@ -240,11 +241,11 @@ export default function ActiveWorkout() {<ConfirmSheetopen={confirmFinish}icon={Flag}- title="Finish Workout?"- message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}- confirmLabel="Finish"- busyLabel="Saving…"- cancelLabel="Keep Going"+ title={t('workouts.active.finishConfirm.title')}+ message={t('workouts.active.finishConfirm.message', { done: completedSets, total: totalSets })}+ confirmLabel={t('workouts.active.finish')}+ busyLabel={t('common.saving')}+ cancelLabel={t('workouts.active.keepGoing')}busy={finish.busy}error={finish.error}onConfirm={() => { void finish.run() }}@@ -256,10 +257,10 @@ export default function ActiveWorkout() {open={confirmCancel}icon={X}destructive- title="Cancel Workout?"- message="All progress will be lost."- confirmLabel="Cancel Workout"- cancelLabel="Keep Going"+ title={t('workouts.active.cancelConfirm.title')}+ message={t('workouts.active.cancelConfirm.message')}+ confirmLabel={t('workouts.active.cancelWorkout')}+ cancelLabel={t('workouts.active.keepGoing')}onConfirm={() => { setOutcome({ kind: 'discarded', session }); cancelSession(); router.replace('/workouts') }}onCancel={() => setConfirmCancel(false)}/>diff --git a/mobile/app/(tabs)/workouts/index.tsx b/mobile/app/(tabs)/workouts/index.tsxindex 0e416e2..dd130fd 100644--- a/mobile/app/(tabs)/workouts/index.tsx+++ b/mobile/app/(tabs)/workouts/index.tsx@@ -3,7 +3,7 @@ import { ActivityIndicator, FlatList, 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 { format } from 'date-fns'-import { weightShort, workoutDay, type Workout } from '@lyftr/shared'+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'import { WorkoutCard } from '../../../src/components/workouts/WorkoutCard'import { WorkoutsSkeleton } from '../../../src/components/workouts/WorkoutsSkeleton'@@ -17,6 +17,7 @@ import { useTheme } from '../../../src/theme/useTheme'const programHref = (id: number) => `/programs/${id}` as unknown as Hrefexport default function Workouts() {+ const { t } = useTranslation()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const unit = weightShort(settings.weight_unit)@@ -100,8 +101,8 @@ export default function Workouts() {<Toastvariant={outcome.progression.is_pr ? 'warning' : 'success'}icon={outcome.progression.is_pr ? Award : TrendingUp}- title={outcome.progression.is_pr ? `New PR in ${outcome.progression.program_name}` : `New targets in ${outcome.progression.program_name}`}- description={`Tap to review ${outcome.progression.count} ${outcome.progression.count === 1 ? 'update' : 'updates'}`}+ title={outcome.progression.is_pr ? t('workouts.toast.newPr', { name: outcome.progression.program_name }) : t('workouts.toast.newTargets', { name: outcome.progression.program_name })}+ description={t('workouts.toast.reviewUpdates', { count: outcome.progression.count })}onPress={() => {const programId = outcome.progression!.program_idclearOutcome()@@ -113,8 +114,8 @@ export default function Workouts() {<Toastvariant="success"icon={CheckCircle2}- title="Workout saved"- description="Tap to view"+ title={t('workouts.toast.saved')}+ description={t('workouts.toast.tapToView')}onPress={() => {clearOutcome()router.push(`/workouts/${outcome.workoutId}`)@@ -126,8 +127,8 @@ export default function Workouts() {<Toastvariant="default"icon={RotateCcw}- title="Workout discarded"- description="Tap to undo"+ title={t('workouts.toast.discarded')}+ description={t('workouts.toast.tapToUndo')}onPress={() => {restoreSession(outcome.session)clearOutcome()@@ -148,8 +149,8 @@ export default function Workouts() {return (<Screen><View className="flex-1 gap-5 py-4">- <PageHeader title="Workouts" subtitle="Track and review your training sessions" />- <ErrorState size="page" title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />+ <PageHeader title={t('workouts.list.title')} subtitle={t('workouts.list.subtitle')} />+ <ErrorState size="page" title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} /></View>{outcomeToast}</Screen>@@ -170,23 +171,25 @@ export default function Workouts() {// These summarize the *loaded* items; while pages remain, the total is a lower bound.// A failed page counts as "pages remain": the hook drops hasMore on error, and// without listError here a dropped connection made the count look more certain.- { label: 'Total', value: mayHaveMore ? `${workouts.length}+` : String(workouts.length), unit: 'logged' },+ { label: t('workouts.stats.total'), failed: t('workouts.stats.totalFailed'), value: mayHaveMore ? `${workouts.length}+` : String(workouts.length), unit: t('workouts.stats.logged') },{- label: 'This Month',+ label: t('workouts.stats.thisMonth'),+ failed: t('workouts.stats.thisMonthFailed'),// The month the workout was logged in, not the month its UTC instant lands in —// a session near a month boundary belongs to the month the lifter trained in.// Newest-first paging means we have seen the whole month only once a loaded row// predates it; until then the count is a lower bound and says so, like Total.value: monthCountKnown ? String(thisMonth) : `${thisMonth}+`,- unit: 'sessions',+ unit: t('workouts.stats.sessions'),},{- label: 'Avg Time',+ label: t('workouts.stats.avgTime'),+ failed: t('workouts.stats.avgTimeFailed'),value:workouts.length > 0? String(Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60)): '—',- unit: 'min',+ unit: t('workouts.stats.min'),},]@@ -210,12 +213,12 @@ export default function Workouts() {ListHeaderComponent={<View className="gap-5 py-4"><PageHeader- title="Workouts"- subtitle="Track and review your training sessions"+ title={t('workouts.list.title')}+ subtitle={t('workouts.list.subtitle')}action={<IconButtonicon={Plus}- label="Log Workout"+ label={t('workouts.list.logWorkout')}variant="solid"size="md"onPress={() => router.push('/workouts/new')}@@ -233,7 +236,7 @@ export default function Workouts() {<Card key={s.label} className="flex-1 rounded-2xl" style={{ paddingHorizontal: 12 }}><Label className="mb-2" numberOfLines={1}>{s.label}</Label>{countsUnknown ? (- <StatFailure label={`Couldn't load ${s.label.toLowerCase()}`} />+ <StatFailure label={s.failed} />) : (<View className="flex-row items-end gap-1"><AppText variant="heading" style={{ fontVariant: ['tabular-nums'] }}>@@ -255,7 +258,7 @@ export default function Workouts() {value={search}onChangeText={setSearch}loading={refreshing}- placeholder="Search workouts…"+ placeholder={t('workouts.list.searchPlaceholder')}/></View>}@@ -275,18 +278,18 @@ export default function Workouts() {loading ? null : listError ? (// Reached only with a search on screen (the early return covers the rest):// "No workouts found" would blame the query for a request that never landed.- <ErrorState title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />+ <ErrorState title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />) : (<EmptyStateicon={Dumbbell}- title="No workouts found"- subtitle={search ? 'Try a different search' : 'Log a workout to get started'}+ title={t('workouts.list.empty.title')}+ subtitle={search ? t('workouts.list.empty.searchHint') : t('workouts.list.empty.startHint')}/>)}ListFooterComponent={listError && workouts.length > 0 ? (- <ErrorState title="Couldn't load your workouts" message={listError} onRetry={retryList} retrying={loading} />+ <ErrorState title={t('workouts.list.loadFailed')} message={listError} onRetry={retryList} retrying={loading} />) : hasMore && loading && workouts.length > 0 ? (<View className="items-center py-3"><ActivityIndicator size="small" color={accent} />diff --git a/mobile/app/(tabs)/workouts/new.tsx b/mobile/app/(tabs)/workouts/new.tsxindex 1a51777..add3bdb 100644--- a/mobile/app/(tabs)/workouts/new.tsx+++ b/mobile/app/(tabs)/workouts/new.tsx@@ -5,7 +5,7 @@ import {AlertCircle, ArrowLeft, BookOpen, CalendarDays, Clock, Dumbbell, FileText, Plus, Zap,} from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { useAsyncAction, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay, dayToInstant, todayStr } from '@lyftr/shared'+import { useAsyncAction, displayToLbs, lbsToDisplay, weightShort, type Exercise, type Program, type ProgramDay, dayToInstant, todayStr, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { AppText, Button, DateInput, EmptyState, Field, IconButton, Label, Screen } from '../../../src/components/ui'import { ExerciseFormCard } from '../../../src/components/workouts/ExerciseFormCard'import { DurationField } from '../../../src/components/workouts/DurationField'@@ -49,6 +49,7 @@ function FieldHeader({ icon: Icon, label, hint }: { icon: LucideIcon; label: str}export default function AddWorkout() {+ const { t } = useTranslation()const settings = useSettingsStore((s) => s.settings)const fetchSettings = useSettingsStore((s) => s.fetch)const wUnit = weightShort(settings.weight_unit)@@ -57,8 +58,9 @@ export default function AddWorkout() {const [showPicker, setShowPicker] = useState(false)const [showProgramPicker, setShowProgramPicker] = useState(false)// Only what the FORM can say before anything is sent. What the SERVER says lives- // on `save` below; both render in the same alert.- const [error, setError] = useState('')+ // on `save` below; both render in the same alert. A UiMessage rather than a sentence, so+ // the alert follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [pickerExercises, setPickerExercises] = useState<Record<number, Exercise>>({})const [formData, setFormData] = useState<WorkoutFormData>({name: '',@@ -90,7 +92,7 @@ export default function AddWorkout() {setPickerExercises(newMap)setFormData((prev) => ({ ...prev, exercises: newExercises }))setShowProgramPicker(false)- setError('')+ setError(null)}const addExercise = (exercise: Exercise) => {@@ -108,7 +110,7 @@ export default function AddWorkout() {],}))setShowPicker(false)- setError('')+ setError(null)}// These handlers are passed to the memoized ExerciseFormCard, so they must be both@@ -175,17 +177,17 @@ export default function AddWorkout() {await client.workoutAPI.create(payload)// Web navigates to /workouts; pop back to the list (it reloads on focus).router.dismissTo('/workouts')- }, 'Failed to create workout')+ }, t('workouts.form.createFailed'))// Web scrolls the window to top on error; here the ScrollView.useEffect(() => {if (error || save.error) scrollRef.current?.scrollTo({ y: 0, animated: true })- }, [error, save.error])+ }, [error, save.failureKey])const handleSubmit = async () => {- if (!formData.name.trim()) { setError('Workout name required'); return }- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }- setError('')+ if (!formData.name.trim()) { setError({ key: 'workouts.form.errors.nameRequired' }); return }+ if (formData.exercises.length === 0) { setError({ key: 'workouts.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -195,6 +197,13 @@ export default function AddWorkout() {(sum, ex) => sum + ex.sets.reduce((s, set) => s + (set.weight || 0), 0),0)+ const counts = {+ exercises: t('workouts.form.exerciseCount', { count: formData.exercises.length }),+ sets: t('workouts.form.setCount', { count: totalSets }),+ }+ const summary = totalWeight > 0+ ? t('workouts.form.summaryWithWeight', { ...counts, weight: Math.round(totalWeight), unit: wUnit })+ : t('workouts.form.summary', counts)return (<Screen>@@ -211,13 +220,10 @@ export default function AddWorkout() {<View className="gap-6 py-4">{/* Back + title */}<View className="flex-row items-center gap-3">- <IconButton icon={ArrowLeft} label="Back" variant="ghost" size="md" onPress={goBack} />+ <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} /><View>- <AppText variant="title">Log Workout</AppText>- <AppText variant="caption" color="muted">- {formData.exercises.length} exercises • {totalSets} sets- {totalWeight > 0 ? ` • ${Math.round(totalWeight)} ${wUnit}` : ''}- </AppText>+ <AppText variant="title">{t('workouts.form.logTitle')}</AppText>+ <AppText variant="caption" color="muted">{summary}</AppText></View></View>@@ -225,16 +231,16 @@ export default function AddWorkout() {{error || save.error ? (<View className="flex-row items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 p-4"><AlertCircle size={16} color={isDark ? brand.errorSoft : brand.error} />- <AppText variant="body" color="error" className="flex-1">{error || save.error}</AppText>+ <AppText variant="body" color="error" className="flex-1">{error ? uiMessage(error) : save.error}</AppText></View>) : null}<View>- <FieldHeader icon={Dumbbell} label="Workout Name" hint="(required)" />+ <FieldHeader icon={Dumbbell} label={t('workouts.form.name')} hint={t('workouts.form.required')} /><Fieldvalue={formData.name}- onChangeText={(t) => setFormData((prev) => ({ ...prev, name: t }))}- placeholder="e.g., Leg Day, Push Day"+ onChangeText={(text) => setFormData((prev) => ({ ...prev, name: text }))}+ placeholder={t('workouts.form.namePlaceholder')}/></View>@@ -244,7 +250,7 @@ export default function AddWorkout() {half-width trigger doesn't crush the calendar. */}<View className="flex-row gap-3"><View className="flex-[2]">- <FieldHeader icon={CalendarDays} label="Date" />+ <FieldHeader icon={CalendarDays} label={t('workouts.form.date')} /><DateInputvalue={formData.date}onChange={(d) => setFormData((prev) => ({ ...prev, date: d }))}@@ -253,7 +259,7 @@ export default function AddWorkout() {</View><View className="flex-1">{/* "min" already rides the value, so the label stays just "Duration". */}- <FieldHeader icon={Clock} label="Duration" />+ <FieldHeader icon={Clock} label={t('workouts.form.duration')} /><DurationFieldvalue={formData.duration}onChange={(m) => setFormData((prev) => ({ ...prev, duration: m }))}@@ -263,11 +269,11 @@ export default function AddWorkout() {</View><View>- <FieldHeader icon={FileText} label="Notes" />+ <FieldHeader icon={FileText} label={t('workouts.form.notes')} /><Fieldvalue={formData.notes}- onChangeText={(t) => setFormData((prev) => ({ ...prev, notes: t }))}- placeholder="How did it feel? Any PRs?"+ onChangeText={(text) => setFormData((prev) => ({ ...prev, notes: text }))}+ placeholder={t('workouts.form.notesPlaceholder')}multiline/></View>@@ -281,8 +287,8 @@ export default function AddWorkout() {<View className="mb-3"><View className="mb-2.5 flex-row items-center gap-2"><Zap size={14} color={accent} strokeWidth={2.2} />- <Label>Exercises</Label>- <AppText variant="caption" color="muted">(required)</AppText>+ <Label>{t('workouts.form.exercises')}</Label>+ <AppText variant="caption" color="muted">{t('workouts.form.required')}</AppText></View><View className="flex-row items-center gap-2"><Pressable@@ -291,7 +297,7 @@ export default function AddWorkout() {className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg border border-surface-border bg-surface-muted px-3 py-2.5 active:scale-95"><BookOpen size={13} color={colors.txSecondary} />- <Text className="font-sans-semibold text-xs text-tx-secondary">Load Program</Text>+ <Text className="font-sans-semibold text-xs text-tx-secondary">{t('workouts.form.loadProgram')}</Text></Pressable><PressableaccessibilityRole="button"@@ -299,7 +305,7 @@ export default function AddWorkout() {className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2.5 active:scale-95"><Plus size={13} color="#ffffff" />- <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>+ <Text className="font-sans-semibold text-xs text-white">{t('workouts.form.addExercise')}</Text></Pressable></View></View>@@ -309,8 +315,8 @@ export default function AddWorkout() {<EmptyStatecompacticon={Dumbbell}- title="No exercises yet"- subtitle="Add an exercise or load a program to start"+ title={t('workouts.form.empty.createTitle')}+ subtitle={t('workouts.form.empty.createHint')}/></View>)}@@ -340,12 +346,12 @@ export default function AddWorkout() {{formData.exercises.length > 0 && (<PressableaccessibilityRole="button"- accessibilityLabel="Add exercise"+ accessibilityLabel={t('workouts.form.addExerciseLabel')}onPress={() => setShowPicker(true)}className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"><Plus size={14} color={accent} />- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>+ <Text className="font-sans-semibold text-xs" style={{ color: accent }}>{t('workouts.form.addExercise')}</Text></Pressable>)}</View>@@ -357,8 +363,8 @@ export default function AddWorkout() {{/* Sticky footer actions — Save stays reachable however long the form grows.-mx-5 lets the divider span edge-to-edge past Screen's px-5. */}<View className="-mx-5 flex-row gap-3 border-t border-surface-border bg-surface-base px-5 pb-2 pt-3">- <Button title="Cancel" variant="secondary" className="flex-1" onPress={goBack} />- <Button title="Save Workout" className="flex-1" onPress={handleSubmit} loading={save.busy} />+ <Button title={t('common.cancel')} variant="secondary" className="flex-1" onPress={goBack} />+ <Button title={t('workouts.form.saveWorkout')} className="flex-1" onPress={handleSubmit} loading={save.busy} /></View>{/* iOS-only Done bar docked above the numeric keypads (they have no return key). */}diff --git a/mobile/app/(tabs)/workouts/start.tsx b/mobile/app/(tabs)/workouts/start.tsxindex 35829c7..92912c9 100644--- a/mobile/app/(tabs)/workouts/start.tsx+++ b/mobile/app/(tabs)/workouts/start.tsx@@ -3,7 +3,7 @@ import { ActivityIndicator, Pressable, ScrollView, View } from 'react-native'import { router } from 'expo-router'import { ArrowLeft, BookOpen, ChevronRight, Play, Timer, Trash2, Zap } from 'lucide-react-native'import type { Program, ProgramDay } from '@lyftr/shared'-import { apiErrorMessage, activeSessionExercisesForDay, sessionNameForDay } from '@lyftr/shared'+import { activeSessionExercisesForDay, sessionNameForDay, defaultWorkoutName, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { AppText, ErrorState, IconButton, Screen } from '../../../src/components/ui'import { DayPickerSheet, pickProgramDay } from '../../../src/components/programs/DayPickerSheet'import { client, useWorkoutSession } from '../../../src/lib/lyftr'@@ -13,6 +13,7 @@ import { useTheme } from '../../../src/theme/useTheme'// resume/discard banner for an in-progress session. Navigates to /workouts/active,// which itself opens the gym overlay when the layout pref is 'gym'.export default function StartWorkout() {+ const { t } = useTranslation()const session = useWorkoutSession((s) => s.session)const startSession = useWorkoutSession((s) => s.startSession)const cancelSession = useWorkoutSession((s) => s.cancelSession)@@ -20,7 +21,8 @@ export default function StartWorkout() {const [programs, setPrograms] = useState<Program[]>([])const [loading, setLoading] = useState(false)- const [error, setError] = useState('')+ // A UiMessage, not its sentence, so the banner follows a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)const [dayPickFor, setDayPickFor] = useState<Program | null>(null)@@ -29,15 +31,14 @@ export default function StartWorkout() {client.programAPI.list().then((data) => setPrograms(data || []))- .catch((err) => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ .catch((err) => setError({ key: 'settings.unknownError', cause: err })).finally(() => setLoading(false))}, [retryKey])const goBack = () => (router.canGoBack() ? router.back() : router.replace('/workouts'))const startQuick = () => {- const name = `Workout — ${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`- startSession(name, [])+ startSession(defaultWorkoutName(), [])router.push('/workouts/active')}@@ -52,8 +53,8 @@ export default function StartWorkout() {<ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 32 }}><View className="gap-6 py-4"><View className="flex-row items-center gap-3">- <IconButton icon={ArrowLeft} label="Back" variant="ghost" size="md" onPress={goBack} />- <AppText variant="title">Start Workout</AppText>+ <IconButton icon={ArrowLeft} label={t('common.back')} variant="ghost" size="md" onPress={goBack} />+ <AppText variant="title">{t('workouts.start.title')}</AppText></View>{/* Active session — resume or discard */}@@ -65,7 +66,7 @@ export default function StartWorkout() {</View><View className="flex-1"><AppText variant="bodySemibold" numberOfLines={1}>{session.name}</AppText>- <AppText variant="caption" style={{ color: '#f59e0b' }}>Workout in progress</AppText>+ <AppText variant="caption" style={{ color: '#f59e0b' }}>{t('workouts.start.inProgress')}</AppText></View></View><View className="flex-row gap-2">@@ -74,14 +75,14 @@ export default function StartWorkout() {className="flex-1 flex-row items-center justify-center gap-2 rounded-xl bg-brand-500 py-2.5 active:scale-95"><Play size={16} color="#ffffff" />- <AppText variant="bodySemibold" color="white">Resume</AppText>+ <AppText variant="bodySemibold" color="white">{t('workouts.start.resume')}</AppText></Pressable><PressableonPress={() => cancelSession()}className="flex-1 flex-row items-center justify-center gap-2 rounded-xl border border-surface-border bg-surface-muted py-2.5 active:scale-95"><Trash2 size={16} color={colors.txMuted} />- <AppText variant="bodySemibold" color="secondary">Discard</AppText>+ <AppText variant="bodySemibold" color="secondary">{t('workouts.start.discard')}</AppText></Pressable></View></View>@@ -96,8 +97,8 @@ export default function StartWorkout() {<Zap size={24} color="#ffffff" /></View><View className="flex-1">- <AppText variant="heading">Quick Start</AppText>- <AppText variant="caption" color="muted" className="mt-0.5">Start blank, add exercises as you go</AppText>+ <AppText variant="heading">{t('workouts.start.quick')}</AppText>+ <AppText variant="caption" color="muted" className="mt-0.5">{t('workouts.start.quickHint')}</AppText></View><ChevronRight size={20} color={colors.txMuted} /></Pressable>@@ -106,7 +107,7 @@ export default function StartWorkout() {<View><View className="mb-3 flex-row items-center gap-2"><BookOpen size={16} color={accent} />- <AppText variant="subheading">Start from Program</AppText>+ <AppText variant="subheading">{t('workouts.start.fromProgram')}</AppText></View>{/* Section-scoped: starting an empty workout does not need this list, so@@ -114,16 +115,16 @@ export default function StartWorkout() {{error ? (<ErrorStatesize="section"- title="Couldn't load your programs"- message={error}- onRetry={() => { setError(''); setRetryKey((k) => k + 1) }}+ title={t('workouts.start.programsLoadFailed')}+ message={uiMessage(error)}+ onRetry={() => { setError(null); setRetryKey((k) => k + 1) }}/>) : null}{loading ? (<View className="flex-row items-center justify-center gap-2 py-12"><ActivityIndicator color={accent} />- <AppText variant="body" color="muted">Loading programs…</AppText>+ <AppText variant="body" color="muted">{t('workouts.start.loadingPrograms')}</AppText></View>) : error ? (// The error above already owns this space. Stacking "No programs yet"@@ -133,9 +134,9 @@ export default function StartWorkout() {) : programs.length === 0 ? (<View className="items-center rounded-2xl border border-surface-border bg-surface-raised py-10"><BookOpen size={32} color={colors.txMuted} />- <AppText variant="body" color="muted" className="mt-2">No programs yet</AppText>+ <AppText variant="body" color="muted" className="mt-2">{t('workouts.start.noPrograms')}</AppText><Pressable onPress={() => router.navigate('/programs/new')} className="mt-3 active:opacity-60">- <AppText variant="caption" style={{ color: accent }}>Create your first program →</AppText>+ <AppText variant="caption" style={{ color: accent }}>{t('workouts.start.createFirst')}</AppText></Pressable></View>) : (@@ -156,7 +157,7 @@ export default function StartWorkout() {<View className="flex-1"><AppText variant="bodySemibold" numberOfLines={1}>{p.name}</AppText><AppText variant="caption" color="muted" className="mt-0.5">- {dayCount > 0 ? `${dayCount} day${dayCount === 1 ? '' : 's'}` : 'No days yet'}+ {dayCount > 0 ? t('workouts.start.days', { count: dayCount }) : t('workouts.start.noDays')}</AppText></View><Play size={16} color={accent} />diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsxindex 7b34f12..d523a58 100644--- a/mobile/app/_layout.tsx+++ b/mobile/app/_layout.tsx@@ -13,7 +13,7 @@ import {PlusJakartaSans_700Bold,PlusJakartaSans_800ExtraBold,} from '@expo-google-fonts/plus-jakarta-sans'-import { useAuthStore, useServerStore, useSettingsStore, useThemeStore, useWorkoutSession } from '../src/lib/lyftr'+import { useAuthStore, useLanguageStore, useServerStore, useSettingsStore, useThemeStore, useWorkoutSession } from '../src/lib/lyftr'import { useTheme } from '../src/theme/useTheme'import { Loading } from '../src/components/ui'import { WorkoutSessionLayer } from '../src/components/workouts/WorkoutSessionLayer'@@ -58,10 +58,12 @@ export default function RootLayout() {const hydrateAuth = useAuthStore((s) => s.hydrate)const hydrateServer = useServerStore((s) => s.hydrate)const hydrateTheme = useThemeStore((s) => s.hydrate)+ const hydrateLanguage = useLanguageStore((s) => s.hydrate)const hydrateWorkout = useWorkoutSession((s) => s.hydrate)const hydratePrefs = useSettingsStore((s) => s.hydratePrefs)const isHydrated = useAuthStore((s) => s.isHydrated)const themeHydrated = useThemeStore((s) => s.isHydrated)+ const languageHydrated = useLanguageStore((s) => s.isHydrated)const isAuthed = useAuthStore((s) => s.isAuthenticated)const { mode, isDark } = useTheme()const [fontsLoaded] = useFonts({@@ -72,19 +74,20 @@ export default function RootLayout() {PlusJakartaSans_700Bold,PlusJakartaSans_800ExtraBold,})- const ready = isHydrated && themeHydrated && fontsLoaded+ const ready = isHydrated && themeHydrated && languageHydrated && fontsLoadeduseEffect(() => {hydrateAuth()hydrateServer()hydrateTheme()+ hydrateLanguage()hydrateWorkout()// Device-only prefs (workout_layout, rest_enabled, rest_seconds_default). Without// this they stay at the store defaults until the settings fetch returns, so a// gym-mode user can land on the workout screen in the list layout — the same gap// web closes in its own hydrate step.hydratePrefs()- }, [hydrateAuth, hydrateServer, hydrateTheme, hydrateWorkout, hydratePrefs])+ }, [hydrateAuth, hydrateServer, hydrateTheme, hydrateLanguage, hydrateWorkout, hydratePrefs])// React has mounted → the barbell loader (or the app, if already ready) is on screen.// Drop the native splash now so it flows straight into the animated loader.diff --git a/mobile/package.json b/mobile/package.jsonindex 6825455..54ce58d 100644--- a/mobile/package.json+++ b/mobile/package.json@@ -39,6 +39,7 @@"expo-secure-store": "~15.0.8","expo-splash-screen": "~31.0.13","expo-status-bar": "~3.0.9",+ "intl-pluralrules": "^2.0.1","lucide-react-native": "^0.460.0","nativewind": "^4.1.23","react": "19.1.0",diff --git a/mobile/src/components/AuthScaffold.tsx b/mobile/src/components/AuthScaffold.tsxindex 9d5cba0..9adb595 100644--- a/mobile/src/components/AuthScaffold.tsx+++ b/mobile/src/components/AuthScaffold.tsx@@ -3,6 +3,7 @@ import { View, Text, Platform, Animated } from 'react-native'import { LinearGradient } from 'expo-linear-gradient'import { StatusBar } from 'expo-status-bar'import { SafeAreaView } from 'react-native-safe-area-context'+import { useTranslation } from '@lyftr/shared'import { BarbellMark } from './Logo'import { useTheme } from '../theme/useTheme'@@ -18,6 +19,7 @@ export function AuthScaffold({subtitle: stringchildren: ReactNode}) {+ const { t } = useTranslation()const { colors } = useTheme()// Stretchy pull-down header (classic iOS): track the scroll offset and, on@@ -133,7 +135,7 @@ export function AuthScaffold({marginTop: 6,}}>- TRAIN · TRACK · PROGRESS+ {t('auth.tagline')}</Text></View></View>diff --git a/mobile/src/components/authui.tsx b/mobile/src/components/authui.tsxindex 35f0dd9..7212750 100644--- a/mobile/src/components/authui.tsx+++ b/mobile/src/components/authui.tsx@@ -18,7 +18,9 @@ import {testServerConnection,normalizeServerUrl,isInsecureServerUrl,- INSECURE_SERVER_WARNING,+ useTranslation,+ uiMessage,+ type UiMessage,} from '@lyftr/shared'const FONT = {@@ -208,35 +210,41 @@ export function SecondaryButton({ title, hint, onPress }: { title: string; hint?}export function AuthDivider() {+ const { t } = useTranslation()const { colors } = useTheme()return (<View style={{ flexDirection: 'row', alignItems: 'center', gap: 14, marginVertical: 22 }}><View style={{ flex: 1, height: 1, backgroundColor: colors.border }} />- <Text style={{ fontFamily: FONT.label, fontSize: 11, letterSpacing: 1.8, color: colors.txMuted }}>OR</Text>+ <Text style={{ fontFamily: FONT.label, fontSize: 11, letterSpacing: 1.8, color: colors.txMuted }}>{t('auth.divider.or')}</Text><View style={{ flex: 1, height: 1, backgroundColor: colors.border }} /></View>)}+// What the row last learned, kept as its inputs so the line follows a language switch.+type ServerResult =+ | { kind: 'invalid' }+ | { kind: 'connected'; name: string; version: string }+ | { kind: 'saved'; failure: UiMessage }+// Server settings row that expands to a URL field (self-hosted users).export function ServerRow() {+ const { t } = useTranslation()const { colors, brand, accent } = useTheme()const serverUrl = useServerStore((s) => s.serverUrl)const setServerUrl = useServerStore((s) => s.setServerUrl)const [open, setOpen] = useState(false)const [url, setUrl] = useState(serverUrl)- const [msg, setMsg] = useState<string | null>(null)- const [ok, setOk] = useState(false)+ const [result, setResult] = useState<ServerResult | null>(null)const [testing, setTesting] = useState(false)const insecure = isInsecureServerUrl(serverUrl)const save = async () => {setTesting(true)- setMsg(null)+ setResult(null)const base = normalizeServerUrl(url)if (url.trim() && !base) {- setOk(false)- setMsg('Include http:// or https://')+ setResult({ kind: 'invalid' })setTesting(false)return}@@ -244,12 +252,11 @@ export function ServerRow() {// whose server is unreachable for any reason can never store a URL from this screen —// exactly the dead end hit when the device itself blocks the connection (issue #79).await setServerUrl(base)- const result = await testServerConnection(base)- setOk(result.ok)- setMsg(- result.ok- ? `Connected to ${result.info.name} v${result.info.version}`- : `Saved — ${result.message}`,+ const probe = await testServerConnection(base)+ setResult(+ probe.ok+ ? { kind: 'connected', name: probe.info.name, version: probe.info.version }+ : { kind: 'saved', failure: probe.failure },)setTesting(false)}@@ -271,11 +278,11 @@ export function ServerRow() {}}><Server size={16} color={brand.violet} strokeWidth={2} />- <Text style={{ flex: 1, fontFamily: FONT.body, fontSize: 13, color: colors.txPrimary }}>Server settings</Text>+ <Text style={{ flex: 1, fontFamily: FONT.body, fontSize: 13, color: colors.txPrimary }}>{t('server.settingsTitle')}</Text>{/* Stays visible while the row is collapsed — the risk outlives the moment of entry. */}{insecure ? <AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} /> : null}<Text style={{ fontFamily: FONT.body, fontSize: 12, color: insecure ? brand.warning : colors.txSecondary }}>- {serverUrl ? serverUrl.replace(/^https?:\/\//, '') : 'default'}+ {serverUrl ? serverUrl.replace(/^https?:\/\//, '') : t('server.defaultShort')}</Text><ChevronDown size={14} color={colors.txMuted} strokeWidth={2.4} /></Pressable>@@ -283,8 +290,8 @@ export function ServerRow() {<View style={{ marginTop: 8, gap: 8 }}><TextInputvalue={url}- onChangeText={(t) => { setMsg(null); setUrl(t) }}- placeholder="https://your-server.example.com"+ onChangeText={(text) => { setResult(null); setUrl(text) }}+ placeholder={t('settings.server.url.placeholder')}placeholderTextColor={colors.txMuted}autoCapitalize="none"autoCorrect={false}@@ -301,14 +308,20 @@ export function ServerRow() {fontSize: 14,}}/>- {msg ? (- <Text style={{ fontFamily: FONT.body, fontSize: 12, color: ok ? brand.success : brand.error }}>{msg}</Text>+ {result ? (+ <Text style={{ fontFamily: FONT.body, fontSize: 12, color: result.kind === 'connected' ? brand.success : brand.error }}>+ {result.kind === 'invalid'+ ? t('server.status.invalidUrl')+ : result.kind === 'connected'+ ? t('server.status.connectedTo', { name: result.name, version: result.version })+ : t('settings.server.savedWithWarning', { message: uiMessage(result.failure) })}+ </Text>) : null}{insecure ? (<View style={{ flexDirection: 'row', gap: 6, alignItems: 'flex-start' }}><AlertTriangle size={13} color={brand.warning} strokeWidth={2.4} style={{ marginTop: 1 }} /><Text style={{ flex: 1, fontFamily: FONT.body, fontSize: 12, color: brand.warning }}>- {INSECURE_SERVER_WARNING}+ {t('server.insecureWarning')}</Text></View>) : null}@@ -327,7 +340,7 @@ export function ServerRow() {{testing ? (<ActivityIndicator color={accent} />) : (- <Text style={{ fontFamily: FONT.btn, fontSize: 14, color: colors.txSecondary }}>Test & save</Text>+ <Text style={{ fontFamily: FONT.btn, fontSize: 14, color: colors.txSecondary }}>{t('settings.server.url.testAndSave')}</Text>)}</Pressable></View>diff --git a/mobile/src/components/dashboard/DashboardCharts.tsx b/mobile/src/components/dashboard/DashboardCharts.tsxindex 947f9bd..633a493 100644--- a/mobile/src/components/dashboard/DashboardCharts.tsx+++ b/mobile/src/components/dashboard/DashboardCharts.tsx@@ -2,8 +2,10 @@ import { useState } from 'react'import { View } from 'react-native'import * as Haptics from 'expo-haptics'import Svg, { Circle, Line, Path, Rect, Text as SvgText } from 'react-native-svg'+import { useTranslation } from '@lyftr/shared'import { AppText } from '../ui'import { useTheme } from '../../theme/useTheme'+import { muscleLabel } from '../../utils/exerciseUtils'// react-native-svg reimplementations of the web Dashboard's recharts widgets (bar /// line / donut) plus the custom MuscleSparkline (already raw SVG on web). Web reads@@ -176,6 +178,8 @@ export function MuscleDonut({ data, total, colorFor, size = 160 }: {data: DonutSlice[]; total: number; colorFor: (name: string) => string; size?: number}) {const { colors } = useTheme()+ // Re-renders on a language switch: the selected slice's muscle is named from the catalog.+ const { t } = useTranslation()const [sel, setSel] = useState<number | null>(null)if (!data.length || total <= 0) return null@@ -216,7 +220,7 @@ export function MuscleDonut({ data, total, colorFor, size = 160 }: {tooltip; the legend already lists every value, so the hole is the natural read-out). */}{selSlice ? (<View pointerEvents="none" style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }}>- <AppText variant="caption" color="muted" className="capitalize" numberOfLines={1}>{selSlice.d.name}</AppText>+ <AppText variant="caption" color="muted" className="capitalize" numberOfLines={1}>{muscleLabel(selSlice.d.name)}</AppText><AppText variant="bodySemibold" style={{ fontVariant: ['tabular-nums'] }}>{selSlice.d.value}</AppText><AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>{Math.round((selSlice.d.value / total) * 100)}%@@ -225,7 +229,7 @@ export function MuscleDonut({ data, total, colorFor, size = 160 }: {) : (<View pointerEvents="none" style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }}><AppText variant="bodySemibold" style={{ fontVariant: ['tabular-nums'], color: colors.txMuted }}>{total}</AppText>- <AppText variant="caption" color="muted">sets</AppText>+ <AppText variant="caption" color="muted">{t('home.muscle.donutSets')}</AppText></View>)}</View>diff --git a/mobile/src/components/dashboard/QuickWeighInSheet.tsx b/mobile/src/components/dashboard/QuickWeighInSheet.tsxindex 84ff243..55b422d 100644--- a/mobile/src/components/dashboard/QuickWeighInSheet.tsx+++ b/mobile/src/components/dashboard/QuickWeighInSheet.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'import { Pressable, View } from 'react-native'import * as Haptics from 'expo-haptics'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 { useAsyncAction, dayToInstant, displayToLbs, maxWeight, todayStr, weightError, weightShort, type WeightLog, entryDay, BODYWEIGHT_STEP, clampStep, useTranslation } from '@lyftr/shared'import {Alert, AppText, Button, DateInput, Field, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID,Sheet, StepperTile,@@ -24,6 +24,7 @@ interface Props {// Dashboard. Same logic as the Weight page's log form (prefill, same-day duplicate// guard, collapsible date/note, validation) but self-contained in a Sheet.export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess }: Props) {+ const { t } = useTranslation()const settings = useSettingsStore((s) => s.settings)const unit = settings.weight_unitconst wUnit = weightShort(unit)@@ -33,7 +34,9 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccessconst [date, setDate] = useState(todayStr())const [notes, setNotes] = useState('')const [showExtras, setShowExtras] = useState(false)- const [error, setError] = useState('')+ // The rejected weight, not the sentence about it: the text is made at render from the current+ // unit and language, so a banner already on screen follows a switch of either.+ const [rejected, setRejected] = useState<number | null>(null)const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)const [dupDismissed, setDupDismissed] = useState(false)@@ -44,7 +47,7 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccesssetDate(todayStr())setNotes('')setShowExtras(false)- setError('')+ setRejected(null)setShowDuplicateWarning(false)setDupDismissed(false)}, [open, lastValue])@@ -58,21 +61,23 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccessHaptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})onSuccess(log)onClose()- }, 'Failed to save')+ }, t('home.quickWeighIn.saveFailed'))++ const error = rejected === null ? '' : weightError(rejected, unit) ?? ''const submit = async (forceDismissed = false) => {if (save.busy) returnconst w = parseFloat(value)const wErr = weightError(w, unit)if (wErr) {- setError(wErr)+ setRejected(w)return}if (!(forceDismissed || dupDismissed) && lastLog && entryDay(lastLog) === date) {setShowDuplicateWarning(true)return}- setError('')+ setRejected(null)setShowDuplicateWarning(false)void save.run(w)}@@ -86,9 +91,9 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess<View className="h-8 w-8 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10"><Scale size={16} color={accent} /></View>- <AppText variant="heading">Log Weight</AppText>+ <AppText variant="heading">{t('home.quickWeighIn.title')}</AppText></View>- <Pressable onPress={onClose} hitSlop={8} className="p-1.5 active:opacity-60" accessibilityLabel="Close">+ <Pressable onPress={onClose} hitSlop={8} className="p-1.5 active:opacity-60" accessibilityLabel={t('common.close')}><X size={20} color={colors.txMuted} /></Pressable></View>@@ -102,22 +107,22 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccess<Alertvariant="warning"actions={[- { label: 'Cancel', onPress: () => setShowDuplicateWarning(false) },+ { label: t('common.cancel'), onPress: () => setShowDuplicateWarning(false) },{- label: 'Log Anyway',+ label: t('home.quickWeighIn.logAnyway'),primary: true,onPress: () => { setDupDismissed(true); setShowDuplicateWarning(false); submit(true) },},]}>- Already logged today ({lastValue} {wUnit}). Log again anyway?+ {t('home.quickWeighIn.duplicateToday', { weight: lastValue, unit: wUnit })}</Alert>) : null}<StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('home.quickWeighIn.weightWithUnit', { unit: wUnit })}+ name={t('home.quickWeighIn.weightName')}step={BODYWEIGHT_STEP}onStep={(d) => setValue(String(clampStep(parseFloat(value) || 0, d, { min: 0, max: maxWeight(unit) })))}>@@ -126,30 +131,30 @@ export function QuickWeighInSheet({ open, lastValue, lastLog, onClose, onSuccessvalue={value}onChange={setValue}placeholder="0"- accessibilityLabel="Weight"+ accessibilityLabel={t('home.quickWeighIn.weight')}inputAccessoryViewID={NUMERIC_ACCESSORY_ID}/></StepperTile>{!showExtras ? (<Pressable onPress={() => setShowExtras(true)} hitSlop={6} className="self-start active:opacity-60">- <AppText variant="caption" color="brand">+ Change date or add a note</AppText>+ <AppText variant="caption" color="brand">{t('home.quickWeighIn.changeDateOrNote')}</AppText></Pressable>) : (<View className="gap-3">- <DateInput label="Date" value={date} onChange={setDate} maximumDate={new Date()} />+ <DateInput label={t('home.quickWeighIn.date')} value={date} onChange={setDate} maximumDate={new Date()} /><Field- label="Note (optional)"+ label={t('home.quickWeighIn.noteOptional')}value={notes}onChangeText={setNotes}- placeholder="e.g., morning, post-workout"+ placeholder={t('home.quickWeighIn.notePlaceholder')}maxLength={200}/></View>)}<Button- title={save.busy ? 'Saving…' : 'Save'}+ title={save.busy ? t('common.saving') : t('common.save')}onPress={() => submit()}loading={save.busy}disabled={!(parseFloat(value) > 0) || save.busy}diff --git a/mobile/src/components/nutrition/BarcodeLookup.tsx b/mobile/src/components/nutrition/BarcodeLookup.tsxindex b29dd9a..b5f2efa 100644--- a/mobile/src/components/nutrition/BarcodeLookup.tsx+++ b/mobile/src/components/nutrition/BarcodeLookup.tsx@@ -10,7 +10,7 @@ import Animated, {withTiming,} from 'react-native-reanimated'import { Barcode } from 'lucide-react-native'-import { eanModules, formatBarcode } from '@lyftr/shared'+import { eanModules, formatBarcode, useTranslation } from '@lyftr/shared'import { AppText, Card } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -51,6 +51,7 @@ function Bars({ code, color }: { code: string; color: string }) {// Shown in place of the results while a scanned code is looked up: the barcode and its// digits, as printed on the pack, so the scan visibly landed. Mirrors web BarcodeLookup.export function BarcodeLookup({ code }: { code: string }) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const [slow, setSlow] = useState(false)useEffect(() => {@@ -82,7 +83,7 @@ export function BarcodeLookup({ code }: { code: string }) {{formatBarcode(code)}</AppText><AppText variant="body" color="muted" className="mt-3 text-center">- {slow ? 'Still looking. This can take a few seconds.' : 'Looking up this product…'}+ {slow ? t('food.lookup.slow') : t('food.lookup.looking')}</AppText></Card>)diff --git a/mobile/src/components/nutrition/BarcodeScanner.tsx b/mobile/src/components/nutrition/BarcodeScanner.tsxindex e182f49..ff05836 100644--- a/mobile/src/components/nutrition/BarcodeScanner.tsx+++ b/mobile/src/components/nutrition/BarcodeScanner.tsx@@ -3,6 +3,7 @@ import { Modal, Pressable, StyleSheet, View } from 'react-native'import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'import { CameraView, useCameraPermissions } from 'expo-camera'import * as Haptics from 'expo-haptics'+import { useTranslation } from '@lyftr/shared'import { AlertCircle, X } from 'lucide-react-native'import { AppText, Button } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -17,6 +18,7 @@ interface Props {// code back to LogFood (→ foodAPI.barcode). Web buzzed via navigator.vibrate on a hit;// here that's a success haptic. Rendered inside a Modal so it fully covers the tab bar.export function BarcodeScanner({ onResult, onClose }: Props) {+ const { t } = useTranslation()const { colors } = useTheme()const [permission, requestPermission] = useCameraPermissions()const resolvedRef = useRef(false)@@ -54,16 +56,14 @@ export function BarcodeScanner({ onResult, onClose }: Props) {<SafeAreaView className="flex-1 items-center justify-center px-8"><AlertCircle size={40} color={colors.txMuted} /><AppText variant="heading" color="white" className="mt-4 text-center">- {denied ? 'Camera access denied' : 'Camera permission needed'}+ {denied ? t('food.scan.deniedTitle') : t('food.scan.neededTitle')}</AppText><AppText variant="body" color="muted" className="mt-2 text-center">- {denied- ? 'Enable camera access for Lyftr in your device settings to scan barcodes.'- : 'Allow camera access to scan a food barcode.'}+ {denied ? t('food.scan.deniedBody') : t('food.scan.neededBody')}</AppText>{!denied ? (<View className="mt-5 w-full">- <Button title="Allow camera" onPress={requestPermission} />+ <Button title={t('food.scan.allow')} onPress={requestPermission} /></View>) : null}</SafeAreaView>@@ -73,7 +73,7 @@ export function BarcodeScanner({ onResult, onClose }: Props) {{permission?.granted ? (<View style={StyleSheet.absoluteFill} className="items-center justify-center" pointerEvents="none"><View style={{ width: 260, height: 160, borderWidth: 2, borderColor: 'rgba(255,255,255,0.85)', borderRadius: 16 }} />- <AppText variant="body" color="white" className="mt-4">Point at a barcode</AppText>+ <AppText variant="body" color="white" className="mt-4">{t('food.scan.point')}</AppText></View>) : null}@@ -82,7 +82,7 @@ export function BarcodeScanner({ onResult, onClose }: Props) {<View className="flex-row justify-end px-4 pt-2"><PressableaccessibilityRole="button"- accessibilityLabel="Close scanner"+ accessibilityLabel={t('food.scan.close')}onPress={onClose}hitSlop={16}className="h-11 w-11 items-center justify-center rounded-full active:scale-90"diff --git a/mobile/src/components/nutrition/FoodEntryRow.test.tsx b/mobile/src/components/nutrition/FoodEntryRow.test.tsxindex f9c66b5..0cb3aa9 100644--- a/mobile/src/components/nutrition/FoodEntryRow.test.tsx+++ b/mobile/src/components/nutrition/FoodEntryRow.test.tsx@@ -1,5 +1,5 @@import { render, screen } from '@testing-library/react-native'-import type { FoodLog } from '@lyftr/shared'+import { i18n, type FoodLog } from '@lyftr/shared'import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'import { FoodEntryRow } from './FoodEntryRow'@@ -32,6 +32,23 @@ const entry = (overrides: Partial<FoodLog> = {}): FoodLog => ({const row = (e: FoodLog) =>render(<FoodEntryRow entry={e} first onPress={() => {}} onEdit={() => {}} onDeleted={() => {}} />)+describe('FoodEntryRow copy', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ const view = row(entry({ meal: 'dinner' }))+ try {+ expect(screen.getByText('Cena')).toBeTruthy()+ expect(screen.getByText('G')).toBeTruthy()+ expect(screen.getByLabelText('Opciones de Extra Virgin Olive Oil')).toBeTruthy()+ expect(screen.queryByText('Dinner')).toBeNull()+ } finally {+ // Unmount first: restoring English under a mounted tree is a state update outside act.+ view.unmount()+ await i18n.changeLanguage('en')+ }+ })+})+describe('FoodEntryRow amount', () => {// The bug this pins: the row rendered `entry.servings` raw, so a third of a 15 ml// serving read "× 0.3333333333333333" here while the entry's own screen — which goesdiff --git a/mobile/src/components/nutrition/FoodEntryRow.tsx b/mobile/src/components/nutrition/FoodEntryRow.tsxindex 22f97a5..aba7719 100644--- a/mobile/src/components/nutrition/FoodEntryRow.tsx+++ b/mobile/src/components/nutrition/FoodEntryRow.tsx@@ -1,4 +1,4 @@-import { formatLoggedAmount, useAsyncAction } from '@lyftr/shared'+import { formatLoggedAmount, useAsyncAction, useTranslation } from '@lyftr/shared'import { useState } from 'react'import { Pressable, View } from 'react-native'import * as Haptics from 'expo-haptics'@@ -8,17 +8,18 @@ import { ActionSheet, AppText, ConfirmSheet, IconButton, deleteAction, deleteConimport { useTheme } from '../../theme/useTheme'import { client } from '../../lib/lyftr'import { FoodThumb } from './FoodImage'-import { MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, MEAL_LABELS, type Meal } from './nutritionMeta'+import { MACRO_TEXT, MEAL_COLORS, MEAL_ICONS, mealLabel, type Meal } from './nutritionMeta'// Compact meal tag shown on each row now that meals share one list (icon + label in the// meal's tint). 8-digit hex (#RRGGBBAA) for the fill/border is fine on RN core Views.function MealChip({ meal }: { meal: Meal }) {+ useTranslation()const Icon = MEAL_ICONS[meal]const color = MEAL_COLORS[meal]return (<View className="flex-row items-center gap-1 rounded-full border px-2 py-0.5" style={{ backgroundColor: `${color}1A`, borderColor: `${color}40` }}><Icon size={11} color={color} />- <AppText variant="caption" style={{ fontSize: 10, color, fontWeight: '700' }}>{MEAL_LABELS[meal]}</AppText>+ <AppText variant="caption" style={{ fontSize: 10, color, fontWeight: '700' }}>{mealLabel(meal)}</AppText></View>)}@@ -40,6 +41,7 @@ interface Props {// ActionSheet (Edit / Delete) with a thumbnail+macros preview header. Delete routes through// the shared ConfirmSheet.export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props) {+ const { t } = useTranslation()const { colors } = useTheme()const [menuOpen, setMenuOpen] = useState(false)const [confirming, setConfirming] = useState(false)@@ -51,7 +53,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Propsawait client.foodAPI.delete(entry.id)Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})onDeleted(entry.id)- }, 'Failed to delete entry')+ }, t('food.entry.deleteFailed'))const Thumb = ({ size = 44 }: { size?: number }) => <FoodThumb src={entry.image_url} size={size} />@@ -67,9 +69,9 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props<AppText variant="caption" color="secondary" style={{ fontWeight: '600', fontVariant: ['tabular-nums'] }}>{Math.round(entry.calories)} kcal</AppText></View>{([- ['P', entry.protein, MACRO_TEXT.protein],- ['C', entry.carbs, MACRO_TEXT.carbs],- ['F', entry.fat, MACRO_TEXT.fat],+ [t('food.macro.proteinInitial'), entry.protein, MACRO_TEXT.protein],+ [t('food.macro.carbsInitial'), entry.carbs, MACRO_TEXT.carbs],+ [t('food.macro.fatInitial'), entry.fat, MACRO_TEXT.fat],] as const).map(([label, value, color]) => (<View key={label} className="flex-row items-center gap-1"><View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: color }} />@@ -96,7 +98,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props</View><IconButtonicon={MoreVertical}- label={`${entry.name} options`}+ label={t('food.entry.optionsNamed', { name: entry.name })}variant="ghost"size="sm"onPress={() => setMenuOpen(true)}@@ -124,7 +126,7 @@ export function FoodEntryRow({ entry, first, onPress, onEdit, onDeleted }: Props/><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete entry?', subject: `"${entry.name}"` })}+ {...deleteConfirmProps({ title: t('food.entry.deleteTitle'), subject: `"${entry.name}"` })}open={confirming}busy={remove.busy}error={remove.error}diff --git a/mobile/src/components/nutrition/FoodResultRow.test.tsx b/mobile/src/components/nutrition/FoodResultRow.test.tsxindex 367b8f3..7fcd1ea 100644--- a/mobile/src/components/nutrition/FoodResultRow.test.tsx+++ b/mobile/src/components/nutrition/FoodResultRow.test.tsx@@ -1,5 +1,5 @@import { fireEvent, render, screen } from '@testing-library/react-native'-import type { FoodSearchResult } from '@lyftr/shared'+import { i18n, type FoodSearchResult } from '@lyftr/shared'// The `mock` prefix is what lets a jest.mock factory close over an import — the rule is// jest's, and it means the async-storage mock needs no require() inside the factory.import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'@@ -32,6 +32,23 @@ const item = (overrides: Partial<FoodSearchResult> = {}): FoodSearchResult => ({const ADD = 'Add Chicken Breast to Favorites'const REMOVE = 'Remove Chicken Breast from Favorites'+describe('FoodResultRow copy', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ const view = render(<FoodResultRow item={item()} onPress={() => {}} favorited={false} onToggleFavorite={() => {}} />)+ try {+ expect(screen.getByLabelText('Añadir Chicken Breast a Favoritos')).toBeTruthy()+ expect(screen.getByText('31g P')).toBeTruthy()+ expect(screen.getByText('4g G')).toBeTruthy()+ expect(screen.queryByLabelText(ADD)).toBeNull()+ } finally {+ // Unmount first: restoring English under a mounted tree is a state update outside act.+ view.unmount()+ await i18n.changeLanguage('en')+ }+ })+})+describe('FoodResultRow', () => {// The label carries the toggle state, because the fill that conveys it visually is// invisible to a screen reader.diff --git a/mobile/src/components/nutrition/FoodResultRow.tsx b/mobile/src/components/nutrition/FoodResultRow.tsxindex b60fe95..49dfbb7 100644--- a/mobile/src/components/nutrition/FoodResultRow.tsx+++ b/mobile/src/components/nutrition/FoodResultRow.tsx@@ -1,6 +1,6 @@import { ActivityIndicator, Pressable, View } from 'react-native'import { ChevronRight, Star } from 'lucide-react-native'-import type { FoodSearchResult } from '@lyftr/shared'+import { useTranslation, type FoodSearchResult } from '@lyftr/shared'import { AppText } from '../ui'import { useTheme } from '../../theme/useTheme'import { FoodThumb } from './FoodImage'@@ -34,6 +34,7 @@ export function FoodResultRow({item, onPress, favorited, onToggleFavorite, togglingFavorite = false, loading = false,}: Props) {const { colors } = useTheme()+ const { t } = useTranslation()return (<Pressable@@ -48,11 +49,11 @@ export function FoodResultRow({<View className="mt-1 flex-row flex-wrap items-center gap-x-1.5"><AppText variant="caption" color="secondary" style={{ fontWeight: '600', fontVariant: ['tabular-nums'] }}>{Math.round(item.calories)} kcal</AppText><Dot />- <AppText variant="caption" style={{ color: MACRO_TEXT.protein, fontVariant: ['tabular-nums'] }}>{item.protein.toFixed(0)}g P</AppText>+ <AppText variant="caption" style={{ color: MACRO_TEXT.protein, fontVariant: ['tabular-nums'] }}>{item.protein.toFixed(0)}g {t('food.macro.proteinInitial')}</AppText><Dot />- <AppText variant="caption" style={{ color: MACRO_TEXT.carbs, fontVariant: ['tabular-nums'] }}>{item.carbs.toFixed(0)}g C</AppText>+ <AppText variant="caption" style={{ color: MACRO_TEXT.carbs, fontVariant: ['tabular-nums'] }}>{item.carbs.toFixed(0)}g {t('food.macro.carbsInitial')}</AppText><Dot />- <AppText variant="caption" style={{ color: MACRO_TEXT.fat, fontVariant: ['tabular-nums'] }}>{item.fat.toFixed(0)}g F</AppText>+ <AppText variant="caption" style={{ color: MACRO_TEXT.fat, fontVariant: ['tabular-nums'] }}>{item.fat.toFixed(0)}g {t('food.macro.fatInitial')}</AppText>{item.serving_size ? (<><Dot /><AppText variant="caption" color="muted" style={{ fontSize: 10 }}>{item.serving_size}</AppText></>) : null}</View></View>@@ -78,6 +79,7 @@ export function FavoriteStar({ favorited: boolean; busy?: boolean; name: string; onPress: () => void; size?: 'sm' | 'md' | 'header' },) {const { colors, accent } = useTheme()+ const { t } = useTranslation()// Same box, hit slop and press feedback as ui/IconButton — written out rather than// reusing it because a filled star needs an SVG `fill`, and adding a fill prop to the// shared primitive for one toggle is the wrong place to put it.@@ -88,7 +90,7 @@ export function FavoriteStar(<PressableaccessibilityRole="button"accessibilityState={{ selected: favorited }}- accessibilityLabel={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}+ accessibilityLabel={t(favorited ? 'food.favorites.remove' : 'food.favorites.add', { name })}onPress={onPress}disabled={busy}hitSlop={size === 'header' ? 6 : 8}diff --git a/mobile/src/components/nutrition/NutritionCharts.tsx b/mobile/src/components/nutrition/NutritionCharts.tsxindex 83518c0..b7ee2cb 100644--- a/mobile/src/components/nutrition/NutritionCharts.tsx+++ b/mobile/src/components/nutrition/NutritionCharts.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { View } from 'react-native'import * as Haptics from 'expo-haptics'import Svg, { Circle, G, Line, Path, Rect, Text as SvgText } from 'react-native-svg'-import { formatDay } from '@lyftr/shared'+import { formatDay, useTranslation } from '@lyftr/shared'import { AppText } from '../ui'import { useTheme } from '../../theme/useTheme'import { MACRO_COLORS } from './nutritionMeta'@@ -75,6 +75,7 @@ export interface MacroHistoryPoint { date: string; protein: number; carbs: numbeexport function MacroHistoryChart({ data, width, height = 200 }: {data: MacroHistoryPoint[]; width: number; height?: number}) {+ const { t } = useTranslation()const { colors } = useTheme()const [sel, setSel] = useState<number | null>(null)if (!data.length || width <= 0) return null@@ -114,7 +115,7 @@ export function MacroHistoryChart({ data, width, height = 200 }: {// Thin x-labels so they never overlap (recharts auto-skips too).const maxLabels = Math.max(2, Math.floor(plotW / 44))const every = Math.ceil(n / maxLabels)- const fmt = (d: string) => formatDay(d, 'M/d')+ const fmt = (d: string) => formatDay(d, 'numericMonthDay')const selPt = sel != null ? data[sel] : null@@ -166,12 +167,12 @@ export function MacroHistoryChart({ data, width, height = 200 }: {className="absolute rounded-lg border border-surface-border bg-surface-raised px-2.5 py-1.5"style={{ left: clamp(xAt(sel!) - 60, 0, Math.max(0, width - 120)), top: 0, width: 120 }}>- <AppText variant="caption" color="muted">{formatDay(selPt.date, 'MMM d')}</AppText>+ <AppText variant="caption" color="muted">{formatDay(selPt.date, 'monthDay')}</AppText><View className="mt-0.5 gap-0.5">{[- { label: 'Protein', value: selPt.protein, color: MACRO_COLORS.protein },- { label: 'Carbs', value: selPt.carbs, color: MACRO_COLORS.carbs },- { label: 'Fat', value: selPt.fat, color: MACRO_COLORS.fat },+ { label: t('food.macro.protein'), value: selPt.protein, color: MACRO_COLORS.protein },+ { label: t('food.macro.carbs'), value: selPt.carbs, color: MACRO_COLORS.carbs },+ { label: t('food.macro.fat'), value: selPt.fat, color: MACRO_COLORS.fat },].map((m) => (<View key={m.label} className="flex-row items-center justify-between"><View className="flex-row items-center gap-1.5">diff --git a/mobile/src/components/nutrition/NutritionSkeleton.tsx b/mobile/src/components/nutrition/NutritionSkeleton.tsxindex 3db5fe0..febc0fc 100644--- a/mobile/src/components/nutrition/NutritionSkeleton.tsx+++ b/mobile/src/components/nutrition/NutritionSkeleton.tsx@@ -1,4 +1,5 @@import { View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { Card, PageHeader, Screen, Skeleton } from '../ui'// Initial-load skeleton for the Nutrition page — content-shaped placeholders laid out@@ -7,10 +8,11 @@ import { Card, PageHeader, Screen, Skeleton } from '../ui'// its own shape instead of popping after a blank spinner. Mirrors WeightSkeleton /// ProgramsSkeleton. The PageHeader is the real, live title.export function NutritionSkeleton() {+ const { t } = useTranslation()return (<Screen><View className="gap-4 py-4">- <PageHeader title="Nutrition" subtitle="Macros & meals" action={<Skeleton width={92} height={32} radius={10} />} />+ <PageHeader title={t('food.page.title')} subtitle={t('food.page.subtitle')} action={<Skeleton width={92} height={32} radius={10} />} />{/* Diary / Trends switch */}<Skeleton height={44} radius={12} />diff --git a/mobile/src/components/nutrition/nutritionMeta.test.ts b/mobile/src/components/nutrition/nutritionMeta.test.tsindex 5d33101..374e440 100644--- a/mobile/src/components/nutrition/nutritionMeta.test.ts+++ b/mobile/src/components/nutrition/nutritionMeta.test.ts@@ -1,11 +1,18 @@-import { MACRO_TEXT, MEAL_COLORS, MEAL_LABELS, MEALS } from './nutritionMeta'+import { i18n } from '@lyftr/shared'+import { MACRO_TEXT, MEAL_COLORS, MEALS, mealLabel } from './nutritionMeta'// This suite also acts as a canary: nutritionMeta imports lucide-react-native (ESM), so// a green run here proves jest.config's transformIgnorePatterns whitelist is correct.describe('nutritionMeta', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })+it('labels every meal', () => {- expect(MEAL_LABELS.breakfast).toBe('Breakfast')- expect(Object.keys(MEAL_LABELS).sort()).toEqual(['breakfast', 'dinner', 'lunch', 'snacks'])+ expect(MEALS.map(mealLabel)).toEqual(['Breakfast', 'Lunch', 'Dinner', 'Snacks'])+ })++ it('labels every meal in Spanish after a language switch', async () => {+ await i18n.changeLanguage('es')+ expect(MEALS.map(mealLabel)).toEqual(['Desayuno', 'Almuerzo', 'Cena', 'Snacks'])})it('has a color for every meal', () => {diff --git a/mobile/src/components/nutrition/nutritionMeta.ts b/mobile/src/components/nutrition/nutritionMeta.tsindex 205cc29..50b68aa 100644--- a/mobile/src/components/nutrition/nutritionMeta.ts+++ b/mobile/src/components/nutrition/nutritionMeta.ts@@ -1,5 +1,5 @@import { Coffee, Cookie, Moon, Sun, type LucideIcon } from 'lucide-react-native'-import type { FoodLog } from '@lyftr/shared'+import { i18n, type FoodLog } from '@lyftr/shared'// Meal + macro presentation constants, ported 1:1 from web (Food.tsx / LogFood.tsx +// utils/macroColors.ts). Web expressed colors as Tailwind text-* classes; on native@@ -10,12 +10,7 @@ export type Meal = FoodLog['meal']export const MEALS: readonly Meal[] = ['breakfast', 'lunch', 'dinner', 'snacks']-export const MEAL_LABELS: Record<Meal, string> = {- breakfast: 'Breakfast',- lunch: 'Lunch',- dinner: 'Dinner',- snacks: 'Snacks',-}+export const mealLabel = (meal: Meal): string => i18n.t(`food.meal.${meal}`)export const MEAL_ICONS: Record<Meal, LucideIcon> = {breakfast: Coffee,diff --git a/mobile/src/components/programs/DayExercisesEditor.tsx b/mobile/src/components/programs/DayExercisesEditor.tsxindex 1db55ea..aeec3fe 100644--- a/mobile/src/components/programs/DayExercisesEditor.tsx+++ b/mobile/src/components/programs/DayExercisesEditor.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { Pressable, Text, View } from 'react-native'import { Dumbbell, Plus } from 'lucide-react-native'-import type { Exercise } from '@lyftr/shared'+import { useTranslation, type Exercise } from '@lyftr/shared'import { EmptyState } from '../ui'import { ExerciseFormCard } from '../workouts/ExerciseFormCard'import { ExercisePicker } from '../workouts/ExercisePicker'@@ -26,6 +26,7 @@ interface Props {export function DayExercisesEditor({exercises, onChange, pickerExercises, onCacheExercise, unit, restSecondsDefault, inputAccessoryViewID,}: Props) {+ const { t } = useTranslation()const { accent } = useTheme()const [showPicker, setShowPicker] = useState(false)@@ -82,12 +83,12 @@ export function DayExercisesEditor({className="mb-3 flex-row items-center justify-center gap-1.5 rounded-lg bg-brand-500 px-3 py-2.5 active:scale-95"><Plus size={13} color="#ffffff" />- <Text className="font-sans-semibold text-xs text-white">Add Exercise</Text>+ <Text className="font-sans-semibold text-xs text-white">{t('workouts.form.addExercise')}</Text></Pressable>{exercises.length === 0 ? (<View className="rounded-2xl border border-dashed border-surface-border">- <EmptyState compact icon={Dumbbell} title="No exercises yet" subtitle="Add an exercise to this day" />+ <EmptyState compact icon={Dumbbell} title={t('programs.form.dayEditor.emptyTitle')} subtitle={t('programs.form.dayEditor.emptySubtitle')} /></View>) : (<View className="gap-4">@@ -111,12 +112,12 @@ export function DayExercisesEditor({))}<PressableaccessibilityRole="button"- accessibilityLabel="Add exercise"+ accessibilityLabel={t('workouts.form.addExerciseLabel')}onPress={() => setShowPicker(true)}className="h-11 flex-row items-center justify-center gap-1.5 rounded-2xl border border-dashed border-surface-border active:opacity-60"><Plus size={14} color={accent} />- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Exercise</Text>+ <Text className="font-sans-semibold text-xs" style={{ color: accent }}>{t('workouts.form.addExercise')}</Text></Pressable></View>)}diff --git a/mobile/src/components/programs/DayPickerSheet.tsx b/mobile/src/components/programs/DayPickerSheet.tsxindex 3209128..b81f843 100644--- a/mobile/src/components/programs/DayPickerSheet.tsx+++ b/mobile/src/components/programs/DayPickerSheet.tsx@@ -1,7 +1,7 @@import { ScrollView, View } from 'react-native'import { Dumbbell } from 'lucide-react-native'import type { Program, ProgramDay } from '@lyftr/shared'-import { workoutDays, dayLabel, todaysDay } from '@lyftr/shared'+import { workoutDays, dayLabel, todaysDay, useTranslation } from '@lyftr/shared'import { AppText, ListRow, Sheet } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -33,6 +33,7 @@ export function pickProgramDay(// load from them) so the caller can pick which one to start/load. Only ever shown// when pickProgramDay() determined the program has more than one workout day.export function DayPickerSheet({ program, onSelect, onClose }: Props) {+ const { t } = useTranslation()const { accent } = useTheme()if (!program) return nullconst days = workoutDays(program)@@ -45,7 +46,7 @@ export function DayPickerSheet({ program, onSelect, onClose }: Props) {<AppText variant="label" color="muted" className="uppercase" style={{ letterSpacing: 1.5 }}>{program.name}</AppText>- <AppText variant="heading" className="mt-0.5">Pick a Day</AppText>+ <AppText variant="heading" className="mt-0.5">{t('programs.form.dayPicker.title')}</AppText></View><ScrollView style={{ maxHeight: 360 }} showsVerticalScrollIndicator={false}>{days.map((day, i) => (@@ -56,12 +57,12 @@ export function DayPickerSheet({ program, onSelect, onClose }: Props) {<AppText variant="bodySemibold">{dayLabel(day, day.order_index)}</AppText>{day.id === todayId ? (<View className="rounded-full bg-brand-500/15 px-1.5 py-0.5">- <AppText variant="caption" style={{ color: accent }}>TODAY</AppText>+ <AppText variant="caption" style={{ color: accent }}>{t('programs.detail.todayChip')}</AppText></View>) : null}</View>}- secondary={`${(day.exercises ?? []).length} exercise${(day.exercises ?? []).length === 1 ? '' : 's'}`}+ secondary={t('programs.count.exercises', { count: (day.exercises ?? []).length })}right={<Dumbbell size={16} color={accent} />}onPress={() => onSelect(program, day)}/>diff --git a/mobile/src/components/programs/ProgramCard.tsx b/mobile/src/components/programs/ProgramCard.tsxindex dad2332..ee3ca7e 100644--- a/mobile/src/components/programs/ProgramCard.tsx+++ b/mobile/src/components/programs/ProgramCard.tsx@@ -1,12 +1,11 @@import { useState } from 'react'import { Pressable, View } from 'react-native'import { router, type Href } from 'expo-router'-import { format } from 'date-fns'import { BookOpen, ChevronRight, Dumbbell, Layers, Moon, MoreVertical, Play, Sun } from 'lucide-react-native'import type { Program, ProgramDay } from '@lyftr/shared'import { useAsyncAction,activeSessionExercisesForDay, allExercises, dayLabel, isDayStartable, programExerciseCount, programSetCount,- sessionNameForDay, todaysDay,+ sessionNameForDay, todaysDay, formatDate, useTranslation} from '@lyftr/shared'import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -30,6 +29,7 @@ const activeHref = '/workouts/active' as unknown as Href// (the primary Start action), a kebab (⋮) ActionSheet (Edit / Delete — same as// WorkoutCard), and a chevron. Delete routes through the shared ConfirmSheet.export function ProgramCard({ program, onPress, onDeleted }: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const { session, startSession } = useWorkoutSession()const [confirming, setConfirming] = useState(false)@@ -71,7 +71,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {const remove = useAsyncAction(async () => {await client.programAPI.delete(program.id)onDeleted(program.id)- }, 'Failed to delete program')+ }, t('programs.deleteFailed'))return (<Pressable accessibilityRole="button" onPress={onPress} className="active:scale-[0.99]">@@ -80,19 +80,19 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {<View className="flex-1"><AppText variant="subheading" numberOfLines={1}>{program.name}</AppText><AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">- {format(new Date(program.created_at), 'MMM d, yyyy')}+ {formatDate(new Date(program.created_at), 'monthDayYear')}</AppText>{/* Metric chips with leading icons — shared taxonomy with WorkoutCard:Dumbbell = exercises, Layers = sets. */}<View className="mt-0.5 flex-row items-center gap-x-2 flex-wrap"><View className="flex-row items-center gap-1"><Dumbbell size={12} color={colors.txMuted} />- <AppText variant="caption" color="muted" numberOfLines={1}>{exCount} exercise{exCount === 1 ? '' : 's'}</AppText>+ <AppText variant="caption" color="muted" numberOfLines={1}>{t('programs.count.exercises', { count: exCount })}</AppText></View><AppText variant="caption" color="muted">·</AppText><View className="flex-row items-center gap-1"><Layers size={12} color={colors.txMuted} />- <AppText variant="caption" color="muted" numberOfLines={1}>{totalSets} set{totalSets === 1 ? '' : 's'}</AppText>+ <AppText variant="caption" color="muted" numberOfLines={1}>{t('programs.count.sets', { count: totalSets })}</AppText></View>{dayCount > 1 && today ? (<>@@ -100,7 +100,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {{today.is_rest_day ? (<View className="flex-row items-center gap-1"><Moon size={12} color={colors.txMuted} />- <AppText variant="caption" color="muted" numberOfLines={1}>Rest today</AppText>+ <AppText variant="caption" color="muted" numberOfLines={1}>{t('programs.card.restToday')}</AppText></View>) : (<View className="flex-row items-center gap-1">@@ -109,7 +109,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {things next to each other. Sun/Moon reads as a natural due/rest pair. */}<Sun size={12} color={accent} /><AppText variant="caption" numberOfLines={1} style={{ color: accent }}>- Today: {dayLabel(today, today.order_index)}+ {t('programs.card.today', { day: dayLabel(today, today.order_index) })}</AppText></View>)}@@ -121,7 +121,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {(Hevy/Strong pattern: 1-tap start from the list), kept out of the ⋮ menu. */}<IconButtonicon={Play}- label={`Start ${program.name}`}+ label={t('programs.card.startNamed', { name: program.name })}variant="solid"size="sm"onPress={handleStart}@@ -129,7 +129,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {/><IconButtonicon={MoreVertical}- label={`${program.name} options`}+ label={t('programs.card.optionsNamed', { name: program.name })}variant="ghost"size="sm"onPress={() => setMenuOpen(true)}@@ -148,7 +148,10 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {<View className="flex-1"><AppText variant="subheading" numberOfLines={1}>{program.name}</AppText><AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">- {exCount} exercise{exCount === 1 ? '' : 's'} · {totalSets} set{totalSets === 1 ? '' : 's'}+ {t('programs.card.summary', {+ exercises: t('programs.count.exercises', { count: exCount }),+ sets: t('programs.count.sets', { count: totalSets }),+ })}</AppText></View></View>@@ -160,7 +163,7 @@ export function ProgramCard({ program, onPress, onDeleted }: Props) {/><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete Program?', subject: `"${program.name}"` })}+ {...deleteConfirmProps({ title: t('programs.deleteConfirmTitle'), subject: `"${program.name}"` })}open={confirming}busy={remove.busy}error={remove.error}diff --git a/mobile/src/components/programs/ProgramDaysEditor.test.tsx b/mobile/src/components/programs/ProgramDaysEditor.test.tsxindex 2361f5b..541d079 100644--- a/mobile/src/components/programs/ProgramDaysEditor.test.tsx+++ b/mobile/src/components/programs/ProgramDaysEditor.test.tsx@@ -1,4 +1,5 @@import { fireEvent, render, screen } from '@testing-library/react-native'+import { i18n } from '@lyftr/shared'// Same transitive-import stubs as DayPickerSheet.test.tsx (ui barrel → useTheme →// lib/lyftr → expo-router; storage adapter → AsyncStorage; Sheet → safe-area).@@ -38,6 +39,33 @@ const renderEditor = (days: DayDraft[], onChange = jest.fn()) => {}describe('ProgramDaysEditor', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ const view = render(+ <ProgramDaysEditor+ days={[dayDraft({ exercises: [{ exercise_id: 1, notes: '', rest_seconds: 90, sets: [] }] }), dayDraft({ order_index: 1, is_rest_day: true })]}+ onChange={jest.fn()}+ pickerExercises={{}}+ onCacheExercise={() => {}}+ unit="lbs"+ restSecondsDefault={90}+ />+ )+ try {+ expect(screen.getByText('Agregar día de entrenamiento')).toBeTruthy()+ expect(screen.getByText('Agregar día de descanso')).toBeTruthy()+ expect(screen.getByText('1 ejercicio')).toBeTruthy()+ expect(screen.getAllByLabelText('Quitar día')).toHaveLength(2)+ expect(screen.getByLabelText('Subir el día 1')).toBeTruthy()+ expect(screen.getByPlaceholderText('Día de descanso 2')).toBeTruthy()+ expect(screen.queryByText('Add Workout Day')).toBeNull()+ } finally {+ // Unmount first: restoring English under a mounted tree is a state update outside act.+ view.unmount()+ await i18n.changeLanguage('en')+ }+ })+it('renders the empty state when there are no days', () => {renderEditor([])expect(screen.getByText(/No days yet/)).toBeTruthy()diff --git a/mobile/src/components/programs/ProgramDaysEditor.tsx b/mobile/src/components/programs/ProgramDaysEditor.tsxindex c9c9709..96d5ebf 100644--- a/mobile/src/components/programs/ProgramDaysEditor.tsx+++ b/mobile/src/components/programs/ProgramDaysEditor.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { Pressable, View } from 'react-native'import { ChevronDown, ChevronRight, ChevronUp, Dumbbell, Moon, Plus, Trash2 } from 'lucide-react-native'-import type { Exercise } from '@lyftr/shared'+import { useTranslation, type Exercise } from '@lyftr/shared'import { AppText, Field, IconButton, SegmentedControl } from '../ui'import { useTheme } from '../../theme/useTheme'import { DayExercisesEditor } from './DayExercisesEditor'@@ -24,6 +24,7 @@ interface Props {export function ProgramDaysEditor({days, onChange, pickerExercises, onCacheExercise, unit, restSecondsDefault, inputAccessoryViewID,}: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const [expanded, setExpanded] = useState<number | null>(() => days.findIndex((d) => !d.is_rest_day))@@ -59,7 +60,7 @@ export function ProgramDaysEditor({<View className="gap-3">{days.length === 0 ? (<AppText variant="caption" color="muted" className="py-4 text-center">- No days yet — add a workout or rest day below.+ {t('programs.form.daysEditor.empty')}</AppText>) : null}@@ -72,10 +73,10 @@ export function ProgramDaysEditor({><View className="flex-row items-center gap-2 p-3"><View className="flex-shrink-0">- <Pressable accessibilityRole="button" accessibilityLabel={`Move day ${idx + 1} up`} onPress={() => moveDay(idx, -1)} disabled={idx === 0} hitSlop={4} className={idx === 0 ? 'opacity-20' : 'active:opacity-60'}>+ <Pressable accessibilityRole="button" accessibilityLabel={t('programs.form.daysEditor.moveUpNumbered', { number: idx + 1 })} onPress={() => moveDay(idx, -1)} disabled={idx === 0} hitSlop={4} className={idx === 0 ? 'opacity-20' : 'active:opacity-60'}><ChevronUp size={16} color={colors.txMuted} /></Pressable>- <Pressable accessibilityRole="button" accessibilityLabel={`Move day ${idx + 1} down`} onPress={() => moveDay(idx, 1)} disabled={idx === days.length - 1} hitSlop={4} className={idx === days.length - 1 ? 'opacity-20' : 'active:opacity-60'}>+ <Pressable accessibilityRole="button" accessibilityLabel={t('programs.form.daysEditor.moveDownNumbered', { number: idx + 1 })} onPress={() => moveDay(idx, 1)} disabled={idx === days.length - 1} hitSlop={4} className={idx === days.length - 1 ? 'opacity-20' : 'active:opacity-60'}><ChevronDown size={16} color={colors.txMuted} /></Pressable></View>@@ -87,18 +88,18 @@ export function ProgramDaysEditor({<View className="flex-1"><Fieldvalue={day.name}- onChangeText={(t) => updateDay(idx, { name: t })}- placeholder={day.is_rest_day ? `Rest Day ${idx + 1}` : `Day ${idx + 1}`}+ onChangeText={(text) => updateDay(idx, { name: text })}+ placeholder={day.is_rest_day ? t('programs.form.daysEditor.restPlaceholder', { number: idx + 1 }) : t('programs.day.numbered', { number: idx + 1 })}/></View>- <IconButton icon={Trash2} label="Remove day" variant="ghost" size="sm" onPress={() => removeDay(idx)} />+ <IconButton icon={Trash2} label={t('programs.form.daysEditor.remove')} variant="ghost" size="sm" onPress={() => removeDay(idx)} /></View><View className="px-3 pb-3"><SegmentedControlsize="sm"- options={[{ value: 'workout', label: 'Workout' }, { value: 'rest', label: 'Rest' }] as const}+ options={[{ value: 'workout', label: t('programs.form.daysEditor.workout') }, { value: 'rest', label: t('programs.form.daysEditor.rest') }] as const}value={day.is_rest_day ? 'rest' : 'workout'}onChange={(v) => setDayType(idx, v === 'rest')}/>@@ -111,7 +112,7 @@ export function ProgramDaysEditor({className="flex-row items-center justify-between border-t border-surface-border/60 px-3 py-2.5 active:bg-surface-muted/40"><AppText variant="caption" color="muted">- {day.exercises.length} exercise{day.exercises.length === 1 ? '' : 's'}+ {t('programs.count.exercises', { count: day.exercises.length })}</AppText>{isOpen ? <ChevronDown size={14} color={colors.txMuted} /> : <ChevronRight size={14} color={colors.txMuted} />}</Pressable>@@ -141,7 +142,7 @@ export function ProgramDaysEditor({className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg border border-brand-500/20 bg-brand-500/10 py-2.5 active:scale-95"><Plus size={14} color={accent} />- <AppText variant="label" style={{ color: accent }}>Add Workout Day</AppText>+ <AppText variant="label" style={{ color: accent }}>{t('programs.form.daysEditor.addWorkoutDay')}</AppText></Pressable><PressableaccessibilityRole="button"@@ -149,7 +150,7 @@ export function ProgramDaysEditor({className="flex-1 flex-row items-center justify-center gap-1.5 rounded-lg border border-surface-border bg-surface-muted py-2.5 active:scale-95"><Moon size={14} color={colors.txMuted} />- <AppText variant="label" color="secondary">Add Rest Day</AppText>+ <AppText variant="label" color="secondary">{t('programs.form.daysEditor.addRestDay')}</AppText></Pressable></View></View>diff --git a/mobile/src/components/programs/ProgramsSkeleton.tsx b/mobile/src/components/programs/ProgramsSkeleton.tsxindex 966fc44..27c802f 100644--- a/mobile/src/components/programs/ProgramsSkeleton.tsx+++ b/mobile/src/components/programs/ProgramsSkeleton.tsx@@ -1,4 +1,5 @@import { router } from 'expo-router'+import { useTranslation } from '@lyftr/shared'import { Plus } from 'lucide-react-native'import { IconButton, ListScreenSkeleton } from '../ui'@@ -8,15 +9,16 @@ import { IconButton, ListScreenSkeleton } from '../ui'// The PageHeader + its "New Program" action are the REAL controls, live immediately;// only the data-shaped regions are placeholders. Mirrors WorkoutsSkeleton.export function ProgramsSkeleton() {+ const { t } = useTranslation()return (<ListScreenSkeleton- title="Programs"- subtitle="Reusable workout templates"+ title={t('programs.title')}+ subtitle={t('programs.subtitle')}statCount={2}action={<IconButtonicon={Plus}- label="New Program"+ label={t('programs.newProgram')}variant="solid"size="md"onPress={() => router.push('/programs/new')}diff --git a/mobile/src/components/settings/LanguageSheet.test.tsx b/mobile/src/components/settings/LanguageSheet.test.tsxnew file mode 100644index 0000000..136269c--- /dev/null+++ b/mobile/src/components/settings/LanguageSheet.test.tsx@@ -0,0 +1,74 @@+import { fireEvent, render, screen } from '@testing-library/react-native'++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 }),+}))++import { LANGUAGE_ORDER, LANGUAGE_NAMES } from '@lyftr/shared'+import { LanguageSheet, filterLanguages } from './LanguageSheet'++const setup = (value: 'system' | 'en' | 'es' = 'system') => {+ const onSelect = jest.fn()+ const onClose = jest.fn()+ render(<LanguageSheet open value={value} onSelect={onSelect} onClose={onClose} />)+ return { onSelect, onClose }+}++describe('LanguageSheet', () => {+ it('lists System first, then names in registry order', () => {+ setup()+ const buttons = screen.getAllByRole('button')+ const labels = ['System (English)', ...LANGUAGE_ORDER.map((c) => LANGUAGE_NAMES[c])]+ expect(buttons).toHaveLength(labels.length)+ labels.forEach((l) => expect(screen.getByText(l)).toBeTruthy())+ expect(buttons[0]).toHaveTextContent('System (English)')+ LANGUAGE_ORDER.forEach((c, i) => expect(buttons[i + 1]).toHaveTextContent(new RegExp('^' + LANGUAGE_NAMES[c])))+ })++ it('marks only the current value as selected', () => {+ setup('es')+ const buttons = screen.getAllByRole('button')+ const selected = buttons.filter((b) => b.props.accessibilityState?.selected === true)+ expect(selected).toHaveLength(1)+ expect(selected[0]).toHaveTextContent(/^Español/)+ })+++ it('pressing a different language closes and selects', () => {+ const { onSelect, onClose } = setup('system')+ fireEvent.press(screen.getByText('English'))+ expect(onClose).toHaveBeenCalled()+ expect(onSelect).toHaveBeenCalledWith('en')+ })++ it('pressing the current language closes without selecting', () => {+ const { onSelect, onClose } = setup('en')+ fireEvent.press(screen.getByText('English'))+ expect(onClose).toHaveBeenCalled()+ expect(onSelect).not.toHaveBeenCalled()+ })++ it('has no search field at the current language count', () => {+ setup()+ expect(screen.queryByPlaceholderText('Search languages')).toBeNull()+ })+})++describe('filterLanguages', () => {+ it.each([+ ['', ['en', 'es']],+ [' ', ['en', 'es']],+ ['espanol', ['es']],+ ['ESP', ['es']],+ ['es', ['es']],+ ['zz', []],+ ])('%j -> %j', (q, want) => {+ expect(filterLanguages(LANGUAGE_ORDER, q)).toEqual(want)+ })+})diff --git a/mobile/src/components/settings/LanguageSheet.tsx b/mobile/src/components/settings/LanguageSheet.tsxnew file mode 100644index 0000000..659b554--- /dev/null+++ b/mobile/src/components/settings/LanguageSheet.tsx@@ -0,0 +1,81 @@+import { useState } from 'react'+import { ScrollView, View } from 'react-native'+import { Check } from 'lucide-react-native'+import {+ useTranslation,+ SUPPORTED_LANGUAGES,+ LANGUAGE_NAMES,+ LANGUAGE_ORDER,+ languageChoiceLabel,+ type Language,+ type LanguagePreference,+} from '@lyftr/shared'+import { AppText, ListRow, SearchField, Sheet } from '../ui'+import { useTheme } from '../../theme/useTheme'++// About 7 rows of ~48px fit in the 360px list below; search appears once the list stops fitting.+export const LANGUAGE_SEARCH_FROM = 8++const fold = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()++export function filterLanguages(codes: readonly Language[], query: string): Language[] {+ const q = fold(query.trim())+ if (!q) return [...codes]+ return codes.filter((c) => fold(LANGUAGE_NAMES[c]).includes(q) || c.toLowerCase().includes(q))+}++interface Props {+ open: boolean+ value: LanguagePreference+ onSelect: (p: LanguagePreference) => void+ onClose: () => void+}++export function LanguageSheet({ open, value, onSelect, onClose }: Props) {+ const { t } = useTranslation()+ const { accent } = useTheme()+ const [query, setQuery] = useState('')+ const showSearch = SUPPORTED_LANGUAGES.length >= LANGUAGE_SEARCH_FROM+ const shown = filterLanguages(LANGUAGE_ORDER, showSearch ? query : '')++ const pick = (p: LanguagePreference) => {+ onClose()+ if (p !== value) onSelect(p)+ }+ const mark = (p: LanguagePreference) => (value === p ? <Check size={18} color={accent} /> : undefined)++ return (+ <Sheet open={open} onClose={onClose} haptic="selection">+ <View className="px-6">+ <View className="items-center pb-4">+ <AppText variant="heading">{t('settings.language.label')}</AppText>+ </View>+ {showSearch ? (+ <View className="pb-2">+ <SearchField value={query} onChangeText={setQuery} placeholder={t('settings.language.search')} />+ </View>+ ) : null}+ <ScrollView style={{ maxHeight: 360 }} keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false}>+ <ListRow+ primary={languageChoiceLabel('system')}+ right={mark('system')}+ selected={value === 'system'}+ onPress={() => pick('system')}+ />+ {shown.map((code) => (+ <ListRow+ key={code}+ primary={<AppText variant="bodySemibold" accessibilityLanguage={code}>{LANGUAGE_NAMES[code]}</AppText>}+ right={mark(code)}+ selected={value === code}+ onPress={() => pick(code)}+ />+ ))}+ {shown.length === 0 ? (+ <AppText variant="caption" color="muted" className="py-3">{t('settings.language.noMatches')}</AppText>+ ) : null}+ </ScrollView>+ </View>+ </Sheet>+ )+}diff --git a/mobile/src/components/settings/SettingsLanguageRow.test.tsx b/mobile/src/components/settings/SettingsLanguageRow.test.tsxnew file mode 100644index 0000000..9b69afa--- /dev/null+++ b/mobile/src/components/settings/SettingsLanguageRow.test.tsx@@ -0,0 +1,48 @@+import { act, fireEvent, render, screen } from '@testing-library/react-native'++jest.mock('expo-router', () => ({+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn(), back: jest.fn(), canGoBack: () => false },+}))+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', () => {+ const { View } = require('react-native')+ return {+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),+ SafeAreaView: View,+ }+})++import { i18n } from '@lyftr/shared'+import { useLanguageStore, useSettingsStore } from '../../lib/lyftr'+import SettingsScreen from '../../../app/(tabs)/settings/index'++// Renders the real Settings screen, so it fails if the screen stops rendering <LanguageSheet>+// (the sheet's own test cannot catch that: it renders the sheet directly).+describe('Settings screen Language row', () => {+ beforeEach(() => {+ useSettingsStore.setState({ loaded: true, loadFailed: false, fetch: jest.fn().mockResolvedValue(undefined) })+ })++ it('opens the language sheet and switches language', async () => {+ render(<SettingsScreen />)++ expect(screen.getByText('Language')).toBeTruthy()+ expect(screen.queryByText('Español')).toBeNull()++ fireEvent.press(screen.getByText('Language'))++ expect(screen.getByText('Español')).toBeTruthy()+ // The row's own value reads "System (English)" too, so the sheet's option makes two.+ expect(screen.getAllByText('System (English)')).toHaveLength(2)+ expect(screen.getByText('English')).toBeTruthy()++ await act(async () => {+ fireEvent.press(screen.getByText('Español'))+ })++ expect(useLanguageStore.getState().preference).toBe('es')+ expect(i18n.language).toBe('es')+ })+})diff --git a/mobile/src/components/ui/ActionSheet.tsx b/mobile/src/components/ui/ActionSheet.tsxindex 4c55150..07dc591 100644--- a/mobile/src/components/ui/ActionSheet.tsx+++ b/mobile/src/components/ui/ActionSheet.tsx@@ -1,6 +1,7 @@import type { ReactNode } from 'react'import { View } from 'react-native'import type { LucideIcon } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'import { AppText } from './Typography'import { SheetButton } from './SheetButton'import { Sheet, SHEET_ANIM_MS } from './Sheet'@@ -37,8 +38,9 @@ interface Props {// when there are exactly two. An action's onPress fires *after* the sheet dismisses so// a follow-up modal (e.g. a delete ConfirmSheet) isn't presented mid-close.export function ActionSheet({- open, title, subtitle, header, actions, cancelLabel = 'Cancel', layout = 'stack', onClose,+ open, title, subtitle, header, actions, cancelLabel, layout = 'stack', onClose,}: Props) {+ const { t } = useTranslation()const run = (onPress: () => void) => {onClose()setTimeout(onPress, SHEET_ANIM_MS)@@ -85,7 +87,7 @@ export function ActionSheet({) : (actions.map((a, i) => button(a, i)))}- <SheetButton label={cancelLabel} variant="muted" onPress={onClose} />+ <SheetButton label={cancelLabel ?? t('common.cancel')} variant="muted" onPress={onClose} /></View></View></Sheet>diff --git a/mobile/src/components/ui/ConfirmSheet.tsx b/mobile/src/components/ui/ConfirmSheet.tsxindex c5d8382..bc450bc 100644--- a/mobile/src/components/ui/ConfirmSheet.tsx+++ b/mobile/src/components/ui/ConfirmSheet.tsx@@ -1,5 +1,6 @@import { View } from 'react-native'import type { LucideIcon } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { AppText } from './Typography'import { Alert } from './Alert'@@ -32,9 +33,10 @@ export interface ConfirmSheetProps {// is centered under it, and a Cancel / confirm button pair sits below. The sheet// chrome (slide-up, scrim, insets, grabber) lives in the generic Sheet.export function ConfirmSheet({- open, title, message, confirmLabel, busyLabel, cancelLabel = 'Cancel',+ open, title, message, confirmLabel, busyLabel, cancelLabel,destructive = false, icon: Icon, busy = false, error, onConfirm, onCancel,}: ConfirmSheetProps) {+ const { t } = useTranslation()const { brand, accent, isDark } = useTheme()// errorSoft reads on dark, error on light — same split as IconButton.const badgeIconColor = destructive ? (isDark ? brand.errorSoft : brand.error) : accent@@ -61,7 +63,7 @@ export function ConfirmSheet({<View className="flex-row gap-3"><View className="flex-1">- <SheetButton label={cancelLabel} variant="muted" disabled={busy} onPress={onCancel} />+ <SheetButton label={cancelLabel ?? t('common.cancel')} variant="muted" disabled={busy} onPress={onCancel} /></View><View className="flex-1"><SheetButtondiff --git a/mobile/src/components/ui/DateInput.tsx b/mobile/src/components/ui/DateInput.tsxindex 9bb1d73..96f3e88 100644--- a/mobile/src/components/ui/DateInput.tsx+++ b/mobile/src/components/ui/DateInput.tsx@@ -3,7 +3,7 @@ import { Modal, Platform, Pressable, View } from 'react-native'import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'import DateTimePicker, { type DateTimePickerEvent } from '@react-native-community/datetimepicker'import { CalendarDays } from 'lucide-react-native'-import { format } from 'date-fns'+import { formatDate, useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { AppText, Label } from './Typography'@@ -36,6 +36,7 @@ const toValue = (d: Date): string => `${d.getFullYear()}-${pad(d.getMonth() + 1)// full-width Modal (its own view hierarchy → nest a SafeAreaProvider, same rule as// ExercisePicker) where width is unconstrained.export function DateInput({ label, value, onChange, maximumDate }: Props) {+ const { t } = useTranslation()const { colors, accent, isDark } = useTheme()const [open, setOpen] = useState(false)const date = toLocalDate(value)@@ -65,12 +66,12 @@ export function DateInput({ label, value, onChange, maximumDate }: Props) {{label ? <Label>{label}</Label> : null}<PressableaccessibilityRole="button"- accessibilityLabel={label ?? 'Pick date'}+ accessibilityLabel={label ?? t('common.pickDate')}onPress={() => setOpen((o) => !o)}className="h-12 flex-row items-center gap-2.5 rounded-lg border border-surface-border bg-surface-overlay px-3.5 active:scale-[0.99]"><CalendarDays size={16} color={colors.txMuted} />- <AppText variant="body">{format(date, 'MMM d, yyyy')}</AppText>+ <AppText variant="body">{formatDate(date, 'monthDayYear')}</AppText></Pressable>{/* Android: mount inline — it's a self-contained dialog. */}@@ -99,14 +100,14 @@ export function DateInput({ label, value, onChange, maximumDate }: Props) {className="mx-3 mb-3 rounded-2xl border border-surface-border bg-surface-base p-2"><View className="flex-row items-center justify-between px-2 pb-1 pt-2">- <AppText variant="bodySemibold">{label ?? 'Select date'}</AppText>+ <AppText variant="bodySemibold">{label ?? t('common.selectDate')}</AppText><PressableaccessibilityRole="button"onPress={() => setOpen(false)}hitSlop={8}className="px-2 py-1 active:opacity-60">- <AppText variant="bodySemibold" color="brand">Done</AppText>+ <AppText variant="bodySemibold" color="brand">{t('common.done')}</AppText></Pressable></View><DateTimePickerdiff --git a/mobile/src/components/ui/ErrorState.test.tsx b/mobile/src/components/ui/ErrorState.test.tsxindex c8ba128..1388d37 100644--- a/mobile/src/components/ui/ErrorState.test.tsx+++ b/mobile/src/components/ui/ErrorState.test.tsx@@ -1,6 +1,7 @@import { fireEvent, render, screen } from '@testing-library/react-native'import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'import { Button } from './Button'+import { i18n } from '@lyftr/shared'import { ErrorState } from './ErrorState'// Same preamble as the other component tests: expo-router can't load under bare jest, and@@ -20,6 +21,19 @@ jest.mock('react-native-safe-area-context', () => ({// supposed to read as one screen, and a test that only exists on one side is how they// quietly stop matching.describe('ErrorState', () => {+ it('reads its retry label from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ const view = render(<ErrorState title="x" message="y" onRetry={() => {}} />)+ try {+ expect(screen.getByText('Intentar de nuevo')).toBeTruthy()+ expect(screen.queryByText('Try again')).toBeNull()+ } finally {+ // Unmount first: restoring English under a mounted tree is a state update outside act.+ view.unmount()+ await i18n.changeLanguage('en')+ }+ })+it('names what failed and why', () => {render(<ErrorState title="Couldn't load your dashboard" message="The server didn't respond in time." />)expect(screen.getByText("Couldn't load your dashboard")).toBeTruthy()diff --git a/mobile/src/components/ui/ErrorState.tsx b/mobile/src/components/ui/ErrorState.tsxindex 06fd8f5..44b3a69 100644--- a/mobile/src/components/ui/ErrorState.tsx+++ b/mobile/src/components/ui/ErrorState.tsx@@ -1,5 +1,6 @@import type { ReactNode } from 'react'import { View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { semanticInk } from '../../theme/theme'import { useTheme } from '../../theme/useTheme'import { AppText } from './Typography'@@ -37,10 +38,11 @@ export function ErrorState({message,size = 'section',onRetry,- retryLabel = 'Try again',+ retryLabel,retrying = false,secondary,}: Props) {+ const { t } = useTranslation()const { isDark } = useTheme()// Status colour, not the muted grey of an empty state — and via semanticInk because// the raw 400s fail AA on this app's light surface (see alertContrast.test.ts).@@ -70,7 +72,7 @@ export function ErrorState({{onRetry || secondary ? (<View className="mt-1 flex-row flex-wrap items-center justify-center gap-2">{onRetry ? (- <Button title={retrying ? 'Retrying…' : retryLabel} onPress={onRetry} loading={retrying} disabled={retrying} />+ <Button title={retrying ? t('common.retrying') : (retryLabel ?? t('common.tryAgain'))} onPress={onRetry} loading={retrying} disabled={retrying} />) : null}{secondary}</View>diff --git a/mobile/src/components/ui/ListRow.tsx b/mobile/src/components/ui/ListRow.tsxindex ab4d2fb..a6598d8 100644--- a/mobile/src/components/ui/ListRow.tsx+++ b/mobile/src/components/ui/ListRow.tsx@@ -9,6 +9,8 @@ interface Props {/** Right-aligned slot — an IconButton, a value, a chevron. */right?: ReactNodeonPress?: () => void+ /** Announced as selected to screen readers; the visual mark is the caller's `right` node. */+ selected?: booleanclassName?: string}@@ -16,7 +18,7 @@ interface Props {// secondary text with a right-hand action, separated by hairline borders. Rendered// as a Pressable only when tappable so non-interactive rows don't announce as// buttons to screen readers.-export function ListRow({ primary, secondary, right, onPress, className = '' }: Props) {+export function ListRow({ primary, secondary, right, onPress, selected, className = '' }: Props) {const body = (<><View className="flex-1 pr-3">@@ -38,7 +40,7 @@ export function ListRow({ primary, secondary, right, onPress, className = '' }:)const rowClass = `flex-row items-center justify-between py-3 border-b border-surface-border ${className}`return onPress ? (- <Pressable accessibilityRole="button" onPress={onPress} className={`${rowClass} active:bg-surface-muted`}>+ <Pressable accessibilityRole="button" accessibilityState={selected === undefined ? undefined : { selected }} onPress={onPress} className={`${rowClass} active:bg-surface-muted`}>{body}</Pressable>) : (diff --git a/mobile/src/components/ui/Loading.tsx b/mobile/src/components/ui/Loading.tsxindex 0cf64a8..99e6b6a 100644--- a/mobile/src/components/ui/Loading.tsx+++ b/mobile/src/components/ui/Loading.tsx@@ -13,6 +13,7 @@ import Animated, {withTiming,} from 'react-native-reanimated'import { LinearGradient } from 'expo-linear-gradient'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { AppText } from './Typography'@@ -62,7 +63,8 @@ function RepDot({ index, mutedColor }: { index: number; mutedColor: string }) {)}-export function Loading({ sublabel = 'Loading' }: { sublabel?: string }) {+export function Loading({ sublabel }: { sublabel?: string }) {+ const { t: translate } = useTranslation()const { colors, brand } = useTheme()const t = useSharedValue(0)@@ -143,7 +145,7 @@ export function Loading({ sublabel = 'Loading' }: { sublabel?: string }) {<View className="items-center"><AppText variant="heading" className="tracking-tight">lyftr</AppText><AppText variant="label" color="muted" className="mt-2 uppercase" style={{ letterSpacing: 3 }}>- {sublabel}+ {sublabel ?? translate('common.loading')}</AppText></View></View>diff --git a/mobile/src/components/ui/NumericKeyboardAccessory.tsx b/mobile/src/components/ui/NumericKeyboardAccessory.tsxindex 3a4cca8..c963d20 100644--- a/mobile/src/components/ui/NumericKeyboardAccessory.tsx+++ b/mobile/src/components/ui/NumericKeyboardAccessory.tsx@@ -1,4 +1,5 @@import { InputAccessoryView, Keyboard, Platform, Pressable, View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { AppText } from './Typography'// iOS number-pad / decimal-pad keyboards have NO return key, so there's no built-in way@@ -10,12 +11,13 @@ import { AppText } from './Typography'export const NUMERIC_ACCESSORY_ID = 'lyftr-numeric-done'export function NumericKeyboardAccessory() {+ const { t } = useTranslation()if (Platform.OS !== 'ios') return nullreturn (<InputAccessoryView nativeID={NUMERIC_ACCESSORY_ID}><View className="flex-row justify-end border-t border-surface-border bg-surface-raised px-2 py-1.5">- <Pressable onPress={() => Keyboard.dismiss()} hitSlop={8} accessibilityLabel="Dismiss keyboard" className="rounded-lg px-4 py-1.5 active:opacity-60">- <AppText variant="bodySemibold" color="brand">Done</AppText>+ <Pressable onPress={() => Keyboard.dismiss()} hitSlop={8} accessibilityLabel={t('common.dismissKeyboard')} className="rounded-lg px-4 py-1.5 active:opacity-60">+ <AppText variant="bodySemibold" color="brand">{t('common.done')}</AppText></Pressable></View></InputAccessoryView>diff --git a/mobile/src/components/ui/PasswordField.tsx b/mobile/src/components/ui/PasswordField.tsxindex 2b46542..f8679ca 100644--- a/mobile/src/components/ui/PasswordField.tsx+++ b/mobile/src/components/ui/PasswordField.tsx@@ -2,7 +2,7 @@ import type { ReactNode } from 'react'import { useState } from 'react'import { Pressable, View } from 'react-native'import { Check, Eye, EyeOff, X } from 'lucide-react-native'-import type { RuleState } from '@lyftr/shared'+import { useTranslation, type RuleState } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { Field } from './Field'import { AppText } from './Typography'@@ -45,6 +45,7 @@ interface Props {// No Caps Lock warning here, unlike web: a soft keyboard shows its own shift state, and// React Native surfaces no modifier state to read anyway.export function PasswordField({ label, value, onChangeText, textContentType, children }: Props) {+ const { t } = useTranslation()const { colors } = useTheme()const [visible, setVisible] = useState(false)@@ -68,7 +69,7 @@ export function PasswordField({ label, value, onChangeText, textContentType, chionPress={() => setVisible((v) => !v)}hitSlop={10}accessibilityRole="button"- accessibilityLabel={`${visible ? 'Hide' : 'Show'} ${label.toLowerCase()}`}+ accessibilityLabel={t(visible ? 'common.password.hide' : 'common.password.show', { label: label.toLowerCase() })}>{visible? <EyeOff size={18} color={colors.txMuted} strokeWidth={2} />diff --git a/mobile/src/components/ui/SearchField.tsx b/mobile/src/components/ui/SearchField.tsxindex 6f2d5b8..e6c03c1 100644--- a/mobile/src/components/ui/SearchField.tsx+++ b/mobile/src/components/ui/SearchField.tsx@@ -1,5 +1,6 @@import { ActivityIndicator, Pressable, type TextInputProps } from 'react-native'import { Search, X } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { Field } from './Field'@@ -16,14 +17,15 @@ interface Props extends Omit<TextInputProps, 'value' | 'onChangeText'> {// slot that is a spinner while `loading`, a clear (×) button when there's text, or// empty. Reusable across every searchable list (Workouts, Exercises, Food, …) so the// search affordance — icon, clear, loading — is identical everywhere.-export function SearchField({ value, onChangeText, loading = false, placeholder = 'Search…', ...rest }: Props) {+export function SearchField({ value, onChangeText, loading = false, placeholder, ...rest }: Props) {+ const { t } = useTranslation()const { accent, colors } = useTheme()return (<FieldleftIcon={Search}value={value}onChangeText={onChangeText}- placeholder={placeholder}+ placeholder={placeholder ?? t('common.search')}autoCapitalize="none"autoCorrect={false}returnKeyType="search"@@ -33,7 +35,7 @@ export function SearchField({ value, onChangeText, loading = false, placeholder) : value.length > 0 ? (<PressableaccessibilityRole="button"- accessibilityLabel="Clear search"+ accessibilityLabel={t('common.clearSearch')}hitSlop={10}onPress={() => onChangeText('')}className="active:opacity-60"diff --git a/mobile/src/components/ui/StatFailure.tsx b/mobile/src/components/ui/StatFailure.tsxindex da31f01..a39e783 100644--- a/mobile/src/components/ui/StatFailure.tsx+++ b/mobile/src/components/ui/StatFailure.tsx@@ -1,4 +1,5 @@import { View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { semanticInk } from '../../theme/theme'import { useTheme } from '../../theme/useTheme'import { BarbellBroken } from './BarbellBroken'@@ -6,10 +7,11 @@ import { BarbellBroken } from './BarbellBroken'// A stat tile whose figure could not be loaded. Mirrors web ui/StatFailure: the dropped// barbell at tile-figure size, no words — the tile's own label already says what is// missing, and a 0 in its place would claim a figure we never got.-export function StatFailure({ label = "Couldn't load this figure" }: { label?: string }) {+export function StatFailure({ label }: { label?: string }) {+ const { t } = useTranslation()const { isDark } = useTheme()return (- <View accessible accessibilityRole="image" accessibilityLabel={label}>+ <View accessible accessibilityRole="image" accessibilityLabel={label ?? t('common.figureFailed')}><BarbellBroken size={26} color={semanticInk[isDark ? 'dark' : 'light'].error} /></View>)diff --git a/mobile/src/components/ui/StepperTile.tsx b/mobile/src/components/ui/StepperTile.tsxindex 8a438df..a407e2a 100644--- a/mobile/src/components/ui/StepperTile.tsx+++ b/mobile/src/components/ui/StepperTile.tsx@@ -3,6 +3,7 @@ import { Pressable, View } from 'react-native'import { Minus, Plus } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'import * as Haptics from 'expo-haptics'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { Label } from './Typography'@@ -31,6 +32,7 @@ export function StepperTile({disabled = false,children,}: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const tap = (delta: number) => {@@ -43,7 +45,7 @@ export function StepperTile({const stepBtn = (delta: number, StepIcon: LucideIcon, side: string) => (<PressableaccessibilityRole="button"- accessibilityLabel={`${delta < 0 ? 'Decrease' : 'Increase'} ${name}`}+ accessibilityLabel={t(delta < 0 ? 'common.stepper.decrease' : 'common.stepper.increase', { name })}disabled={disabled}onPress={() => tap(delta)}className={`flex-1 py-2.5 items-center justify-center active:bg-surface-muted ${disabled ? 'opacity-30' : ''} ${side}`}diff --git a/mobile/src/components/ui/Toast.tsx b/mobile/src/components/ui/Toast.tsxindex c60be40..0776472 100644--- a/mobile/src/components/ui/Toast.tsx+++ b/mobile/src/components/ui/Toast.tsx@@ -3,6 +3,7 @@ import { Pressable, View } from 'react-native'import Animated, { FadeInUp, FadeOutDown } from 'react-native-reanimated'import { X, ChevronRight } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'import { AppText } from './Typography'@@ -46,6 +47,7 @@ export function Toast({autoDismissMs = 4000,className = '',}: Props) {+ const { t } = useTranslation()const { colors, brand, accent, isDark } = useTheme()// Armed once on mount — parent re-renders must not extend the window (0 disables).@@ -104,7 +106,7 @@ export function Toast({)}<PressableonPress={onDismiss}- accessibilityLabel="Dismiss"+ accessibilityLabel={t('common.dismiss')}hitSlop={8}className="p-1.5 -m-1.5 active:opacity-60">diff --git a/mobile/src/components/ui/sheetActions.ts b/mobile/src/components/ui/sheetActions.tsindex 64701e0..20d8150 100644--- a/mobile/src/components/ui/sheetActions.ts+++ b/mobile/src/components/ui/sheetActions.ts@@ -1,4 +1,5 @@import { Edit2, Trash2 } from 'lucide-react-native'+import { i18n } from '@lyftr/shared'import type { SheetAction } from './ActionSheet'import type { ConfirmSheetProps } from './ConfirmSheet'@@ -8,11 +9,11 @@ import type { ConfirmSheetProps } from './ConfirmSheet'// SheetButton/ActionSheet primitives free of any app concepts. Add a preset here when// an action recurs across screens (duplicate, share, …); pass a label to override.-export function editAction(onPress: () => void, label = 'Edit'): SheetAction {+export function editAction(onPress: () => void, label = i18n.t('common.edit')): SheetAction {return { label, icon: Edit2, onPress }}-export function deleteAction(onPress: () => void, label = 'Delete'): SheetAction {+export function deleteAction(onPress: () => void, label = i18n.t('common.delete')): SheetAction {return { label, icon: Trash2, destructive: true, onPress }}@@ -26,9 +27,9 @@ export function deleteConfirmProps(): Pick<ConfirmSheetProps, 'title' | 'message' | 'confirmLabel' | 'busyLabel' | 'destructive' | 'icon'> {return {title,- message: `${subject} will be permanently deleted.`,- confirmLabel: 'Delete',- busyLabel: 'Deleting…',+ message: i18n.t('common.deleteConfirmMessage', { subject }),+ confirmLabel: i18n.t('common.delete'),+ busyLabel: i18n.t('common.deleting'),destructive: true,icon: Trash2,}diff --git a/mobile/src/components/weight/WeightEntryRow.tsx b/mobile/src/components/weight/WeightEntryRow.tsxindex 00ed1e2..7ed6eff 100644--- a/mobile/src/components/weight/WeightEntryRow.tsx+++ b/mobile/src/components/weight/WeightEntryRow.tsx@@ -3,7 +3,7 @@ import { Pressable, Text, View } from 'react-native'import { router } from 'expo-router'import * as Haptics from 'expo-haptics'import { ChevronRight, MoreVertical, Scale, TrendingDown, TrendingUp } from 'lucide-react-native'-import { useAsyncAction, displayWeight, entryDay, weightShort, type WeightLog, formatDay } from '@lyftr/shared'+import { useAsyncAction, displayWeight, entryDay, weightShort, type WeightLog, formatDay, useTranslation } from '@lyftr/shared'import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'import { useTheme } from '../../theme/useTheme'import { client } from '../../lib/lyftr'@@ -22,6 +22,7 @@ interface Props {// (Edit / Delete). Edit deep-links the detail straight into its inline edit form (?edit=1);// Delete routes through the shared ConfirmSheet.export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {+ const { t } = useTranslation()const { colors, accent, brand } = useTheme()const wUnit = weightShort(unit)const [menuOpen, setMenuOpen] = useState(false)@@ -30,7 +31,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {const deltaLbs = next ? item.weight - next.weight : 0const displayW = displayWeight(item.weight, unit)const displayDelta = displayWeight(Math.abs(deltaLbs), unit)- const dateLabel = formatDay(entryDay(item), 'MMM d, yyyy')+ const dateLabel = formatDay(entryDay(item), 'monthDayYear')// The catch here just put the card back - "a failed delete quietly restores the// card" - which is indistinguishable from a tap that never registered. The@@ -39,7 +40,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {await client.weightAPI.delete(item.id)Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {})onDeleted(item.id)- }, 'Failed to delete entry')+ }, t('weight.deleteFailed'))return (<Pressable onPress={() => router.push(`/weight/${item.id}`)} className="mb-2 active:scale-[0.99]">@@ -69,7 +70,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {</View><IconButtonicon={MoreVertical}- label={`${Math.round(displayW)} ${wUnit} options`}+ label={t('weight.row.options', { weight: Math.round(displayW), unit: wUnit })}variant="ghost"size="sm"onPress={() => setMenuOpen(true)}@@ -102,7 +103,7 @@ export function WeightEntryRow({ item, next, unit, onDeleted }: Props) {/><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete Entry?', subject: `${dateLabel} · ${Math.round(displayW)} ${wUnit}` })}+ {...deleteConfirmProps({ title: t('weight.deleteTitle'), subject: t('weight.deleteSubject', { date: dateLabel, weight: Math.round(displayW), unit: wUnit }) })}open={confirming}busy={remove.busy}error={remove.error}diff --git a/mobile/src/components/weight/WeightSkeleton.tsx b/mobile/src/components/weight/WeightSkeleton.tsxindex 74e3098..b5feab7 100644--- a/mobile/src/components/weight/WeightSkeleton.tsx+++ b/mobile/src/components/weight/WeightSkeleton.tsx@@ -1,4 +1,5 @@import { View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { Card, PageHeader, Screen, Skeleton, SkeletonList, SkeletonStatRow } from '../ui'// Initial-load skeleton for the Weight page — content-shaped placeholders laid out@@ -7,12 +8,13 @@ import { Card, PageHeader, Screen, Skeleton, SkeletonList, SkeletonStatRow } fro// after a blank spinner. The PageHeader is the real, live title. Mirrors the pattern// of WorkoutsSkeleton / ProgramsSkeleton.export function WeightSkeleton() {+ const { t } = useTranslation()return (<Screen><View className="gap-5 py-4"><PageHeader- title="Weight"- subtitle="Track your body weight over time"+ title={t('weight.title')}+ subtitle={t('weight.subtitle')}action={<Skeleton width={44} height={24} radius={999} />}/>diff --git a/mobile/src/components/workouts/ActiveExerciseCard.test.tsx b/mobile/src/components/workouts/ActiveExerciseCard.test.tsxindex 6c58205..a79808b 100644--- a/mobile/src/components/workouts/ActiveExerciseCard.test.tsx+++ b/mobile/src/components/workouts/ActiveExerciseCard.test.tsx@@ -1,5 +1,17 @@-import { renderHook, act } from '@testing-library/react-native'-import { useNumericText } from '@lyftr/shared'+import { renderHook, act, render, screen } from '@testing-library/react-native'+import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'+import { i18n, useNumericText, type ActiveSessionExercise } from '@lyftr/shared'+import { ActiveExerciseCard } from './ActiveExerciseCard'++// Same preamble as the other component tests: expo-router can't load under bare jest, and+// the card reaches it directly and via useTheme -> lib/lyftr.+jest.mock('expo-router', () => ({+ router: { push: jest.fn(), navigate: jest.fn(), replace: jest.fn() },+}))+jest.mock('@react-native-async-storage/async-storage', () => mockAsyncStorage)+jest.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),+}))// Regression guard for the defect review found in #146: sanitizeNumericInput was wired// into ActiveExerciseCard, but the weight field had no useNumericText buffer. Its `value`@@ -41,3 +53,34 @@ describe('ActiveExerciseCard weight entry', () => {expect(result.current[0]).toBe('102.5')})})++const exercise = {+ exercise_id: 1,+ exercise: { id: 1, name: 'Bench Press', muscle_group: 'chest' },+ notes: '',+ sets: [{ set_number: 1, target_reps: 8, target_weight: 100, actual_reps: 0, actual_weight: 0, completed: false }],+} as unknown as ActiveSessionExercise++describe('ActiveExerciseCard copy', () => {+ it('reads its column headers and add-set label from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ const noop = () => {}+ const view = render(+ <ActiveExerciseCard+ index={0} ex={exercise} isActive isLast wUnit="kg" weightUnit="kg"+ onCardLayout={noop} onRemoveExercise={noop} onNotesChange={noop} onAddSet={noop} onRemoveSet={noop}+ onUpdateSet={noop} onCompleteSet={noop} onJumpToExercise={noop} onRequestFinish={noop}+ />,+ )+ try {+ expect(screen.getByText('Peso (kg)')).toBeTruthy()+ expect(screen.getByText('Agregar serie')).toBeTruthy()+ expect(screen.getByText('0/1 series')).toBeTruthy()+ expect(screen.queryByText('Add Set')).toBeNull()+ } finally {+ // Unmount first: restoring English under a mounted tree is a state update outside act.+ view.unmount()+ await i18n.changeLanguage('en')+ }+ })+})diff --git a/mobile/src/components/workouts/ActiveExerciseCard.tsx b/mobile/src/components/workouts/ActiveExerciseCard.tsxindex 54f6b5c..5b28d3a 100644--- a/mobile/src/components/workouts/ActiveExerciseCard.tsx+++ b/mobile/src/components/workouts/ActiveExerciseCard.tsx@@ -2,11 +2,11 @@ import { memo } from 'react'import { Pressable, Text, TextInput, View, type LayoutChangeEvent } from 'react-native'import { router, type Href } from 'expo-router'import { CheckCircle2, ChevronLeft, ChevronRight, Flag, Plus, X } from 'lucide-react-native'-import { displayToLbs, displayWeight, sanitizeNumericInput, useNumericText, type ActiveSessionExercise } from '@lyftr/shared'+import { displayToLbs, displayWeight, sanitizeNumericInput, useNumericText, useTranslation, type ActiveSessionExercise } from '@lyftr/shared'import { AppText, NUMERIC_ACCESSORY_ID } from '../ui'import { ExerciseImage } from './ExerciseImage'import { useTheme } from '../../theme/useTheme'-import { muscleColor } from '../../utils/exerciseUtils'+import { muscleColor, muscleLabel } from '../../utils/exerciseUtils'const exerciseHref = (id: number) => `/workouts/exercise/${id}` as unknown as Href@@ -90,6 +90,7 @@ function ActiveExerciseCardBase({onCardLayout, onRemoveExercise, onNotesChange, onAddSet, onRemoveSet, onUpdateSet, onCompleteSet,onJumpToExercise, onRequestFinish,}: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const allSetsComplete = ex.sets.length > 0 && ex.sets.every((s) => s.completed)const completedHere = ex.sets.filter((s) => s.completed).length@@ -107,9 +108,9 @@ function ActiveExerciseCardBase({<AppText variant="bodySemibold" numberOfLines={1}>{ex.exercise.name}</AppText><View className="mt-1 flex-row items-center gap-2"><View className={`rounded px-1.5 py-0.5 ${tint?.chip ?? 'bg-surface-muted'}`}>- <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{ex.exercise.muscle_group}</AppText>+ <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscleLabel(ex.exercise.muscle_group)}</AppText></View>- <AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>{completedHere}/{ex.sets.length} sets</AppText>+ <AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>{t('workouts.active.setProgress', { done: completedHere, total: ex.sets.length })}</AppText></View></Pressable>{allSetsComplete ? (@@ -117,7 +118,7 @@ function ActiveExerciseCardBase({<CheckCircle2 size={18} color="#ffffff" /></View>) : (- <Pressable onPress={() => onRemoveExercise(index)} hitSlop={6} accessibilityLabel="Remove exercise" className="h-9 w-9 items-center justify-center rounded-xl active:bg-error-500/10">+ <Pressable onPress={() => onRemoveExercise(index)} hitSlop={6} accessibilityLabel={t('workouts.active.removeExercise')} className="h-9 w-9 items-center justify-center rounded-xl active:bg-error-500/10"><X size={16} color={colors.txMuted} /></Pressable>)}@@ -128,20 +129,20 @@ function ActiveExerciseCardBase({<TextInputdefaultValue={ex.notes}onEndEditing={(e) => onNotesChange(index, e.nativeEvent.text)}- placeholder="+ Add note…"+ placeholder={t('workouts.active.notes.placeholderMobile')}placeholderTextColor={colors.txMuted}className="font-sans text-xs text-tx-secondary"- accessibilityLabel={`Notes, ${ex.exercise.name}`}+ accessibilityLabel={t('workouts.active.notes.label', { name: ex.exercise.name })}/></View>{/* Sets */}<View className="gap-2 px-3 pb-3"><View className="flex-row items-center gap-2 px-1">- <View className="w-8 items-center"><AppText variant="caption" color="muted">Set</AppText></View>- <View className="flex-1 items-center"><AppText variant="caption" color="muted">Reps</AppText></View>- <View className="flex-1 items-center"><AppText variant="caption" color="muted">Weight ({wUnit})</AppText></View>- <View className="w-12 items-center"><AppText variant="caption" color="muted">Done</AppText></View>+ <View className="w-8 items-center"><AppText variant="caption" color="muted">{t('workouts.active.columns.set')}</AppText></View>+ <View className="flex-1 items-center"><AppText variant="caption" color="muted">{t('workouts.active.columns.reps')}</AppText></View>+ <View className="flex-1 items-center"><AppText variant="caption" color="muted">{t('workouts.active.columns.weightUnit', { unit: wUnit })}</AppText></View>+ <View className="w-12 items-center"><AppText variant="caption" color="muted">{t('workouts.active.columns.done')}</AppText></View><View className="w-7" /></View>{ex.sets.map((set, setIdx) => {@@ -162,7 +163,7 @@ function ActiveExerciseCardBase({onChange={(v) => onUpdateSet(index, setIdx, 'actual_reps', Number(v) || 0)}placeholder={set.target_reps > 0 ? String(set.target_reps) : '—'}placeholderColor={colors.txMuted}- accessibilityLabel={`Reps, set ${set.set_number}, ${ex.exercise.name}`}+ accessibilityLabel={t('workouts.active.repsLabel', { number: set.set_number, name: ex.exercise.name })}/></View><View className="flex-1">@@ -173,18 +174,18 @@ function ActiveExerciseCardBase({onChange={(v) => onUpdateSet(index, setIdx, 'actual_weight', displayToLbs(Number(v) || 0, weightUnit))}placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '—'}placeholderColor={colors.txMuted}- accessibilityLabel={`Weight, set ${set.set_number}, ${ex.exercise.name}`}+ accessibilityLabel={t('workouts.active.weightLabel', { number: set.set_number, name: ex.exercise.name })}/></View><PressableonPress={() => onCompleteSet(index, setIdx)}className={`h-11 w-12 items-center justify-center ${set.completed ? 'bg-brand-500' : isNextSet ? 'bg-brand-500/20' : ''}`}accessibilityRole="button"- accessibilityLabel={`${set.completed ? 'Completed' : 'Complete'} set ${set.set_number}, ${ex.exercise.name}`}+ accessibilityLabel={t(set.completed ? 'workouts.active.completedSet' : 'workouts.active.completeSet', { number: set.set_number, name: ex.exercise.name })}><CheckCircle2 size={24} color={set.completed ? '#ffffff' : isNextSet ? accent : colors.txMuted} /></Pressable>- <Pressable onPress={() => onRemoveSet(index, setIdx)} hitSlop={6} accessibilityLabel="Remove set" className="w-7 items-center justify-center">+ <Pressable onPress={() => onRemoveSet(index, setIdx)} hitSlop={6} accessibilityLabel={t('workouts.active.removeSet')} className="w-7 items-center justify-center"><X size={14} color={colors.txMuted} /></Pressable></View>@@ -194,24 +195,24 @@ function ActiveExerciseCardBase({{/* Add Set / Prev / Next / Finish */}<View className="mt-1 flex-row gap-2">{isActive && index > 0 ? (- <Pressable onPress={() => onJumpToExercise(index - 1)} accessibilityLabel="Previous exercise" className="items-center justify-center rounded-xl border border-surface-border bg-surface-muted px-3 py-2.5 active:scale-95">+ <Pressable onPress={() => onJumpToExercise(index - 1)} accessibilityLabel={t('workouts.active.previous')} className="items-center justify-center rounded-xl border border-surface-border bg-surface-muted px-3 py-2.5 active:scale-95"><ChevronLeft size={16} color={colors.txSecondary} /></Pressable>) : null}<Pressable onPress={() => onAddSet(index)} className="flex-1 flex-row items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border py-2.5 active:opacity-60"><Plus size={14} color={colors.txMuted} />- <Text className="font-sans-semibold text-xs text-tx-muted">Add Set</Text>+ <Text className="font-sans-semibold text-xs text-tx-muted">{t('workouts.active.addSet')}</Text></Pressable>{isActive && !isLast ? (<Pressable onPress={() => onJumpToExercise(index + 1)} className={`flex-row items-center justify-center gap-1 rounded-xl px-3 py-2.5 active:scale-95 ${allSetsComplete ? 'bg-brand-500' : 'border border-surface-border bg-surface-muted'}`}>- <Text className={`font-sans-semibold text-xs ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>Next</Text>+ <Text className={`font-sans-semibold text-xs ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>{t('workouts.active.next')}</Text><ChevronRight size={14} color={allSetsComplete ? '#ffffff' : colors.txSecondary} /></Pressable>) : null}{isActive && isLast ? (<Pressable onPress={onRequestFinish} className={`flex-row items-center justify-center gap-1 rounded-xl px-3 py-2.5 active:scale-95 ${allSetsComplete ? 'bg-brand-500' : 'border border-surface-border bg-surface-muted'}`}><Flag size={14} color={allSetsComplete ? '#ffffff' : colors.txSecondary} />- <Text className={`font-sans-semibold text-xs ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>Finish</Text>+ <Text className={`font-sans-semibold text-xs ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>{t('workouts.active.finish')}</Text></Pressable>) : null}</View>diff --git a/mobile/src/components/workouts/DurationField.tsx b/mobile/src/components/workouts/DurationField.tsxindex 24ae08b..2a91350 100644--- a/mobile/src/components/workouts/DurationField.tsx+++ b/mobile/src/components/workouts/DurationField.tsx@@ -1,6 +1,6 @@import { Pressable, Text, TextInput, View } from 'react-native'import { Minus, Plus } from 'lucide-react-native'-import { sanitizeNumericInput } from '@lyftr/shared'+import { sanitizeNumericInput, useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'// A thumb-friendly duration input: one unified stepper — −/+ as integrated end@@ -15,6 +15,7 @@ export function DurationField({ value, onChange, inputAccessoryViewID }: {onChange: (minutes: number) => voidinputAccessoryViewID?: string}) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const step = (delta: number) => onChange(Math.max(0, value + delta))const canDec = value > 0@@ -23,7 +24,7 @@ export function DurationField({ value, onChange, inputAccessoryViewID }: {<View className="h-12 flex-row items-stretch overflow-hidden rounded-xl border border-surface-border bg-surface-overlay"><PressableaccessibilityRole="button"- accessibilityLabel="Decrease duration"+ accessibilityLabel={t('workouts.form.durationField.decrease')}onPress={() => step(-STEP)}disabled={!canDec}className={`w-8 items-center justify-center border-r border-surface-border active:bg-surface-muted ${canDec ? '' : 'opacity-40'}`}@@ -43,14 +44,14 @@ export function DurationField({ value, onChange, inputAccessoryViewID }: {<View className="flex-row items-baseline"><TextInputvalue={value ? String(value) : ''}- onChangeText={(t) => onChange(Number(sanitizeNumericInput(t, 'numeric')) || 0)}+ onChangeText={(text) => onChange(Number(sanitizeNumericInput(text, 'numeric')) || 0)}keyboardType="number-pad"returnKeyType="done"selectTextOnFocusinputAccessoryViewID={inputAccessoryViewID}placeholder="0"placeholderTextColor={colors.txMuted}- accessibilityLabel="Duration in minutes"+ accessibilityLabel={t('workouts.form.durationField.inputLabel')}className="py-0 text-center text-base text-tx-primary"// fontFamily inline (not via className) so the input never renders one frame// in the system fallback font before the brand font resolves. lineHeight +@@ -63,14 +64,14 @@ export function DurationField({ value, onChange, inputAccessoryViewID }: {className="ml-0.5 text-xs text-tx-muted"style={{ fontFamily: 'PlusJakartaSans_500Medium', includeFontPadding: false }}>- min+ {t('workouts.form.durationField.unit')}</Text></View></View><PressableaccessibilityRole="button"- accessibilityLabel="Increase duration"+ accessibilityLabel={t('workouts.form.durationField.increase')}onPress={() => step(STEP)}className="w-8 items-center justify-center border-l border-surface-border active:bg-surface-muted">diff --git a/mobile/src/components/workouts/ExerciseDetailScreen.tsx b/mobile/src/components/workouts/ExerciseDetailScreen.tsxindex 70246f8..85304d1 100644--- a/mobile/src/components/workouts/ExerciseDetailScreen.tsx+++ b/mobile/src/components/workouts/ExerciseDetailScreen.tsx@@ -14,19 +14,19 @@ import Animated, {withTiming,} from 'react-native-reanimated'import {- apiErrorMessage,+ uiMessage,displayWeight,weightShort,type Exercise,type ExerciseHistoryPoint,- type PersonalRecord,+ type PersonalRecord, type UiMessage, formatDate, useTranslation} from '@lyftr/shared'import { AppText, Button, ErrorState, Screen, SegmentedControl } from '../ui'import { MuscleDiagram } from './MuscleDiagram'import { ExerciseHistoryChart, type ChartPoint } from './ExerciseHistoryChart'import { client, useSettingsStore, useWorkoutSession } from '../../lib/lyftr'import { useTheme } from '../../theme/useTheme'-import { muscleColor, EQUIPMENT_LABEL } from '../../utils/exerciseUtils'+import { muscleColor, muscleLabel, equipmentLabel, categoryLabel } from '../../utils/exerciseUtils'// 1:1 port of web/src/pages/ExerciseDetail.tsx. Read-only exercise reference: identity +// muscles worked (front/back diagram), image, equipment/category tags, secondary muscles,@@ -43,7 +43,6 @@ import { muscleColor, EQUIPMENT_LABEL } from '../../utils/exerciseUtils'const HISTORY_PERIODS = ['1m', '3m', '6m', 'All'] as consttype HistoryPeriod = typeof HISTORY_PERIODS[number]const HISTORY_DAYS: Record<HistoryPeriod, number | null> = { '1m': 30, '3m': 90, '6m': 180, 'All': null }-const PERIOD_OPTIONS = HISTORY_PERIODS.map((p) => ({ value: p, label: p }))// Header muscle badge (web muscleColorBordered) + borderless variant for "Also works"// (web muscleColor). px-2 py-0.5 rounded, matching the web spans.@@ -58,7 +57,7 @@ function MuscleBadge({ muscle, bordered }: { muscle: string; bordered?: boolean>{/* Tint via inline style — see exerciseUtils.ts for why not a className. */}<AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>- {muscle}+ {muscleLabel(muscle)}</AppText></View>)@@ -86,6 +85,7 @@ function LoadingPulse() {}export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {+ const { t } = useTranslation()const { exerciseId } = useLocalSearchParams<{ exerciseId: string }>()const session = useWorkoutSession((s) => s.session)const settings = useSettingsStore((s) => s.settings)@@ -101,7 +101,8 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('3m')const [imgFailed, setImgFailed] = useState(false)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // A UiMessage rather than a sentence, so a failure already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Bumping this re-runs the load effect — three lines, rather than restructuring a// working effect to gain a retry button.const [retryKey, setRetryKey] = useState(0)@@ -126,7 +127,7 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {setPR(prData)setHistory(histData || [])})- .catch((err) => { if (!cancelled) setError(apiErrorMessage(err, "The server didn't say what went wrong.")) })+ .catch((err) => { if (!cancelled) setError({ key: 'settings.unknownError', cause: err }) }).finally(() => { if (!cancelled) setLoading(false) })return () => { cancelled = true }// eslint-disable-next-line react-hooks/exhaustive-deps@@ -146,10 +147,10 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {<Screen><ErrorStatesize="page"- title="Couldn't load this exercise"- message={error}+ title={t('exercises.detail.loadFailed')}+ message={uiMessage(error)}onRetry={() => { setError(null); setRetryKey((k) => k + 1) }}- secondary={<Button title="Go back" variant="secondary" onPress={goBack} />}+ secondary={<Button title={t('common.goBack')} variant="secondary" onPress={goBack} />}/></Screen>)@@ -157,10 +158,11 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {if (loading || !exercise) return <LoadingPulse />- const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment+ const equipLabel = equipmentLabel(exercise.equipment)+ const periodOptions = HISTORY_PERIODS.map((p) => ({ value: p, label: t(`exercises.detail.period.${p}`) }))const descLines = exercise.description ? exercise.description.split('\n').filter((l) => l.trim()) : []const chartData: ChartPoint[] = [...filteredHistory].reverse().map((h) => ({- date: format(new Date(h.date), 'M/d'),+ date: formatDate(new Date(h.date), 'numericMonthDay'),weight: displayWeight(h.max_weight, wUnit),}))@@ -189,7 +191,7 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {onPress={goBack}hitSlop={8}accessibilityRole="button"- accessibilityLabel="Back"+ accessibilityLabel={t('common.back')}className="absolute left-4 top-3 h-9 w-9 items-center justify-center rounded-full bg-black/40 active:bg-black/60"><ArrowLeft size={20} color="#ffffff" />@@ -204,7 +206,7 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {onPress={goBack}hitSlop={8}accessibilityRole="button"- accessibilityLabel="Back"+ accessibilityLabel={t('common.back')}className="-ml-2 h-9 w-9 items-center justify-center rounded-lg active:bg-surface-muted"><ArrowLeft size={20} color={colors.txMuted} />@@ -223,7 +225,7 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {) : null}{exercise.category ? (<View className="rounded-full border border-brand-500/20 bg-brand-500/10 px-3 py-1">- <AppText variant="caption" className="capitalize" style={{ color: accent }}>{exercise.category}</AppText>+ <AppText variant="caption" className="capitalize" style={{ color: accent }}>{categoryLabel(exercise.category)}</AppText></View>) : null}</View>@@ -231,14 +233,14 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {{/* Muscles worked */}<View className="rounded-2xl border border-surface-border bg-surface-raised p-4">- <AppText variant="label" color="muted" className="mb-3 uppercase">Muscles Worked</AppText>+ <AppText variant="label" color="muted" className="mb-3 uppercase">{t('exercises.detail.musclesWorked')}</AppText><MuscleDiagram exercise={exercise} /></View>{/* Secondary muscles */}{exercise.secondary_muscles?.length > 0 ? (<View>- <AppText variant="label" color="muted" className="mb-2 uppercase">Also works</AppText>+ <AppText variant="label" color="muted" className="mb-2 uppercase">{t('exercises.detail.alsoWorks')}</AppText><View className="flex-row flex-wrap gap-1.5">{exercise.secondary_muscles.map((m) => <MuscleBadge key={m} muscle={m} />)}</View>@@ -254,20 +256,20 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {<View className="h-7 w-7 items-center justify-center rounded-full bg-warning-500/15"><Trophy size={15} color={brand.warningSoft} /></View>- <AppText variant="label" color="muted" className="uppercase">Personal Best</AppText>+ <AppText variant="label" color="muted" className="uppercase">{t('exercises.detail.personalBest')}</AppText></View>- <AppText variant="caption" color="muted">{format(new Date(pr.date), 'MMM d, yyyy')}</AppText>+ <AppText variant="caption" color="muted">{formatDate(new Date(pr.date), 'monthDayYear')}</AppText></View><View className="mt-3 flex-row items-end gap-2"><Text className="font-display text-3xl text-tx-primary" style={{ fontVariant: ['tabular-nums'] }}>{displayWeight(pr.weight, wUnit)}</Text>- <AppText variant="body" color="muted" className="mb-1">{wUnit} × {pr.reps} reps</AppText>+ <AppText variant="body" color="muted" className="mb-1">{t('exercises.detail.bestSet', { unit: wUnit, count: pr.reps })}</AppText></View><View className="mt-3 flex-row items-center justify-between border-t border-warning-500/15 pt-3">- <AppText variant="caption" color="muted">Estimated 1RM</AppText>+ <AppText variant="caption" color="muted">{t('exercises.detail.estimated1rm')}</AppText><AppText variant="bodySemibold" style={{ fontVariant: ['tabular-nums'] }}>{displayWeight(pr.estimated_1rm, wUnit)} {wUnit}</AppText>@@ -280,12 +282,12 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {<View className="rounded-2xl border border-surface-border bg-surface-raised p-4">{/* Label + period selector STACKED: the 4-option control + label don't fiton one row at real device widths (overflowed/clipped the card). */}- <AppText variant="label" color="muted" className="mb-3 uppercase">Weight Progression</AppText>- <SegmentedControl size="sm" className="mb-3" options={PERIOD_OPTIONS} value={historyPeriod} onChange={setHistoryPeriod} />+ <AppText variant="label" color="muted" className="mb-3 uppercase">{t('exercises.detail.weightProgression')}</AppText>+ <SegmentedControl size="sm" className="mb-3" options={periodOptions} value={historyPeriod} onChange={setHistoryPeriod} /><View onLayout={(e) => setChartWidth(e.nativeEvent.layout.width)}>{chartData.length < 2 ? (<View className="h-[110px] items-center justify-center">- <AppText variant="body" color="muted">No data for this period</AppText>+ <AppText variant="body" color="muted">{t('exercises.detail.noPeriodData')}</AppText></View>) : (<ExerciseHistoryChart data={chartData} width={chartWidth} unit={wUnit} />@@ -297,7 +299,7 @@ export function ExerciseDetailScreen({ backFallback }: { backFallback: Href }) {{/* Instructions */}{descLines.length > 0 ? (<View className="rounded-2xl border border-surface-border bg-surface-raised p-4">- <AppText variant="label" color="muted" className="mb-3 uppercase">Instructions</AppText>+ <AppText variant="label" color="muted" className="mb-3 uppercase">{t('exercises.detail.instructions')}</AppText><View className="gap-2.5">{descLines.map((line, i) => {const m = line.match(/^(\d+\.)\s*(.*)/)diff --git a/mobile/src/components/workouts/ExerciseFormCard.tsx b/mobile/src/components/workouts/ExerciseFormCard.tsxindex 94dde50..7abe054 100644--- a/mobile/src/components/workouts/ExerciseFormCard.tsx+++ b/mobile/src/components/workouts/ExerciseFormCard.tsx@@ -5,7 +5,7 @@ import type { Exercise } from '@lyftr/shared'import { AppText, IconButton, Label } from '../ui'import { ExerciseImage } from './ExerciseImage'import { RestPicker } from './RestPicker'-import { sanitizeNumericInput, useNumericText } from '@lyftr/shared'+import { equipmentLabel, muscleLabel, sanitizeNumericInput, useNumericText, useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'interface SetData {@@ -59,6 +59,7 @@ function WeightCell({ value, onChange, placeholderColor, inputRef, onNext, inputonNext?: () => voidinputAccessoryViewID?: string}) {+ const { t } = useTranslation()const [text, setText] = useNumericText(value)const emit = (raw: string) => {const v = sanitizeNumericInput(raw, 'decimal')@@ -78,7 +79,7 @@ function WeightCell({ value, onChange, placeholderColor, inputRef, onNext, inputinputAccessoryViewID={inputAccessoryViewID}placeholder="0"placeholderTextColor={placeholderColor}- accessibilityLabel="Set weight"+ accessibilityLabel={t('workouts.form.setWeightLabel')}className={CELL}style={{ fontVariant: ['tabular-nums'] }}/>@@ -95,6 +96,7 @@ function ExerciseFormCardBase({onRemove, onNotesChange, onAddSet, onRemoveSet, onUpdateSet, onRestChange,inputAccessoryViewID,}: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()// Once revealed the input stays mounted for the card's lifetime, so typed text// can never be hidden; cards with saved notes start revealed.@@ -127,12 +129,12 @@ function ExerciseFormCardBase({<View className="flex-1"><AppText variant="bodySemibold" numberOfLines={1}>{exercise?.name}</AppText><AppText variant="caption" color="muted" numberOfLines={1}>- {exercise?.muscle_group} • {exercise?.equipment}+ {muscleLabel(exercise?.muscle_group)} • {equipmentLabel(exercise?.equipment)}</AppText></View><IconButtonicon={Trash2}- label={`Remove ${exercise?.name ?? 'exercise'}`}+ label={t('workouts.form.removeNamed', { name: exercise?.name ?? t('workouts.form.exerciseFallback') })}variant="ghost"size="sm"onPress={() => onRemove(index)}@@ -142,9 +144,9 @@ function ExerciseFormCardBase({{/* Set table — column labels once, then one tight row per set. */}<View className="gap-1.5"><View className="flex-row items-center gap-2">- <View className={`${COL_SET} items-center`}><Label>Set</Label></View>- <View className="flex-1 items-center"><Label>Reps</Label></View>- <View className="flex-1 items-center"><Label>{`Weight (${unit})`}</Label></View>+ <View className={`${COL_SET} items-center`}><Label>{t('workouts.form.set')}</Label></View>+ <View className="flex-1 items-center"><Label>{t('workouts.form.reps')}</Label></View>+ <View className="flex-1 items-center"><Label>{t('workouts.form.weightWithUnit', { unit })}</Label></View><View className={COL_DELETE} /></View>{sets.map((set, setIdx) => (@@ -158,7 +160,7 @@ function ExerciseFormCardBase({<TextInputref={(r) => { repsRefs.current[setIdx] = r }}value={set.reps ? String(set.reps) : ''}- onChangeText={(t) => onUpdateSet(index, setIdx, 'reps', sanitizeNumericInput(t, 'numeric'))}+ onChangeText={(text) => onUpdateSet(index, setIdx, 'reps', sanitizeNumericInput(text, 'numeric'))}keyboardType="number-pad"returnKeyType="next"submitBehavior="submit"@@ -167,7 +169,7 @@ function ExerciseFormCardBase({inputAccessoryViewID={inputAccessoryViewID}placeholder="0"placeholderTextColor={colors.txMuted}- accessibilityLabel="Set reps"+ accessibilityLabel={t('workouts.form.setRepsLabel')}className={CELL}style={{ fontVariant: ['tabular-nums'] }}/>@@ -185,7 +187,7 @@ function ExerciseFormCardBase({/></View><View className={`${COL_DELETE} items-center`}>- <IconButton icon={X} label="Remove set" variant="ghost" size="sm" onPress={() => onRemoveSet(index, setIdx)} />+ <IconButton icon={X} label={t('workouts.form.removeSet')} variant="ghost" size="sm" onPress={() => onRemoveSet(index, setIdx)} /></View></View>))}@@ -203,18 +205,18 @@ function ExerciseFormCardBase({><Plus size={13} color={accent} />{/* accent (not text-brand-500): raw brand cyan washes out on light. */}- <Text className="font-sans-semibold text-xs" style={{ color: accent }}>Add Set</Text>+ <Text className="font-sans-semibold text-xs" style={{ color: accent }}>{t('workouts.form.addSet')}</Text></Pressable>{!showNotes && (<PressableaccessibilityRole="button"- accessibilityLabel="Add exercise note"+ accessibilityLabel={t('workouts.form.addNoteLabel')}onPress={() => setShowNotes(true)}hitSlop={{ top: 6, bottom: 6 }}className="h-9 flex-row items-center gap-1.5 rounded-lg px-3 active:opacity-60"><FileText size={13} color={colors.txMuted} />- <Text className="font-sans-semibold text-xs text-tx-muted">Note</Text>+ <Text className="font-sans-semibold text-xs text-tx-muted">{t('workouts.form.note')}</Text></Pressable>)}</View>@@ -225,15 +227,15 @@ function ExerciseFormCardBase({<View className="mt-2.5 flex-row items-center gap-2"><TextInputvalue={notes}- onChangeText={(t) => onNotesChange(index, t)}- placeholder="e.g., Felt strong"+ onChangeText={(text) => onNotesChange(index, text)}+ placeholder={t('workouts.form.exerciseNotesPlaceholder')}placeholderTextColor={colors.txMuted}- accessibilityLabel="Exercise notes"+ accessibilityLabel={t('workouts.form.exerciseNotesLabel')}className="h-9 flex-1 rounded-lg border border-surface-border/60 bg-surface-overlay px-3 py-0 font-sans text-sm text-tx-primary"/><IconButtonicon={X}- label="Remove note"+ label={t('workouts.form.removeNoteLabel')}variant="ghost"size="sm"onPress={() => { onNotesChange(index, ''); setShowNotes(false) }}@@ -247,7 +249,7 @@ function ExerciseFormCardBase({<View className="mt-3 border-t border-surface-border/60 pt-3"><View className="mb-1 flex-row items-center gap-1.5"><Timer size={13} color={accent} />- <Label>Rest between sets</Label>+ <Label>{t('workouts.form.restBetweenSets')}</Label></View><RestPicker value={restSeconds} onChange={(secs) => onRestChange(index, secs)} /></View>diff --git a/mobile/src/components/workouts/ExerciseHistoryChart.tsx b/mobile/src/components/workouts/ExerciseHistoryChart.tsxindex 5c347a2..c69a595 100644--- a/mobile/src/components/workouts/ExerciseHistoryChart.tsx+++ b/mobile/src/components/workouts/ExerciseHistoryChart.tsx@@ -2,6 +2,7 @@ import { useState } from 'react'import { View } from 'react-native'import * as Haptics from 'expo-haptics'import Svg, { Path, Circle, Line, Text as SvgText, Defs, LinearGradient, Stop } from 'react-native-svg'+import { useTranslation } from '@lyftr/shared'import { AppText } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -78,7 +79,7 @@ export function ExerciseHistoryChart({width,unit,height = 132,- readoutNote = 'Max weight',+ readoutNote,}: {data: ChartPoint[]width: number@@ -89,6 +90,8 @@ export function ExerciseHistoryChart({readoutNote?: string}) {const { colors } = useTheme()+ const { t } = useTranslation()+ const note = readoutNote ?? t('exercises.detail.maxWeight')const [selected, setSelected] = useState<number | null>(null)if (data.length < 2 || width <= 0) return null@@ -202,7 +205,7 @@ export function ExerciseHistoryChart({}}><AppText variant="caption" style={{ fontVariant: ['tabular-nums'] }}>- {data[selected].weight} {unit}{readoutNote ? ` · ${readoutNote}` : ''}+ {data[selected].weight} {unit}{note ? ` · ${note}` : ''}</AppText>{data[selected].sub ? (<AppText variant="caption" color="muted">{data[selected].sub}</AppText>diff --git a/mobile/src/components/workouts/ExercisePicker.tsx b/mobile/src/components/workouts/ExercisePicker.tsxindex fee062d..1cef848 100644--- a/mobile/src/components/workouts/ExercisePicker.tsx+++ b/mobile/src/components/workouts/ExercisePicker.tsx@@ -2,12 +2,12 @@ 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 { useTranslation, type Exercise } from '@lyftr/shared'import { AppText, ErrorState, 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 { equipmentLabel, muscleLabel } from '../../utils/exerciseUtils'import { ExerciseImage } from './ExerciseImage'interface Props {@@ -23,6 +23,7 @@ const PAGE_SIZE = 50const DEBOUNCE_MS = 250function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => void }) {+ useTranslation() // re-renders on a language switch: the labels below come from the catalogreturn (<PressableaccessibilityRole="button"@@ -38,12 +39,12 @@ function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => vkeep the taxonomy legible but let the exercise name be the hero. */}<View className="rounded border border-surface-border bg-surface-muted px-1.5 py-0.5"><AppText variant="caption" color="muted" className="capitalize">- {exercise.muscle_group}+ {muscleLabel(exercise.muscle_group)}</AppText></View>{exercise.equipment && exercise.equipment !== 'other' ? (<AppText variant="caption" color="muted">- {EQUIPMENT_LABEL[exercise.equipment] || exercise.equipment}+ {equipmentLabel(exercise.equipment)}</AppText>) : null}</View>@@ -57,13 +58,14 @@ function PickerRow({ exercise, onPress }: { exercise: Exercise; onPress: () => v// search state resets per open — a routed screen can't hand the picked Exercise// back to the form without a store detour, hence Modal).export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {+ const { t } = useTranslation()const { accent, colors } = useTheme()const [query, setQuery] = useState('')const [debouncedQuery, setDebouncedQuery] = useState('')useEffect(() => {- const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)- return () => clearTimeout(t)+ const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ return () => clearTimeout(timer)}, [query])// Every page comes from the server, which queries open-exercise-db. The client@@ -98,16 +100,16 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {<SafeAreaView className="flex-1 bg-surface-base" edges={['top']}>{/* Header */}<View className="flex-row items-center gap-3 border-b border-surface-border px-4 pb-4 pt-3">- <IconButton icon={ArrowLeft} label="Close exercise picker" variant="ghost" size="md" onPress={onClose} />+ <IconButton icon={ArrowLeft} label={t('exercises.picker.close')} variant="ghost" size="md" onPress={onClose} /><View>{/* Large title (matches the sibling "Log Workout" screen title) — the18px heading read undersized for a full-screen surface. */}- <AppText variant="title">Add Exercise</AppText>+ <AppText variant="title">{t('exercises.picker.title')}</AppText>{/* Only true if the fetch landed — on a failure this read "0 loaded"above a message saying we could not load anything. */}{listError ? null : (<AppText variant="caption" color="muted">- {available.length} loaded{hasMore ? '…' : ''}+ {t(hasMore ? 'exercises.picker.loadedMore' : 'exercises.picker.loaded', { count: available.length })}</AppText>)}</View>@@ -126,7 +128,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {className="flex-1 font-sans text-base text-tx-primary"value={query}onChangeText={setQuery}- placeholder="Search exercises…"+ placeholder={t('exercises.picker.search')}placeholderTextColor={colors.txMuted}autoCapitalize="none"autoCorrect={false}@@ -139,7 +141,7 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {{initialLoading ? (<View className="flex-row items-center justify-center gap-2 py-16"><ActivityIndicator color={accent} />- <AppText variant="body" color="muted">Loading exercises…</AppText>+ <AppText variant="body" color="muted">{t('exercises.picker.loading')}</AppText></View>) : (<FlatList@@ -158,10 +160,10 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {// "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.listError ? (- <ErrorState title="Couldn't load exercises" message={listError} onRetry={retryList} />+ <ErrorState title={t('exercises.picker.loadFailed')} message={listError} onRetry={retryList} />) : (<View className="items-center py-16">- <AppText variant="body" color="muted">No exercises found</AppText>+ <AppText variant="body" color="muted">{t('exercises.picker.empty')}</AppText></View>)}@@ -172,11 +174,11 @@ export function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {// exercise already selected the list is empty, and the slot above would// render the same failure a second time.listError && available.length > 0 ? (- <ErrorState title="Couldn't load more exercises" message={listError} onRetry={retryList} />+ <ErrorState title={t('exercises.picker.loadMoreFailed')} message={listError} onRetry={retryList} />) : hasMore && available.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>+ <AppText variant="caption" color="muted">{t('exercises.picker.loadingMore')}</AppText></View>) : null}diff --git a/mobile/src/components/workouts/GymModeWorkout.tsx b/mobile/src/components/workouts/GymModeWorkout.tsxindex fa556fb..fd5bee0 100644--- a/mobile/src/components/workouts/GymModeWorkout.tsx+++ b/mobile/src/components/workouts/GymModeWorkout.tsx@@ -9,7 +9,7 @@ import {Play, Plus, Repeat, Timer, Trash2, X,} from 'lucide-react-native'import {- useAsyncAction, displayToLbs, displayWeight, weightShort, type Exercise,+ useAsyncAction, displayToLbs, displayWeight, weightShort, useTranslation, type Exercise,} from '@lyftr/shared'import { AppText, ConfirmSheet, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, StepperTile } from '../ui'import { RestPicker } from './RestPicker'@@ -20,7 +20,7 @@ import { client, useSettingsStore, useWorkoutSession } from '../../lib/lyftr'import { useWorkoutOutcome } from '../../lib/workoutOutcome'import { useTheme } from '../../theme/useTheme'import { PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange } from '@lyftr/shared'-import { muscleColor, EQUIPMENT_LABEL } from '../../utils/exerciseUtils'+import { muscleColor, muscleLabel, equipmentLabel, categoryLabel } from '../../utils/exerciseUtils'// Port of web/pages/GymModeWorkout.tsx — full-screen 3-phase FSM overlay// (overview → exercise-info → exercise). Mounted at the ROOT layout when a session@@ -30,18 +30,19 @@ function MuscleBadge({ muscle, small }: { muscle: string; small?: boolean }) {const tint = muscleColor(muscle)return (<View className={`rounded ${small ? 'px-1.5 py-0.5' : 'px-2 py-0.5'} ${tint?.chip ?? 'bg-surface-muted'} ${tint?.border ? `border ${tint.border}` : ''}`}>- <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscle}</AppText>+ <AppText variant="caption" style={{ color: tint?.text ?? colors.txMuted }}>{muscleLabel(muscle)}</AppText></View>)}function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {+ const { t } = useTranslation()const { colors } = useTheme()return (<TextInputdefaultValue={notes}onEndEditing={(e) => onSave(exIdx, e.nativeEvent.text)}- placeholder="+ Add note…"+ placeholder={t('workouts.active.notes.placeholderMobile')}placeholderTextColor={colors.txMuted}className="font-sans text-xs text-tx-secondary"/>@@ -49,6 +50,8 @@ function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string;}export function GymModeWorkout() {+ // Also re-renders on a language switch for the labels read from the catalog.+ const { t } = useTranslation()const session = useWorkoutSession((s) => s.session)const minimizeGym = useWorkoutSession((s) => s.minimizeGym)const phase = useWorkoutSession((s) => s.gymPhase)@@ -121,7 +124,7 @@ export function GymModeWorkout() {cancelSession()minimizeGym()router.replace('/workouts')- }, 'Failed to save workout')+ }, t('workouts.active.saveFailed'))if (!session) return null@@ -163,18 +166,18 @@ export function GymModeWorkout() {<ConfirmSheetopen={confirmFinish}icon={Flag}- title="Finish Workout?"- message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}- confirmLabel="Finish" busyLabel="Saving…" cancelLabel="Keep Going" busy={finish.busy}+ title={t('workouts.active.finishConfirm.title')}+ message={t('workouts.active.finishConfirm.message', { done: completedSets, total: totalSets })}+ confirmLabel={t('workouts.active.finish')} busyLabel={t('common.saving')} cancelLabel={t('workouts.active.keepGoing')} busy={finish.busy}error={finish.error}onConfirm={() => { void finish.run() }} onCancel={() => { setConfirmFinish(false); finish.reset() }}/><ConfirmSheetopen={confirmCancel}icon={Trash2} destructive- title="Discard workout?"- message="This ends the workout without saving — all progress is lost."- confirmLabel="Discard" cancelLabel="Keep Going"+ title={t('gym.discard.title')}+ message={t('gym.discard.message')}+ confirmLabel={t('gym.discard.confirm')} cancelLabel={t('workouts.active.keepGoing')}onConfirm={() => { setOutcome({ kind: 'discarded', session }); cancelSession(); handleMinimize() }}onCancel={() => setConfirmCancel(false)}/>@@ -204,7 +207,7 @@ export function GymModeWorkout() {<Pressablekey={i}onPress={() => setGymState('exercise-info', i, 0)}- accessibilityLabel={`Go to exercise ${i + 1}`}+ accessibilityLabel={t('gym.goToExercise', { number: i + 1 })}className={`h-1.5 rounded-full ${i === activeIdx ? 'w-6 bg-brand-500' : done ? 'w-2 bg-brand-500/40' : 'w-2 bg-surface-border'}`}/>)@@ -215,12 +218,12 @@ export function GymModeWorkout() {<View className="flex-shrink-0 flex-row items-center gap-1"><Pressable onPress={() => setConfirmFinish(true)} className={`flex-row items-center gap-1.5 rounded-xl px-3 py-2 ${allDone ? 'bg-brand-500' : 'border border-surface-border bg-surface-muted'}`}><Flag size={14} color={allDone ? '#ffffff' : colors.txMuted} />- <Text className={`font-sans-semibold text-xs ${allDone ? 'text-white' : 'text-tx-muted'}`}>Finish</Text>+ <Text className={`font-sans-semibold text-xs ${allDone ? 'text-white' : 'text-tx-muted'}`}>{t('workouts.active.finish')}</Text></Pressable>- <Pressable onPress={handleMinimize} hitSlop={6} accessibilityLabel="Minimize workout" className="rounded-xl p-2 active:bg-surface-muted">+ <Pressable onPress={handleMinimize} hitSlop={6} accessibilityLabel={t('gym.minimizeWorkout')} className="rounded-xl p-2 active:bg-surface-muted"><Minimize2 size={16} color={colors.txMuted} /></Pressable>- <Pressable onPress={() => setConfirmCancel(true)} hitSlop={6} accessibilityLabel="Discard workout" className="rounded-xl p-2 active:bg-error-500/10">+ <Pressable onPress={() => setConfirmCancel(true)} hitSlop={6} accessibilityLabel={t('gym.discardWorkout')} className="rounded-xl p-2 active:bg-error-500/10"><X size={20} color={colors.txMuted} /></Pressable></View>@@ -234,14 +237,14 @@ export function GymModeWorkout() {<><View className="flex-row items-center justify-between border-b border-surface-border px-5 pb-4 pt-2"><View className="flex-1">- <AppText variant="label" color="muted" className="uppercase">Workout</AppText>+ <AppText variant="label" color="muted" className="uppercase">{t('gym.workout')}</AppText><AppText variant="heading" numberOfLines={1}>{session.name}</AppText></View><View className="flex-row items-center gap-1">- <Pressable onPress={handleMinimize} hitSlop={6} accessibilityLabel="Minimize" className="rounded-xl p-2 active:bg-surface-muted">+ <Pressable onPress={handleMinimize} hitSlop={6} accessibilityLabel={t('gym.minimize')} className="rounded-xl p-2 active:bg-surface-muted"><Minimize2 size={16} color={colors.txMuted} /></Pressable>- <Pressable onPress={() => setConfirmCancel(true)} hitSlop={6} accessibilityLabel="Discard workout" className="rounded-xl p-2 active:bg-error-500/10">+ <Pressable onPress={() => setConfirmCancel(true)} hitSlop={6} accessibilityLabel={t('gym.discardWorkout')} className="rounded-xl p-2 active:bg-error-500/10"><X size={20} color={colors.txMuted} /></Pressable></View>@@ -249,9 +252,9 @@ export function GymModeWorkout() {<View className="flex-row border-b border-surface-border px-5 py-4">{[- { v: session.exercises.length, l: 'Exercises' },- { v: totalSets, l: 'Total Sets' },- { v: muscles, l: 'Muscles' },+ { v: session.exercises.length, l: t('gym.overview.exercises') },+ { v: totalSets, l: t('gym.overview.totalSets') },+ { v: muscles, l: t('gym.overview.muscles') },].map((s) => (<View key={s.l} className="flex-1 items-center"><Text className="font-display text-xl text-tx-primary" style={{ fontVariant: ['tabular-nums'] }}>{s.v}</Text>@@ -264,7 +267,7 @@ export function GymModeWorkout() {{session.exercises.length === 0 ? (<View className="items-center gap-3 py-16"><Dumbbell size={40} color={colors.txMuted} />- <AppText variant="body" color="muted">No exercises added yet</AppText>+ <AppText variant="body" color="muted">{t('gym.overview.empty')}</AppText></View>) : (session.exercises.map((ex, i) => {@@ -285,7 +288,7 @@ export function GymModeWorkout() {<AppText variant="bodySemibold" numberOfLines={1}>{ex.exercise.name}</AppText><View className="mt-0.5 flex-row items-center gap-2"><MuscleBadge muscle={ex.exercise.muscle_group} small />- <AppText variant="caption" color="muted">{ex.sets.length} sets</AppText>+ <AppText variant="caption" color="muted">{t('workouts.detail.setCount', { count: ex.sets.length })}</AppText></View></View>{done ? <CheckCircle2 size={16} color={accent} /> : null}@@ -298,12 +301,12 @@ export function GymModeWorkout() {<View className="gap-2 border-t border-surface-border px-5 pt-4" style={{ paddingBottom: restShown ? 16 : insets.bottom + 16 }}><Pressable onPress={() => setShowPicker(true)} className="flex-row items-center justify-center gap-2 rounded-2xl border border-surface-border bg-surface-muted py-3 active:scale-95"><Plus size={16} color={colors.txSecondary} />- <Text className="font-sans-semibold text-sm text-tx-secondary">Add Exercise</Text>+ <Text className="font-sans-semibold text-sm text-tx-secondary">{t('workouts.active.addExercise')}</Text></Pressable>{session.exercises.length > 0 ? (<Pressable onPress={() => setGymState('exercise-info', 0, 0)} className="flex-row items-center justify-center gap-2 rounded-2xl bg-brand-500 py-4 active:scale-95"><Play size={20} color="#ffffff" />- <Text className="font-sans-bold text-base text-white">Start Workout</Text>+ <Text className="font-sans-bold text-base text-white">{t('gym.overview.startWorkout')}</Text></Pressable>) : null}</View>@@ -321,14 +324,14 @@ export function GymModeWorkout() {// ── Exercise info ─────────────────────────────────────────if (phase === 'exercise-info') {const exercise = ex.exercise- const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment+ const equipLabel = equipmentLabel(exercise.equipment)const descLines = exercise.description ? exercise.description.split('\n').filter((l) => l.trim()) : []const repsVals = ex.sets.map((s) => s.target_reps).filter((r) => r > 0)const wtVals = ex.sets.map((s) => displayWeight(s.target_weight, wUnit)).filter((w) => w > 0)const planStats = [- { icon: Layers, label: 'Sets', value: String(ex.sets.length) },- { icon: Repeat, label: 'Reps', value: numericRange(repsVals) },- { icon: Dumbbell, label: 'Weight', value: `${numericRange(wtVals)} ${wUnit}` },+ { icon: Layers, label: t('gym.labels.sets'), value: String(ex.sets.length) },+ { icon: Repeat, label: t('gym.labels.reps'), value: numericRange(repsVals) },+ { icon: Dumbbell, label: t('gym.labels.weight'), value: `${numericRange(wtVals)} ${wUnit}` },]return overlay(<>@@ -346,7 +349,7 @@ export function GymModeWorkout() {<View className="rounded-full border border-surface-border bg-surface-muted px-3 py-1"><AppText variant="caption" color="secondary">{equipLabel}</AppText></View>) : null}{exercise.category ? (- <View className="rounded-full border border-surface-border bg-surface-muted px-3 py-1"><AppText variant="caption" color="secondary" className="capitalize">{exercise.category}</AppText></View>+ <View className="rounded-full border border-surface-border bg-surface-muted px-3 py-1"><AppText variant="caption" color="secondary" className="capitalize">{categoryLabel(exercise.category)}</AppText></View>) : null}</View></View>@@ -366,9 +369,9 @@ export function GymModeWorkout() {<View className="rounded-2xl border border-surface-border bg-surface-raised p-4"><View className="flex-row items-center gap-2"><Timer size={16} color={accent} />- <AppText variant="label" color="muted" className="uppercase">Rest between sets</AppText>+ <AppText variant="label" color="muted" className="uppercase">{t('gym.info.restTitle')}</AppText></View>- <AppText variant="caption" color="muted" className="mb-3 mt-1">Auto-starts when you complete a set</AppText>+ <AppText variant="caption" color="muted" className="mb-3 mt-1">{t('gym.info.restHint')}</AppText><View className="mt-3"><RestPicker value={ex.rest_seconds ?? (settings.rest_seconds_default ?? 90)} onChange={(secs) => setExerciseRest(activeIdx, secs)} /></View>@@ -376,7 +379,7 @@ export function GymModeWorkout() {{exercise.secondary_muscles?.length > 0 ? (<View>- <AppText variant="label" color="muted" className="mb-2 uppercase">Also works</AppText>+ <AppText variant="label" color="muted" className="mb-2 uppercase">{t('exercises.detail.alsoWorks')}</AppText><View className="flex-row flex-wrap gap-1.5">{exercise.secondary_muscles.map((m) => <MuscleBadge key={m} muscle={m} small />)}</View>@@ -385,13 +388,13 @@ export function GymModeWorkout() {{/* Muscle diagram */}<View className="rounded-2xl border border-surface-border bg-surface-raised p-4">- <AppText variant="label" color="muted" className="mb-3 uppercase">Muscles Worked</AppText>+ <AppText variant="label" color="muted" className="mb-3 uppercase">{t('exercises.detail.musclesWorked')}</AppText><MuscleDiagram exercise={exercise} /></View>{descLines.length > 0 ? (<View className="rounded-2xl border border-surface-border bg-surface-raised p-4">- <AppText variant="label" color="muted" className="mb-3 uppercase">Instructions</AppText>+ <AppText variant="label" color="muted" className="mb-3 uppercase">{t('exercises.detail.instructions')}</AppText><View className="gap-2.5">{descLines.map((line, i) => {const m = line.match(/^(\d+\.)\s*(.*)/)@@ -409,7 +412,7 @@ export function GymModeWorkout() {<View className="border-t border-surface-border px-5 pt-4" style={{ paddingBottom: restShown ? 16 : insets.bottom + 16 }}><Pressable onPress={() => setPhase('exercise')} className="flex-row items-center justify-center gap-2 rounded-2xl bg-brand-500 py-4 active:scale-95"><Play size={20} color="#ffffff" />- <Text className="font-sans-bold text-base text-white">Begin Exercise</Text>+ <Text className="font-sans-bold text-base text-white">{t('gym.info.begin')}</Text></Pressable></View></>,@@ -470,11 +473,11 @@ export function GymModeWorkout() {<AppText variant="heading" numberOfLines={1}>{ex.exercise.name}</AppText><View className="mt-1 flex-row items-center gap-2"><MuscleBadge muscle={ex.exercise.muscle_group} small />- <AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>{completedHere}/{ex.sets.length} sets done</AppText>+ <AppText variant="caption" color="muted" style={{ fontVariant: ['tabular-nums'] }}>{t('workouts.active.setsDone', { done: completedHere, total: ex.sets.length })}</AppText></View></View>{!allSetsComplete ? (- <Pressable onPress={handleRemoveExercise} hitSlop={6} accessibilityLabel="Remove this exercise" className="rounded-lg p-1.5 active:bg-error-500/10">+ <Pressable onPress={handleRemoveExercise} hitSlop={6} accessibilityLabel={t('gym.removeExercise')} className="rounded-lg p-1.5 active:bg-error-500/10"><Trash2 size={16} color={colors.txMuted} /></Pressable>) : null}@@ -494,7 +497,12 @@ export function GymModeWorkout() {<Pressablekey={i}onPress={() => setActiveSetIdx(i)}- accessibilityLabel={`Set ${i + 1}${s.completed ? ', done' : ''}${resting ? ', resting' : ''}`}+ accessibilityLabel={t(+ s.completed+ ? (resting ? 'gym.set.chipDoneResting' : 'gym.set.chipDone')+ : (resting ? 'gym.set.chipResting' : 'gym.set.chip'),+ { number: i + 1 },+ )}className={`h-10 min-w-[44px] flex-row items-center justify-center gap-1 rounded-full px-3 active:scale-95 ${i === clampedSetIdx ? 'bg-brand-500' : s.completed ? `bg-brand-500/15 ${resting ? 'border border-brand-500/60' : ''}` : 'bg-surface-muted'}`}@@ -509,7 +517,7 @@ export function GymModeWorkout() {{/* target reference */}{set.target_reps > 0 || set.target_weight > 0 ? (<AppText variant="body" color="muted" className="text-center">- Target <Text className="font-sans-semibold" style={{ color: colors.txSecondary, fontVariant: ['tabular-nums'] }}>{set.target_reps > 0 ? set.target_reps : '—'} reps</Text>+ {t('gym.target.label')}{' '}<Text className="font-sans-semibold" style={{ color: colors.txSecondary, fontVariant: ['tabular-nums'] }}>{set.target_reps > 0 ? t('gym.target.reps', { count: set.target_reps }) : t('gym.target.repsUnknown')}</Text>{set.target_weight > 0 ? <Text> · <Text className="font-sans-semibold" style={{ color: colors.txSecondary, fontVariant: ['tabular-nums'] }}>{displayWeight(set.target_weight, wUnit)} {wUnit}</Text></Text> : null}</AppText>) : null}@@ -517,13 +525,13 @@ export function GymModeWorkout() {{/* reps + weight steppers */}<View className="w-full flex-row gap-3"><View className="flex-1">- <StepperTile icon={Repeat} label="Reps" name="reps" step={REP_STEP} disabled={set.completed} onStep={(d) => updateSet(activeIdx, clampedSetIdx, 'actual_reps', clampStep(set.actual_reps || 0, d, { min: 0 }))}>- <NumberField key={`reps-${activeIdx}-${clampedSetIdx}`} inputMode="numeric" value={set.actual_reps ? String(set.actual_reps) : ''} onChange={(v) => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.round(clampValue(v)))} placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'} disabled={set.completed} accessibilityLabel="Reps" inputAccessoryViewID={NUMERIC_ACCESSORY_ID} />+ <StepperTile icon={Repeat} label={t('gym.labels.reps')} name={t('gym.labels.repsName')} step={REP_STEP} disabled={set.completed} onStep={(d) => updateSet(activeIdx, clampedSetIdx, 'actual_reps', clampStep(set.actual_reps || 0, d, { min: 0 }))}>+ <NumberField key={`reps-${activeIdx}-${clampedSetIdx}`} inputMode="numeric" value={set.actual_reps ? String(set.actual_reps) : ''} onChange={(v) => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.round(clampValue(v)))} placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'} disabled={set.completed} accessibilityLabel={t('gym.labels.reps')} inputAccessoryViewID={NUMERIC_ACCESSORY_ID} /></StepperTile></View><View className="flex-1">- <StepperTile icon={Dumbbell} label={`Weight (${wUnit})`} name="weight" step={PLATE_STEP} disabled={set.completed} onStep={(d) => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampStep(displayWeight(set.actual_weight, wUnit), d, { min: 0 }), settings.weight_unit))}>- <NumberField key={`wt-${activeIdx}-${clampedSetIdx}`} inputMode="decimal" value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''} onChange={(v) => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampValue(v), settings.weight_unit))} placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'} disabled={set.completed} accessibilityLabel="Weight" inputAccessoryViewID={NUMERIC_ACCESSORY_ID} />+ <StepperTile icon={Dumbbell} label={t('workouts.form.weightWithUnit', { unit: wUnit })} name={t('weight.log.weightName')} step={PLATE_STEP} disabled={set.completed} onStep={(d) => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampStep(displayWeight(set.actual_weight, wUnit), d, { min: 0 }), settings.weight_unit))}>+ <NumberField key={`wt-${activeIdx}-${clampedSetIdx}`} inputMode="decimal" value={set.actual_weight ? String(displayWeight(set.actual_weight, wUnit)) : ''} onChange={(v) => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampValue(v), settings.weight_unit))} placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'} disabled={set.completed} accessibilityLabel={t('gym.labels.weight')} inputAccessoryViewID={NUMERIC_ACCESSORY_ID} /></StepperTile></View></View>@@ -533,11 +541,11 @@ export function GymModeWorkout() {<View className="w-full items-center gap-6"><Pressable onPress={() => handleCompleteSetGym(clampedSetIdx)} className={`w-full flex-row items-center justify-center gap-3 rounded-2xl py-5 active:scale-95 ${set.completed ? 'border-2 border-brand-500/40 bg-brand-500/15' : 'bg-brand-500'}`}><CheckCircle2 size={24} color={set.completed ? accent : '#ffffff'} />- <Text className={`font-sans-bold text-base ${set.completed ? '' : 'text-white'}`} style={set.completed ? { color: accent } : undefined}>{set.completed ? 'Completed' : 'Complete Set'}</Text>+ <Text className={`font-sans-bold text-base ${set.completed ? '' : 'text-white'}`} style={set.completed ? { color: accent } : undefined}>{set.completed ? t('gym.completed') : t('gym.completeSet')}</Text></Pressable>{ex.sets.length > 1 ? (<Pressable onPress={() => handleRemoveSet(clampedSetIdx)} className="active:opacity-60">- <Text className="font-sans text-xs text-tx-muted">Remove this set</Text>+ <Text className="font-sans text-xs text-tx-muted">{t('gym.removeSet')}</Text></Pressable>) : null}</View>@@ -560,7 +568,7 @@ export function GymModeWorkout() {</Pressable><Pressable onPress={() => { addSet(activeIdx); setActiveSetIdx(ex.sets.length) }} className="flex-1 flex-row items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border py-3 active:opacity-60"><Plus size={14} color={colors.txMuted} />- <Text className="font-sans-semibold text-xs text-tx-muted">Add Set</Text>+ <Text className="font-sans-semibold text-xs text-tx-muted">{t('workouts.active.addSet')}</Text></Pressable><Pressable onPress={() => setActiveSetIdx(clampedSetIdx + 1)} disabled={clampedSetIdx >= ex.sets.length - 1} className={`rounded-xl border border-surface-border bg-surface-muted p-3 active:scale-95 ${clampedSetIdx >= ex.sets.length - 1 ? 'opacity-30' : ''}`}><ChevronRight size={16} color={colors.txSecondary} />@@ -569,16 +577,16 @@ export function GymModeWorkout() {<View className="flex-row gap-2"><Pressable onPress={() => setPhase('exercise-info')} className="flex-row items-center gap-1.5 rounded-xl border border-surface-border bg-surface-muted px-4 py-3 active:scale-95"><ChevronLeft size={16} color={colors.txSecondary} />- <Text className="font-sans-semibold text-sm text-tx-secondary">Info</Text>+ <Text className="font-sans-semibold text-sm text-tx-secondary">{t('gym.nav.info')}</Text></Pressable>{isLast ? (<Pressable onPress={() => setConfirmFinish(true)} className={`flex-1 flex-row items-center justify-center gap-2 rounded-xl py-3 active:scale-95 ${allSetsComplete ? 'bg-brand-500' : 'border border-brand-500/30 bg-brand-500/10'}`}><Flag size={16} color={allSetsComplete ? '#ffffff' : accent} />- <Text className={`font-sans-bold text-sm ${allSetsComplete ? 'text-white' : ''}`} style={allSetsComplete ? undefined : { color: accent }}>Finish Workout</Text>+ <Text className={`font-sans-bold text-sm ${allSetsComplete ? 'text-white' : ''}`} style={allSetsComplete ? undefined : { color: accent }}>{t('gym.nav.finishWorkout')}</Text></Pressable>) : (<Pressable onPress={() => setGymState('exercise-info', activeIdx + 1, 0)} className={`flex-1 flex-row items-center justify-center gap-2 rounded-xl py-3 active:scale-95 ${allSetsComplete ? 'bg-brand-500' : 'border border-surface-border bg-surface-muted'}`}>- <Text className={`font-sans-bold text-sm ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>Next Exercise</Text>+ <Text className={`font-sans-bold text-sm ${allSetsComplete ? 'text-white' : 'text-tx-secondary'}`}>{t('gym.nav.nextExercise')}</Text><ChevronRight size={16} color={allSetsComplete ? '#ffffff' : colors.txSecondary} /></Pressable>)}diff --git a/mobile/src/components/workouts/KeyboardDoneBar.tsx b/mobile/src/components/workouts/KeyboardDoneBar.tsxindex d574879..63172c2 100644--- a/mobile/src/components/workouts/KeyboardDoneBar.tsx+++ b/mobile/src/components/workouts/KeyboardDoneBar.tsx@@ -1,4 +1,5 @@import { InputAccessoryView, Keyboard, Platform, Pressable, Text, View } from 'react-native'+import { useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'// iOS numeric keypads (number-pad / decimal-pad) have no return key, so once the@@ -9,6 +10,7 @@ import { useTheme } from '../../theme/useTheme'// nativeID and pass the same ID to their numeric inputs' `inputAccessoryViewID`.// Kept in workouts/ (not ui/) until a second surface needs it.export function KeyboardDoneBar({ nativeID }: { nativeID: string }) {+ const { t } = useTranslation()const { accent } = useTheme()if (Platform.OS !== 'ios') return nullreturn (@@ -16,12 +18,12 @@ export function KeyboardDoneBar({ nativeID }: { nativeID: string }) {<View className="flex-row justify-end border-t border-surface-border bg-surface-raised px-5 py-2"><PressableaccessibilityRole="button"- accessibilityLabel="Dismiss keyboard"+ accessibilityLabel={t('common.dismissKeyboard')}onPress={() => Keyboard.dismiss()}hitSlop={10}className="active:opacity-60">- <Text className="font-sans-semibold text-sm" style={{ color: accent }}>Done</Text>+ <Text className="font-sans-semibold text-sm" style={{ color: accent }}>{t('common.done')}</Text></Pressable></View></InputAccessoryView>diff --git a/mobile/src/components/workouts/MuscleDiagram.tsx b/mobile/src/components/workouts/MuscleDiagram.tsxindex c8f6089..c64746b 100644--- a/mobile/src/components/workouts/MuscleDiagram.tsx+++ b/mobile/src/components/workouts/MuscleDiagram.tsx@@ -1,7 +1,7 @@import { memo } from 'react'import { View } from 'react-native'import Body, { type Slug } from 'react-native-body-highlighter'-import type { Exercise } from '@lyftr/shared'+import { useTranslation, type Exercise } from '@lyftr/shared'import { muscleToBodySlugs } from '../../utils/exerciseUtils'import { useTheme } from '../../theme/useTheme'import { AppText } from '../ui'@@ -17,6 +17,7 @@ const COLORS = ['#0e7490', '#22d3ee'] // [intensity1 = secondary, intensity2 = pexport const MuscleDiagram = memo(function MuscleDiagram({ exercise }: { exercise: Exercise }) {const { isDark } = useTheme()+ const { t } = useTranslation()const primary = muscleToBodySlugs(exercise.muscle_group)const secondary = (exercise.secondary_muscles || []).flatMap((m) => muscleToBodySlugs(m))@@ -35,21 +36,21 @@ export const MuscleDiagram = memo(function MuscleDiagram({ exercise }: { exercis<View className="flex-row items-start justify-center gap-6"><View className="items-center gap-1"><Body data={data} side="front" scale={0.85} colors={COLORS} defaultFill={bodyColor} border="none" />- <AppText variant="caption" color="muted">Front</AppText>+ <AppText variant="caption" color="muted">{t('exercises.detail.bodyFront')}</AppText></View><View className="items-center gap-1"><Body data={data} side="back" scale={0.85} colors={COLORS} defaultFill={bodyColor} border="none" />- <AppText variant="caption" color="muted">Back</AppText>+ <AppText variant="caption" color="muted">{t('exercises.detail.bodyBack')}</AppText></View></View><View className="mt-3 flex-row items-center justify-center gap-4"><View className="flex-row items-center gap-1.5"><View className="h-3 w-3 rounded-full" style={{ backgroundColor: '#22d3ee' }} />- <AppText variant="caption" color="muted">Primary</AppText>+ <AppText variant="caption" color="muted">{t('exercises.detail.primary')}</AppText></View><View className="flex-row items-center gap-1.5"><View className="h-3 w-3 rounded-full" style={{ backgroundColor: '#0e7490' }} />- <AppText variant="caption" color="muted">Secondary</AppText>+ <AppText variant="caption" color="muted">{t('exercises.detail.secondary')}</AppText></View></View></View>diff --git a/mobile/src/components/workouts/ProgramPicker.tsx b/mobile/src/components/workouts/ProgramPicker.tsxindex 6b18cd6..d91c36b 100644--- a/mobile/src/components/workouts/ProgramPicker.tsx+++ b/mobile/src/components/workouts/ProgramPicker.tsx@@ -1,8 +1,8 @@import { useEffect, useMemo, useState } from 'react'import { ActivityIndicator, FlatList, Modal, Pressable, View } from 'react-native'import { BookOpen, ChevronRight, Dumbbell, Moon, X } from 'lucide-react-native'-import type { Program, ProgramDay } from '@lyftr/shared'-import { apiErrorMessage, workoutDays, dayLabel, todaysDay } from '@lyftr/shared'+import type { Program, ProgramDay, UiMessage } from '@lyftr/shared'+import { workoutDays, dayLabel, todaysDay, uiMessage, useTranslation } from '@lyftr/shared'import { AppText, EmptyState, ErrorState, Field, IconButton } from '../ui'import { client } from '../../lib/lyftr'import { useTheme } from '../../theme/useTheme'@@ -18,19 +18,21 @@ interface Props {// skips the day step, same as web). One directed addition over web: a search field —// client-side name filter, since the program list is a single un-paginated fetch.export function ProgramPicker({ onSelect, onClose }: Props) {+ const { t } = useTranslation()const { colors, accent } = useTheme()const [programs, setPrograms] = useState<Program[]>([])const [query, setQuery] = useState('')const [loading, setLoading] = useState(true)- const [error, setError] = useState('')+ // A UiMessage rather than a sentence, so a failure already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [dayPickFor, setDayPickFor] = useState<Program | null>(null)const [retryKey, setRetryKey] = useState(0)useEffect(() => {setLoading(true)client.programAPI.list()- .then((data) => { setPrograms(data || []); setError('') })- .catch((err) => setError(apiErrorMessage(err, "Couldn't load your programs.")))+ .then((data) => { setPrograms(data || []); setError(null) })+ .catch((err) => setError({ key: 'workouts.form.programPicker.loadFailed', cause: err })).finally(() => setLoading(false))}, [retryKey])@@ -43,8 +45,8 @@ export function ProgramPicker({ onSelect, onClose }: Props) {// DayPickerSheet.tsx's pickProgramDay — reused here instead of re-branching it.const pickProgram = (p: Program) => pickProgramDay(p, onSelect, setDayPickFor)- const title = dayPickFor ? dayPickFor.name : 'Load from Program'- const subtitle = dayPickFor ? 'Pick a day to pre-fill exercises' : 'Pick a program to pre-fill exercises'+ const title = dayPickFor ? dayPickFor.name : t('workouts.form.programPicker.title')+ const subtitle = dayPickFor ? t('workouts.form.programPicker.pickDay') : t('workouts.form.programPicker.pickProgram')return (<Modal visible transparent animationType="fade" onRequestClose={dayPickFor ? () => setDayPickFor(null) : onClose}>@@ -58,7 +60,7 @@ export function ProgramPicker({ onSelect, onClose }: Props) {</View><IconButtonicon={X}- label="Close program picker"+ label={t('workouts.form.programPicker.close')}variant="ghost"size="md"onPress={dayPickFor ? () => setDayPickFor(null) : onClose}@@ -86,12 +88,12 @@ export function ProgramPicker({ onSelect, onClose }: Props) {<AppText variant="subheading" numberOfLines={1}>{dayLabel(day, day.order_index)}</AppText>{isToday ? (<View className="rounded-full bg-brand-500/15 px-1.5 py-0.5">- <AppText variant="caption" style={{ color: accent }}>TODAY</AppText>+ <AppText variant="caption" style={{ color: accent }}>{t('workouts.form.programPicker.today')}</AppText></View>) : null}</View><AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">- {(day.exercises ?? []).length} exercise{(day.exercises ?? []).length === 1 ? '' : 's'}+ {t('workouts.form.exerciseCount', { count: (day.exercises ?? []).length })}</AppText></View><ChevronRight size={16} color={colors.txMuted} />@@ -105,7 +107,7 @@ export function ProgramPicker({ onSelect, onClose }: Props) {<Fieldvalue={query}onChangeText={setQuery}- placeholder="Search programs…"+ placeholder={t('workouts.form.programPicker.searchPlaceholder')}autoCapitalize="none"autoCorrect={false}returnKeyType="search"@@ -115,20 +117,20 @@ export function ProgramPicker({ onSelect, onClose }: Props) {{loading ? (<View className="flex-row items-center justify-center gap-2 p-8"><ActivityIndicator color={accent} />- <AppText variant="body" color="muted">Loading programs…</AppText>+ <AppText variant="body" color="muted">{t('workouts.start.loadingPrograms')}</AppText></View>) : error ? (<ErrorState- title="Couldn't load your programs"- message={error}+ title={t('workouts.start.programsLoadFailed')}+ message={uiMessage(error)}onRetry={() => setRetryKey((k) => k + 1)}/>) : shown.length === 0 ? (<EmptyStatecompacticon={BookOpen}- title={query ? 'No matching programs' : 'No programs yet'}- subtitle={query ? 'Try a different search' : 'Create a program first'}+ title={query ? t('workouts.form.programPicker.noMatches') : t('workouts.start.noPrograms')}+ subtitle={query ? t('workouts.list.empty.searchHint') : t('workouts.form.programPicker.createFirst')}/>) : (<FlatList@@ -152,7 +154,7 @@ export function ProgramPicker({ onSelect, onClose }: Props) {<View className="mt-0.5 flex-row items-center gap-1.5"><Dumbbell size={12} color={colors.txMuted} /><AppText variant="caption" color="muted" numberOfLines={1}>- {days.length === 0 ? 'No exercises yet' : `${days.length} workout day${days.length === 1 ? '' : 's'}`}+ {days.length === 0 ? t('workouts.form.programPicker.noExercises') : t('workouts.form.programPicker.workoutDays', { count: days.length })}</AppText>{(item.days ?? []).some((d) => d.is_rest_day) ? (<Moon size={12} color={colors.txMuted} />diff --git a/mobile/src/components/workouts/RestPicker.tsx b/mobile/src/components/workouts/RestPicker.tsxindex 2da7916..d81152d 100644--- a/mobile/src/components/workouts/RestPicker.tsx+++ b/mobile/src/components/workouts/RestPicker.tsx@@ -3,7 +3,7 @@ import { Pressable, Text, TextInput, View } from 'react-native'import * as Haptics from 'expo-haptics'import { Clock, Minus, Pencil, Plus, TimerOff } from 'lucide-react-native'import type { LucideIcon } from 'lucide-react-native'-import { sanitizeNumericInput } from '@lyftr/shared'+import { sanitizeNumericInput, useTranslation } from '@lyftr/shared'import { useTheme } from '../../theme/useTheme'interface Props {@@ -12,12 +12,12 @@ interface Props {}const PRESETS = [0, 60, 90, 120, 180]-const SEGMENTS: { v: number; label: string; Icon: LucideIcon }[] = [- { v: 0, label: 'Off', Icon: TimerOff },- { v: 60, label: '60s', Icon: Clock },- { v: 90, label: '90s', Icon: Clock },- { v: 120, label: '120s', Icon: Clock },- { v: 180, label: '180s', Icon: Clock },+const SEGMENTS: { v: number; Icon: LucideIcon }[] = [+ { v: 0, Icon: TimerOff },+ { v: 60, Icon: Clock },+ { v: 90, Icon: Clock },+ { v: 120, Icon: Clock },+ { v: 180, Icon: Clock },]const clamp = (n: number) => Math.max(0, Math.min(3600, n))@@ -30,6 +30,7 @@ const clamp = (n: number) => Math.max(0, Math.min(3600, n))// The seconds TextInput has no focus-reactive styling → no re-render on focus// (Fabric-safe by construction).export function RestPicker({ value, onChange }: Props) {+ const { t } = useTranslation()const { colors } = useTheme()const isCustom = !PRESETS.includes(value)const [showCustom, setShowCustom] = useState(false)@@ -56,7 +57,7 @@ export function RestPicker({ value, onChange }: Props) {return (<View><View className="flex-row overflow-hidden rounded-xl border border-surface-border">- {SEGMENTS.map(({ v, label, Icon }) => {+ {SEGMENTS.map(({ v, Icon }) => {const active = !customActive && value === vreturn (<Pressable@@ -67,7 +68,7 @@ export function RestPicker({ value, onChange }: Props) {className={seg(active)}><Icon size={13} color={active ? '#ffffff' : colors.txSecondary} strokeWidth={2.2} />- <Text className={segText(active)}>{label}</Text>+ <Text className={segText(active)}>{v === 0 ? t('workouts.rest.off') : t('common.duration.seconds', { value: v })}</Text></Pressable>)})}@@ -81,7 +82,7 @@ export function RestPicker({ value, onChange }: Props) {className={seg(customActive, true)}><Pencil size={13} color={customActive ? '#ffffff' : colors.txSecondary} strokeWidth={2.2} />- <Text className={segText(customActive)}>{isCustom ? `${value}s` : 'Custom'}</Text>+ <Text className={segText(customActive)}>{isCustom ? t('common.duration.seconds', { value }) : t('workouts.rest.custom')}</Text></Pressable></View>@@ -89,7 +90,7 @@ export function RestPicker({ value, onChange }: Props) {<View className="mt-3 flex-row items-center justify-center gap-2"><PressableaccessibilityRole="button"- accessibilityLabel="Minus 5 seconds"+ accessibilityLabel={t('workouts.rest.stepDown5Spoken')}onPress={() => step(-5)}className="rounded-xl border border-surface-border bg-surface-muted p-2.5 active:scale-95">@@ -102,16 +103,16 @@ export function RestPicker({ value, onChange }: Props) {keyboardType="number-pad"returnKeyType="done"selectTextOnFocus- accessibilityLabel="Rest seconds"+ accessibilityLabel={t('workouts.rest.secondsLabel')}placeholderTextColor={colors.txMuted}className="flex-1 py-0 text-center font-sans-semibold text-base text-tx-primary"style={{ fontVariant: ['tabular-nums'] }}/>- <Text className="font-sans text-xs text-tx-muted">sec</Text>+ <Text className="font-sans text-xs text-tx-muted">{t('workouts.rest.secondsUnit')}</Text></View><PressableaccessibilityRole="button"- accessibilityLabel="Plus 5 seconds"+ accessibilityLabel={t('workouts.rest.stepUp5Spoken')}onPress={() => step(5)}className="rounded-xl border border-surface-border bg-surface-muted p-2.5 active:scale-95">diff --git a/mobile/src/components/workouts/RestTimerBanner.tsx b/mobile/src/components/workouts/RestTimerBanner.tsxindex b0cfda6..73374aa 100644--- a/mobile/src/components/workouts/RestTimerBanner.tsx+++ b/mobile/src/components/workouts/RestTimerBanner.tsx@@ -7,7 +7,7 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context'import { Check, Pause, Play, SkipForward } from 'lucide-react-native'import { useWorkoutSession } from '../../lib/lyftr'import { useRestTimer } from '../../hooks/useRestTimer'-import { fmtClock, nextIncompleteSet } from '@lyftr/shared'+import { fmtClock, nextIncompleteSet, useTranslation } from '@lyftr/shared'import { AppText, IconButton } from '../ui'import { useTheme } from '../../theme/useTheme'@@ -19,6 +19,7 @@ import { useTheme } from '../../theme/useTheme'// the last child of every gym phase, below its bottom actions, so it never covers a// control. When minimized the countdown is the session-pill chip instead.export function RestTimerBanner() {+ const { t } = useTranslation()const { colors, brand } = useTheme()const insets = useSafeAreaInsets()const restDurationSec = useWorkoutSession((s) => s.restDurationSec)@@ -82,14 +83,14 @@ export function RestTimerBanner() {const doneSetNum = restEx != null && restSetIdx != null ? restSetIdx + 1 : nullconst label =doneSetNum == null- ? done ? 'Rest over' : paused ? 'Paused' : 'Rest'+ ? done ? t('workouts.rest.label.over') : paused ? t('workouts.rest.label.paused') : t('workouts.rest.label.resting'): done- ? nextIdx !== -1 ? `Rest over · set ${nextIdx + 1} next` : 'Rest over'+ ? nextIdx !== -1 ? t('workouts.rest.label.overNext', { next: nextIdx + 1 }) : t('workouts.rest.label.over'): paused- ? `Set ${doneSetNum} done · paused`+ ? t('workouts.rest.label.setDonePaused', { done: doneSetNum }): nextIdx !== -1- ? `Set ${doneSetNum} done · set ${nextIdx + 1} next`- : `Set ${doneSetNum} done · resting`+ ? t('workouts.rest.label.setDoneNext', { done: doneSetNum, next: nextIdx + 1 })+ : t('workouts.rest.label.setDoneResting', { done: doneSetNum })// Urgency cue: the last 10 running seconds shift the drain + countdown to amber// (paused doesn't count down, so it never goes hot). Time-based (not fraction-based)@@ -128,7 +129,7 @@ export function RestTimerBanner() {<Check size={26} color={brand.success} /></Animated.View><Pressable onPress={() => clearRest()} className="w-full items-center justify-center rounded-2xl bg-brand-500 py-4 active:scale-95">- <Text className="font-sans-bold text-base text-white">Done</Text>+ <Text className="font-sans-bold text-base text-white">{t('common.done')}</Text></Pressable></View>) : (@@ -139,7 +140,7 @@ export function RestTimerBanner() {<View className="w-14 items-center"><IconButtonicon={paused ? Play : Pause}- label={paused ? 'Resume rest timer' : 'Pause rest timer'}+ label={paused ? t('workouts.rest.resume') : t('workouts.rest.pause')}variant="brand"size="lg"onPress={paused ? resumeRest : pauseRest}@@ -151,15 +152,15 @@ export function RestTimerBanner() {<View className="w-14" /></View><View className="flex-row gap-2.5">- <Pressable onPress={() => adjustRest(-15)} accessibilityLabel="Shorten rest by 15 seconds" className={secBtn}>+ <Pressable onPress={() => adjustRest(-15)} accessibilityLabel={t('workouts.rest.shorten')} className={secBtn}><Text className="font-sans-bold text-base text-tx-secondary" style={{ fontVariant: ['tabular-nums'] }}>−15</Text></Pressable>- <Pressable onPress={() => adjustRest(15)} accessibilityLabel="Extend rest by 15 seconds" className={secBtn}>+ <Pressable onPress={() => adjustRest(15)} accessibilityLabel={t('workouts.rest.extend')} className={secBtn}><Text className="font-sans-bold text-base text-tx-secondary" style={{ fontVariant: ['tabular-nums'] }}>+15</Text></Pressable><Pressable onPress={() => clearRest()} className={brandBtn}><SkipForward size={18} color="#ffffff" />- <Text className="font-sans-bold text-base text-white">Skip</Text>+ <Text className="font-sans-bold text-base text-white">{t('workouts.rest.skip')}</Text></Pressable></View></>diff --git a/mobile/src/components/workouts/SessionPill.tsx b/mobile/src/components/workouts/SessionPill.tsxindex db4406b..40309b6 100644--- a/mobile/src/components/workouts/SessionPill.tsx+++ b/mobile/src/components/workouts/SessionPill.tsx@@ -3,13 +3,14 @@ import { router, usePathname } from 'expo-router'import { ChevronRight, Timer } from 'lucide-react-native'import { useSettingsStore, useWorkoutSession } from '../../lib/lyftr'import { useRestTimer } from '../../hooks/useRestTimer'-import { fmtClock, formatElapsed, useElapsedSeconds } from '@lyftr/shared'+import { fmtClock, formatElapsed, useElapsedSeconds, useTranslation } from '@lyftr/shared'// Port of web Layout's ActiveSessionBar — the minimized session pill. Floats above the// tab bar on every screen except: the gym overlay (gym layout, open) and the active// screen itself (list layout). Tapping opens the gym overlay (gym) or the active// screen (list). Carries the rest-countdown chip so "rest over" clears while minimized.export function SessionPill() {+ const { t } = useTranslation()const session = useWorkoutSession((s) => s.session)const openGym = useWorkoutSession((s) => s.openGym)const layout = useSettingsStore((s) => s.settings.workout_layout)@@ -45,11 +46,11 @@ export function SessionPill() {</View><View><Text className="font-sans-bold text-xs text-white" numberOfLines={1} style={{ maxWidth: 140 }}>{session.name}</Text>- <Text className="text-[11px] text-white/70">{completedSets}/{totalSets} sets · {formatElapsed(elapsed)}</Text>+ <Text className="text-[11px] text-white/70">{t('nav.session.sets', { done: completedSets, total: totalSets })} · {formatElapsed(elapsed)}</Text></View>{resting ? (<View className="flex-row items-center gap-1.5 rounded-full bg-white/15 py-1 pl-2.5 pr-1">- <Text className="text-[10px] font-sans-semibold uppercase text-white/70">{done ? 'Rest over' : paused ? 'Paused' : 'Rest'}</Text>+ <Text className="text-[10px] font-sans-semibold uppercase text-white/70">{done ? t('nav.session.restOver') : paused ? t('nav.session.paused') : t('nav.session.rest')}</Text>{!done ? <Text className="font-sans-bold text-xs text-white" style={{ fontVariant: ['tabular-nums'] }}>{fmtClock(left)}</Text> : null}</View>) : null}diff --git a/mobile/src/components/workouts/WorkoutCard.tsx b/mobile/src/components/workouts/WorkoutCard.tsxindex f61f43d..aa51d24 100644--- a/mobile/src/components/workouts/WorkoutCard.tsx+++ b/mobile/src/components/workouts/WorkoutCard.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { Pressable, View } from 'react-native'import { router } from 'expo-router'import { ChevronRight, Clock, Dumbbell, MoreVertical, TrendingUp } from 'lucide-react-native'-import { useAsyncAction, displayVolume, type Workout, workoutDay, formatDay } from '@lyftr/shared'+import { useAsyncAction, displayVolume, type Workout, workoutDay, formatDay, useTranslation } from '@lyftr/shared'import { ActionSheet, AppText, Card, ConfirmSheet, IconButton, deleteAction, deleteConfirmProps, editAction } from '../ui'import { useTheme } from '../../theme/useTheme'import { client } from '../../lib/lyftr'@@ -21,6 +21,7 @@ interface Props {// AND a kebab (⋮) menu. Mirrors the web card's mobile kebab → options (Edit / Delete);// the menu is a native ActionSheet and Delete routes through the shared ConfirmSheet.export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {+ const { t } = useTranslation()const { colors } = useTheme()const [confirming, setConfirming] = useState(false)const [menuOpen, setMenuOpen] = useState(false)@@ -38,13 +39,20 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {unit)+ const exerciseCount = t('workouts.card.exercises', { count: workout.exercises?.length || 0 })+ const headerMeta = [+ formatDay(workoutDay(workout), 'monthDayYear'),+ ...(durationMin > 0 ? [t('workouts.card.minutes', { minutes: durationMin })] : []),+ exerciseCount,+ ].join(' · ')+// The catch here just put the card back - "a failed delete quietly restores the// card" - which is indistinguishable from a tap that never registered. The// confirm stays up now and says why it did not work.const remove = useAsyncAction(async () => {await client.workoutAPI.delete(workout.id)onDeleted(workout.id)- }, 'Failed to delete workout')+ }, t('workouts.deleteFailed'))return (<Pressable accessibilityRole="button" onPress={onPress} className="active:scale-[0.99]">@@ -56,14 +64,14 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {then exercises + volume — three items on one line truncated at 390pt. */}<View className="flex-row items-center gap-x-2 mt-0.5"><AppText variant="caption" color="muted" numberOfLines={1}>- {formatDay(workoutDay(workout), 'MMM d, yyyy')}+ {formatDay(workoutDay(workout), 'monthDayYear')}</AppText>{durationMin > 0 && (<><AppText variant="caption" color="muted">·</AppText><View className="flex-row items-center gap-1"><Clock size={12} color={colors.txMuted} />- <AppText variant="caption" color="muted">{durationMin} min</AppText>+ <AppText variant="caption" color="muted">{t('workouts.card.minutes', { minutes: durationMin })}</AppText></View></>)}@@ -73,7 +81,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {<View className="flex-row items-center gap-1"><Dumbbell size={12} color={colors.txMuted} /><AppText variant="caption" color="muted" numberOfLines={1}>- {workout.exercises?.length || 0} exercises+ {exerciseCount}</AppText></View>{totalVolume > 0 && (@@ -94,7 +102,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {Delete, and Delete still routes through the ConfirmSheet. */}<IconButtonicon={MoreVertical}- label={`${workout.name} options`}+ label={t('workouts.card.optionsNamed', { name: workout.name })}variant="ghost"size="sm"onPress={() => setMenuOpen(true)}@@ -115,14 +123,12 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {<View className="flex-1"><AppText variant="subheading" numberOfLines={1}>{workout.name}</AppText><AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">- {formatDay(workoutDay(workout), 'MMM d, yyyy')}- {durationMin > 0 ? ` · ${durationMin} min` : ''}- {` · ${workout.exercises?.length || 0} exercises`}+ {headerMeta}</AppText>{totalVolume > 0 ? (<View className="mt-1.5 flex-row items-center gap-1"><TrendingUp size={12} color={colors.txMuted} />- <AppText variant="caption" color="muted">{compact(totalVolume)} {unit} total volume</AppText>+ <AppText variant="caption" color="muted">{t('workouts.card.totalVolume', { amount: compact(totalVolume), unit })}</AppText></View>) : null}</View>@@ -135,7 +141,7 @@ export function WorkoutCard({ workout, unit, onPress, onDeleted }: Props) {/><ConfirmSheet- {...deleteConfirmProps({ title: 'Delete Workout?', subject: `"${workout.name}"` })}+ {...deleteConfirmProps({ title: t('workouts.deleteConfirmTitle'), subject: `"${workout.name}"` })}open={confirming}busy={remove.busy}error={remove.error}diff --git a/mobile/src/components/workouts/WorkoutsSkeleton.tsx b/mobile/src/components/workouts/WorkoutsSkeleton.tsxindex ce2d050..ad36a96 100644--- a/mobile/src/components/workouts/WorkoutsSkeleton.tsx+++ b/mobile/src/components/workouts/WorkoutsSkeleton.tsx@@ -1,4 +1,5 @@import { router } from 'expo-router'+import { useTranslation } from '@lyftr/shared'import { Plus } from 'lucide-react-native'import { IconButton, ListScreenSkeleton } from '../ui'@@ -7,15 +8,16 @@ import { IconButton, ListScreenSkeleton } from '../ui'// "Log Workout" action are the REAL controls, live immediately; only the data-shaped// regions are placeholders.export function WorkoutsSkeleton() {+ const { t } = useTranslation()return (<ListScreenSkeleton- title="Workouts"- subtitle="Track and review your training sessions"+ title={t('workouts.list.title')}+ subtitle={t('workouts.list.subtitle')}statCount={3}action={<IconButtonicon={Plus}- label="Log Workout"+ label={t('workouts.list.logWorkout')}variant="solid"size="md"onPress={() => router.push('/workouts/new')}diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.tsindex 15ea233..345392b 100644--- a/mobile/src/lib/lyftr.ts+++ b/mobile/src/lib/lyftr.ts@@ -9,6 +9,7 @@ import {createServerStore,createSettingsStore,createThemeStore,+ createLanguageStore,createWorkoutSession,testServerConnection,useServerInfoFor,@@ -41,6 +42,9 @@ const detectTimezone = () => Localization.getCalendars()[0]?.timeZone ?? nullexport const useSettingsStore = createSettingsStore(client, storage, detectTimezone)// Light-first on mobile (per product); mirrors the web's theme logic + 'theme' key.export const useThemeStore = createThemeStore(storage, 'light')+// Raw device tags only; shared resolveLanguage() decides which supported language they mean.+const detectLanguages = () => Localization.getLocales().map((l) => l.languageTag)+export const useLanguageStore = createLanguageStore(storage, detectLanguages)// Workout session state (active workout + gym UI position) — device-local via// AsyncStorage; rest-timer state is in-memory only (see the store).export const useWorkoutSession = createWorkoutSession(storage)diff --git a/mobile/src/lib/pluralRules.test.ts b/mobile/src/lib/pluralRules.test.tsnew file mode 100644index 0000000..8ea1b71--- /dev/null+++ b/mobile/src/lib/pluralRules.test.ts@@ -0,0 +1,48 @@+// Pins the Hermes path. Hermes ships no Intl.PluralRules, and i18next >=24 has no fallback+// without it, so Spanish _one/_many would silently never resolve. polyfills.ts is the+// module the app entry imports first; this proves it supplies PluralRules and that+// i18next then picks the right forms from the shared catalog.++jest.mock('react-native-gesture-handler', () => ({}))+jest.mock('react-native-url-polyfill/auto', () => ({}))++describe('Intl.PluralRules on a runtime without it', () => {+ const real = Intl.PluralRules++ afterAll(() => {+ ;(Intl as any).PluralRules = real+ })++ it('is installed by polyfills and drives plural keys in es', async () => {+ delete (Intl as any).PluralRules+ expect(typeof Intl.PluralRules).toBe('undefined')++ const errors = jest.spyOn(console, 'error').mockImplementation(() => {})+ const warns = jest.spyOn(console, 'warn').mockImplementation(() => {})++ let shared: typeof import('@lyftr/shared')+ /* eslint-disable @typescript-eslint/no-require-imports */+ jest.isolateModules(() => {+ require('./polyfills')+ shared = require('@lyftr/shared')+ })++ /* eslint-enable @typescript-eslint/no-require-imports */+ expect(typeof Intl.PluralRules).toBe('function')++ const { i18n } = shared!+ await i18n.changeLanguage('es')+ const t = (count: number) => i18n.t('settings.library.refreshed', { count, amount: String(count) })+ expect(t(1)).toBe('Se actualizó 1 ejercicio')+ expect(t(2)).toBe('Se actualizaron 2 ejercicios')+ // The polyfill lists the same es categories as Node's ICU, so the catalog guard's key+ // set is right on device. (Its `many` rule is older and does not fire for 1000000 the+ // way Node's does; that gap is a known difference, not something to pin here.)+ expect(new Intl.PluralRules('es').resolvedOptions().pluralCategories).toEqual(['one', 'many', 'other'])++ const calls = [...errors.mock.calls, ...warns.mock.calls].map((c) => c.join(' '))+ expect(calls.filter((c) => c.includes('Intl'))).toEqual([])+ errors.mockRestore()+ warns.mockRestore()+ })+})diff --git a/mobile/src/lib/polyfills.ts b/mobile/src/lib/polyfills.tsindex 88b3bf8..64599d6 100644--- a/mobile/src/lib/polyfills.ts+++ b/mobile/src/lib/polyfills.ts@@ -3,4 +3,8 @@// uses `new URL()`.// - gesture-handler: required by react-native-screens / reanimated navigation.import 'react-native-gesture-handler'+// - Intl.PluralRules: Hermes ships no PluralRules (its IntlAPIs.md lists only Collator,+// NumberFormat and DateTimeFormat), and i18next >=24 has no fallback without it, so+// Spanish _one/_many would silently never resolve. Installs itself only when missing.+import 'intl-pluralrules'import 'react-native-url-polyfill/auto'diff --git a/mobile/src/lib/supportedLocales.test.ts b/mobile/src/lib/supportedLocales.test.tsnew file mode 100644index 0000000..88bcd17--- /dev/null+++ b/mobile/src/lib/supportedLocales.test.ts@@ -0,0 +1,32 @@+// app.json cannot import the language registry, so this test is what keeps the OS per-app+// language list and the in-app list the same. The allowDynamicLocaleChangesAndroid assertion+// pins a plugin quirk: its default applies only when no options object is passed, so passing+// supportedLocales alone would drop locale|layoutDirection from MainActivity's configChanges.++jest.mock('react-native-gesture-handler', () => ({}))+jest.mock('react-native-url-polyfill/auto', () => ({}))++import { SUPPORTED_LANGUAGES } from '@lyftr/shared'+import appJson from '../../app.json'++type Options = {+ supportedLocales: { ios: string[]; android: string[] }+ allowDynamicLocaleChangesAndroid: boolean+}++describe('expo-localization plugin config', () => {+ const entry = (appJson.expo.plugins as unknown[]).find(+ (p) => Array.isArray(p) && p[0] === 'expo-localization',+ ) as [string, Options] | undefined++ it('registers exactly the supported languages with iOS and Android', () => {+ expect(entry).toBeDefined()+ const want = [...SUPPORTED_LANGUAGES].sort()+ expect([...entry![1].supportedLocales.ios].sort()).toEqual(want)+ expect([...entry![1].supportedLocales.android].sort()).toEqual(want)+ })++ it('keeps allowDynamicLocaleChangesAndroid on', () => {+ expect(entry![1].allowDynamicLocaleChangesAndroid).toBe(true)+ })+})diff --git a/mobile/src/lib/useAsyncAction.test.ts b/mobile/src/lib/useAsyncAction.test.tsindex ab496cb..89bbe22 100644--- a/mobile/src/lib/useAsyncAction.test.ts+++ b/mobile/src/lib/useAsyncAction.test.ts@@ -1,5 +1,6 @@import { renderHook, act, waitFor } from '@testing-library/react-native'-import { useAsyncAction } from '@lyftr/shared'+import { useEffect } from 'react'+import { i18n, useAsyncAction } from '@lyftr/shared'// The hook lives in @lyftr/shared, but its test lives here: `packages/shared` is plain// ts-jest with no renderer, and adding one for this would be a dependency the repo does@@ -89,6 +90,23 @@ describe('useAsyncAction', () => {expect(result.current.error).toBe('Failed to save')})+ // The hook keeps the failure, not its text. A screen that re-passes its fallback in the new+ // language (as every call site does, via t(...) at render) gets the new sentence for a+ // message that was raised before the switch.+ it('stores the cause, so a later render with a different fallback changes the message', async () => {+ const { result, rerender } = renderHook(+ ({ fallback }: { fallback: string }) =>+ useAsyncAction(async () => { throw httpError(400) }, fallback),+ { initialProps: { fallback: 'Failed to save' } },+ )++ await act(async () => { await result.current.run() })+ expect(result.current.error).toBe('Failed to save')++ rerender({ fallback: 'No se pudo guardar' })+ expect(result.current.error).toBe('No se pudo guardar')+ })+it('drops a stale message when the next attempt starts', async () => {let fail = trueconst { result } = renderHook(() =>@@ -141,4 +159,33 @@ describe('useAsyncAction', () => {expect(action).toHaveBeenCalledWith(7, 'squat')})++ // Screens raise a toast from an effect when a failure appears. `error` is re-derived in the+ // new language, so an effect keyed on it re-fires (re-raising a dismissed toast) on a+ // language switch; `failureKey` only moves when a request actually fails.+ describe('failureKey', () => {+ afterEach(async () => { await act(async () => { await i18n.changeLanguage('en') }) })++ it('does not change with the language, so an effect keyed on it does not re-fire', async () => {+ const raised = jest.fn()+ const { result } = renderHook(() => {+ const a = useAsyncAction(async () => { throw new Error('boom') }, i18n.t('settings.deleteAccount.failed'))+ useEffect(() => { if (a.failureKey) raised(a.failureKey) }, [a.failureKey])+ return a+ })+ expect(result.current.failureKey).toBe(0)++ await act(async () => { await result.current.run() })+ expect(raised).toHaveBeenCalledTimes(1)+ const english = result.current.error+ expect(english).not.toBe('')++ await act(async () => { await i18n.changeLanguage('es') })+ expect(result.current.error).not.toBe(english)+ expect(raised).toHaveBeenCalledTimes(1)++ await act(async () => { await result.current.run() })+ expect(raised).toHaveBeenCalledTimes(2)+ })+ })})diff --git a/mobile/src/utils/exerciseUtils.test.ts b/mobile/src/utils/exerciseUtils.test.tsindex 4e84f15..a33c910 100644--- a/mobile/src/utils/exerciseUtils.test.ts+++ b/mobile/src/utils/exerciseUtils.test.ts@@ -1,6 +1,6 @@import { muscleColor, muscleToBodySlugs } from './exerciseUtils'-// The lookup rule and EQUIPMENT_LABEL are covered in+// The lookup rule and the equipment and muscle labels are covered in// packages/shared/src/utils/exerciseUtils.test.ts. What's left here is what is// genuinely mobile's: the tint shape and the RN body-highlighter slug remaps.diff --git a/mobile/src/utils/exerciseUtils.ts b/mobile/src/utils/exerciseUtils.tsindex 8648681..d060c8a 100644--- a/mobile/src/utils/exerciseUtils.ts+++ b/mobile/src/utils/exerciseUtils.ts@@ -1,8 +1,8 @@import { resolveMuscleSlugs } from '@lyftr/shared'// Mobile's half of exercise presentation: the RN tint table and the-// react-native-body-highlighter slug table. EQUIPMENT_LABEL and the lookup rule are-// shared — see packages/shared/src/utils/exerciseUtils.ts for why these two are not.+// react-native-body-highlighter slug table. The equipment and muscle labels and the lookup+// rule are shared — see packages/shared/src/utils/exerciseUtils.ts for why these two are not.//// The text tint is a hex, not a class, because AppText always resolves a default// text-colour class and two colour classes on one Text leave the winner to stylesheet@@ -10,7 +10,7 @@ import { resolveMuscleSlugs } from '@lyftr/shared'// The hexes are Tailwind's own *-400 values, identical to web's text-*-400 classes.// `border` carries web's muscleColorBordered() border class for the picker badges;// borderless badges (detail screen) simply don't apply it.-export { EQUIPMENT_LABEL } from '@lyftr/shared'+export { categoryLabel, equipmentLabel, muscleLabel } from '@lyftr/shared'export interface MuscleTint {/** NativeWind class for the badge background (bg only — no text class). */diff --git a/package-lock.json b/package-lock.jsonindex 76c5638..0302f63 100644--- a/package-lock.json+++ b/package-lock.json@@ -40,6 +40,7 @@"expo-secure-store": "~15.0.8","expo-splash-screen": "~31.0.13","expo-status-bar": "~3.0.9",+ "intl-pluralrules": "^2.0.1","lucide-react-native": "^0.460.0","nativewind": "^4.1.23","react": "19.1.0",@@ -11496,6 +11497,14 @@"devOptional": true,"license": "MIT"},+ "node_modules/html-parse-stringify": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-4.0.1.tgz",+ "integrity": "sha512-0zHsZJrK7S3K2aucXWL6ycoYJ/iNtIcFHC/nYQgFklPtrv5LpJctIiSCroWZWeuoXvuyFdzp6KzjJQ+OT5MfFw==",+ "funding": {+ "url": "https://locize.com"+ }+ },"node_modules/http-cache-semantics": {"version": "4.2.0","resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.2.0.tgz",@@ -11590,6 +11599,33 @@"integrity": "sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw==","license": "BSD-3-Clause"},+ "node_modules/i18next": {+ "version": "26.4.3",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.4.3.tgz",+ "integrity": "sha512-QIIueUYS2giFVIY3hu/X5Dz7/qTzwcXE06H29m1DKVhUGVPCyT0wnsh14wEn/cTy9nZ/B6VhbDItdXotOKSO8A==",+ "funding": [+ {+ "type": "individual",+ "url": "https://www.locize.com/i18next"+ },+ {+ "type": "individual",+ "url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"+ },+ {+ "type": "individual",+ "url": "https://www.locize.com"+ }+ ],+ "peerDependencies": {+ "typescript": "^5 || ^6 || ^7"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/iconv-lite": {"version": "0.6.3","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",@@ -11768,6 +11804,11 @@"node": ">=12"}},+ "node_modules/intl-pluralrules": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/intl-pluralrules/-/intl-pluralrules-2.0.1.tgz",+ "integrity": "sha512-astxTLzIdXPeN0K9Rumi6LfMpm3rvNO0iJE+h/k8Kr/is+wPbRe4ikyDjlLr6VTh/mEfNv8RjN+gu3KwDiuhqg=="+ },"node_modules/invariant": {"version": "2.2.4","resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",@@ -16169,6 +16210,32 @@"react": ">=17.0.0"}},+ "node_modules/react-i18next": {+ "version": "17.0.16",+ "resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.0.16.tgz",+ "integrity": "sha512-7uImVD9hG5yUOaP5KHVied1x0A004Di/KU031ULR35Ma+9e9H5GdnNZHgQEIByyAz+IAXBkRDTedNVzjPUH8ZA==",+ "dependencies": {+ "@babel/runtime": "^7.29.7",+ "html-parse-stringify": "^4.0.1",+ "use-sync-external-store": "^1.6.0"+ },+ "peerDependencies": {+ "i18next": ">= 26.2.0",+ "react": ">= 16.8.0",+ "typescript": "^5 || ^6 || ^7"+ },+ "peerDependenciesMeta": {+ "react-dom": {+ "optional": true+ },+ "react-native": {+ "optional": true+ },+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/react-is": {"version": "19.2.7","resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.7.tgz",@@ -20075,7 +20142,9 @@"version": "0.0.0","dependencies": {"axios": "^1.6.2",- "date-fns": "^3.0.0"+ "date-fns": "^3.0.0",+ "i18next": "^26.4.3",+ "react-i18next": "^17.0.16"},"devDependencies": {"@types/jest": "^29.5.12",diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex a28b464..c10b561 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -11,7 +11,9 @@},"dependencies": {"axios": "^1.6.2",- "date-fns": "^3.0.0"+ "date-fns": "^3.0.0",+ "i18next": "^26.4.3",+ "react-i18next": "^17.0.16"},"peerDependencies": {"react": ">=18",diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.tsindex 5129e44..cc7b1e1 100644--- a/packages/shared/src/client.test.ts+++ b/packages/shared/src/client.test.ts@@ -1,5 +1,8 @@import axios from 'axios'-import { createClient } from './client'+import { apiErrorMessage, createClient, uiMessage } from './client'+import { i18n } from './i18n'+import en from './i18n/locales/en.json'+import es from './i18n/locales/es.json'import { StorageAdapter, STORAGE_KEYS } from './storage'const memStorage = (): StorageAdapter => {@@ -588,3 +591,36 @@ describe('a 401 that arrives while this device is switching to its new tokens',expect(await store.get(STORAGE_KEYS.refresh)).toBeNull()})})++describe('apiErrorMessage and uiMessage translate when they run', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })+ const bad502 = { response: { status: 502, data: '<html>Bad Gateway</html>' } }++ it('apiErrorMessage on a 502 follows the language switch, and en is unchanged after restoring', async () => {+ expect(apiErrorMessage(bad502, 'fallback')).toBe('The server is restarting or unreachable. Try again in a moment.')+ await i18n.changeLanguage('es')+ expect(apiErrorMessage(bad502, 'fallback')).toBe(es.errors.api.restarting)+ await i18n.changeLanguage('en')+ expect(apiErrorMessage(bad502, 'fallback')).toBe(en.errors.api.restarting)+ })++ it('a server-sent sentence passes through untranslated', async () => {+ await i18n.changeLanguage('es')+ expect(apiErrorMessage({ response: { status: 400, data: { error: 'Email already taken' } } }, 'x')).toBe('Email already taken')+ })++ it('uiMessage fills placeholders and re-translates the same stored message in es', async () => {+ const m = { key: 'food.favorites.addFailed', params: { name: 'Oats' } } as const+ expect(uiMessage(m)).toBe("Couldn't add Oats to Favorites.")+ await i18n.changeLanguage('es')+ expect(uiMessage(m)).toBe(es.food.favorites.addFailed.replace('{{name}}', 'Oats'))+ })++ it('uiMessage with a cause hands the failure to apiErrorMessage, with the key as its fallback', async () => {+ const m = { key: 'server.test.unreachable', cause: { response: { status: 418, data: {} } } } as const+ expect(uiMessage(m)).toBe("Couldn't reach the server.")+ await i18n.changeLanguage('es')+ expect(uiMessage(m)).toBe(es.server.test.unreachable)+ expect(uiMessage({ ...m, cause: bad502 })).toBe(es.errors.api.restarting)+ })+})diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex db826c5..f1a1ac6 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -4,6 +4,8 @@ import { StorageAdapter, STORAGE_KEYS } from './storage'import { normalizeServerUrl } from './utils/serverUrl'import { networkFailureMessage, type MessageDetail } from './utils/networkError'import { withLoggedOn, utcOffsetMinutes } from './utils/dateUtils'+import { i18n } from './i18n'+import type { ParseKeys } from 'i18next'// Every API call lives under this versioned path. `origin` is an absolute server// origin for a cross-origin backend, or '' for the same-origin reverse proxy (web).@@ -43,7 +45,7 @@ export const apiErrorMessage = (err: any, fallback: string, detail: MessageDetaiif (serverError) return serverErrorconst status = err.response.statusif (status === 404 || status === 405) {- return "Server URL looks misconfigured — the API endpoint wasn't found. Check Server settings."+ return i18n.t('errors.api.misconfigured')}// Ordered ABOVE the HTML sniff on purpose. Every reverse proxy — nginx, Caddy,// Traefik — serves its 502 as an HTML page, so sniffing for a document first@@ -51,7 +53,7 @@ export const apiErrorMessage = (err: any, fallback: string, detail: MessageDetai// most self-hosted moment there is, when the settings are fine and the stack is// mid-upgrade. Status is the stronger signal when we have one.if (status === 502 || status === 503 || status === 504) {- return 'The server is restarting or unreachable. Try again in a moment.'+ return i18n.t('errors.api.restarting')}// A reverse proxy answers with its own HTML page when the app behind it is down,// restarting, or was never there — the body is a document, not our {"error"} envelope.@@ -61,28 +63,46 @@ export const apiErrorMessage = (err: any, fallback: string, detail: MessageDetai// what reads as an app bug.const body = err.response.dataif (typeof body === 'string' && /^\s*<(!doctype|html)/i.test(body)) {- return 'That address returned a web page, not the Lyftr API. Check Server settings.'+ return i18n.t('errors.api.notApi')}- if (status >= 500) return 'Server error. Please try again shortly.'+ if (status >= 500) return i18n.t('errors.api.serverError')return fallback}return networkFailureMessage(err, detail)}+// What a screen keeps in state instead of a sentence: the catalog key and its inputs, plus+// the failure that caused it. The text is made by uiMessage() at render, so a banner that is+// already on screen follows a language switch instead of staying in the language it was+// raised in.+export type UiMessage = {+ key: ParseKeys+ params?: Record<string, unknown>+ cause?: unknown+ detail?: MessageDetail+}++export const uiMessage = (m: UiMessage): string => {+ // The key is checked where the message is written; the union of every key cannot be+ // checked against one params shape here.+ const text = (i18n.t as (key: string, params?: Record<string, unknown>) => string)(m.key, m.params)+ return 'cause' in m ? apiErrorMessage(m.cause, text, m.detail) : text+}+// Probe a server's public /info endpoint to confirm it's reachable and is a Lyftr// backend. Pass '' for the default/reverse-proxy origin.export const testServerConnection = async (base: string,-): Promise<{ ok: true; info: ServerInfo } | { ok: false; message: string }> => {+): Promise<{ ok: true; info: ServerInfo } | { ok: false; failure: UiMessage }> => {try {const res = await axios.get<{ data: ServerInfo }>(`${apiUrl(base)}/info`, { timeout: 8000 })const info = res.data?.dataif (!info?.name) {- return { ok: false, message: "That responded, but it doesn't look like a Lyftr server." }+ return { ok: false, failure: { key: 'server.test.notLyftr' } }}return { ok: true, info }} catch (err) {- return { ok: false, message: apiErrorMessage(err, "Couldn't reach the server.", 'full') }+ return { ok: false, failure: { key: 'server.test.unreachable', cause: err, detail: 'full' } }}}diff --git a/packages/shared/src/hooks/useAsyncAction.ts b/packages/shared/src/hooks/useAsyncAction.tsindex cc6b3db..d5c9aa8 100644--- a/packages/shared/src/hooks/useAsyncAction.ts+++ b/packages/shared/src/hooks/useAsyncAction.ts@@ -1,11 +1,14 @@import { useCallback, useEffect, useRef, useState } from 'react'import { apiErrorMessage } from '../client'+import { useTranslation } from '../i18n'export interface AsyncAction<A extends unknown[]> {/** True while the action is in flight. Gate the button on this. */busy: boolean/** '' until the action fails, then the sentence a person should read. */error: string+ /** Counts failures, 0 until the first. Unlike `error`, it does not change with the language, so key an effect that raises a toast or scrolls on this. */+ failureKey: number/** Runs the action. Resolves true on success, false if it failed. */run: (...args: A) => Promise<boolean>/** Drop a stale message — on dismiss, or when the form changes underneath it. */@@ -33,8 +36,14 @@ export function useAsyncAction<A extends unknown[] = []>(action: (...args: A) => Promise<unknown>,fallbackMessage: string,): AsyncAction<A> {+ // Subscribes this hook to a language switch, so `error` below is re-derived in the new+ // language rather than frozen in the one the failure happened in.+ useTranslation()const [busy, setBusy] = useState(false)- const [error, setError] = useState('')+ // The failure itself, not its text: the sentence is made at render from the fallback the+ // caller passes this render, so a visible banner follows a live language switch.+ const [failure, setFailure] = useState<{ cause: unknown } | null>(null)+ const [failureKey, setFailureKey] = useState(0)// Latest-callback refs. Screens pass an inline closure that reads current state, so// `action` has a fresh identity every render — capturing it in the useCallback deps@@ -57,12 +66,15 @@ export function useAsyncAction<A extends unknown[] = []>(const run = useCallback(async (...args: A): Promise<boolean> => {setBusy(true)- setError('')+ setFailure(null)try {await latest.current(...args)return true} catch (err) {- if (mounted.current) setError(apiErrorMessage(err, fallback.current))+ if (mounted.current) {+ setFailure({ cause: err })+ setFailureKey((k) => k + 1)+ }return false} finally {// In `finally`, not only on the failure path: a screen that stays put after@@ -71,7 +83,8 @@ export function useAsyncAction<A extends unknown[] = []>(}}, [])- const reset = useCallback(() => setError(''), [])+ const reset = useCallback(() => setFailure(null), [])- return { busy, error, run, reset }+ const error = failure ? apiErrorMessage(failure.cause, fallback.current) : ''+ return { busy, error, failureKey, run, reset }}diff --git a/packages/shared/src/hooks/useFavorites.ts b/packages/shared/src/hooks/useFavorites.tsindex 0589f09..9bdcae4 100644--- a/packages/shared/src/hooks/useFavorites.ts+++ b/packages/shared/src/hooks/useFavorites.ts@@ -1,5 +1,6 @@import { useRef, useState } from 'react'-import { apiErrorMessage } from '../client'+import { uiMessage, type UiMessage } from '../client'+import { useTranslation } from '../i18n'import type { FoodSearchResult, SavedFood } from '../types'import { findSavedFood, normaliseFoodKey } from '../utils/food'@@ -21,7 +22,8 @@ export interface Favorites {toggle: (item: FoodSearchResult) => Promise<'added' | 'removed' | null>/** The sentence to show when a toggle failed, in the server's words. */error: string | null- setError: (error: string | null) => void+ /** Dismiss the sentence. */+ setError: (error: null) => void/*** Bumped when a toggle starts and again when it settles. A list load captures it and* drops its own result if it moved while the load was in flight — otherwise a refresh@@ -50,7 +52,9 @@ const keyOf = (item: FoodSearchResult) => `${normaliseFoodKey(item.name)}|${normexport function useFavorites(api: SavedFoodsApi): Favorites {const [savedFoods, setSavedFoods] = useState<SavedFood[]>([])const [toggling, setToggling] = useState<Set<string>>(new Set())- const [error, setError] = useState<string | null>(null)+ // Subscribes to a language switch: `error` is made from `failure` at render.+ useTranslation()+ const [failure, setFailure] = useState<UiMessage | null>(null)const epoch = useRef(0)const tempId = useRef(0)@@ -74,7 +78,7 @@ export function useFavorites(api: SavedFoodsApi): Favorites {if (inFlight.current.has(key)) return nullinFlight.current.add(key)setToggling(new Set(inFlight.current))- setError(null)+ setFailure(null)epoch.current += 1const existing = favoriteOf(item)const food = {@@ -106,9 +110,11 @@ export function useFavorites(api: SavedFoodsApi): Favorites {setSavedFoods(prev => existing? insertByName(prev, existing): prev.filter(f => f.id !== pending.id))- setError(apiErrorMessage(err, existing- ? `Couldn't remove ${item.name} from Favorites.`- : `Couldn't add ${item.name} to Favorites.`))+ setFailure({+ key: existing ? 'food.favorites.removeFailed' : 'food.favorites.addFailed',+ params: { name: item.name },+ cause: err,+ })return null} finally {epoch.current += 1@@ -117,5 +123,6 @@ export function useFavorites(api: SavedFoodsApi): Favorites {}}- return { savedFoods, setSavedFoods, favoriteOf, isToggling, toggle, error, setError, epoch }+ const error = failure ? uiMessage(failure) : null+ return { savedFoods, setSavedFoods, favoriteOf, isToggling, toggle, error, setError: setFailure, epoch }}diff --git a/packages/shared/src/hooks/useFoodAmount.ts b/packages/shared/src/hooks/useFoodAmount.tsindex 210b3ed..8b229a7 100644--- a/packages/shared/src/hooks/useFoodAmount.ts+++ b/packages/shared/src/hooks/useFoodAmount.ts@@ -1,4 +1,5 @@import { useCallback, useState } from 'react'+import { i18n, useTranslation } from '../i18n'import type { FoodSearchResult } from '../types'import {amountForServings, formatServings, MAX_SERVINGS, maxAmountFor, servingBasis,@@ -48,6 +49,8 @@ export interface FoodAmount {export function useFoodAmount(selected: Pick<FoodSearchResult, 'serving_quantity' | 'serving_unit'> | null,): FoodAmount {+ // Subscribes to a language switch: `limitHint` is made from the catalog at render.+ useTranslation()const [text, setText] = useState('1')const [refused, setRefused] = useState(false)@@ -100,7 +103,7 @@ export function useFoodAmount(// what is loggable — and on servings, which is the number the server bounds too, so// the two cannot refuse different things.overLimit: servings > MAX_SERVINGS,- limitHint: servings > MAX_SERVINGS || refused ? `One entry holds at most ${maxAmountFor(basis)}` : null,+ limitHint: servings > MAX_SERVINGS || refused ? i18n.t('food.limitHint', { amount: maxAmountFor(basis) }) : null,step: (direction) => {const size = basis ? basis.quantity : 0.5// Stops at the ceiling as it stops at zero: a stepper that walks past what onediff --git a/packages/shared/src/hooks/useServerInfo.ts b/packages/shared/src/hooks/useServerInfo.tsindex ed60f14..47b85d7 100644--- a/packages/shared/src/hooks/useServerInfo.ts+++ b/packages/shared/src/hooks/useServerInfo.ts@@ -3,7 +3,7 @@ import type { ServerInfo } from '../client'type Probe = (base: string,-) => Promise<{ ok: true; info: ServerInfo } | { ok: false; message: string }>+) => Promise<{ ok: true; info: ServerInfo } | { ok: false }>// Cache keyed by server URL, module-level so it survives remounts. Both apps share it// because both have exactly one server selected at a time.diff --git a/packages/shared/src/hooks/useServerList.ts b/packages/shared/src/hooks/useServerList.tsindex d19615b..dc0816c 100644--- a/packages/shared/src/hooks/useServerList.ts+++ b/packages/shared/src/hooks/useServerList.ts@@ -20,13 +20,14 @@// the stale results.import { useState, useEffect, useRef, useCallback } from 'react'import { apiErrorMessage } from '../client'+import { useTranslation } from '../i18n'interface Options<T> {fetcher: (offset: number, limit: number) => Promise<T[]>pageSize?: number// Changing any dep resets the list and re-fetches from offset 0 (e.g. search query)deps?: readonly unknown[]- // Shown when the server gives us nothing better to say.+ // Shown when the server gives us nothing better to say. Pass it translated, at render.errorFallback?: string}@@ -58,13 +59,17 @@ export function useServerList<T>({fetcher,pageSize = 20,deps = [],- errorFallback = "Couldn't load this list.",+ errorFallback,}: Options<T>): Result<T> {+ const { t } = useTranslation()const [items, setItems] = useState<T[]>([])const [hasMore, setHasMore] = useState(true)const [loading, setLoading] = useState(false)const [refreshing, setRefreshing] = useState(false)- const [error, setError] = useState<string | null>(null)+ // 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 offsetRef = useRef(0)// Tracks whether a fetch is in flight to prevent double-fetches (onEndReached can// fire repeatedly during momentum scrolling)@@ -96,11 +101,11 @@ export function useServerList<T>({if (!Array.isArray(page)) {if (myId === reqIdRef.current) {setHasMore(false)- setError('The server sent something we could not read.')+ setFailure({ unreadable: true })}return}- setError(null)+ setFailure(null)setItems(prev => (replace ? page : [...prev, ...page]))offsetRef.current = currentOffset + page.lengthsetHasMore(page.length === pageSize)@@ -113,7 +118,7 @@ export function useServerList<T>({// all there is". Name it and let the screen offer retry().if (myId === reqIdRef.current) {setHasMore(false)- setError(apiErrorMessage(err, errorFallback))+ setFailure({ cause: err })}} finally {// Only the latest fetch owns the shared flags — a stale response bows out without@@ -124,7 +129,7 @@ export function useServerList<T>({setLoading(false)}}- }, [fetcher, pageSize, errorFallback])+ }, [fetcher, pageSize])// Deps change (e.g. the search query): reset pagination and refetch page 0, but keep// the previous results on screen until the fresh page replaces them (stale-while-@@ -133,7 +138,7 @@ export function useServerList<T>({useEffect(() => {offsetRef.current = 0setHasMore(true)- setError(null)+ setFailure(null)fetchingRef.current = falsesetRefreshing(true)fetchPage(0, true).finally(() => setRefreshing(false))@@ -154,11 +159,15 @@ export function useServerList<T>({// one that never came. hasMore has to go back up first — loadMore checks it, and the// failure is what set it false.const retry = useCallback(() => {- setError(null)+ setFailure(null)setHasMore(true)fetchPage(offsetRef.current, offsetRef.current === 0)}, [fetchPage])+ 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,initialLoading: loading && !initializedRef.current,diff --git a/packages/shared/src/i18n/catalog.test.ts b/packages/shared/src/i18n/catalog.test.tsnew file mode 100644index 0000000..5e7eef6--- /dev/null+++ b/packages/shared/src/i18n/catalog.test.ts@@ -0,0 +1,169 @@+import { readFileSync } from 'fs'+import { join } from 'path'+import en from './locales/en.json'+import es from './locales/es.json'+import {+ i18n, resolveLanguage, SUPPORTED_LANGUAGES, LANGUAGE_NAMES, LANGUAGE_ORDER,+ languageChoiceLabel,+} from './index'++// The CI guard for the catalogs. Runs on Node's full ICU under an en-US jest, so+// Intl.PluralRules here knows every locale; the Hermes path is pinned separately by+// mobile/src/lib/pluralRules.test.ts.++const catalogs: Record<string, unknown> = { en, es }++const flatten = (obj: unknown, prefix = ''): Record<string, string> => {+ const out: Record<string, string> = {}+ for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {+ const key = prefix ? `${prefix}.${k}` : k+ if (v !== null && typeof v === 'object') Object.assign(out, flatten(v, key))+ else out[key] = v as string+ }+ return out+}++const PLURAL = /^(.*)_(zero|one|two|few|many|other)$/+const placeholders = (s: string) =>+ new Set([...s.matchAll(/\{\{\s*([^},\s]+)/g)].map((m) => m[1]))+const tags = (s: string) => [...s.matchAll(/<\/?([a-zA-Z0-9]+)/g)].map((m) => m[1])+const sorted = (s: Iterable<string>) => [...s].sort()++const flat: Record<string, Record<string, string>> = {}+for (const [code, cat] of Object.entries(catalogs)) flat[code] = flatten(cat)++const pluralBases = [...new Set(Object.keys(flat.en).map((k) => PLURAL.exec(k)?.[1]).filter((b): b is string => !!b))]+const categoriesOf = (locale: string) => new Intl.PluralRules(locale).resolvedOptions().pluralCategories++// A key's expected shape in a locale: en's non-plural keys, plus base_<cat> for each of the+// locale's own categories.+const expectedKeys = (locale: string) => {+ const keys = Object.keys(flat.en).filter((k) => !PLURAL.test(k))+ for (const base of pluralBases) for (const c of categoriesOf(locale)) keys.push(`${base}_${c}`)+ return keys.sort()+}++describe('catalogs', () => {+ it('has no empty values', () => {+ for (const [code, cat] of Object.entries(flat)) {+ const empty = Object.entries(cat).filter(([, v]) => typeof v !== 'string' || v.trim() === '').map(([k]) => k)+ expect({ code, empty }).toEqual({ code, empty: [] })+ }+ })++ it('en carries exactly the plural categories English needs', () => {+ for (const base of pluralBases) {+ const have = Object.keys(flat.en).filter((k) => PLURAL.exec(k)?.[1] === base).map((k) => PLURAL.exec(k)![2])+ expect({ base, have: sorted(have) }).toEqual({ base, have: sorted(categoriesOf('en')) })+ }+ })++ it.each(Object.keys(catalogs))('%s has exactly the English key set and its own plural categories', (code) => {+ const actual = Object.keys(flat[code]).sort()+ const expected = expectedKeys(code)+ expect({ missing: expected.filter((k) => !actual.includes(k)) }).toEqual({ missing: [] })+ expect({ extra: actual.filter((k) => !expected.includes(k)) }).toEqual({ extra: [] })+ })++ it.each(Object.keys(catalogs))('%s uses the same {{placeholders}} as English', (code) => {+ const mismatches: string[] = []+ for (const [key, value] of Object.entries(flat[code])) {+ const m = PLURAL.exec(key)+ const enKey = m ? `${m[1]}_other` : key+ const want = placeholders(flat.en[enKey])+ const got = placeholders(value)+ if (m) { want.delete('count'); got.delete('count') }+ if (sorted(want).join() !== sorted(got).join()) mismatches.push(key)+ }+ expect(mismatches).toEqual([])+ })++ it.each(Object.keys(catalogs))('%s uses the same <tags> as English (Trans keys)', (code) => {+ const mismatches: string[] = []+ for (const [key, value] of Object.entries(flat[code])) {+ const m = PLURAL.exec(key)+ const enKey = m ? `${m[1]}_other` : key+ if (sorted(tags(flat.en[enKey])).join() !== sorted(tags(value)).join()) mismatches.push(key)+ }+ expect(mismatches).toEqual([])+ })++ it.each(Object.keys(catalogs))('%s plural variants keep {{count}} wherever the English singular has it', (code) => {+ const dropped: string[] = []+ for (const base of pluralBases) {+ if (!placeholders(flat.en[`${base}_one`]).has('count')) continue+ for (const [key, value] of Object.entries(flat[code])) {+ if (PLURAL.exec(key)?.[1] === base && !placeholders(value).has('count')) dropped.push(key)+ }+ }+ expect(dropped).toEqual([])+ })+})++describe('plural selection', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('en picks one / other', () => {+ expect(i18n.t('settings.library.refreshed', { count: 1, amount: '1' })).toBe(en.settings.library.refreshed_one.replace('{{amount}}', '1'))+ expect(i18n.t('settings.library.refreshed', { count: 2, amount: '2' })).toBe(en.settings.library.refreshed_other.replace('{{amount}}', '2'))+ expect(i18n.t('settings.library.refreshed', { count: 0, amount: '0' })).toBe(en.settings.library.refreshed_other.replace('{{amount}}', '0'))+ })++ it('es picks one / other / many', async () => {+ await i18n.changeLanguage('es')+ const lib = es.settings.library+ expect(i18n.t('settings.library.refreshed', { count: 1, amount: '1' })).toBe(lib.refreshed_one.replace('{{amount}}', '1'))+ expect(i18n.t('settings.library.refreshed', { count: 2, amount: '2' })).toBe(lib.refreshed_other.replace('{{amount}}', '2'))+ expect(i18n.t('settings.library.refreshed', { count: 1000000, amount: '1.000.000' })).toBe(lib.refreshed_many.replace('{{amount}}', '1.000.000'))+ })+})++describe('resolveLanguage', () => {+ it.each([+ ['system', ['es-MX', 'en'], 'es'],+ ['system', ['fr-FR', 'es'], 'es'],+ ['system', ['fr'], 'en'],+ ['system', [], 'en'],+ ['system', [''], 'en'],+ ['system', ['ES_es'], 'es'],+ ['en', ['es'], 'en'],+ ] as const)('%s + %j -> %s', (pref, tags, want) => {+ expect(resolveLanguage(pref, tags)).toBe(want)+ })+})++describe('key safety', () => {+ it('rejects an unknown key at type level', () => {+ // @ts-expect-error unknown key is a type error+ i18n.t('settings.noSuchKey')+ })+})++describe('language registry', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('locales/README.md mirrors the registry', () => {+ const readme = readFileSync(join(__dirname, 'locales', 'README.md'), 'utf8')+ const rows = [...readme.matchAll(/^\| `([a-z-]+)` \| ([^|]+?) \|/gm)]+ expect(rows.map((r) => r[1]).sort()).toEqual([...SUPPORTED_LANGUAGES].sort())+ for (const [, code, rawName] of rows) {+ const name = rawName.trim()+ const c = code as keyof typeof LANGUAGE_NAMES+ expect({ code, name }).toEqual({ code, name: LANGUAGE_NAMES[c] })+ }+ })++ it('LANGUAGE_ORDER is a permutation of SUPPORTED_LANGUAGES', () => {+ expect([...LANGUAGE_ORDER].sort()).toEqual([...SUPPORTED_LANGUAGES].sort())+ expect(LANGUAGE_ORDER).toEqual(['en', 'es'])+ })++ it('languageChoiceLabel names the resolved language and never translates an endonym', async () => {+ expect(languageChoiceLabel('system')).toBe('System (English)')+ expect(languageChoiceLabel('en')).toBe('English')+ await i18n.changeLanguage('es')+ expect(languageChoiceLabel('system')).toBe('Sistema (Español)')+ expect(languageChoiceLabel('en')).toBe('English')+ })++})diff --git a/packages/shared/src/i18n/index.ts b/packages/shared/src/i18n/index.tsnew file mode 100644index 0000000..3279d87--- /dev/null+++ b/packages/shared/src/i18n/index.ts@@ -0,0 +1,70 @@+import i18n from 'i18next'+import { initReactI18next } from 'react-i18next'+import en from './locales/en.json'+import es from './locales/es.json'++// The registry. SUPPORTED_LANGUAGES is derived from this object, never written out again.+const resources = {+ en: { translation: en },+ es: { translation: es },+} as const++export type Language = keyof typeof resources+export const SUPPORTED_LANGUAGES = Object.keys(resources) as Language[]+export type LanguagePreference = 'system' | Language++// Endonyms: never translated, so someone stuck in a language they cannot read can still+// find their own.+export const LANGUAGE_NAMES = { en: 'English', es: 'Español' } satisfies Record<Language, string>++// Mirrored in locales/README.md; catalog.test.ts fails when the two disagree.++// One fixed collation (CLDR root; 'en' has no tailoring, so scripts group together) so the+// picker does not reshuffle the moment the reader switches language.+export const LANGUAGE_ORDER: readonly Language[] = [...SUPPORTED_LANGUAGES].sort((a, b) =>+ LANGUAGE_NAMES[a].localeCompare(LANGUAGE_NAMES[b], 'en'),+)++// Mapping device tags to a supported language lives here, not in an i18next detector+// plugin: each app only reports raw BCP-47 tags, and this is the one place that picks.+export function resolveLanguage(pref: LanguagePreference, deviceTags: readonly string[]): Language {+ if (pref !== 'system') return pref+ for (const tag of deviceTags) {+ const primary = String(tag).split(/[-_]/)[0].toLowerCase()+ if ((SUPPORTED_LANGUAGES as string[]).includes(primary)) return primary as Language+ }+ return 'en'+}++// Synchronous init at module load so tests and the first render get English with no+// hydration. Numbers and dates are NOT formatted through i18next (CLAUDE.md, Numbers &+// Locale): callers pass the already-formatted text in as a placeholder.+void i18n.use(initReactI18next).init({+ resources,+ lng: 'en',+ fallbackLng: 'en',+ supportedLngs: SUPPORTED_LANGUAGES,+ initAsync: false,+ returnEmptyString: false,+ interpolation: { escapeValue: false },+ react: { useSuspense: false },+})++export { i18n }++export function languageChoiceLabel(p: LanguagePreference): string {+ if (p !== 'system') return LANGUAGE_NAMES[p]+ const cur = i18n.resolvedLanguage+ const name = cur && cur in LANGUAGE_NAMES ? LANGUAGE_NAMES[cur as Language] : LANGUAGE_NAMES.en+ return i18n.t('settings.language.systemChoice', { name })+}+++export { useTranslation, Trans } from 'react-i18next'++declare module 'i18next' {+ interface CustomTypeOptions {+ defaultNS: 'translation'+ resources: { translation: typeof en }+ }+}diff --git a/packages/shared/src/i18n/locales/README.md b/packages/shared/src/i18n/locales/README.mdnew file mode 100644index 0000000..83bfad4--- /dev/null+++ b/packages/shared/src/i18n/locales/README.md@@ -0,0 +1,16 @@+# Locale catalogs++One JSON catalog per language, shared by web and mobile. `en.json` is the source and the+fallback; every other file must carry exactly its keys (enforced by `../catalog.test.ts`).+The languages the app ships are listed here.++| Code | Language | Source |+|------|----------|--------|+| `en` | English | written by hand |+| `es` | Español | `en.json` |++`../catalog.test.ts` fails when a supported language has no row here, or a row's name differs+from `LANGUAGE_NAMES`.++How to add a language, and the key-naming rules: see the "Translations" section of+[CONTRIBUTING.md](../../../../../CONTRIBUTING.md).diff --git a/packages/shared/src/i18n/locales/en.json b/packages/shared/src/i18n/locales/en.jsonnew file mode 100644index 0000000..b53a5bf--- /dev/null+++ b/packages/shared/src/i18n/locales/en.json@@ -0,0 +1,1384 @@+{+ "settings": {+ "title": "Settings",+ "subtitle": "Preferences and account configuration",+ "back": "Home",+ "saved": "Settings saved successfully",+ "unknownError": "The server didn't say what went wrong.",+ "language": {+ "label": "Language",+ "description": "Defaults to your device language",+ "systemChoice": "System ({{name}})",+ "search": "Search languages",+ "noMatches": "No languages match"+ },+ "account": {+ "title": "Account",+ "name": {+ "label": "Name",+ "description": "The name the app greets you by. Leave it empty and we'll use your email instead.",+ "loadFailed": "Couldn't load your name, so we won't offer to overwrite it.",+ "saveFailed": "Couldn't save your name.",+ "save": "Save",+ "saving": "Saving…",+ "title": "Name",+ "subtitle": "The name the app greets you by.",+ "emptyHint": "Leave it empty and we'll use your email instead.",+ "saveFailedFallback": "Couldn't save your name. Please try again."+ },+ "email": {+ "label": "Email",+ "description": "Your login email address",+ "change": "Change",+ "changeLabel": "Change email",+ "pageTitle": "Change email",+ "pageSubtitle": "You will sign in with the new address. Changing more than the letter case signs out your other devices.",+ "current": "Current email",+ "new": "New email",+ "submit": "Update email",+ "failedFallback": "Couldn't change your email. Please try again.",+ "changedTitle": "Email changed",+ "signInWith": "Sign in with <email>{{email}}</email> from now on.",+ "signInWithPlain": "Sign in with {{email}} from now on.",+ "caseOnly": "Only the letter case changed, so your other devices stay signed in.",+ "signedOutElsewhere": "You stay signed in here; your other devices are signed out."+ },+ "memberSince": {+ "label": "Member since"+ },+ "password": {+ "label": "Password",+ "description": "Changing it signs you out on your other devices",+ "change": "Change",+ "current": "Current password",+ "new": "New password",+ "confirmNew": "Confirm new password",+ "pageTitle": "Change password",+ "pageSubtitle": "You will stay signed in here. Every other device is signed out.",+ "submit": "Update password",+ "failedFallback": "Couldn't change your password. Please try again.",+ "changedTitle": "Password changed",+ "changedBody": "You are still signed in here. Every other device has been signed out and will need the new password."+ },+ "backLink": "Settings",+ "backToSettings": "Back to settings",+ "saving": "Saving"+ },+ "appearance": {+ "title": "Appearance",+ "theme": {+ "label": "Theme",+ "description": "Interface color scheme",+ "dark": "Dark",+ "light": "Light"+ },+ "darkMode": {+ "label": "Dark mode",+ "description": "Use the dark color scheme"+ }+ },+ "workout": {+ "title": "Workout",+ "footnote": "Default rest seeds new exercises · a per-exercise rest overrides it.",+ "layout": {+ "label": "Active workout layout",+ "description": "How exercises are shown during a workout",+ "list": "List",+ "gym": "Gym Mode"+ },+ "defaultView": {+ "label": "Default workout view"+ },+ "restTimer": {+ "label": "Rest timer",+ "description": "Auto-start a countdown between sets",+ "gymDescription": "Auto-start a countdown between sets in gym mode",+ "off": "Off",+ "on": "On"+ },+ "defaultRest": {+ "label": "Default rest",+ "description": "Seeds new exercises · per-exercise rest overrides it",+ "preset": "{{seconds}}s",+ "custom": "Custom",+ "customLabel": "Custom rest seconds",+ "secondsUnit": "sec",+ "minusFive": "−5 seconds",+ "plusFive": "+5 seconds",+ "decrease": "Decrease rest by 5 seconds",+ "increase": "Increase rest by 5 seconds"+ }+ },+ "goalsUnits": {+ "title": "Goals & Units",+ "loadFailedMessage": "These are your saved targets and units, so we won't guess at them. Everything else on this page still works."+ },+ "unitsTargets": {+ "title": "Units & Targets",+ "footnote": "Weight unit applies instantly across the app. Nutrition targets power the dashboard rings.",+ "loadFailedMessage": "These are your saved targets and units, so we won't guess at them. Everything else here still works.",+ "saved": "Targets saved",+ "changeUnitFailedTitle": "Could not change units"+ },+ "targets": {+ "loadFailedTitle": "Couldn't load your goals",+ "weightUnit": {+ "label": "Weight unit",+ "description": "Changes apply immediately across the app",+ "changeFailed": "Couldn't change the weight unit.",+ "changeFailedFallback": "Could not change the weight unit"+ },+ "calorie": {+ "label": "Calorie target",+ "description": "Daily calorie goal"+ },+ "protein": {+ "label": "Protein target",+ "description": "Daily protein goal"+ },+ "carb": {+ "label": "Carb target",+ "description": "Daily carb goal"+ },+ "fat": {+ "label": "Fat target",+ "description": "Daily fat goal"+ },+ "saveHint": "Save calorie and macro targets",+ "save": "Save targets",+ "saving": "Saving...",+ "saveFailedFallback": "Failed to save settings",+ "saveFailed": "Could not save targets"+ },+ "server": {+ "title": "Server",+ "webTitle": "Self-Hosted Instance",+ "footnote": "The self-hosted backend this app talks to. Leave the URL blank to use the default.",+ "api": {+ "label": "API server",+ "description": "Backend server this client is connected to",+ "default": "This site (reverse proxy)"+ },+ "backend": {+ "label": "Backend",+ "default": "Default backend"+ },+ "url": {+ "label": "Server URL",+ "placeholder": "https://your-server.example.com",+ "invalid": "Enter a full URL including http:// or https://",+ "testAndSave": "Test & save"+ },+ "connected": "Connected · {{name}} v{{version}}",+ "savedWithWarning": "Saved — {{message}}",+ "database": {+ "label": "Database",+ "description": "Storage backend"+ },+ "version": {+ "label": "Version",+ "description": "lyftr backend version"+ }+ },+ "library": {+ "title": "Exercise Library",+ "database": {+ "label": "Exercise database",+ "description": "Exercises come from open-exercise-db, queried as you search. This server keeps a copy of the ones it has shown."+ },+ "cached_one": "{{amount}} cached",+ "cached_other": "{{amount}} cached",+ "cachedUnknown": "— cached",+ "refreshed_one": "Refreshed {{amount}} exercise",+ "refreshed_other": "Refreshed {{amount}} exercises",+ "cleared_one": "Cleared {{amount}} unused exercise",+ "cleared_other": "Cleared {{amount}} unused exercises",+ "refresh": "Refresh cached",+ "refreshing": "Refreshing...",+ "refreshFailed": "Couldn't refresh the cache.",+ "clear": "Clear unused",+ "clearing": "Clearing...",+ "clearFailed": "Couldn't clear the cache."+ },+ "danger": {+ "title": "Danger Zone",+ "actionsTitle": "Account actions"+ },+ "signOut": {+ "label": "Sign out",+ "description": "Log out of this device",+ "button": "Sign out"+ },+ "deleteAccount": {+ "label": "Delete account",+ "description": "Permanently delete all your data",+ "button": "Delete",+ "sheetTitle": "Delete account?",+ "sheetMessage": "This permanently deletes your account and all of your data. This can't be undone.",+ "confirm": "Delete account",+ "busy": "Deleting…",+ "failed": "Could not delete account"+ }+ },+ "common": {+ "there": "there",+ "duration": {+ "seconds": "{{value}}s",+ "minutes": "{{value}}m"+ },+ "close": "Close",+ "dateFormat": {+ "monthDay": "MMM d",+ "monthDayYear": "MMM d, yyyy",+ "numericMonthDay": "M/d",+ "weekdayDate": "EEEE, MMMM d, yyyy",+ "monthShort": "MMM",+ "longDate": "MMMM d, yyyy",+ "weekdayNarrow": "EEEEE",+ "weekdayMonthDayLong": "EEEE, MMMM d",+ "weekdayMonthDay": "EEE, MMM d",+ "weekdayMonthDayYear": "EEE, MMM d, yyyy",+ "year": "yyyy",+ "monthYearLong": "MMMM yyyy"+ },+ "day": {+ "today": "Today",+ "yesterday": "Yesterday"+ },+ "cancel": "Cancel",+ "tryAgain": "Try again",+ "retrying": "Retrying…",+ "loading": "Loading",+ "search": "Search…",+ "clearSearch": "Clear search",+ "edit": "Edit",+ "delete": "Delete",+ "deleting": "Deleting…",+ "deleteConfirmMessage": "{{subject}} will be permanently deleted.",+ "dismiss": "Dismiss",+ "done": "Done",+ "dismissKeyboard": "Dismiss keyboard",+ "pickDate": "Pick date",+ "selectDate": "Select date",+ "capsLockOn": "Caps Lock is on",+ "figureFailed": "Couldn't load this figure",+ "stepper": {+ "decrease": "Decrease {{name}}",+ "increase": "Increase {{name}}"+ },+ "password": {+ "show": "Show {{label}}",+ "hide": "Hide {{label}}"+ },+ "back": "Back",+ "goBack": "Go back",+ "save": "Save",+ "saving": "Saving…"+ },+ "errors": {+ "api": {+ "misconfigured": "Server URL looks misconfigured — the API endpoint wasn't found. Check Server settings.",+ "restarting": "The server is restarting or unreachable. Try again in a moment.",+ "notApi": "That address returned a web page, not the Lyftr API. Check Server settings.",+ "serverError": "Server error. Please try again shortly."+ },+ "network": {+ "brief": {+ "cleartextBlocked": "Blocked because the server URL uses http://. Check Server settings.",+ "certificateUntrusted": "The server's certificate isn't trusted by this device. Check Server settings.",+ "hostnameMismatch": "The server's certificate doesn't cover this address. Check Server settings.",+ "timeout": "The server didn't respond in time. Try again in a moment.",+ "unreachable": "Couldn't reach the server. Check that it's running.",+ "unknown": "Can't reach the server right now."+ },+ "full": {+ "cleartextBlocked": "This device blocked the connection because the URL uses plain http://. Switch the server to https:// — a reverse proxy can issue a certificate for a LAN-only hostname with no ports open.",+ "certificateUntrusted": "The server's certificate isn't trusted by this device. Best fix: give the server a real certificate — a reverse proxy can issue one for a LAN-only hostname with no ports open. Or install your own CA under Settings → Security → Encryption & credentials, which trusts it for every app on the device, not just Lyftr.",+ "hostnameMismatch": "The server's certificate doesn't cover this address. Reissue it with this hostname or IP listed in the certificate's Subject Alternative Name (SAN).",+ "timeout": "The server didn't respond in time. Check that it's running and reachable from this device.",+ "unreachable": "Couldn't connect to the server. Check the URL and that the backend is running.",+ "unknownWeb": "Can't reach the server. Check the URL, that the backend is running, and that it allows this app's origin (CORS).",+ "unknownNative": "Can't reach the server. Check the URL and that the backend is running and reachable from this device.",+ "withDetail": "{{message}} ({{detail}})"+ }+ },+ "list": {+ "loadFailed": "Couldn't load this list.",+ "unreadable": "The server sent something we could not read.",+ "title": "Couldn't load {{subject}}"+ },+ "boundary": {+ "title": "Couldn't show {{subject}}",+ "thisPage": "this page",+ "message": "Something went wrong on our side. Try again, and if it keeps happening reload the page."+ }+ },+ "server": {+ "insecureWarning": "Not encrypted — anyone on this network can read your login and stay signed in as you. Use https:// if you can.",+ "mixedContentWarning": "This browser will block it — an HTTPS page can't call an http:// server. Use https:// for the server too, or leave this blank to use this site's own backend.",+ "test": {+ "notLyftr": "That responded, but it doesn't look like a Lyftr server.",+ "unreachable": "Couldn't reach the server."+ },+ "settingsTitle": "Server settings",+ "blocked": "Blocked",+ "notEncrypted": "Not encrypted",+ "blankPlaceholder": "Leave blank to use this site",+ "fullUrlHint": "Full URL, e.g. <url>https://lyftr.example.com</url>",+ "testing": "Testing…",+ "testAndSave": "Test & Save",+ "current": "Current: {{url}}",+ "usingSite": "Using this site’s address (reverse proxy)",+ "defaultShort": "default",+ "status": {+ "invalidUrlExample": "Include http:// or https:// — e.g. http://192.168.1.10:3000",+ "invalidUrl": "Include http:// or https://",+ "storageBlocked": "Couldn't save the server URL — this browser is blocking storage.",+ "connected": "Connected · {{name}} {{version}}",+ "connectedTo": "Connected to {{name}} v{{version}}"+ }+ },+ "auth": {+ "passwordRules": {+ "minLength_one": "At least {{count}} character",+ "minLength_other": "At least {{count}} characters",+ "maxBytes_one": "At most {{count}} character (accents and emoji count for more)",+ "maxBytes_other": "At most {{count}} characters (accents and emoji count for more)",+ "different": "Different from your current password",+ "match": "Passwords match",+ "mismatch": "Passwords do not match",+ "repeat": "Repeat the new password"+ },+ "divider": {+ "or": "OR",+ "orLower": "or"+ },+ "field": {+ "email": "Email",+ "password": "Password",+ "confirmPassword": "Confirm password",+ "emailPlaceholder": "[email protected]"+ },+ "validation": {+ "emailInvalid": "Enter a valid email address",+ "passwordRequired": "Enter your password"+ },+ "closed": {+ "notice": "This server is not accepting new accounts."+ },+ "tagline": "TRAIN · TRACK · PROGRESS",+ "hero": {+ "headline": "Log. Lift.",+ "headlineAccent": "Progress.",+ "description": "Your self-hosted fitness tracker. Track workouts, log food, monitor weight — all under your control, running on your own server.",+ "features": {+ "workouts": "Track workouts",+ "food": "Log food + macros",+ "progress": "See progress"+ }+ },+ "login": {+ "heading": "Welcome back",+ "subtitle": "Sign in to continue training.",+ "submit": "Sign in",+ "submitting": "Signing in…",+ "failed": "Invalid email or password.",+ "demoFailed": "Couldn't sign in to the demo account.",+ "demo": "Try demo account",+ "demoHint": "no sign-up",+ "newHere": "New here?",+ "createAccountLink": "Create account"+ },+ "register": {+ "heading": "Create account",+ "subtitle": "Start tracking your fitness today.",+ "subtitleNative": "Start your training log.",+ "closedHeading": "Registration closed",+ "closedBody": "The owner of this Lyftr instance has turned off new signups. If you should have an account here, ask them to create one for you.",+ "backToSignIn": "Back to sign in",+ "submit": "Create account",+ "submitting": "Creating account…",+ "failed": "Registration failed.",+ "haveAccount": "Already have an account?",+ "haveAccountShort": "Have an account?",+ "signInLink": "Sign in"+ }+ },+ "weight": {+ "errors": {+ "invalid": "Enter a valid weight",+ "tooHigh": "Weight must be under {{max}} {{unit}}",+ "trendFailed": "Couldn't load your weight trend.",+ "statsFailed": "Couldn't load your weight stats."+ },+ "bodyweightShort": "BW",+ "duplicateWarning": "Already logged on {{date}} ({{weight}} {{unit}}). Log again anyway?",+ "title": "Weight",+ "subtitle": "Track your body weight over time",+ "loadFailed": "Couldn't load your weight",+ "deleteTitle": "Delete Entry?",+ "deleteSubject": "{{date}} · {{weight}} {{unit}}",+ "deleteFailed": "Failed to delete entry",+ "log": {+ "title": "Log Weight",+ "last": "last: {{weight}} {{unit}}",+ "weightLabel": "Weight ({{unit}})",+ "weightField": "Weight",+ "weightName": "weight",+ "dateAndNote": "Date & note",+ "collapse": "Collapse",+ "notePlaceholder": "Note — e.g. morning, post-run",+ "addDateAndNote": "Add date & note",+ "logAnyway": "Log Anyway",+ "submit": "Log Weight",+ "submitting": "Logging…",+ "tip": "Best logged in the morning, after the bathroom",+ "failed": "Failed to log weight"+ },+ "hero": {+ "current": "Current Weight",+ "empty": "The scale doesn't know you exist yet. Fix that.",+ "changeGained": "{{amount}} {{unit}} gained over {{period}}",+ "changeLost": "{{amount}} {{unit}} lost over {{period}}",+ "changeNone": "{{amount}} {{unit}} no change over {{period}}"+ },+ "period": {+ "chip": {+ "7d": "7d",+ "30d": "30d",+ "90d": "90d",+ "All": "All"+ },+ "span": {+ "7d": "7d",+ "30d": "30d",+ "90d": "90d",+ "All": "All"+ }+ },+ "stats": {+ "avg": {+ "label": "Avg",+ "tip": "Average weight for selected period",+ "failed": "Couldn't load avg weight"+ },+ "low": {+ "label": "Low",+ "tip": "Lowest recorded weight in period",+ "failed": "Couldn't load low weight"+ },+ "high": {+ "label": "High",+ "tip": "Highest recorded weight in period",+ "failed": "Couldn't load high weight"+ }+ },+ "stale": "Couldn't refresh these — showing the last we loaded.",+ "trend": {+ "title": "Trend",+ "loading": "Loading your trend",+ "loadFailed": "Couldn't load your trend",+ "noData": "No data for this period",+ "needMore": "Log another entry to see the trend"+ },+ "history": {+ "title": "History",+ "subject": "your weight history",+ "loadingMore": "Loading more…",+ "loadMoreFailed": "Couldn't load more entries"+ },+ "detail": {+ "back": "Weight",+ "loadFailed": "Couldn't load this entry",+ "gone": "That entry no longer exists.",+ "backToWeight": "Back to weight",+ "editLabel": "Edit entry",+ "deleteLabel": "Delete entry",+ "entryLabel": "Weight Entry",+ "editing": "Editing…",+ "editTitle": "Edit Entry",+ "date": "Date",+ "notesOptional": "Notes <hint>(optional)</hint>",+ "notesOptionalPlain": "Notes (optional)",+ "notePlaceholder": "e.g., morning, post-workout",+ "saveFailed": "Failed to save"+ },+ "row": {+ "options": "{{weight}} {{unit}} options"+ }+ },+ "programs": {+ "day": {+ "rest": "Rest Day",+ "numbered": "Day {{number}}"+ },+ "createdOn": "Created {{date}}",+ "title": "Programs",+ "subtitle": "Reusable workout templates",+ "newProgram": "New Program",+ "startWorkout": "Start Workout",+ "deleteConfirmTitle": "Delete Program?",+ "deleteFailed": "Failed to delete program",+ "count": {+ "exercises_one": "{{count}} exercise",+ "exercises_other": "{{count}} exercises",+ "sets_one": "{{count}} set",+ "sets_other": "{{count}} sets",+ "reps_one": "{{count}} rep",+ "reps_other": "{{count}} reps",+ "days_one": "{{count}} day",+ "days_other": "{{count}} days"+ },+ "list": {+ "searchPlaceholder": "Search programs…",+ "empty": {+ "title": "No programs found",+ "searchHint": "Try a different search",+ "startHint": "Create a program to get started"+ },+ "loadFailed": "Couldn't load your programs",+ "errorSubject": "your programs",+ "loadingMore": "Loading more…"+ },+ "stats": {+ "total": "Total",+ "totalUnit": "programs",+ "totalFailed": "Couldn't load total",+ "avgExercises": "Avg Exercises",+ "avgExercisesFailed": "Couldn't load avg exercises",+ "perProgram": "per program"+ },+ "card": {+ "deleteTitle": "Delete \"{{name}}\"?",+ "cannotUndo": "This cannot be undone",+ "summary": "{{exercises}} · {{sets}}",+ "restToday": "Rest today",+ "today": "Today: {{day}}",+ "options": "Options",+ "optionsNamed": "{{name}} options",+ "menuHeading": "Program",+ "startTitle": "Start workout",+ "restDayTitle": "Rest day today — open program",+ "viewProgram": "View Program",+ "editProgram": "Edit Program",+ "deleteProgram": "Delete Program",+ "editNamed": "Edit {{name}}",+ "startNamed": "Start {{name}}"+ },+ "detail": {+ "loadFailed": "Couldn't load this program",+ "gone": "That program no longer exists.",+ "backToPrograms": "Back to programs",+ "back": "Programs",+ "restDayTitle": "Rest day — nothing to start",+ "start": "Start",+ "startLabel": "Start workout",+ "editLabel": "Edit program",+ "deleteLabel": "Delete program",+ "suggestions": {+ "title": "New targets from your last workout",+ "set": "Set {{number}}",+ "accept": "Accept {{name}} set {{number}}",+ "dismiss": "Dismiss {{name}} set {{number}}",+ "showLess": "Show less",+ "showAll": "Show all {{total}}",+ "dismissAll": "Dismiss all",+ "applyAll": "Apply all ({{total}})",+ "saveFailed": "Couldn't save those targets.",+ "exerciseFallback": "Exercise"+ },+ "stats": {+ "cycle": "Cycle",+ "exercises": "Exercises",+ "totalSets": "Total Sets"+ },+ "noDays": "No days yet",+ "addDay": "Add a day →",+ "todayChip": "TODAY",+ "restDayHint": "No exercises scheduled — recover and come back stronger.",+ "noExercises": "No exercises on this day yet",+ "target": "target {{weight}} {{unit}}"+ },+ "form": {+ "newTitle": "New Program",+ "editTitle": "Edit Program",+ "summary": "{{days}} • {{exercises}} • {{sets}}",+ "errors": {+ "nameRequired": "Program name required",+ "noDays": "Add at least one day",+ "noExercises": "Add at least one exercise to a workout day"+ },+ "createFailed": "Failed to create program",+ "updateFailed": "Failed to update program",+ "name": "Program Name",+ "required": "(required)",+ "namePlaceholder": "e.g., Push Pull Legs, Upper Lower",+ "notesPlaceholder": "Program description or goals…",+ "days": "Days",+ "targetSets": "Target Sets",+ "daysHintNew": "(required — repeats in this order)",+ "daysHintEdit": "(repeats in this order)",+ "saveProgram": "Save Program",+ "dayEditor": {+ "emptyInline": "No exercises yet — add one above.",+ "emptyTitle": "No exercises yet",+ "emptySubtitle": "Add an exercise to this day",+ "notesPlaceholder": "e.g., Focus on controlled eccentric",+ "targetReps": "Target Reps",+ "targetWeight": "Target Weight"+ },+ "daysEditor": {+ "empty": "No days yet — add a workout or rest day below.",+ "moveUp": "Move day up",+ "moveDown": "Move day down",+ "moveUpNumbered": "Move day {{number}} up",+ "moveDownNumbered": "Move day {{number}} down",+ "restPlaceholder": "Rest Day {{number}}",+ "workout": "Workout",+ "rest": "Rest",+ "collapse": "Collapse day",+ "expand": "Expand day",+ "remove": "Remove day",+ "addWorkoutDay": "Add Workout Day",+ "addRestDay": "Add Rest Day"+ },+ "dayPicker": {+ "title": "Pick a Day"+ }+ }+ },+ "food": {+ "servings_one": "{{count}} serving",+ "servings_other": "{{count}} servings",+ "customEntry": "Custom entry",+ "limitHint": "One entry holds at most {{amount}}",+ "favorites": {+ "addFailed": "Couldn't add {{name}} to Favorites.",+ "removeFailed": "Couldn't remove {{name}} from Favorites.",+ "add": "Add {{name}} to Favorites",+ "remove": "Remove {{name}} from Favorites",+ "subject": "your favourites",+ "loadFailed": "Couldn't load your favourites.",+ "empty": {+ "title": "No favorites yet",+ "hint": "Star foods while logging to find them here"+ }+ },+ "diary": {+ "title": "Food",+ "titleToday": "Today's Food",+ "logFood": "Log Food",+ "previousDay": "Previous day",+ "nextDay": "Next day",+ "loadFailed": "Couldn't load your food log",+ "deleteFailed": "Couldn't delete that entry.",+ "addTo": "Add to {{meal}}",+ "tapToAdd": "+ Tap to add food",+ "deleteConfirm": "Delete <name>{{name}}</name>?",+ "calories": "Calories",+ "over": "{{amount}} over",+ "left": "{{amount}} left",+ "goal": "{{amount}} kcal goal",+ "totalsFailed": "Couldn't load today's totals",+ "totalsFailedMessage": "Something went wrong on our end.",+ "items_one": "{{count}} item",+ "items_other": "{{count}} items",+ "filteredCount": "{{shown}} of {{total}}",+ "searchPlaceholder": "Search this day's food…",+ "noMatches": "No matches for “{{query}}”",+ "empty": {+ "title": "No food logged yet",+ "hint": "Tap to log your first meal"+ },+ "entryUpdated": "Entry updated",+ "addedTo": "Added to {{meal}}"+ },+ "entry": {+ "logged": "Logged",+ "deleteFailed": "Failed to delete entry",+ "deleteTitle": "Delete entry?",+ "loadFailed": "Couldn't load this entry",+ "gone": "That entry no longer exists.",+ "backToNutrition": "Back to nutrition",+ "back": "Nutrition",+ "editLabel": "Edit entry",+ "deleteLabel": "Delete entry",+ "servingSize": "Serving size",+ "amount": "Amount",+ "meal": "Meal",+ "optionsNamed": "{{name}} options"+ },+ "page": {+ "title": "Nutrition",+ "subtitle": "Macros & meals"+ },+ "meal": {+ "breakfast": "Breakfast",+ "lunch": "Lunch",+ "dinner": "Dinner",+ "snacks": "Snacks"+ },+ "macro": {+ "protein": "Protein",+ "carbs": "Carbs",+ "fat": "Fat",+ "fiber": "Fiber",+ "proteinInitial": "P",+ "carbsInitial": "C",+ "fatInitial": "F"+ },+ "view": {+ "diary": "Diary",+ "trends": "Trends"+ },+ "trends": {+ "dailyAverage": "Daily average · {{period}}",+ "averageFailed": "Couldn't load average {{macro}}"+ },+ "history": {+ "title": "Macro History",+ "loading": "Loading…",+ "loadFailed": "Couldn't load your history",+ "empty": "No data yet — start logging meals"+ },+ "log": {+ "title": "Log Food",+ "editTitle": "Edit Food",+ "details": "Details",+ "newEntry": "New Entry",+ "backToFood": "Back to food",+ "submit": "Log Food",+ "saveChanges": "Save Changes",+ "saveFailed": "Failed to save",+ "editLoadFailed": "Couldn't load that entry.",+ "searchPlaceholder": "Search food…",+ "scan": "Scan",+ "scanLabel": "Scan barcode",+ "tab": {+ "recent": "Recent",+ "favorites": "Favorites",+ "search": "Search"+ },+ "rateLimited": "Too many requests — wait a moment and try again",+ "searchUnavailable": "Food search unavailable — enter details manually",+ "lookupFailedTitle": "Couldn't look up this barcode",+ "lookupFailed": "Couldn't look up that barcode.",+ "enterManually": "Enter it manually",+ "rereadFailed": "Couldn't re-read this product.",+ "quickAdd": "Quick add {{kcal}} kcal",+ "noMacroBreakdown": "No macro breakdown",+ "recent": {+ "subject": "what you logged today",+ "loadFailed": "Couldn't load what you logged today.",+ "empty": {+ "title": "No recent items today",+ "hint": "Search or scan to log food"+ }+ },+ "search": {+ "emptyTitle": "Search millions of foods",+ "emptyHint": "Or scan a barcode",+ "searching": "Searching…",+ "noResults": "No results for \"{{query}}\"",+ "manualEntry": "+ Enter \"{{query}}\" manually",+ "manualEntryWide": "+ Enter \"{{query}}\" manually"+ },+ "staleServing": "{{note}} Showing search results, which are always per {{serving}}.",+ "per": "per {{serving}}",+ "servingEach": "({{serving}} each)",+ "servings": "Servings",+ "amountIn": "Amount in {{unit}}",+ "decreaseAmount": "Decrease amount",+ "increaseAmount": "Increase amount",+ "decreaseServings": "Decrease servings",+ "increaseServings": "Increase servings",+ "enterAmount": "Enter an amount to log this",+ "enterAmountIn": "Enter an amount in {{unit}} to log this",+ "servingsOf_one": "{{count}} serving of {{serving}}",+ "servingsOf_other": "{{count}} servings of {{serving}}",+ "when": "When"+ },+ "scan": {+ "title": "Scan barcode",+ "close": "Close scanner",+ "httpsTitle": "Camera needs HTTPS",+ "httpsBody": "Browsers only allow camera access on secure pages. This site is served over plain <mono>http://</mono> — put it behind a reverse proxy with HTTPS to scan barcodes.",+ "searchByName": "Search by name instead",+ "unavailable": "Camera unavailable",+ "hint": "Point camera at barcode — it will scan automatically",+ "deniedTitle": "Camera access denied",+ "neededTitle": "Camera permission needed",+ "deniedBody": "Enable camera access for Lyftr in your device settings to scan barcodes.",+ "neededBody": "Allow camera access to scan a food barcode.",+ "allow": "Allow camera",+ "point": "Point at a barcode"+ },+ "lookup": {+ "looking": "Looking up this product…",+ "slow": "Still looking. This can take a few seconds."+ }+ },+ "workouts": {+ "defaultName": "Workout — {{date}}",+ "stats": {+ "total": "Total",+ "logged": "logged",+ "thisMonth": "This Month",+ "sessions": "sessions",+ "avgTime": "Avg Time",+ "min": "min",+ "totalFailed": "Couldn't load total",+ "thisMonthFailed": "Couldn't load this month",+ "avgTimeFailed": "Couldn't load avg time"+ },+ "list": {+ "title": "Workouts",+ "subtitle": "Track and review your training sessions",+ "logWorkout": "Log Workout",+ "searchPlaceholder": "Search workouts…",+ "empty": {+ "title": "No workouts found",+ "searchHint": "Try a different search",+ "startHint": "Log a workout to get started"+ },+ "loadFailed": "Couldn't load your workouts",+ "errorSubject": "your workouts",+ "loadingMore": "Loading more…"+ },+ "deleteFailed": "Failed to delete workout",+ "deleteConfirmTitle": "Delete Workout?",+ "toast": {+ "newPr": "New PR in {{name}}",+ "newTargets": "New targets in {{name}}",+ "reviewUpdates_one": "Tap to review {{count}} update",+ "reviewUpdates_other": "Tap to review {{count}} updates",+ "saved": "Workout saved",+ "tapToView": "Tap to view",+ "discarded": "Workout discarded",+ "tapToUndo": "Tap to undo"+ },+ "card": {+ "deleteTitle": "Delete \"{{name}}\"?",+ "cannotUndo": "This cannot be undone",+ "minutes": "{{minutes}} min",+ "exercises_one": "{{count}} exercise",+ "exercises_other": "{{count}} exercises",+ "options": "Options",+ "optionsNamed": "{{name}} options",+ "menuHeading": "Workout",+ "editWorkout": "Edit Workout",+ "deleteWorkout": "Delete Workout",+ "editNamed": "Edit {{name}}",+ "totalVolume": "{{amount}} {{unit}} total volume"+ },+ "detail": {+ "loadFailed": "Couldn't load this workout",+ "gone": "That workout no longer exists.",+ "backToWorkouts": "Back to workouts",+ "back": "Workouts",+ "editLabel": "Edit workout",+ "deleteLabel": "Delete workout",+ "duration": "Duration",+ "minutesUnit": "min",+ "sets": "Sets",+ "volume": "Volume",+ "restOff": "Rest timer is off — turn it on in Settings",+ "setCount_one": "{{count}} set",+ "setCount_other": "{{count}} sets",+ "best": "best",+ "noRest": "No rest"+ },+ "start": {+ "title": "Start Workout",+ "inProgress": "Workout in progress",+ "resume": "Resume",+ "discard": "Discard",+ "quick": "Quick Start",+ "quickHint": "Start blank, add exercises as you go",+ "fromProgram": "Start from Program",+ "fromProgramHint": "Load a saved routine's day",+ "programsLoadFailed": "Couldn't load your programs",+ "loadingPrograms": "Loading programs…",+ "noPrograms": "No programs yet",+ "createFirst": "Create your first program →",+ "days_one": "{{count}} day",+ "days_other": "{{count}} days",+ "noDays": "No days yet"+ },+ "form": {+ "logTitle": "Log Workout",+ "editTitle": "Edit Workout",+ "summary": "{{exercises}} • {{sets}}",+ "summaryWithWeight": "{{exercises}} • {{sets}} • {{weight}} {{unit}}",+ "exerciseCount_one": "{{count}} exercise",+ "exerciseCount_other": "{{count}} exercises",+ "setCount_one": "{{count}} set",+ "setCount_other": "{{count}} sets",+ "errors": {+ "nameRequired": "Workout name required",+ "noExercises": "Add at least one exercise"+ },+ "createFailed": "Failed to create workout",+ "updateFailed": "Failed to update workout",+ "name": "Workout Name",+ "required": "(required)",+ "namePlaceholder": "e.g., Leg Day, Push Day",+ "date": "Date",+ "durationMinutes": "Duration (minutes)",+ "duration": "Duration",+ "durationHm": "{{hours}}h {{minutes}}m",+ "notes": "Notes",+ "notesPlaceholder": "How did it feel? Any PRs?",+ "totalUnit": "Total {{unit}}",+ "exercises": "Exercises",+ "sets": "Sets",+ "loadProgram": "Load Program",+ "addExercise": "Add Exercise",+ "addExerciseLabel": "Add exercise",+ "removeExercise": "Remove exercise",+ "removeNamed": "Remove {{name}}",+ "exerciseFallback": "exercise",+ "exerciseNotesPlaceholder": "e.g., Felt strong",+ "restBetweenSets": "Rest between sets",+ "set": "Set",+ "reps": "Reps",+ "weight": "Weight",+ "weightWithUnit": "Weight ({{unit}})",+ "setWeightLabel": "Set weight",+ "setRepsLabel": "Set reps",+ "addSet": "Add Set",+ "removeSet": "Remove set",+ "note": "Note",+ "addNoteLabel": "Add exercise note",+ "removeNoteLabel": "Remove note",+ "exerciseNotesLabel": "Exercise notes",+ "saveWorkout": "Save Workout",+ "saveChanges": "Save Changes",+ "empty": {+ "createTitle": "No exercises yet",+ "createHint": "Add an exercise or load a program to start",+ "editTitle": "No exercises",+ "editHint": "Add an exercise to this workout"+ },+ "durationField": {+ "decrease": "Decrease duration",+ "increase": "Increase duration",+ "inputLabel": "Duration in minutes",+ "unit": "min"+ },+ "programPicker": {+ "title": "Load from Program",+ "pickProgram": "Pick a program to pre-fill exercises",+ "pickDay": "Pick a day to pre-fill exercises",+ "loadFailed": "Couldn't load your programs.",+ "back": "← Back to programs",+ "today": "TODAY",+ "workoutDays_one": "{{count}} workout day",+ "workoutDays_other": "{{count}} workout days",+ "noExercises": "No exercises yet",+ "restDays": "rest days",+ "createFirst": "Create a program first",+ "close": "Close program picker",+ "searchPlaceholder": "Search programs…",+ "noMatches": "No matching programs"+ }+ },+ "active": {+ "noWorkout": {+ "title": "No active workout",+ "hintHome": "Start one from the home page",+ "hintTab": "Start one from the Workouts tab",+ "goHome": "Go Home",+ "goWorkouts": "Go to Workouts"+ },+ "setsDone": "{{done}}/{{total}} sets done",+ "finish": "Finish",+ "empty": {+ "title": "No exercises yet",+ "hint": "Add exercises below"+ },+ "setProgress": "{{done}}/{{total}} sets",+ "removeExercise": "Remove exercise",+ "notes": {+ "placeholder": "Add a note…",+ "add": "+ Add note",+ "placeholderMobile": "+ Add note…",+ "label": "Notes, {{name}}"+ },+ "columns": {+ "set": "Set",+ "reps": "Reps",+ "weight": "Weight",+ "weightUnit": "Weight ({{unit}})",+ "done": "Done"+ },+ "completeSetWeb": "Set {{number}}, mark done",+ "completeSet": "Complete set {{number}}, {{name}}",+ "completedSet": "Completed set {{number}}, {{name}}",+ "repsLabel": "Reps, set {{number}}, {{name}}",+ "weightLabel": "Weight, set {{number}}, {{name}}",+ "removeSet": "Remove set",+ "previous": "Previous exercise",+ "addSet": "Add Set",+ "next": "Next",+ "addExercise": "Add Exercise",+ "cancelWorkout": "Cancel Workout",+ "saveFailed": "Failed to save workout",+ "keepGoing": "Keep Going",+ "finishConfirm": {+ "title": "Finish Workout?",+ "message": "{{done}} of {{total}} sets completed. Workout will be saved."+ },+ "cancelConfirm": {+ "title": "Cancel Workout?",+ "message": "All progress will be lost."+ }+ },+ "rest": {+ "off": "Off",+ "custom": "Custom",+ "stepDown5": "−5 seconds",+ "stepDown5Spoken": "Minus 5 seconds",+ "stepUp5": "+5 seconds",+ "stepUp5Spoken": "Plus 5 seconds",+ "secondsLabel": "Rest seconds",+ "secondsUnit": "sec",+ "label": {+ "ready": "Ready",+ "paused": "Paused",+ "resting": "Rest",+ "over": "Rest over",+ "upNext": "Set {{next}} up next",+ "setDone": "Set {{done}} done",+ "setDonePaused": "Set {{done}} done · paused",+ "setDoneNext": "Set {{done}} done · set {{next}} next",+ "setDoneResting": "Set {{done}} done · resting",+ "overNext": "Rest over · set {{next}} next"+ },+ "pause": "Pause rest timer",+ "resume": "Resume rest timer",+ "shorten": "Shorten rest by 15 seconds",+ "extend": "Extend rest by 15 seconds",+ "skip": "Skip"+ }+ },+ "gym": {+ "workout": "Workout",+ "goToExercise": "Go to exercise {{number}}",+ "minimizeWorkout": "Minimize workout",+ "minimize": "Minimize",+ "discardWorkout": "Discard workout",+ "discard": {+ "title": "Discard workout?",+ "message": "This ends the workout without saving — all progress is lost.",+ "confirm": "Discard"+ },+ "labels": {+ "sets": "Sets",+ "reps": "Reps",+ "weight": "Weight",+ "repsName": "reps"+ },+ "overview": {+ "exercises": "Exercises",+ "totalSets": "Total Sets",+ "muscles": "Muscles",+ "empty": "No exercises added yet",+ "startWorkout": "Start Workout"+ },+ "info": {+ "restTitle": "Rest between sets",+ "restHint": "Auto-starts when you complete a set",+ "begin": "Begin Exercise"+ },+ "set": {+ "chip": "Set {{number}}",+ "chipDone": "Set {{number}}, done",+ "chipResting": "Set {{number}}, resting",+ "chipDoneResting": "Set {{number}}, done, resting"+ },+ "target": {+ "label": "Target",+ "reps_one": "{{count}} rep",+ "reps_other": "{{count}} reps",+ "repsUnknown": "— reps"+ },+ "completeSet": "Complete Set",+ "completed": "Completed",+ "removeSet": "Remove this set",+ "removeExercise": "Remove this exercise",+ "nav": {+ "info": "Info",+ "finishWorkout": "Finish Workout",+ "nextExercise": "Next Exercise"+ }+ },+ "exercises": {+ "estimated1rm": "Est. 1RM: {{weight}} {{unit}} · {{date}}",+ "equipment": {+ "body-only": "Bodyweight",+ "barbell": "Barbell",+ "dumbbell": "Dumbbell",+ "machine": "Machine",+ "cable": "Cable",+ "kettlebells": "Kettlebell",+ "bands": "Bands",+ "medicine-ball": "Med Ball",+ "e-z-curl-bar": "EZ Bar",+ "exercise-ball": "Exercise Ball",+ "foam-roll": "Foam Roll",+ "none": "None",+ "other": "Other"+ },+ "category": {+ "strength": "strength",+ "stretching": "stretching",+ "plyometrics": "plyometrics",+ "strongman": "strongman",+ "powerlifting": "powerlifting",+ "cardio": "cardio",+ "olympic-weightlifting": "olympic-weightlifting"+ },+ "muscle": {+ "abdominals": "abdominals",+ "abductors": "abductors",+ "abs": "abs",+ "adductors": "adductors",+ "back": "back",+ "biceps": "biceps",+ "calves": "calves",+ "chest": "chest",+ "core": "core",+ "forearms": "forearms",+ "full-body": "full-body",+ "glutes": "glutes",+ "hamstrings": "hamstrings",+ "lats": "lats",+ "legs": "legs",+ "lower-back": "lower-back",+ "middle-back": "middle-back",+ "neck": "neck",+ "obliques": "obliques",+ "other": "other",+ "quadriceps": "quadriceps",+ "shoulders": "shoulders",+ "traps": "traps",+ "triceps": "triceps"+ },+ "picker": {+ "title": "Add Exercise",+ "loaded_one": "{{count}} loaded",+ "loaded_other": "{{count}} loaded",+ "loadedMore_one": "{{count}} loaded…",+ "loadedMore_other": "{{count}} loaded…",+ "search": "Search exercises…",+ "loading": "Loading exercises…",+ "loadingShort": "Loading…",+ "loadingMore": "Loading more…",+ "loadMore": "Load more",+ "empty": "No exercises found",+ "errorSubject": "these exercises",+ "close": "Close exercise picker",+ "backToWorkout": "Back to workout",+ "loadFailed": "Couldn't load exercises",+ "loadMoreFailed": "Couldn't load more exercises"+ },+ "detail": {+ "loadFailed": "Couldn't load this exercise",+ "musclesWorked": "Muscles Worked",+ "bodyFront": "Front",+ "bodyBack": "Back",+ "primary": "Primary",+ "secondary": "Secondary",+ "alsoWorks": "Also works",+ "yourBest": "Your Best",+ "personalBest": "Personal Best",+ "estimated1rm": "Estimated 1RM",+ "weightProgression": "Weight Progression",+ "noPeriodData": "No data for this period",+ "maxWeight": "Max weight",+ "instructions": "Instructions",+ "bestSet_one": "{{unit}} × {{count}} rep",+ "bestSet_other": "{{unit}} × {{count}} reps",+ "period": {+ "1m": "1m",+ "3m": "3m",+ "6m": "6m",+ "All": "All"+ }+ }+ },+ "home": {+ "heatmap": {+ "workouts_one": "{{date}} · {{count}} workout",+ "workouts_other": "{{date}} · {{count}} workouts",+ "restDay": "{{date}} · rest day",+ "less": "Less",+ "more": "More"+ },+ "greeting": {+ "morning": "Good morning, {{name}}",+ "morning_anonymous": "Good morning, there",+ "afternoon": "Good afternoon, {{name}}",+ "afternoon_anonymous": "Good afternoon, there",+ "evening": "Good evening, {{name}}",+ "evening_anonymous": "Good evening, there"+ },+ "loadFailed": "Couldn't load your dashboard",+ "header": {+ "start": "Start",+ "resume": "Resume"+ },+ "activeSession": {+ "title": "Workout in progress",+ "tapToResume": "{{name}} — tap to resume"+ },+ "upNext": {+ "label": "Up next · {{name}}",+ "viewRoutine": "View {{name}} routine",+ "start": "Start {{name}}",+ "exercises_one": "{{count}} exercise",+ "exercises_other": "{{count}} exercises",+ "loadFailed": "Couldn't load your programs"+ },+ "kpi": {+ "week": "Week",+ "sessions": "sessions",+ "cals": "Cals",+ "caloriesFailed": "Couldn't load today's calories",+ "proteinFailed": "Couldn't load today's protein"+ },+ "thisWeek": {+ "title": "This Week",+ "unit_one": "session",+ "unit_other": "sessions"+ },+ "volume": {+ "title": "Volume Trend",+ "empty": "Log workouts to see trends",+ "tooltip": "Volume"+ },+ "consistency": {+ "title": "Consistency",+ "range": "12 weeks",+ "empty": "Start working out to build your streak"+ },+ "lastWorkout": {+ "title": "Last workout",+ "all": "All",+ "minutes": "{{mins}} min",+ "sets_one": "{{count}} set",+ "sets_other": "{{count}} sets",+ "moreExercises_one": "+{{count}} more exercises",+ "moreExercises_other": "+{{count}} more exercises",+ "empty": "No workouts logged yet",+ "startFirst": "Start your first workout →"+ },+ "nutrition": {+ "title": "Today's Nutrition",+ "log": "Log →",+ "loadFailed": "Couldn't load today's food"+ },+ "macro": {+ "protein": "Protein",+ "carbs": "Carbs",+ "fat": "Fat"+ },+ "muscle": {+ "title": "Muscle Balance",+ "workouts_one": "{{count}} workout",+ "workouts_other": "{{count}} workouts",+ "empty": "Log workouts to see which muscles you train most.",+ "noData": "No workout data yet",+ "top": "top",+ "tooltip_one": "{{count}} set ({{percent}}%)",+ "tooltip_other": "{{count}} sets ({{percent}}%)",+ "donutSets": "sets"+ },+ "weight": {+ "title": "Weight",+ "view": "View",+ "loadFailed": "Couldn't load your weight",+ "logFirst": "Log your first weight",+ "logFirstHint": "Tap to start tracking",+ "logAria": "Log weight",+ "noChange7d": "7d · no change",+ "trendDown": "7d · ↓{{amount}} {{unit}}",+ "trendUp": "7d · ↑{{amount}} {{unit}}"+ },+ "muscleRoast": {+ "chest": "All chest, no legs. Classic bro.",+ "back": "Built like a refrigerator. Respect.",+ "shoulders": "Can't fit through doorways. Good.",+ "biceps": "Mirror selfies loading…",+ "triceps": "Horseshoe gang. Handshakes must be terrifying.",+ "legs": "Actually training legs. You're a unicorn.",+ "quadriceps": "Quads for days. Jeans don't stand a chance.",+ "hamstrings": "Posterior chain warrior. Deadlift god incoming.",+ "glutes": "Glute guy/gal. We respect the commitment.",+ "calves": "Calf king/queen. The rarest of all lifters.",+ "core": "Beach season ready 365 days a year.",+ "abs": "Six pack incoming. Or already here. Either way.",+ "forearms": "Popeye called. He wants his arms back.",+ "traps": "No neck, no problem.",+ "lats": "Walking around like a cobra. Wings deployed.",+ "full-body": "A true all-rounder. Or you just did burpees.",+ "fallback": "Mysterious training patterns. We respect it."+ },+ "quip": {+ "barDoesNotCare": "The bar does not care how you feel about it.",+ "progressiveOverload": "Progressive overload: the only pyramid scheme that works.",+ "warmUp": "Nobody has ever regretted the warm-up.",+ "couch": "The hardest rep is the one that gets you off the couch.",+ "formFirst": "Form first. Ego lifts are for the parking lot.",+ "legs": "Legs are not optional. They are just unpopular.",+ "chalk": "Chalk is not a personality. It helps, though.",+ "unfilledLog": "You cannot out-train a log you never fill in.",+ "deload": "Deload weeks count. Reluctantly.",+ "mirror": "Mirror check later. Barbell now.",+ "halfReps": "Half reps, full lies.",+ "badSet": "The only bad set is the one you talked yourself out of.",+ "squatRack": "Somewhere a squat rack is holding a coat. Not yours.",+ "showingUp": "Showing up is the part most people skip.",+ "proteinSleep": "Protein is not optional. Neither is sleep.",+ "rest": "Rest is part of the plan, not a gap in it."+ },+ "quickWeighIn": {+ "title": "Log Weight",+ "duplicateToday": "Already logged today ({{weight}} {{unit}}). Log again anyway?",+ "logAnyway": "Log Anyway",+ "weightWithUnit": "Weight ({{unit}})",+ "weight": "Weight",+ "weightName": "weight",+ "changeDateOrNote": "+ Change date or add a note",+ "date": "Date",+ "note": "Note",+ "optional": "(optional)",+ "noteOptional": "Note (optional)",+ "notePlaceholder": "e.g., morning, post-workout",+ "saveFailed": "Failed to save"+ }+ },+ "nav": {+ "home": "Home",+ "workouts": "Workouts",+ "programs": "Programs",+ "food": "Food",+ "nutrition": "Nutrition",+ "weight": "Weight",+ "userMenu": "User menu",+ "settings": "Settings",+ "lightMode": "Light mode",+ "darkMode": "Dark mode",+ "signOut": "Sign out",+ "session": {+ "sets": "{{done}}/{{total}} sets",+ "restOver": "Rest over",+ "paused": "Paused",+ "rest": "Rest"+ }+ },+ "app": {+ "documentTitle": "Lyftr — Workout & Nutrition Tracker"+ }+}diff --git a/packages/shared/src/i18n/locales/es.json b/packages/shared/src/i18n/locales/es.jsonnew file mode 100644index 0000000..49ffab6--- /dev/null+++ b/packages/shared/src/i18n/locales/es.json@@ -0,0 +1,1414 @@+{+ "settings": {+ "title": "Ajustes",+ "subtitle": "Preferencias y configuración de la cuenta",+ "back": "Inicio",+ "saved": "Ajustes guardados correctamente",+ "unknownError": "El servidor no indicó qué salió mal.",+ "language": {+ "label": "Idioma",+ "description": "Por defecto, el idioma de tu dispositivo",+ "systemChoice": "Sistema ({{name}})",+ "search": "Buscar idiomas",+ "noMatches": "Ningún idioma coincide"+ },+ "account": {+ "title": "Cuenta",+ "name": {+ "label": "Nombre",+ "description": "El nombre con el que te saluda la app. Si lo dejas vacío, usaremos tu correo.",+ "loadFailed": "No se pudo cargar tu nombre, así que no te ofreceremos sobrescribirlo.",+ "saveFailed": "No se pudo guardar tu nombre.",+ "save": "Guardar",+ "saving": "Guardando…",+ "title": "Nombre",+ "subtitle": "El nombre con el que te saluda la app.",+ "emptyHint": "Si lo dejas vacío, usaremos tu correo.",+ "saveFailedFallback": "No se pudo guardar tu nombre. Inténtalo de nuevo."+ },+ "email": {+ "label": "Correo",+ "description": "Tu correo de inicio de sesión",+ "change": "Cambiar",+ "changeLabel": "Cambiar correo",+ "pageTitle": "Cambiar correo",+ "pageSubtitle": "Iniciarás sesión con la nueva dirección. Si cambias algo más que las mayúsculas y minúsculas, se cierra tu sesión en tus otros dispositivos.",+ "current": "Correo actual",+ "new": "Correo nuevo",+ "submit": "Actualizar correo",+ "failedFallback": "No se pudo cambiar tu correo. Inténtalo de nuevo.",+ "changedTitle": "Correo cambiado",+ "signInWith": "De ahora en adelante, inicia sesión con <email>{{email}}</email>.",+ "signInWithPlain": "De ahora en adelante, inicia sesión con {{email}}.",+ "caseOnly": "Solo cambiaron las mayúsculas y minúsculas, así que tus otros dispositivos siguen con la sesión iniciada.",+ "signedOutElsewhere": "Aquí sigues con la sesión iniciada; en tus otros dispositivos se cerró la sesión."+ },+ "memberSince": {+ "label": "Miembro desde"+ },+ "password": {+ "label": "Contraseña",+ "description": "Al cambiarla, se cierra tu sesión en tus otros dispositivos",+ "change": "Cambiar",+ "current": "Contraseña actual",+ "new": "Contraseña nueva",+ "confirmNew": "Confirma la contraseña nueva",+ "pageTitle": "Cambiar contraseña",+ "pageSubtitle": "Seguirás con la sesión iniciada aquí. Se cierra la sesión en todos los demás dispositivos.",+ "submit": "Actualizar contraseña",+ "failedFallback": "No se pudo cambiar tu contraseña. Inténtalo de nuevo.",+ "changedTitle": "Contraseña cambiada",+ "changedBody": "Sigues con la sesión iniciada aquí. Se cerró la sesión en todos los demás dispositivos y necesitarán la contraseña nueva."+ },+ "backLink": "Ajustes",+ "backToSettings": "Volver a ajustes",+ "saving": "Guardando"+ },+ "appearance": {+ "title": "Apariencia",+ "theme": {+ "label": "Tema",+ "description": "Esquema de color de la interfaz",+ "dark": "Oscuro",+ "light": "Claro"+ },+ "darkMode": {+ "label": "Modo oscuro",+ "description": "Usar el esquema de color oscuro"+ }+ },+ "workout": {+ "title": "Entrenamiento",+ "footnote": "El descanso predeterminado se aplica a los ejercicios nuevos · el descanso de cada ejercicio lo reemplaza.",+ "layout": {+ "label": "Diseño del entrenamiento activo",+ "description": "Cómo se muestran los ejercicios durante un entrenamiento",+ "list": "Lista",+ "gym": "Modo gimnasio"+ },+ "defaultView": {+ "label": "Vista de entrenamiento predeterminada"+ },+ "restTimer": {+ "label": "Temporizador de descanso",+ "description": "Inicia una cuenta atrás entre series",+ "gymDescription": "Inicia una cuenta atrás entre series en el modo gimnasio",+ "off": "No",+ "on": "Sí"+ },+ "defaultRest": {+ "label": "Descanso predeterminado",+ "description": "Se aplica a los ejercicios nuevos · el descanso de cada ejercicio lo reemplaza",+ "preset": "{{seconds}} s",+ "custom": "Otro",+ "customLabel": "Segundos de descanso personalizados",+ "secondsUnit": "s",+ "minusFive": "−5 segundos",+ "plusFive": "+5 segundos",+ "decrease": "Reducir el descanso en 5 segundos",+ "increase": "Aumentar el descanso en 5 segundos"+ }+ },+ "goalsUnits": {+ "title": "Objetivos y unidades",+ "loadFailedMessage": "Son tus objetivos y unidades guardados, así que no los adivinaremos. Todo lo demás de esta página sigue funcionando."+ },+ "unitsTargets": {+ "title": "Unidades y objetivos",+ "footnote": "La unidad de peso se aplica al instante en toda la app. Los objetivos de nutrición alimentan los anillos del panel.",+ "loadFailedMessage": "Son tus objetivos y unidades guardados, así que no los adivinaremos. Todo lo demás aquí sigue funcionando.",+ "saved": "Objetivos guardados",+ "changeUnitFailedTitle": "No se pudieron cambiar las unidades"+ },+ "targets": {+ "loadFailedTitle": "No se pudieron cargar tus objetivos",+ "weightUnit": {+ "label": "Unidad de peso",+ "description": "Los cambios se aplican de inmediato en toda la app",+ "changeFailed": "No se pudo cambiar la unidad de peso.",+ "changeFailedFallback": "No se pudo cambiar la unidad de peso"+ },+ "calorie": {+ "label": "Objetivo de calorías",+ "description": "Meta diaria de calorías"+ },+ "protein": {+ "label": "Objetivo de proteína",+ "description": "Meta diaria de proteína"+ },+ "carb": {+ "label": "Objetivo de carbohidratos",+ "description": "Meta diaria de carbohidratos"+ },+ "fat": {+ "label": "Objetivo de grasa",+ "description": "Meta diaria de grasa"+ },+ "saveHint": "Guardar los objetivos de calorías y macros",+ "save": "Guardar objetivos",+ "saving": "Guardando...",+ "saveFailedFallback": "No se pudieron guardar los ajustes",+ "saveFailed": "No se pudieron guardar los objetivos"+ },+ "server": {+ "title": "Servidor",+ "webTitle": "Instancia autoalojada",+ "footnote": "El backend autoalojado con el que habla esta app. Deja la URL en blanco para usar el predeterminado.",+ "api": {+ "label": "Servidor de API",+ "description": "Servidor backend al que está conectado este cliente",+ "default": "Este sitio (proxy inverso)"+ },+ "backend": {+ "label": "Backend",+ "default": "Backend predeterminado"+ },+ "url": {+ "label": "URL del servidor",+ "placeholder": "https://your-server.example.com",+ "invalid": "Introduce una URL completa que incluya http:// o https://",+ "testAndSave": "Probar y guardar"+ },+ "connected": "Conectado · {{name}} v{{version}}",+ "savedWithWarning": "Guardado — {{message}}",+ "database": {+ "label": "Base de datos",+ "description": "Almacenamiento del backend"+ },+ "version": {+ "label": "Versión",+ "description": "Versión del backend de lyftr"+ }+ },+ "library": {+ "title": "Biblioteca de ejercicios",+ "database": {+ "label": "Base de datos de ejercicios",+ "description": "Los ejercicios vienen de open-exercise-db y se consultan mientras buscas. Este servidor guarda una copia de los que ha mostrado."+ },+ "cached_one": "{{amount}} en caché",+ "cached_many": "{{amount}} en caché",+ "cached_other": "{{amount}} en caché",+ "cachedUnknown": "— en caché",+ "refreshed_one": "Se actualizó {{amount}} ejercicio",+ "refreshed_many": "Se actualizaron {{amount}} de ejercicios",+ "refreshed_other": "Se actualizaron {{amount}} ejercicios",+ "cleared_one": "Se eliminó {{amount}} ejercicio sin usar",+ "cleared_many": "Se eliminaron {{amount}} de ejercicios sin usar",+ "cleared_other": "Se eliminaron {{amount}} ejercicios sin usar",+ "refresh": "Actualizar caché",+ "refreshing": "Actualizando...",+ "refreshFailed": "No se pudo actualizar la caché.",+ "clear": "Borrar sin usar",+ "clearing": "Borrando...",+ "clearFailed": "No se pudo borrar la caché."+ },+ "danger": {+ "title": "Zona de peligro",+ "actionsTitle": "Acciones de la cuenta"+ },+ "signOut": {+ "label": "Cerrar sesión",+ "description": "Cierra la sesión en este dispositivo",+ "button": "Cerrar sesión"+ },+ "deleteAccount": {+ "label": "Eliminar cuenta",+ "description": "Elimina permanentemente todos tus datos",+ "button": "Eliminar",+ "sheetTitle": "¿Eliminar la cuenta?",+ "sheetMessage": "Esto elimina permanentemente tu cuenta y todos tus datos. No se puede deshacer.",+ "confirm": "Eliminar cuenta",+ "busy": "Eliminando…",+ "failed": "No se pudo eliminar la cuenta"+ }+ },+ "common": {+ "there": "usuario",+ "duration": {+ "seconds": "{{value}} s",+ "minutes": "{{value}} min"+ },+ "close": "Cerrar",+ "dateFormat": {+ "monthDay": "d MMM",+ "monthDayYear": "d MMM yyyy",+ "numericMonthDay": "d/M",+ "weekdayDate": "EEEE, d 'de' MMMM 'de' yyyy",+ "monthShort": "MMM",+ "longDate": "d 'de' MMMM 'de' yyyy",+ "weekdayNarrow": "EEEEE",+ "weekdayMonthDayLong": "EEEE, d 'de' MMMM",+ "weekdayMonthDay": "EEE, d MMM",+ "weekdayMonthDayYear": "EEE, d MMM yyyy",+ "year": "yyyy",+ "monthYearLong": "MMMM 'de' yyyy"+ },+ "day": {+ "today": "Hoy",+ "yesterday": "Ayer"+ },+ "cancel": "Cancelar",+ "tryAgain": "Intentar de nuevo",+ "retrying": "Reintentando…",+ "loading": "Cargando",+ "search": "Buscar…",+ "clearSearch": "Borrar búsqueda",+ "edit": "Editar",+ "delete": "Eliminar",+ "deleting": "Eliminando…",+ "deleteConfirmMessage": "{{subject}} se eliminará de forma permanente.",+ "dismiss": "Descartar",+ "done": "Listo",+ "dismissKeyboard": "Cerrar teclado",+ "pickDate": "Elegir fecha",+ "selectDate": "Seleccionar fecha",+ "capsLockOn": "Bloq Mayús está activado",+ "figureFailed": "No se pudo cargar esta cifra",+ "stepper": {+ "decrease": "Disminuir {{name}}",+ "increase": "Aumentar {{name}}"+ },+ "password": {+ "show": "Mostrar {{label}}",+ "hide": "Ocultar {{label}}"+ },+ "back": "Atrás",+ "goBack": "Volver",+ "save": "Guardar",+ "saving": "Guardando…"+ },+ "errors": {+ "api": {+ "misconfigured": "La URL del servidor parece mal configurada — no se encontró el endpoint de la API. Revisa los ajustes del servidor.",+ "restarting": "El servidor se está reiniciando o no está disponible. Inténtalo de nuevo en un momento.",+ "notApi": "Esa dirección devolvió una página web, no la API de Lyftr. Revisa los ajustes del servidor.",+ "serverError": "Error del servidor. Inténtalo de nuevo en breve."+ },+ "network": {+ "brief": {+ "cleartextBlocked": "Bloqueado porque la URL del servidor usa http://. Revisa los ajustes del servidor.",+ "certificateUntrusted": "Este dispositivo no confía en el certificado del servidor. Revisa los ajustes del servidor.",+ "hostnameMismatch": "El certificado del servidor no cubre esta dirección. Revisa los ajustes del servidor.",+ "timeout": "El servidor no respondió a tiempo. Inténtalo de nuevo en un momento.",+ "unreachable": "No se pudo conectar con el servidor. Comprueba que esté en marcha.",+ "unknown": "No se puede conectar con el servidor en este momento."+ },+ "full": {+ "cleartextBlocked": "Este dispositivo bloqueó la conexión porque la URL usa http:// sin cifrar. Cambia el servidor a https:// — un proxy inverso puede emitir un certificado para un nombre de host de red local sin abrir puertos.",+ "certificateUntrusted": "Este dispositivo no confía en el certificado del servidor. La mejor solución: dale al servidor un certificado real — un proxy inverso puede emitir uno para un nombre de host de red local sin abrir puertos. O instala tu propia CA en Ajustes → Seguridad → Cifrado y credenciales, con lo que todas las apps del dispositivo confiarán en ella, no solo Lyftr.",+ "hostnameMismatch": "El certificado del servidor no cubre esta dirección. Vuelve a emitirlo con este nombre de host o esta IP en el Nombre alternativo del sujeto (SAN) del certificado.",+ "timeout": "El servidor no respondió a tiempo. Comprueba que esté en marcha y accesible desde este dispositivo.",+ "unreachable": "No se pudo conectar con el servidor. Revisa la URL y que el backend esté en marcha.",+ "unknownWeb": "No se puede conectar con el servidor. Revisa la URL, que el backend esté en marcha y que permita el origen de esta app (CORS).",+ "unknownNative": "No se puede conectar con el servidor. Revisa la URL y que el backend esté en marcha y accesible desde este dispositivo.",+ "withDetail": "{{message}} ({{detail}})"+ }+ },+ "list": {+ "loadFailed": "No se pudo cargar esta lista.",+ "unreadable": "El servidor envió algo que no pudimos leer.",+ "title": "Error al cargar {{subject}}"+ },+ "boundary": {+ "title": "Error al mostrar {{subject}}",+ "thisPage": "esta página",+ "message": "Algo salió mal de nuestro lado. Inténtalo de nuevo y, si sigue pasando, recarga la página."+ }+ },+ "server": {+ "insecureWarning": "Sin cifrar — cualquiera en esta red puede leer tu inicio de sesión y mantener la sesión abierta como si fuera tú. Usa https:// si puedes.",+ "mixedContentWarning": "Este navegador lo bloqueará — una página HTTPS no puede llamar a un servidor http://. Usa https:// también para el servidor, o déjalo en blanco para usar el backend de este sitio.",+ "test": {+ "notLyftr": "Respondió, pero no parece un servidor de Lyftr.",+ "unreachable": "No se pudo conectar con el servidor."+ },+ "settingsTitle": "Ajustes del servidor",+ "blocked": "Bloqueado",+ "notEncrypted": "Sin cifrar",+ "blankPlaceholder": "Déjalo en blanco para usar este sitio",+ "fullUrlHint": "URL completa, p. ej. <url>https://lyftr.example.com</url>",+ "testing": "Probando…",+ "testAndSave": "Probar y guardar",+ "current": "Actual: {{url}}",+ "usingSite": "Usando la dirección de este sitio (proxy inverso)",+ "defaultShort": "predeterminado",+ "status": {+ "invalidUrlExample": "Incluye http:// o https:// — p. ej. http://192.168.1.10:3000",+ "invalidUrl": "Incluye http:// o https://",+ "storageBlocked": "No se pudo guardar la URL del servidor — este navegador está bloqueando el almacenamiento.",+ "connected": "Conectado · {{name}} {{version}}",+ "connectedTo": "Conectado a {{name}} v{{version}}"+ }+ },+ "auth": {+ "passwordRules": {+ "minLength_one": "Al menos {{count}} carácter",+ "minLength_many": "Al menos {{count}} caracteres",+ "minLength_other": "Al menos {{count}} caracteres",+ "maxBytes_one": "Máximo {{count}} carácter (los acentos y los emoji cuentan como más)",+ "maxBytes_many": "Máximo {{count}} caracteres (los acentos y los emoji cuentan como más)",+ "maxBytes_other": "Máximo {{count}} caracteres (los acentos y los emoji cuentan como más)",+ "different": "Distinta de tu contraseña actual",+ "match": "Las contraseñas coinciden",+ "mismatch": "Las contraseñas no coinciden",+ "repeat": "Repite la nueva contraseña"+ },+ "divider": {+ "or": "O",+ "orLower": "o"+ },+ "field": {+ "email": "Correo",+ "password": "Contraseña",+ "confirmPassword": "Confirmar contraseña",+ "emailPlaceholder": "[email protected]"+ },+ "validation": {+ "emailInvalid": "Ingresa un correo válido",+ "passwordRequired": "Ingresa tu contraseña"+ },+ "closed": {+ "notice": "Este servidor no acepta cuentas nuevas."+ },+ "tagline": "ENTRENA · REGISTRA · PROGRESA",+ "hero": {+ "headline": "Registra. Levanta.",+ "headlineAccent": "Progresa.",+ "description": "Tu app de fitness autoalojada. Registra entrenamientos, comidas y peso — todo bajo tu control, en tu propio servidor.",+ "features": {+ "workouts": "Registra entrenamientos",+ "food": "Registra comidas + macros",+ "progress": "Mira tu progreso"+ }+ },+ "login": {+ "heading": "Hola de nuevo",+ "subtitle": "Inicia sesión para seguir entrenando.",+ "submit": "Iniciar sesión",+ "submitting": "Iniciando sesión…",+ "failed": "Correo o contraseña incorrectos.",+ "demoFailed": "No se pudo iniciar sesión en la cuenta de demostración.",+ "demo": "Probar cuenta demo",+ "demoHint": "sin registro",+ "newHere": "¿Primera vez por aquí?",+ "createAccountLink": "Crear cuenta"+ },+ "register": {+ "heading": "Crear cuenta",+ "subtitle": "Empieza hoy a registrar tu entrenamiento.",+ "subtitleNative": "Empieza tu registro de entrenamiento.",+ "closedHeading": "Registro cerrado",+ "closedBody": "El propietario de esta instancia de Lyftr desactivó los registros nuevos. Si deberías tener una cuenta aquí, pídele que te cree una.",+ "backToSignIn": "Volver a iniciar sesión",+ "submit": "Crear cuenta",+ "submitting": "Creando cuenta…",+ "failed": "No se pudo completar el registro.",+ "haveAccount": "¿Ya tienes una cuenta?",+ "haveAccountShort": "¿Ya tienes cuenta?",+ "signInLink": "Inicia sesión"+ }+ },+ "weight": {+ "errors": {+ "invalid": "Ingresa un peso válido",+ "tooHigh": "El peso debe ser menor de {{max}} {{unit}}",+ "trendFailed": "No se pudo cargar tu tendencia de peso.",+ "statsFailed": "No se pudieron cargar tus estadísticas de peso."+ },+ "bodyweightShort": "PC",+ "duplicateWarning": "Ya registraste el {{date}} ({{weight}} {{unit}}). ¿Registrar de nuevo de todos modos?",+ "title": "Peso",+ "subtitle": "Sigue tu peso corporal a lo largo del tiempo",+ "loadFailed": "No se pudo cargar tu peso",+ "deleteTitle": "¿Eliminar registro?",+ "deleteSubject": "{{date}} · {{weight}} {{unit}}",+ "deleteFailed": "No se pudo eliminar el registro",+ "log": {+ "title": "Registrar peso",+ "last": "último: {{weight}} {{unit}}",+ "weightLabel": "Peso ({{unit}})",+ "weightField": "Peso",+ "weightName": "peso",+ "dateAndNote": "Fecha y nota",+ "collapse": "Contraer",+ "notePlaceholder": "Nota — p. ej., por la mañana, después de correr",+ "addDateAndNote": "Agregar fecha y nota",+ "logAnyway": "Registrar de todos modos",+ "submit": "Registrar peso",+ "submitting": "Registrando…",+ "tip": "Mejor registrarlo por la mañana, después de ir al baño",+ "failed": "No se pudo registrar el peso"+ },+ "hero": {+ "current": "Peso actual",+ "empty": "La báscula aún no sabe que existes. Arregla eso.",+ "changeGained": "Ganaste {{amount}} {{unit}} {{period}}",+ "changeLost": "Perdiste {{amount}} {{unit}} {{period}}",+ "changeNone": "{{amount}} {{unit}}, sin cambios {{period}}"+ },+ "period": {+ "chip": {+ "7d": "7 d",+ "30d": "30 d",+ "90d": "90 d",+ "All": "Todo"+ },+ "span": {+ "7d": "en 7 d",+ "30d": "en 30 d",+ "90d": "en 90 d",+ "All": "en todo el historial"+ }+ },+ "stats": {+ "avg": {+ "label": "Prom.",+ "tip": "Peso promedio del periodo seleccionado",+ "failed": "No se pudo cargar el peso promedio"+ },+ "low": {+ "label": "Mín.",+ "tip": "Peso más bajo registrado en el periodo",+ "failed": "No se pudo cargar el peso mínimo"+ },+ "high": {+ "label": "Máx.",+ "tip": "Peso más alto registrado en el periodo",+ "failed": "No se pudo cargar el peso máximo"+ }+ },+ "stale": "No se pudieron actualizar; se muestra lo último que cargamos.",+ "trend": {+ "title": "Tendencia",+ "loading": "Cargando tu tendencia",+ "loadFailed": "No se pudo cargar tu tendencia",+ "noData": "Sin datos para este periodo",+ "needMore": "Registra otro peso para ver la tendencia"+ },+ "history": {+ "title": "Historial",+ "subject": "tu historial de peso",+ "loadingMore": "Cargando más…",+ "loadMoreFailed": "No se pudieron cargar más registros"+ },+ "detail": {+ "back": "Peso",+ "loadFailed": "No se pudo cargar este registro",+ "gone": "Ese registro ya no existe.",+ "backToWeight": "Volver a peso",+ "editLabel": "Editar registro",+ "deleteLabel": "Eliminar registro",+ "entryLabel": "Registro de peso",+ "editing": "Editando…",+ "editTitle": "Editar registro",+ "date": "Fecha",+ "notesOptional": "Notas <hint>(opcional)</hint>",+ "notesOptionalPlain": "Notas (opcional)",+ "notePlaceholder": "p. ej., por la mañana, después de entrenar",+ "saveFailed": "No se pudo guardar"+ },+ "row": {+ "options": "Opciones de {{weight}} {{unit}}"+ }+ },+ "programs": {+ "day": {+ "rest": "Día de descanso",+ "numbered": "Día {{number}}"+ },+ "createdOn": "Creado el {{date}}",+ "title": "Programas",+ "subtitle": "Plantillas de entrenamiento reutilizables",+ "newProgram": "Nuevo programa",+ "startWorkout": "Iniciar entrenamiento",+ "deleteConfirmTitle": "¿Eliminar programa?",+ "deleteFailed": "No se pudo eliminar el programa",+ "count": {+ "exercises_one": "{{count}} ejercicio",+ "exercises_other": "{{count}} ejercicios",+ "sets_one": "{{count}} serie",+ "sets_other": "{{count}} series",+ "reps_one": "{{count}} rep",+ "reps_other": "{{count}} reps",+ "exercises_many": "{{count}} ejercicios",+ "sets_many": "{{count}} series",+ "reps_many": "{{count}} reps",+ "days_one": "{{count}} día",+ "days_other": "{{count}} días",+ "days_many": "{{count}} días"+ },+ "list": {+ "searchPlaceholder": "Buscar programas…",+ "empty": {+ "title": "No se encontraron programas",+ "searchHint": "Prueba con otra búsqueda",+ "startHint": "Crea un programa para empezar"+ },+ "loadFailed": "No se pudieron cargar tus programas",+ "errorSubject": "tus programas",+ "loadingMore": "Cargando más…"+ },+ "stats": {+ "total": "Total",+ "totalUnit": "programas",+ "totalFailed": "No se pudo cargar el total",+ "avgExercises": "Ejercicios",+ "avgExercisesFailed": "No se pudo cargar el promedio de ejercicios",+ "perProgram": "por programa"+ },+ "card": {+ "deleteTitle": "¿Eliminar \"{{name}}\"?",+ "cannotUndo": "Esto no se puede deshacer",+ "summary": "{{exercises}} · {{sets}}",+ "restToday": "Descanso hoy",+ "today": "Hoy: {{day}}",+ "options": "Opciones",+ "optionsNamed": "Opciones de {{name}}",+ "menuHeading": "Programa",+ "startTitle": "Iniciar entrenamiento",+ "restDayTitle": "Hoy es día de descanso: abrir programa",+ "viewProgram": "Ver programa",+ "editProgram": "Editar programa",+ "deleteProgram": "Eliminar programa",+ "editNamed": "Editar {{name}}",+ "startNamed": "Iniciar {{name}}"+ },+ "detail": {+ "loadFailed": "No se pudo cargar este programa",+ "gone": "Ese programa ya no existe.",+ "backToPrograms": "Volver a programas",+ "back": "Programas",+ "restDayTitle": "Día de descanso: no hay nada que iniciar",+ "start": "Iniciar",+ "startLabel": "Iniciar entrenamiento",+ "editLabel": "Editar programa",+ "deleteLabel": "Eliminar programa",+ "suggestions": {+ "title": "Nuevos objetivos de tu último entrenamiento",+ "set": "Serie {{number}}",+ "accept": "Aceptar {{name}}, serie {{number}}",+ "dismiss": "Descartar {{name}}, serie {{number}}",+ "showLess": "Mostrar menos",+ "showAll": "Mostrar las {{total}}",+ "dismissAll": "Descartar todo",+ "applyAll": "Aplicar todo ({{total}})",+ "saveFailed": "No se pudieron guardar esos objetivos.",+ "exerciseFallback": "Ejercicio"+ },+ "stats": {+ "cycle": "Ciclo",+ "exercises": "Ejercicios",+ "totalSets": "Series totales"+ },+ "noDays": "Aún no hay días",+ "addDay": "Agregar un día →",+ "todayChip": "HOY",+ "restDayHint": "No hay ejercicios programados: recupérate y vuelve más fuerte.",+ "noExercises": "Aún no hay ejercicios en este día",+ "target": "objetivo {{weight}} {{unit}}"+ },+ "form": {+ "newTitle": "Nuevo programa",+ "editTitle": "Editar programa",+ "summary": "{{days}} • {{exercises}} • {{sets}}",+ "errors": {+ "nameRequired": "Falta el nombre del programa",+ "noDays": "Agrega al menos un día",+ "noExercises": "Agrega al menos un ejercicio a un día de entrenamiento"+ },+ "createFailed": "No se pudo crear el programa",+ "updateFailed": "No se pudo actualizar el programa",+ "name": "Nombre del programa",+ "required": "(obligatorio)",+ "namePlaceholder": "p. ej., Empuje-Tirón-Pierna, Torso-Pierna",+ "notesPlaceholder": "Descripción u objetivos del programa…",+ "days": "Días",+ "targetSets": "Series objetivo",+ "daysHintNew": "(obligatorio: se repiten en este orden)",+ "daysHintEdit": "(se repiten en este orden)",+ "saveProgram": "Guardar programa",+ "dayEditor": {+ "emptyInline": "Aún no hay ejercicios: agrega uno arriba.",+ "emptyTitle": "Aún no hay ejercicios",+ "emptySubtitle": "Agrega un ejercicio a este día",+ "notesPlaceholder": "p. ej., Enfócate en una fase excéntrica controlada",+ "targetReps": "Reps objetivo",+ "targetWeight": "Peso objetivo"+ },+ "daysEditor": {+ "empty": "Aún no hay días: agrega abajo un día de entrenamiento o de descanso.",+ "moveUp": "Subir día",+ "moveDown": "Bajar día",+ "moveUpNumbered": "Subir el día {{number}}",+ "moveDownNumbered": "Bajar el día {{number}}",+ "restPlaceholder": "Día de descanso {{number}}",+ "workout": "Entrenamiento",+ "rest": "Descanso",+ "collapse": "Contraer día",+ "expand": "Expandir día",+ "remove": "Quitar día",+ "addWorkoutDay": "Agregar día de entrenamiento",+ "addRestDay": "Agregar día de descanso"+ },+ "dayPicker": {+ "title": "Elige un día"+ }+ }+ },+ "food": {+ "servings_one": "{{count}} porción",+ "servings_many": "{{count}} porciones",+ "servings_other": "{{count}} porciones",+ "customEntry": "Registro personalizado",+ "limitHint": "Un registro admite como máximo {{amount}}",+ "favorites": {+ "addFailed": "No se pudo añadir {{name}} a Favoritos.",+ "removeFailed": "No se pudo quitar {{name}} de Favoritos.",+ "add": "Añadir {{name}} a Favoritos",+ "remove": "Quitar {{name}} de Favoritos",+ "subject": "tus favoritos",+ "loadFailed": "No se pudieron cargar tus favoritos.",+ "empty": {+ "title": "Aún no hay favoritos",+ "hint": "Marca alimentos con la estrella al registrarlos para encontrarlos aquí"+ }+ },+ "diary": {+ "title": "Comida",+ "titleToday": "Comida de hoy",+ "logFood": "Registrar comida",+ "previousDay": "Día anterior",+ "nextDay": "Día siguiente",+ "loadFailed": "No se pudo cargar tu registro de comidas",+ "deleteFailed": "No se pudo eliminar ese registro.",+ "addTo": "Agregar a {{meal}}",+ "tapToAdd": "+ Toca para agregar comida",+ "deleteConfirm": "¿Eliminar <name>{{name}}</name>?",+ "calories": "Calorías",+ "over": "{{amount}} de más",+ "left": "{{amount}} restantes",+ "goal": "Meta de {{amount}} kcal",+ "totalsFailed": "No se pudieron cargar los totales de hoy",+ "totalsFailedMessage": "Algo salió mal de nuestro lado.",+ "items_one": "{{count}} registro",+ "items_many": "{{count}} registros",+ "items_other": "{{count}} registros",+ "filteredCount": "{{shown}} de {{total}}",+ "searchPlaceholder": "Buscar en la comida de este día…",+ "noMatches": "Sin resultados para “{{query}}”",+ "empty": {+ "title": "Aún no hay comida registrada",+ "hint": "Toca para registrar tu primera comida"+ },+ "entryUpdated": "Registro actualizado",+ "addedTo": "Agregado a {{meal}}"+ },+ "entry": {+ "logged": "Registrado",+ "deleteFailed": "No se pudo eliminar el registro",+ "deleteTitle": "¿Eliminar registro?",+ "loadFailed": "No se pudo cargar este registro",+ "gone": "Ese registro ya no existe.",+ "backToNutrition": "Volver a nutrición",+ "back": "Nutrición",+ "editLabel": "Editar registro",+ "deleteLabel": "Eliminar registro",+ "servingSize": "Tamaño de la porción",+ "amount": "Cantidad",+ "meal": "Comida",+ "optionsNamed": "Opciones de {{name}}"+ },+ "page": {+ "title": "Nutrición",+ "subtitle": "Macros y comidas"+ },+ "meal": {+ "breakfast": "Desayuno",+ "lunch": "Almuerzo",+ "dinner": "Cena",+ "snacks": "Snacks"+ },+ "macro": {+ "protein": "Proteína",+ "carbs": "Carbos",+ "fat": "Grasa",+ "fiber": "Fibra",+ "proteinInitial": "P",+ "carbsInitial": "C",+ "fatInitial": "G"+ },+ "view": {+ "diary": "Diario",+ "trends": "Tendencias"+ },+ "trends": {+ "dailyAverage": "Promedio diario · {{period}}",+ "averageFailed": "No se pudo cargar el promedio de {{macro}}"+ },+ "history": {+ "title": "Historial de macros",+ "loading": "Cargando…",+ "loadFailed": "No se pudo cargar tu historial",+ "empty": "Aún no hay datos — empieza a registrar tus comidas"+ },+ "log": {+ "title": "Registrar comida",+ "editTitle": "Editar comida",+ "details": "Detalles",+ "newEntry": "Nuevo registro",+ "backToFood": "Volver a comida",+ "submit": "Registrar comida",+ "saveChanges": "Guardar cambios",+ "saveFailed": "No se pudo guardar",+ "editLoadFailed": "No se pudo cargar ese registro.",+ "searchPlaceholder": "Buscar comida…",+ "scan": "Escanear",+ "scanLabel": "Escanear código de barras",+ "tab": {+ "recent": "Recientes",+ "favorites": "Favoritos",+ "search": "Buscar"+ },+ "rateLimited": "Demasiadas solicitudes — espera un momento e inténtalo de nuevo",+ "searchUnavailable": "Búsqueda de comida no disponible — ingresa los datos manualmente",+ "lookupFailedTitle": "No se pudo buscar este código de barras",+ "lookupFailed": "No se pudo buscar ese código de barras.",+ "enterManually": "Ingrésalo manualmente",+ "rereadFailed": "No se pudo volver a leer este producto.",+ "quickAdd": "Agregar {{kcal}} kcal rápido",+ "noMacroBreakdown": "Sin desglose de macros",+ "recent": {+ "subject": "lo que registraste hoy",+ "loadFailed": "No se pudo cargar lo que registraste hoy.",+ "empty": {+ "title": "Nada reciente hoy",+ "hint": "Busca o escanea para registrar comida"+ }+ },+ "search": {+ "emptyTitle": "Busca entre millones de alimentos",+ "emptyHint": "O escanea un código de barras",+ "searching": "Buscando…",+ "noResults": "Sin resultados para \"{{query}}\"",+ "manualEntry": "+ Ingresar \"{{query}}\" manualmente",+ "manualEntryWide": "+ Ingresar \"{{query}}\" manualmente"+ },+ "staleServing": "{{note}} Se muestran resultados de búsqueda, que siempre son por {{serving}}.",+ "per": "por {{serving}}",+ "servingEach": "({{serving}} c/u)",+ "servings": "Porciones",+ "amountIn": "Cantidad en {{unit}}",+ "decreaseAmount": "Disminuir cantidad",+ "increaseAmount": "Aumentar cantidad",+ "decreaseServings": "Disminuir porciones",+ "increaseServings": "Aumentar porciones",+ "enterAmount": "Ingresa una cantidad para registrarlo",+ "enterAmountIn": "Ingresa una cantidad en {{unit}} para registrarlo",+ "servingsOf_one": "{{count}} porción de {{serving}}",+ "servingsOf_many": "{{count}} porciones de {{serving}}",+ "servingsOf_other": "{{count}} porciones de {{serving}}",+ "when": "Cuándo"+ },+ "scan": {+ "title": "Escanear código de barras",+ "close": "Cerrar escáner",+ "httpsTitle": "La cámara requiere HTTPS",+ "httpsBody": "Los navegadores solo permiten usar la cámara en páginas seguras. Este sitio se sirve por <mono>http://</mono> sin cifrar — ponlo detrás de un proxy inverso con HTTPS para escanear códigos de barras.",+ "searchByName": "Buscar por nombre",+ "unavailable": "Cámara no disponible",+ "hint": "Apunta la cámara al código de barras — se escaneará automáticamente",+ "deniedTitle": "Acceso a la cámara denegado",+ "neededTitle": "Se necesita permiso de cámara",+ "deniedBody": "Activa el acceso a la cámara para Lyftr en los ajustes de tu dispositivo para escanear códigos de barras.",+ "neededBody": "Permite el acceso a la cámara para escanear el código de barras de un alimento.",+ "allow": "Permitir cámara",+ "point": "Apunta a un código de barras"+ },+ "lookup": {+ "looking": "Buscando este producto…",+ "slow": "Sigo buscando. Esto puede tardar unos segundos."+ }+ },+ "workouts": {+ "defaultName": "Entrenamiento — {{date}}",+ "stats": {+ "total": "Total",+ "logged": "registrados",+ "thisMonth": "Este mes",+ "sessions": "sesiones",+ "avgTime": "Promedio",+ "min": "min",+ "totalFailed": "No se pudo cargar el total",+ "thisMonthFailed": "No se pudo cargar este mes",+ "avgTimeFailed": "No se pudo cargar el tiempo promedio"+ },+ "list": {+ "title": "Entrenamientos",+ "subtitle": "Registra y revisa tus sesiones de entrenamiento",+ "logWorkout": "Registrar entreno",+ "searchPlaceholder": "Buscar entrenamientos…",+ "empty": {+ "title": "No se encontraron entrenamientos",+ "searchHint": "Prueba con otra búsqueda",+ "startHint": "Registra un entrenamiento para empezar"+ },+ "loadFailed": "No se pudieron cargar tus entrenamientos",+ "errorSubject": "tus entrenamientos",+ "loadingMore": "Cargando más…"+ },+ "deleteFailed": "No se pudo eliminar el entrenamiento",+ "deleteConfirmTitle": "¿Eliminar entrenamiento?",+ "toast": {+ "newPr": "Nuevo récord en {{name}}",+ "newTargets": "Nuevos objetivos en {{name}}",+ "reviewUpdates_one": "Toca para revisar {{count}} actualización",+ "reviewUpdates_other": "Toca para revisar {{count}} actualizaciones",+ "reviewUpdates_many": "Toca para revisar {{count}} actualizaciones",+ "saved": "Entrenamiento guardado",+ "tapToView": "Toca para ver",+ "discarded": "Entrenamiento descartado",+ "tapToUndo": "Toca para deshacer"+ },+ "card": {+ "deleteTitle": "¿Eliminar \"{{name}}\"?",+ "cannotUndo": "Esto no se puede deshacer",+ "minutes": "{{minutes}} min",+ "exercises_one": "{{count}} ejercicio",+ "exercises_other": "{{count}} ejercicios",+ "exercises_many": "{{count}} ejercicios",+ "options": "Opciones",+ "optionsNamed": "Opciones de {{name}}",+ "menuHeading": "Entrenamiento",+ "editWorkout": "Editar entrenamiento",+ "deleteWorkout": "Eliminar entrenamiento",+ "editNamed": "Editar {{name}}",+ "totalVolume": "Volumen total: {{amount}} {{unit}}"+ },+ "detail": {+ "loadFailed": "No se pudo cargar este entrenamiento",+ "gone": "Ese entrenamiento ya no existe.",+ "backToWorkouts": "Volver a entrenamientos",+ "back": "Entrenamientos",+ "editLabel": "Editar entrenamiento",+ "deleteLabel": "Eliminar entrenamiento",+ "duration": "Duración",+ "minutesUnit": "min",+ "sets": "Series",+ "volume": "Volumen",+ "restOff": "El temporizador de descanso está desactivado: actívalo en Ajustes",+ "setCount_one": "{{count}} serie",+ "setCount_other": "{{count}} series",+ "setCount_many": "{{count}} series",+ "best": "mejor",+ "noRest": "Sin descanso"+ },+ "start": {+ "title": "Empezar entrenamiento",+ "inProgress": "Entrenamiento en curso",+ "resume": "Reanudar",+ "discard": "Descartar",+ "quick": "Inicio rápido",+ "quickHint": "Empieza en blanco y agrega ejercicios sobre la marcha",+ "fromProgram": "Empezar desde un programa",+ "fromProgramHint": "Carga un día de una rutina guardada",+ "programsLoadFailed": "No se pudieron cargar tus programas",+ "loadingPrograms": "Cargando programas…",+ "noPrograms": "Aún no hay programas",+ "createFirst": "Crea tu primer programa →",+ "days_one": "{{count}} día",+ "days_other": "{{count}} días",+ "days_many": "{{count}} días",+ "noDays": "Aún no hay días"+ },+ "form": {+ "logTitle": "Registrar entrenamiento",+ "editTitle": "Editar entrenamiento",+ "summary": "{{exercises}} • {{sets}}",+ "summaryWithWeight": "{{exercises}} • {{sets}} • {{weight}} {{unit}}",+ "exerciseCount_one": "{{count}} ejercicio",+ "exerciseCount_other": "{{count}} ejercicios",+ "exerciseCount_many": "{{count}} ejercicios",+ "setCount_one": "{{count}} serie",+ "setCount_other": "{{count}} series",+ "setCount_many": "{{count}} series",+ "errors": {+ "nameRequired": "El nombre del entrenamiento es obligatorio",+ "noExercises": "Agrega al menos un ejercicio"+ },+ "createFailed": "No se pudo crear el entrenamiento",+ "updateFailed": "No se pudo actualizar el entrenamiento",+ "name": "Nombre del entrenamiento",+ "required": "(obligatorio)",+ "namePlaceholder": "p. ej., Día de piernas, Día de empuje",+ "date": "Fecha",+ "durationMinutes": "Duración (minutos)",+ "duration": "Duración",+ "durationHm": "{{hours}} h {{minutes}} min",+ "notes": "Notas",+ "notesPlaceholder": "¿Cómo te sentiste? ¿Algún récord?",+ "totalUnit": "Total {{unit}}",+ "exercises": "Ejercicios",+ "sets": "Series",+ "loadProgram": "Cargar programa",+ "addExercise": "Agregar ejercicio",+ "addExerciseLabel": "Agregar ejercicio",+ "removeExercise": "Quitar ejercicio",+ "removeNamed": "Quitar {{name}}",+ "exerciseFallback": "ejercicio",+ "exerciseNotesPlaceholder": "p. ej., Me sentí fuerte",+ "restBetweenSets": "Descanso entre series",+ "set": "Serie",+ "reps": "Reps",+ "weight": "Peso",+ "weightWithUnit": "Peso ({{unit}})",+ "setWeightLabel": "Peso de la serie",+ "setRepsLabel": "Repeticiones de la serie",+ "addSet": "Agregar serie",+ "removeSet": "Quitar serie",+ "note": "Nota",+ "addNoteLabel": "Agregar nota del ejercicio",+ "removeNoteLabel": "Quitar nota",+ "exerciseNotesLabel": "Notas del ejercicio",+ "saveWorkout": "Guardar entrenamiento",+ "saveChanges": "Guardar cambios",+ "empty": {+ "createTitle": "Aún no hay ejercicios",+ "createHint": "Agrega un ejercicio o carga un programa para empezar",+ "editTitle": "Sin ejercicios",+ "editHint": "Agrega un ejercicio a este entrenamiento"+ },+ "durationField": {+ "decrease": "Disminuir duración",+ "increase": "Aumentar duración",+ "inputLabel": "Duración en minutos",+ "unit": "min"+ },+ "programPicker": {+ "title": "Cargar desde un programa",+ "pickProgram": "Elige un programa para rellenar los ejercicios",+ "pickDay": "Elige un día para rellenar los ejercicios",+ "loadFailed": "No se pudieron cargar tus programas.",+ "back": "← Volver a programas",+ "today": "HOY",+ "workoutDays_one": "{{count}} día de entrenamiento",+ "workoutDays_other": "{{count}} días de entrenamiento",+ "workoutDays_many": "{{count}} días de entrenamiento",+ "noExercises": "Aún no hay ejercicios",+ "restDays": "días de descanso",+ "createFirst": "Primero crea un programa",+ "close": "Cerrar selector de programas",+ "searchPlaceholder": "Buscar programas…",+ "noMatches": "No hay programas que coincidan"+ }+ },+ "active": {+ "noWorkout": {+ "title": "No hay un entrenamiento activo",+ "hintHome": "Inicia uno desde la página de inicio",+ "hintTab": "Inicia uno desde la pestaña Entrenos",+ "goHome": "Ir al inicio",+ "goWorkouts": "Ir a Entrenos"+ },+ "setsDone": "{{done}}/{{total}} series completadas",+ "finish": "Terminar",+ "empty": {+ "title": "Aún no hay ejercicios",+ "hint": "Agrega ejercicios abajo"+ },+ "setProgress": "{{done}}/{{total}} series",+ "removeExercise": "Quitar ejercicio",+ "notes": {+ "placeholder": "Agrega una nota…",+ "add": "+ Agregar nota",+ "placeholderMobile": "+ Agregar nota…",+ "label": "Notas, {{name}}"+ },+ "columns": {+ "set": "Serie",+ "reps": "Reps",+ "weight": "Peso",+ "weightUnit": "Peso ({{unit}})",+ "done": "Listo"+ },+ "completeSetWeb": "Serie {{number}}, marcar como hecha",+ "completeSet": "Completar serie {{number}}, {{name}}",+ "completedSet": "Serie {{number}} completada, {{name}}",+ "repsLabel": "Reps, serie {{number}}, {{name}}",+ "weightLabel": "Peso, serie {{number}}, {{name}}",+ "removeSet": "Quitar serie",+ "previous": "Ejercicio anterior",+ "addSet": "Agregar serie",+ "next": "Siguiente",+ "addExercise": "Agregar ejercicio",+ "cancelWorkout": "Cancelar entrenamiento",+ "saveFailed": "No se pudo guardar el entrenamiento",+ "keepGoing": "Seguir",+ "finishConfirm": {+ "title": "¿Terminar el entrenamiento?",+ "message": "{{done}} de {{total}} series completadas. Se guardará el entrenamiento."+ },+ "cancelConfirm": {+ "title": "¿Cancelar el entrenamiento?",+ "message": "Se perderá todo el progreso."+ }+ },+ "rest": {+ "off": "Apagado",+ "custom": "Otro",+ "stepDown5": "−5 segundos",+ "stepDown5Spoken": "Menos 5 segundos",+ "stepUp5": "+5 segundos",+ "stepUp5Spoken": "Más 5 segundos",+ "secondsLabel": "Segundos de descanso",+ "secondsUnit": "seg",+ "label": {+ "ready": "Listo",+ "paused": "En pausa",+ "resting": "Descanso",+ "over": "Descanso terminado",+ "upNext": "Sigue la serie {{next}}",+ "setDone": "Serie {{done}} hecha",+ "setDonePaused": "Serie {{done}} hecha · en pausa",+ "setDoneNext": "Serie {{done}} hecha · sigue la serie {{next}}",+ "setDoneResting": "Serie {{done}} hecha · descansando",+ "overNext": "Descanso terminado · sigue la serie {{next}}"+ },+ "pause": "Pausar temporizador de descanso",+ "resume": "Reanudar temporizador de descanso",+ "shorten": "Acortar el descanso 15 segundos",+ "extend": "Alargar el descanso 15 segundos",+ "skip": "Omitir"+ }+ },+ "gym": {+ "workout": "Entrenamiento",+ "goToExercise": "Ir al ejercicio {{number}}",+ "minimizeWorkout": "Minimizar entrenamiento",+ "minimize": "Minimizar",+ "discardWorkout": "Descartar entrenamiento",+ "discard": {+ "title": "¿Descartar el entrenamiento?",+ "message": "Esto termina el entrenamiento sin guardarlo: se pierde todo el progreso.",+ "confirm": "Descartar"+ },+ "labels": {+ "sets": "Series",+ "reps": "Reps",+ "weight": "Peso",+ "repsName": "repeticiones"+ },+ "overview": {+ "exercises": "Ejercicios",+ "totalSets": "Series totales",+ "muscles": "Músculos",+ "empty": "Aún no has agregado ejercicios",+ "startWorkout": "Empezar entrenamiento"+ },+ "info": {+ "restTitle": "Descanso entre series",+ "restHint": "Inicia solo al completar una serie",+ "begin": "Empezar ejercicio"+ },+ "set": {+ "chip": "Serie {{number}}",+ "chipDone": "Serie {{number}}, hecha",+ "chipResting": "Serie {{number}}, en descanso",+ "chipDoneResting": "Serie {{number}}, hecha, en descanso"+ },+ "target": {+ "label": "Objetivo",+ "reps_one": "{{count}} rep",+ "reps_other": "{{count}} reps",+ "repsUnknown": "— reps",+ "reps_many": "{{count}} reps"+ },+ "completeSet": "Completar serie",+ "completed": "Completada",+ "removeSet": "Quitar esta serie",+ "removeExercise": "Quitar este ejercicio",+ "nav": {+ "info": "Info",+ "finishWorkout": "Terminar entrenamiento",+ "nextExercise": "Siguiente ejercicio"+ }+ },+ "exercises": {+ "estimated1rm": "1RM est.: {{weight}} {{unit}} · {{date}}",+ "equipment": {+ "body-only": "Peso corporal",+ "barbell": "Barra",+ "dumbbell": "Mancuerna",+ "machine": "Máquina",+ "cable": "Polea",+ "kettlebells": "Pesa rusa",+ "bands": "Bandas",+ "medicine-ball": "Balón medicinal",+ "e-z-curl-bar": "Barra Z",+ "exercise-ball": "Balón de ejercicio",+ "foam-roll": "Rodillo de espuma",+ "none": "Ninguno",+ "other": "Otro"+ },+ "category": {+ "strength": "fuerza",+ "stretching": "estiramiento",+ "plyometrics": "pliometría",+ "strongman": "strongman",+ "powerlifting": "powerlifting",+ "cardio": "cardio",+ "olympic-weightlifting": "halterofilia"+ },+ "muscle": {+ "abdominals": "abdominales",+ "abductors": "abductores",+ "abs": "abdominales",+ "adductors": "aductores",+ "back": "espalda",+ "biceps": "bíceps",+ "calves": "pantorrillas",+ "chest": "pecho",+ "core": "core",+ "forearms": "antebrazos",+ "full-body": "cuerpo completo",+ "glutes": "glúteos",+ "hamstrings": "isquiotibiales",+ "lats": "dorsales",+ "legs": "piernas",+ "lower-back": "espalda baja",+ "middle-back": "espalda media",+ "neck": "cuello",+ "obliques": "oblicuos",+ "other": "otro",+ "quadriceps": "cuádriceps",+ "shoulders": "hombros",+ "traps": "trapecios",+ "triceps": "tríceps"+ },+ "picker": {+ "title": "Añadir ejercicio",+ "loaded_one": "{{count}} cargado",+ "loaded_other": "{{count}} cargados",+ "loaded_many": "{{count}} cargados",+ "loadedMore_one": "{{count}} cargado…",+ "loadedMore_other": "{{count}} cargados…",+ "loadedMore_many": "{{count}} cargados…",+ "search": "Buscar ejercicios…",+ "loading": "Cargando ejercicios…",+ "loadingShort": "Cargando…",+ "loadingMore": "Cargando más…",+ "loadMore": "Cargar más",+ "empty": "No se encontraron ejercicios",+ "errorSubject": "estos ejercicios",+ "close": "Cerrar selector de ejercicios",+ "backToWorkout": "Volver al entrenamiento",+ "loadFailed": "No se pudieron cargar los ejercicios",+ "loadMoreFailed": "No se pudieron cargar más ejercicios"+ },+ "detail": {+ "loadFailed": "No se pudo cargar este ejercicio",+ "musclesWorked": "Músculos trabajados",+ "bodyFront": "Frente",+ "bodyBack": "Espalda",+ "primary": "Principal",+ "secondary": "Secundario",+ "alsoWorks": "También trabaja",+ "yourBest": "Tu mejor marca",+ "personalBest": "Mejor marca personal",+ "estimated1rm": "1RM estimado",+ "weightProgression": "Progresión de peso",+ "noPeriodData": "Sin datos para este período",+ "maxWeight": "Peso máx.",+ "instructions": "Instrucciones",+ "bestSet_one": "{{unit}} × {{count}} repetición",+ "bestSet_other": "{{unit}} × {{count}} repeticiones",+ "bestSet_many": "{{unit}} × {{count}} repeticiones",+ "period": {+ "1m": "1m",+ "3m": "3m",+ "6m": "6m",+ "All": "Todo"+ }+ }+ },+ "home": {+ "heatmap": {+ "workouts_one": "{{date}} · {{count}} entrenamiento",+ "workouts_many": "{{date}} · {{count}} entrenamientos",+ "workouts_other": "{{date}} · {{count}} entrenamientos",+ "restDay": "{{date}} · día de descanso",+ "less": "Menos",+ "more": "Más"+ },+ "greeting": {+ "morning": "Buenos días, {{name}}",+ "morning_anonymous": "Buenos días",+ "afternoon": "Buenas tardes, {{name}}",+ "afternoon_anonymous": "Buenas tardes",+ "evening": "Buenas noches, {{name}}",+ "evening_anonymous": "Buenas noches"+ },+ "loadFailed": "No se pudo cargar tu panel",+ "header": {+ "start": "Empezar",+ "resume": "Continuar"+ },+ "activeSession": {+ "title": "Entrenamiento en curso",+ "tapToResume": "{{name}} — toca para continuar"+ },+ "upNext": {+ "label": "A continuación · {{name}}",+ "viewRoutine": "Ver la rutina {{name}}",+ "start": "Empezar {{name}}",+ "exercises_one": "{{count}} ejercicio",+ "exercises_many": "{{count}} ejercicios",+ "exercises_other": "{{count}} ejercicios",+ "loadFailed": "No se pudieron cargar tus programas"+ },+ "kpi": {+ "week": "Semana",+ "sessions": "sesiones",+ "cals": "Cal",+ "caloriesFailed": "No se pudieron cargar las calorías de hoy",+ "proteinFailed": "No se pudo cargar la proteína de hoy"+ },+ "thisWeek": {+ "title": "Esta semana",+ "unit_one": "sesión",+ "unit_many": "sesiones",+ "unit_other": "sesiones"+ },+ "volume": {+ "title": "Tendencia de volumen",+ "empty": "Registra entrenamientos para ver tendencias",+ "tooltip": "Volumen"+ },+ "consistency": {+ "title": "Constancia",+ "range": "12 semanas",+ "empty": "Empieza a entrenar para construir tu racha"+ },+ "lastWorkout": {+ "title": "Último entrenamiento",+ "all": "Todos",+ "minutes": "{{mins}} min",+ "sets_one": "{{count}} serie",+ "sets_many": "{{count}} series",+ "sets_other": "{{count}} series",+ "moreExercises_one": "+{{count}} ejercicio más",+ "moreExercises_many": "+{{count}} ejercicios más",+ "moreExercises_other": "+{{count}} ejercicios más",+ "empty": "Aún no hay entrenamientos registrados",+ "startFirst": "Empieza tu primer entrenamiento →"+ },+ "nutrition": {+ "title": "Nutrición de hoy",+ "log": "Registrar →",+ "loadFailed": "No se pudo cargar la comida de hoy"+ },+ "macro": {+ "protein": "Proteína",+ "carbs": "Carbohidratos",+ "fat": "Grasa"+ },+ "muscle": {+ "title": "Equilibrio muscular",+ "workouts_one": "{{count}} entrenamiento",+ "workouts_many": "{{count}} entrenamientos",+ "workouts_other": "{{count}} entrenamientos",+ "empty": "Registra entrenamientos para ver qué músculos entrenas más.",+ "noData": "Aún no hay datos de entrenamientos",+ "top": "principal",+ "tooltip_one": "{{count}} serie ({{percent}}%)",+ "tooltip_many": "{{count}} series ({{percent}}%)",+ "tooltip_other": "{{count}} series ({{percent}}%)",+ "donutSets": "series"+ },+ "weight": {+ "title": "Peso",+ "view": "Ver",+ "loadFailed": "No se pudo cargar tu peso",+ "logFirst": "Registra tu primer peso",+ "logFirstHint": "Toca para empezar a registrar",+ "logAria": "Registrar peso",+ "noChange7d": "7 d · sin cambios",+ "trendDown": "7 d · ↓{{amount}} {{unit}}",+ "trendUp": "7 d · ↑{{amount}} {{unit}}"+ },+ "muscleRoast": {+ "chest": "Todo pecho, nada de piernas. Un clásico.",+ "back": "Con espalda de refrigerador. Respeto.",+ "shoulders": "No cabes por las puertas. Bien.",+ "biceps": "Cargando selfis frente al espejo…",+ "triceps": "Tríceps de herradura. Tus apretones de manos deben dar miedo.",+ "legs": "Entrenas piernas de verdad. Eres un unicornio.",+ "quadriceps": "Cuádriceps de sobra. Los jeans no tienen ninguna oportunidad.",+ "hamstrings": "Guerrero de la cadena posterior. Se viene un dios del peso muerto.",+ "glutes": "Fan de los glúteos. Respetamos el compromiso.",+ "calves": "Rey o reina de las pantorrillas. El levantador más raro de todos.",+ "core": "Listo para la playa los 365 días del año.",+ "abs": "Se viene el six pack. O ya está aquí. Da igual.",+ "forearms": "Llamó Popeye. Quiere sus brazos de vuelta.",+ "traps": "Sin cuello, sin problema.",+ "lats": "Caminas como una cobra. Alas desplegadas.",+ "full-body": "Todo un todoterreno. O solo hiciste burpees.",+ "fallback": "Patrones de entrenamiento misteriosos. Lo respetamos."+ },+ "quip": {+ "barDoesNotCare": "A la barra no le importa cómo te sientas.",+ "progressiveOverload": "Sobrecarga progresiva: el único esquema piramidal que funciona.",+ "warmUp": "Nadie se ha arrepentido jamás de calentar.",+ "couch": "La repetición más difícil es la que te levanta del sofá.",+ "formFirst": "Primero la técnica. Los levantamientos de ego son para el estacionamiento.",+ "legs": "Las piernas no son opcionales. Solo son impopulares.",+ "chalk": "La magnesia no es una personalidad. Aunque ayuda.",+ "unfilledLog": "No hay entrenamiento que compense un registro que nunca llenas.",+ "deload": "Las semanas de descarga cuentan. A regañadientes.",+ "mirror": "El espejo, después. La barra, ahora.",+ "halfReps": "Medias repeticiones, mentiras enteras.",+ "badSet": "La única serie mala es la que te convenciste de no hacer.",+ "squatRack": "En algún lugar, un rack de sentadillas está sosteniendo un abrigo. No el tuyo.",+ "showingUp": "Presentarse es la parte que la mayoría se salta.",+ "proteinSleep": "La proteína no es opcional. El sueño tampoco.",+ "rest": "El descanso es parte del plan, no un hueco en él."+ },+ "quickWeighIn": {+ "title": "Registrar peso",+ "duplicateToday": "Ya registraste hoy ({{weight}} {{unit}}). ¿Registrar de nuevo de todos modos?",+ "logAnyway": "Registrar de todos modos",+ "weightWithUnit": "Peso ({{unit}})",+ "weight": "Peso",+ "weightName": "peso",+ "changeDateOrNote": "+ Cambiar la fecha o añadir una nota",+ "date": "Fecha",+ "note": "Nota",+ "optional": "(opcional)",+ "noteOptional": "Nota (opcional)",+ "notePlaceholder": "p. ej., mañana, después de entrenar",+ "saveFailed": "No se pudo guardar"+ }+ },+ "nav": {+ "home": "Inicio",+ "workouts": "Entrenos",+ "programs": "Programas",+ "food": "Comida",+ "nutrition": "Nutrición",+ "weight": "Peso",+ "userMenu": "Menú de usuario",+ "settings": "Ajustes",+ "lightMode": "Modo claro",+ "darkMode": "Modo oscuro",+ "signOut": "Cerrar sesión",+ "session": {+ "sets": "{{done}}/{{total}} series",+ "restOver": "Descanso terminado",+ "paused": "En pausa",+ "rest": "Descanso"+ }+ },+ "app": {+ "documentTitle": "Lyftr — Registro de entrenamiento y nutrición"+ }+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 5efa017..8f4be50 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -41,5 +41,7 @@ export * from './stores/auth'export * from './stores/server'export * from './stores/settings'export * from './stores/theme'+export * from './stores/language'+export * from './i18n'export * from './stores/workoutSession'export * from './brand/barbell'diff --git a/packages/shared/src/stores/auth.test.ts b/packages/shared/src/stores/auth.test.tsindex bfdec5b..e2c69c3 100644--- a/packages/shared/src/stores/auth.test.ts+++ b/packages/shared/src/stores/auth.test.ts@@ -1,7 +1,9 @@import { createAuthStore } from './auth'import { createMemoryStorage } from '../testing/memoryStorage'import { STORAGE_KEYS } from '../storage'-import type { LyftrClient } from '../client'+import { uiMessage, type LyftrClient } from '../client'+import { i18n } from '../i18n'+import es from '../i18n/locales/es.json'import type { AuthResponse } from '../types'const fakeAuthResponse: AuthResponse = {@@ -45,10 +47,27 @@ describe('auth store (storage-adapter DI)', () => {await expect(useAuth.getState().login('[email protected]', 'nope')).rejects.toBeTruthy()const state = useAuth.getState()expect(state.isAuthenticated).toBe(false)- expect(state.error).toBe('Invalid email or password')+ expect(uiMessage(state.error!)).toBe('Invalid email or password')expect(await storage.get(STORAGE_KEYS.access)).toBeNull()})+ it('keeps the fallback as a message key, so a failure already on screen follows the language', async () => {+ const client = {+ authAPI: { login: async () => { throw { response: { status: 401, data: {} } } }, register: async () => { throw { response: { status: 401, data: {} } } } },+ } as unknown as LyftrClient+ const useAuth = createAuthStore(client, createMemoryStorage())++ await expect(useAuth.getState().login('[email protected]', 'nope')).rejects.toBeTruthy()+ const failure = useAuth.getState().error!+ try {+ expect(uiMessage(failure)).toBe('Invalid email or password.')+ await i18n.changeLanguage('es')+ expect(uiMessage(failure)).toBe(es.auth.login.failed)+ } finally {+ await i18n.changeLanguage('en')+ }+ })+it('logout clears storage and state', async () => {const storage = createMemoryStorage()const useAuth = createAuthStore(fakeClient(), storage)diff --git a/packages/shared/src/stores/auth.ts b/packages/shared/src/stores/auth.tsindex 6ca8101..9154eff 100644--- a/packages/shared/src/stores/auth.ts+++ b/packages/shared/src/stores/auth.ts@@ -1,14 +1,16 @@import { create } from 'zustand'import * as types from '../types'import { StorageAdapter, STORAGE_KEYS } from '../storage'-import { LyftrClient, apiErrorMessage } from '../client'+import type { LyftrClient, UiMessage } from '../client'export interface AuthStore {user: types.User | nullisAuthenticated: booleanisHydrated: boolean // true once initial storage read completesisLoading: boolean- error: string | null+ // The inputs of the message, not its text: the screen runs it through uiMessage() at render, so+ // a failure already on screen follows a language switch.+ error: UiMessage | nullhydrate: () => Promise<void>login: (email: string, password: string) => Promise<void>register: (email: string, password: string) => Promise<void>@@ -48,7 +50,7 @@ export function createAuthStore(client: LyftrClient, storage: StorageAdapter) {} catch (err: any) {// Same message logic as the web login page: server-provided error if present,// else a status-aware hint (network/CORS, 5xx, misconfigured URL) via apiErrorMessage.- set({ error: apiErrorMessage(err, 'Invalid email or password.', 'full'), isLoading: false })+ set({ error: { key: 'auth.login.failed', cause: err, detail: 'full' }, isLoading: false })throw err}},@@ -62,7 +64,7 @@ export function createAuthStore(client: LyftrClient, storage: StorageAdapter) {await storage.set(STORAGE_KEYS.user, JSON.stringify(data.user))set({ user: data.user, isAuthenticated: true, isLoading: false })} catch (err: any) {- set({ error: apiErrorMessage(err, 'Registration failed.', 'full'), isLoading: false })+ set({ error: { key: 'auth.register.failed', cause: err, detail: 'full' }, isLoading: false })throw err}},diff --git a/packages/shared/src/stores/language.test.ts b/packages/shared/src/stores/language.test.tsnew file mode 100644index 0000000..b134f3b--- /dev/null+++ b/packages/shared/src/stores/language.test.ts@@ -0,0 +1,61 @@+import { createLanguageStore } from './language'+import { i18n } from '../i18n'+import { createMemoryStorage } from '../testing/memoryStorage'++afterEach(async () => { await i18n.changeLanguage('en') })++describe('language store', () => {+ // Hydration gates app start on mobile, so an unreadable store must not strand it.+ it('hydrates as system when the stored value cannot be read', async () => {+ const storage = { ...createMemoryStorage(), get: async () => { throw new Error('keychain locked') } }+ const store = createLanguageStore(storage, () => ['es-ES'])+ await store.getState().hydrate()+ expect(store.getState().isHydrated).toBe(true)+ expect(store.getState().preference).toBe('system')+ expect(i18n.language).toBe('es')+ })++ it('still switches language when the choice cannot be saved', async () => {+ const storage = { ...createMemoryStorage(), set: async () => { throw new Error('private mode') } }+ const store = createLanguageStore(storage, () => ['en-US'])+ await store.getState().setPreference('es')+ expect(store.getState().preference).toBe('es')+ expect(i18n.language).toBe('es')+ })++ it('follows the device when nothing is stored', async () => {+ const store = createLanguageStore(createMemoryStorage(), () => ['es-ES'])+ await store.getState().hydrate()+ expect(store.getState().preference).toBe('system')+ expect(store.getState().isHydrated).toBe(true)+ expect(i18n.language).toBe('es')+ })++ it('a stored choice beats the device', async () => {+ const store = createLanguageStore(createMemoryStorage({ lyftr_language: 'en' }), () => ['es'])+ await store.getState().hydrate()+ expect(store.getState().preference).toBe('en')+ expect(i18n.language).toBe('en')+ })++ it('treats an unknown stored value as system', async () => {+ const store = createLanguageStore(createMemoryStorage({ lyftr_language: 'klingon' }), () => [])+ await store.getState().hydrate()+ expect(store.getState().preference).toBe('system')+ })++ it('persists and applies a new preference', async () => {+ const storage = createMemoryStorage()+ const store = createLanguageStore(storage, () => [])+ await store.getState().setPreference('es')+ expect(storage.dump()['lyftr_language']).toBe('es')+ expect(i18n.language).toBe('es')+ })++ it('falls back to English when detection throws', async () => {+ const store = createLanguageStore(createMemoryStorage(), () => { throw new Error('no module') })+ await store.getState().hydrate()+ expect(store.getState().isHydrated).toBe(true)+ expect(i18n.language).toBe('en')+ })+})diff --git a/packages/shared/src/stores/language.ts b/packages/shared/src/stores/language.tsnew file mode 100644index 0000000..cc1d210--- /dev/null+++ b/packages/shared/src/stores/language.ts@@ -0,0 +1,51 @@+import { create } from 'zustand'+import { StorageAdapter } from '../storage'+import { i18n, resolveLanguage, SUPPORTED_LANGUAGES, type LanguagePreference } from '../i18n'++// Device-level preference, persisted like theme. 'system' follows the device's language+// list; anything else pins one supported language.+const LANGUAGE_KEY = 'lyftr_language'++export type LanguageDetector = () => readonly string[]++export interface LanguageStore {+ preference: LanguagePreference+ isHydrated: boolean+ hydrate: () => Promise<void>+ setPreference: (p: LanguagePreference) => Promise<void>+}++const isPreference = (v: string | null): v is LanguagePreference =>+ v === 'system' || (v !== null && (SUPPORTED_LANGUAGES as string[]).includes(v))++export function createLanguageStore(storage: StorageAdapter, detectLanguages: LanguageDetector) {+ const safeTags = (): readonly string[] => {+ try {+ const tags = detectLanguages()+ return Array.isArray(tags) ? tags : []+ } catch {+ return []+ }+ }+ const apply = async (p: LanguagePreference) => {+ await i18n.changeLanguage(resolveLanguage(p, safeTags()))+ }+ return create<LanguageStore>((set) => ({+ preference: 'system',+ isHydrated: false,+ hydrate: async () => {+ // An unreadable store means "no preference", not a language screen that never+ // finishes loading: hydration gates app start on mobile.+ const stored = await storage.get(LANGUAGE_KEY).catch(() => null)+ const preference = isPreference(stored) ? stored : 'system'+ await apply(preference)+ set({ preference, isHydrated: true })+ },+ setPreference: async (p) => {+ // Apply first: a storage failure costs the choice surviving a restart, not the tap.+ set({ preference: p })+ await apply(p)+ await storage.set(LANGUAGE_KEY, p).catch(() => undefined)+ },+ }))+}diff --git a/packages/shared/src/utils/copyLocale.test.ts b/packages/shared/src/utils/copyLocale.test.tsnew file mode 100644index 0000000..cc4d792--- /dev/null+++ b/packages/shared/src/utils/copyLocale.test.ts@@ -0,0 +1,62 @@+import { i18n } from '../i18n'+import { differentRuleLabel, lengthRuleLabel, matchRuleLabel, MAX_PASSWORD_BYTES } from './passwordRules'+import { targetWeightLabel, weightError } from './weight'+import { dayLabel } from './programUtils'+import { formatLoggedAmount, maxAmountFor, scaleServing } from './food'+import { displayName } from './profile'+import { restLabel } from './workoutSets'+import type { FoodSearchResult, ProgramDay } from '../types'++// Copy returned by shared helpers is looked up when the helper runs. Each case switches the+// language to es, asserts the Spanish sentence, and the afterEach puts en back so no other+// test inherits it. The en assertions of the same helpers live in their own test files.+describe('shared helper copy in es', () => {+ beforeEach(async () => { await i18n.changeLanguage('es') })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('password rule labels', () => {+ expect(lengthRuleLabel('')).toBe('Al menos 8 caracteres')+ expect(lengthRuleLabel('a'.repeat(MAX_PASSWORD_BYTES + 1))).toBe('Máximo 72 caracteres (los acentos y los emoji cuentan como más)')+ expect(differentRuleLabel()).toBe('Distinta de tu contraseña actual')+ expect(matchRuleLabel('ok')).toBe('Las contraseñas coinciden')+ expect(matchRuleLabel('bad')).toBe('Las contraseñas no coinciden')+ expect(matchRuleLabel('pending')).toBe('Repite la nueva contraseña')+ })++ it('weight errors keep the number and the unit', () => {+ expect(weightError(0, 'lbs')).toBe('Ingresa un peso válido')+ expect(weightError(3000, 'lbs')).toBe('El peso debe ser menor de 2000 lb')+ expect(weightError(1000, 'kg')).toBe('El peso debe ser menor de 907 kg')+ })++ it('a bodyweight target reads as the es abbreviation, a loaded one keeps its unit', () => {+ expect(targetWeightLabel(0, 'lbs')).toBe('PC')+ expect(targetWeightLabel(135, 'lbs')).toBe('135 lbs')+ })++ it('program day names', () => {+ const day = (d: Partial<ProgramDay>) => d as ProgramDay+ expect(dayLabel(day({ is_rest_day: true }), 0)).toBe('Día de descanso')+ expect(dayLabel(day({}), 2)).toBe('Día 3')+ expect(dayLabel(day({ name: 'Push Day' }), 2)).toBe('Push Day')+ })++ it('servings pick the es plural form and keep the figure as written', () => {+ expect(formatLoggedAmount({ servings: 1 })).toBe('1 porción')+ expect(formatLoggedAmount({ servings: 0.5 })).toBe('0.5 porciones')+ expect(formatLoggedAmount({ servings: 2 })).toBe('2 porciones')+ expect(maxAmountFor(null)).toBe('100 porciones')+ expect(maxAmountFor({ quantity: 100, unit: 'g' })).toBe('10000 g')+ })++ it('a blank entry is stored with the English name, not the UI language', () => {+ const blank = { name: '', calories: 0, protein: 0, carbs: 0, fat: 0 } as FoodSearchResult+ expect(scaleServing(blank, 1).name).toBe('Custom entry')+ })++ it('the fallback for a missing name, and rest labels', () => {+ expect(displayName('', '')).toBe('usuario')+ expect(restLabel(45)).toBe('45 s')+ expect(restLabel(120)).toBe('2 min')+ })+})diff --git a/packages/shared/src/utils/dashboard.test.ts b/packages/shared/src/utils/dashboard.test.tsindex b11904a..7e70633 100644--- a/packages/shared/src/utils/dashboard.test.ts+++ b/packages/shared/src/utils/dashboard.test.ts@@ -1,5 +1,10 @@import { greeting, lifterQuip, muscleHex, muscleRoast, nextStartableDay } from './dashboard'import type { Program } from '../types'+import { i18n } from '../i18n'+import es from '../i18n/locales/es.json'++// Tests that switch language restore English, so no other test sees Spanish.+afterEach(() => i18n.changeLanguage('en'))describe('muscleHex', () => {it('resolves case-insensitively', () => {@@ -25,6 +30,18 @@ describe('muscleRoast', () => {it('falls back for an unknown muscle', () => {expect(muscleRoast('zzz')).toMatch(/Mysterious/)})++ it('keeps the English lines exactly as they were', () => {+ expect(muscleRoast('Chest')).toBe('All chest, no legs. Classic bro.')+ expect(muscleRoast('shoulders')).toBe("Can't fit through doorways. Good.")+ expect(muscleRoast('full body')).toBe('A true all-rounder. Or you just did burpees.')+ })++ it('reads the catalog when called, so es gets the Spanish line', async () => {+ await i18n.changeLanguage('es')+ expect(muscleRoast('chest')).toBe(es.home.muscleRoast.chest)+ expect(muscleRoast('zzz')).toBe(es.home.muscleRoast.fallback)+ })})describe('nextStartableDay', () => {@@ -73,19 +90,35 @@ describe('greeting', () => {const at = (h: number) => new Date(2026, 0, 15, h, 30)it('splits the day at noon and 5pm', () => {- expect(greeting(at(0))).toBe('Good morning')- expect(greeting(at(11))).toBe('Good morning')- expect(greeting(at(12))).toBe('Good afternoon')- expect(greeting(at(16))).toBe('Good afternoon')- expect(greeting(at(17))).toBe('Good evening')- expect(greeting(at(23))).toBe('Good evening')+ expect(greeting(at(0), 'Sam')).toBe('Good morning, Sam')+ expect(greeting(at(11), 'Sam')).toBe('Good morning, Sam')+ expect(greeting(at(12), 'Sam')).toBe('Good afternoon, Sam')+ expect(greeting(at(16), 'Sam')).toBe('Good afternoon, Sam')+ expect(greeting(at(17), 'Sam')).toBe('Good evening, Sam')+ expect(greeting(at(23), 'Sam')).toBe('Good evening, Sam')})it('reads the time it is given, not the clock', () => {// Taking `now` as an argument is what lets the caller sample it per mount; web// previously read a module-load constant, which went stale across midnight.- expect(greeting(at(9))).toBe('Good morning')- expect(greeting(at(21))).toBe('Good evening')+ expect(greeting(at(9), 'Sam')).toBe('Good morning, Sam')+ expect(greeting(at(21), 'Sam')).toBe('Good evening, Sam')+ })++ it('says "there" in English when there is no name', () => {+ // useDisplayName hands the common.there word to a nameless account; the sentence stays+ // what it always read.+ expect(greeting(at(9), 'there')).toBe('Good morning, there')+ expect(greeting(at(9))).toBe('Good morning, there')+ })++ it('in es puts the name in the sentence, and drops it when there is none', async () => {+ await i18n.changeLanguage('es')+ expect(greeting(at(9), 'Sam')).toBe('Buenos días, Sam')+ expect(greeting(at(14), 'Sam')).toBe('Buenas tardes, Sam')+ // The nameless word is "usuario" in es; the greeting must not read "Buenos días, usuario".+ expect(greeting(at(9), es.common.there)).toBe(es.home.greeting.morning_anonymous)+ expect(greeting(at(21), es.common.there)).toBe(es.home.greeting.evening_anonymous)})})describe('lifterQuip', () => {@@ -120,4 +153,49 @@ describe('lifterQuip', () => {it('needs only an account id', () => {expect(typeof lifterQuip(7)).toBe('string')})++ // The list as it was before the lines moved into the catalog. Selection is by index, so a+ // reordered or reworded key would silently change what a given person reads on a given day.+ const BEFORE = [+ 'The bar does not care how you feel about it.',+ 'Progressive overload: the only pyramid scheme that works.',+ 'Nobody has ever regretted the warm-up.',+ 'The hardest rep is the one that gets you off the couch.',+ 'Form first. Ego lifts are for the parking lot.',+ 'Legs are not optional. They are just unpopular.',+ 'Chalk is not a personality. It helps, though.',+ 'You cannot out-train a log you never fill in.',+ 'Deload weeks count. Reluctantly.',+ 'Mirror check later. Barbell now.',+ 'Half reps, full lies.',+ 'The only bad set is the one you talked yourself out of.',+ 'Somewhere a squat rack is holding a coat. Not yours.',+ 'Showing up is the part most people skip.',+ 'Protein is not optional. Neither is sleep.',+ 'Rest is part of the plan, not a gap in it.',+ ]+ const indexFor = (id: string | number, day: string) => {+ const key = `${day}:${id}`+ let sum = 0+ for (let i = 0; i < key.length; i++) sum += key.charCodeAt(i)+ return sum % BEFORE.length+ }++ it('picks the same English line for the same account and day as before', () => {+ const seen = new Set<number>()+ for (const id of [1, 7, 42, 'abc', 9001]) {+ for (let d = 1; d <= 28; d++) {+ const day = `2026-10-${String(d).padStart(2, '0')}`+ expect(lifterQuip(id, day)).toBe(BEFORE[indexFor(id, day)])+ seen.add(indexFor(id, day))+ }+ }+ expect(seen.size).toBe(BEFORE.length) // every line was exercised+ })++ it('picks the same line in es, translated', async () => {+ await i18n.changeLanguage('es')+ const lines = Object.values(es.home.quip)+ expect(lifterQuip(7, '2026-10-06')).toBe(lines[indexFor(7, '2026-10-06')])+ })})diff --git a/packages/shared/src/utils/dashboard.ts b/packages/shared/src/utils/dashboard.tsindex ac3f8bd..f365b27 100644--- a/packages/shared/src/utils/dashboard.ts+++ b/packages/shared/src/utils/dashboard.ts@@ -1,6 +1,8 @@import type { Program, ProgramDay } from '../types'import { isDayStartable, todaysDay } from './programUtils'import { todayStr } from './dateUtils'+import { i18n } from '../i18n'+import type en from '../i18n/locales/en.json'// Per-muscle accent for the dashboard's training-split chart. Hex rather than theme// tokens for the same reason as MACRO_COLORS: both platforms hand these to drawing@@ -14,63 +16,70 @@ const MUSCLE_HEX: Record<string, string> = {export const muscleHex = (m: string): string => MUSCLE_HEX[m?.toLowerCase()] ?? '#6366f1'-// Copy for the dashboard's "most-trained muscle" line. Product copy duplicated across-// platforms is the quietest kind of drift — nothing breaks, the two apps just start-// saying different things — so it lives in one place.-const MUSCLE_ROAST: Record<string, string> = {- chest: 'All chest, no legs. Classic bro.',- back: 'Built like a refrigerator. Respect.',- shoulders: "Can't fit through doorways. Good.",- biceps: 'Mirror selfies loading…',- triceps: 'Horseshoe gang. Handshakes must be terrifying.',- legs: "Actually training legs. You're a unicorn.",- quadriceps: "Quads for days. Jeans don't stand a chance.",- hamstrings: 'Posterior chain warrior. Deadlift god incoming.',- glutes: 'Glute guy/gal. We respect the commitment.',- calves: 'Calf king/queen. The rarest of all lifters.',- core: 'Beach season ready 365 days a year.',- abs: 'Six pack incoming. Or already here. Either way.',- forearms: 'Popeye called. He wants his arms back.',- traps: 'No neck, no problem.',- lats: 'Walking around like a cobra. Wings deployed.',- 'full body': 'A true all-rounder. Or you just did burpees.',+// The key behind the dashboard's "most-trained muscle" line, per muscle. Product copy+// duplicated across platforms is the quietest kind of drift — nothing breaks, the two apps+// just start saying different things — so it lives in one catalog. Keys, not text: the line+// is looked up when drawn, so it follows a language switch.+type RoastKey = `home.muscleRoast.${keyof typeof en.home.muscleRoast}`+const MUSCLE_ROAST: Record<string, RoastKey> = {+ chest: 'home.muscleRoast.chest',+ back: 'home.muscleRoast.back',+ shoulders: 'home.muscleRoast.shoulders',+ biceps: 'home.muscleRoast.biceps',+ triceps: 'home.muscleRoast.triceps',+ legs: 'home.muscleRoast.legs',+ quadriceps: 'home.muscleRoast.quadriceps',+ hamstrings: 'home.muscleRoast.hamstrings',+ glutes: 'home.muscleRoast.glutes',+ calves: 'home.muscleRoast.calves',+ core: 'home.muscleRoast.core',+ abs: 'home.muscleRoast.abs',+ forearms: 'home.muscleRoast.forearms',+ traps: 'home.muscleRoast.traps',+ lats: 'home.muscleRoast.lats',+ 'full body': 'home.muscleRoast.full-body',}export const muscleRoast = (m: string): string =>- MUSCLE_ROAST[m?.toLowerCase()] ?? 'Mysterious training patterns. We respect it.'+ i18n.t(MUSCLE_ROAST[m?.toLowerCase()] ?? 'home.muscleRoast.fallback')-// Time-of-day greeting on the dashboard. Takes the current time rather than reading the-// clock itself, so the caller controls when "now" is sampled — and so this is testable-// without faking timers.-export function greeting(now: Date): string {+// Time-of-day greeting on the dashboard, as the whole sentence: "Good morning, Sam" is not+// "Good morning" + ", " + name, because word order and punctuation belong to the language.+// Takes the current time rather than reading the clock itself, so the caller controls when+// "now" is sampled — and so this is testable without faking timers.+//+// `name` is what useDisplayName returned, which is never empty: with neither a name nor an+// email it is the common.there word. That word means "no name", and the sentence for it is+// its own ('Buenos días', not 'Buenos días, usuario'), picked with the 'anonymous' context.+export function greeting(now: Date, name?: string): string {const h = now.getHours()- if (h < 12) return 'Good morning'- if (h < 17) return 'Good afternoon'- return 'Good evening'+ const band = h < 12 ? 'morning' : h < 17 ? 'afternoon' : 'evening'+ const anonymous = !name || name === i18n.t('common.there')+ return i18n.t(`home.greeting.${band}`, { name, context: anonymous ? 'anonymous' : undefined })}// The line under the greeting. Same voice as MUSCLE_ROAST above — dry, second person,// on the lifter's side. None of these are about how the person looks, and none of them// scold: this is the first thing they read every time they open the app, and a nag you// cannot dismiss stops being funny on about day three.-const LIFTER_QUIPS: string[] = [- 'The bar does not care how you feel about it.',- 'Progressive overload: the only pyramid scheme that works.',- 'Nobody has ever regretted the warm-up.',- 'The hardest rep is the one that gets you off the couch.',- 'Form first. Ego lifts are for the parking lot.',- 'Legs are not optional. They are just unpopular.',- 'Chalk is not a personality. It helps, though.',- 'You cannot out-train a log you never fill in.',- 'Deload weeks count. Reluctantly.',- 'Mirror check later. Barbell now.',- 'Half reps, full lies.',- 'The only bad set is the one you talked yourself out of.',- 'Somewhere a squat rack is holding a coat. Not yours.',- 'Showing up is the part most people skip.',- 'Protein is not optional. Neither is sleep.',- 'Rest is part of the plan, not a gap in it.',-]+const QUIP_KEYS = [+ 'home.quip.barDoesNotCare',+ 'home.quip.progressiveOverload',+ 'home.quip.warmUp',+ 'home.quip.couch',+ 'home.quip.formFirst',+ 'home.quip.legs',+ 'home.quip.chalk',+ 'home.quip.unfilledLog',+ 'home.quip.deload',+ 'home.quip.mirror',+ 'home.quip.halfReps',+ 'home.quip.badSet',+ 'home.quip.squatRack',+ 'home.quip.showingUp',+ 'home.quip.proteinSleep',+ 'home.quip.rest',+] as const// Derived, not random: the dashboard re-renders on every fetch, refresh and tab return,// so Math.random() would rewrite the sentence while it was being read.@@ -85,7 +94,7 @@ export function lifterQuip(accountId: string | number, day: string = todayStr())const key = `${day}:${accountId}`let sum = 0for (let i = 0; i < key.length; i++) sum += key.charCodeAt(i)- return LIFTER_QUIPS[sum % LIFTER_QUIPS.length]+ return i18n.t(QUIP_KEYS[sum % QUIP_KEYS.length])}// The "up next" card: the first program whose day-for-today actually has exercises.diff --git a/packages/shared/src/utils/dateUtils.test.ts b/packages/shared/src/utils/dateUtils.test.tsindex aa578de..4d4bde6 100644--- a/packages/shared/src/utils/dateUtils.test.ts+++ b/packages/shared/src/utils/dateUtils.test.ts@@ -1,4 +1,5 @@-import { todayStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay, memberSince, withLoggedOn, formatDay, UNKNOWN_DAY } from './dateUtils'+import { todayStr, daysAgoStr, dayToInstant, dayToLocalDate, instantToDay, entryDay, workoutDay, memberSince, withLoggedOn, formatDay, formatDate, relativeDayLabel, defaultWorkoutName, UNKNOWN_DAY, type DateFormatName } from './dateUtils'+import { i18n } from '../i18n'describe('dayToInstant', () => {@@ -190,8 +191,8 @@ describe('instantToDay — an unreadable instant has no day', () => {// confident "Jan 1, 1900". Both were observed in the running app.describe('formatDay', () => {it('draws a real day', () => {- expect(formatDay('2026-08-01', 'MMM d, yyyy')).toBe('Aug 1, 2026')- expect(formatDay('2026-08-01', 'M/d')).toBe('8/1')+ expect(formatDay('2026-08-01', 'monthDayYear')).toBe('Aug 1, 2026')+ expect(formatDay('2026-08-01', 'numericMonthDay')).toBe('8/1')})it.each([@@ -203,25 +204,25 @@ describe('formatDay', () => {['null', null],['undefined', undefined],])('reads as unknown when the day is %s', (_label, day) => {- expect(formatDay(day as string, 'MMM d, yyyy')).toBe(UNKNOWN_DAY)+ expect(formatDay(day as string, 'monthDayYear')).toBe(UNKNOWN_DAY)})it('never renders a 1900 for a day it could not read', () => {// The specific lie: Number('') === 0, and new Date(0, -1, 1) is a valid 1899.- expect(formatDay('', 'MMM d, yyyy')).not.toContain('1900')- expect(formatDay('', 'MMM d, yyyy')).not.toContain('1899')+ expect(formatDay('', 'monthDayYear')).not.toContain('1900')+ expect(formatDay('', 'monthDayYear')).not.toContain('1899')})it('never throws, whatever it is handed', () => {for (const bad of ['', 'x', 'NaN-NaN-NaN', '9999999-01-01', '0000-00-00']) {- expect(() => formatDay(bad, 'EEEE, MMMM d, yyyy')).not.toThrow()+ expect(() => formatDay(bad, 'weekdayDate')).not.toThrow()}})it('composes with the day helpers, so an unreadable row reads as unknown end to end', () => {- expect(formatDay(workoutDay({ started_at: 'not-a-date' }), 'MMM d, yyyy')).toBe(UNKNOWN_DAY)- expect(formatDay(entryDay({ logged_at: '' }), 'MMM d, yyyy')).toBe(UNKNOWN_DAY)- expect(formatDay(workoutDay({ started_at: '2026-08-01T10:00:00Z', tz_offset_minutes: 0 }), 'MMM d, yyyy'))+ expect(formatDay(workoutDay({ started_at: 'not-a-date' }), 'monthDayYear')).toBe(UNKNOWN_DAY)+ expect(formatDay(entryDay({ logged_at: '' }), 'monthDayYear')).toBe(UNKNOWN_DAY)+ expect(formatDay(workoutDay({ started_at: '2026-08-01T10:00:00Z', tz_offset_minutes: 0 }), 'monthDayYear')).toBe('Aug 1, 2026')})})@@ -249,4 +250,95 @@ describe('memberSince', () => {expect(memberSince('2026-09-01T00:30:00Z')).toBe('September 2026')expect(memberSince('2026-08-31T23:30:00Z')).toBe('August 2026')})++ // The month name follows the app language; the UTC reading does not change with it.+ describe('in es', () => {+ beforeEach(async () => { await i18n.changeLanguage('es') })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('spells the month in Spanish', () => {+ expect(memberSince('2026-08-19T14:30:00Z')).toBe('agosto de 2026')+ expect(memberSince('2026-08-31T23:30:00Z')).toBe('agosto de 2026')+ })++ it('still reads as unknown for a missing timestamp', () => {+ expect(memberSince(undefined)).toBe('—')+ })+ })+})++// The en value of each name is the pattern the screens used before the patterns moved into the+// catalog, so English output cannot have changed. 2026-10-10 is a Saturday.+describe('display format names', () => {+ const day = '2026-10-10'+ const en: Record<DateFormatName, string> = {+ monthDay: 'Oct 10',+ monthDayYear: 'Oct 10, 2026',+ numericMonthDay: '10/10',+ weekdayDate: 'Saturday, October 10, 2026',+ monthShort: 'Oct',+ longDate: 'October 10, 2026',+ weekdayNarrow: 'S',+ weekdayMonthDayLong: 'Saturday, October 10',+ weekdayMonthDay: 'Sat, Oct 10',+ weekdayMonthDayYear: 'Sat, Oct 10, 2026',+ year: '2026',+ monthYearLong: 'October 2026',+ }++ it.each(Object.entries(en))('en %s', (name, expected) => {+ expect(formatDay(day, name as DateFormatName)).toBe(expected)+ expect(formatDate(dayToLocalDate(day), name as DateFormatName)).toBe(expected)+ })++ describe('in es', () => {+ beforeEach(async () => { await i18n.changeLanguage('es') })+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reorders and translates', () => {+ expect(formatDay(day, 'monthDay')).toBe('10 oct')+ expect(formatDay(day, 'numericMonthDay')).toBe('10/10')+ expect(formatDay('2026-08-01', 'numericMonthDay')).toBe('1/8')+ expect(formatDay(day, 'weekdayDate')).toBe('sábado, 10 de octubre de 2026')+ expect(formatDay(day, 'monthYearLong')).toBe('octubre de 2026')+ })++ it('keeps an unknown day unknown', () => {+ expect(formatDay('', 'monthDay')).toBe(UNKNOWN_DAY)+ })+ })+})++describe('relativeDayLabel', () => {+ it('names today and yesterday, else the weekday and date', () => {+ expect(relativeDayLabel(todayStr())).toBe('Today')+ expect(relativeDayLabel(daysAgoStr(1))).toBe('Yesterday')+ expect(relativeDayLabel('2020-10-10')).toBe('Sat, Oct 10')+ })++ it('follows the language (es)', async () => {+ await i18n.changeLanguage('es')+ try {+ expect(relativeDayLabel(todayStr())).toBe('Hoy')+ expect(relativeDayLabel(daysAgoStr(1))).toBe('Ayer')+ expect(relativeDayLabel('2020-10-10')).toBe('sáb, 10 oct')+ } finally {+ await i18n.changeLanguage('en')+ }+ })+})++describe('defaultWorkoutName', () => {+ it('is "Workout — " and the short date', () => {+ expect(defaultWorkoutName(new Date(2026, 9, 10, 8))).toBe('Workout — Oct 10')+ })++ it('is Spanish in es', async () => {+ await i18n.changeLanguage('es')+ try {+ expect(defaultWorkoutName(new Date(2026, 9, 10, 8))).toBe('Entrenamiento — 10 oct')+ } finally {+ await i18n.changeLanguage('en')+ }+ })})diff --git a/packages/shared/src/utils/dateUtils.ts b/packages/shared/src/utils/dateUtils.tsindex 45fa9c3..11f28e4 100644--- a/packages/shared/src/utils/dateUtils.ts+++ b/packages/shared/src/utils/dateUtils.ts@@ -1,4 +1,8 @@import { format } from 'date-fns'+import { es } from 'date-fns/locale/es'+import type { Locale } from 'date-fns'+import type en from '../i18n/locales/en.json'+import { i18n } from '../i18n'// The one place a calendar day is produced or read on the client.//// The model, which is the one Fitbit, Garmin, Strava and Health Connect all use: a@@ -174,6 +178,22 @@ export const UNKNOWN_DAY = '—'const DAY_RE = /^\d{4}-\d{2}-\d{2}$/+/**+ * A display format is a NAME, not a pattern. The pattern behind each name lives in the+ * catalog (`common.dateFormat.*`) because word order is part of a language: "Oct 10" is+ * "10 oct" in Spanish, and "8/1" is "1/8". Machine formats ('yyyy-MM-dd') are not copy and+ * stay plain date-fns calls at their sites.+ */+export type DateFormatName = keyof typeof en.common.dateFormat++// Imported from the subpath so Metro does not bundle every locale date-fns ships. English+// is date-fns's own default and needs no entry.+const DATE_LOCALES: Record<string, Locale> = { es }++/** A Date, drawn in the app language. Looked up when called, never at module load. */+export const formatDate = (d: Date, name: DateFormatName): string =>+ format(d, i18n.t(`common.dateFormat.${name}`), { locale: DATE_LOCALES[i18n.language] })+/*** A calendar day, drawn. The single point of truth for turning a `YYYY-MM-DD` into text* a person reads — the day equivalent of `formatNumber`, and the only place the idiom@@ -190,20 +210,15 @@ const DAY_RE = /^\d{4}-\d{2}-\d{2}$/* A day we cannot read has to read as unknown. Validating the day STRING rather than the* resulting Date is what separates the two cases, since only one of them is NaN.*/-export const formatDay = (day: string | null | undefined, pattern: string): string => {+export const formatDay = (day: string | null | undefined, name: DateFormatName): string => {if (!day || !DAY_RE.test(day)) return UNKNOWN_DAYconst d = dayToLocalDate(day)// '2026-13-45' matches the shape but rolls over into another month; a day that does// not survive the round trip was never a real one.if (Number.isNaN(d.getTime()) || instantToDay(d.toISOString()) !== day) return UNKNOWN_DAY- return format(d, pattern)+ return formatDate(d, name)}-const MONTH_NAMES = [- 'January', 'February', 'March', 'April', 'May', 'June',- 'July', 'August', 'September', 'October', 'November', 'December',-]-/*** "August 2026" for the Settings → Member since row, or "—" when there is nothing real* to show.@@ -216,13 +231,27 @@ const MONTH_NAMES = [** Read in UTC on purpose. Unlike the day-scoped rows above, `created_at` is a bare* instant with no stored offset, so deriving the month from the reader's clock would move- * someone's join date across a month boundary purely by travelling. Month names are- * spelled out here rather than via toLocaleDateString so both apps render identically- * regardless of the Intl data the runtime happens to ship.+ * someone's join date across a month boundary purely by travelling. The month name comes+ * from date-fns, so both apps render identically regardless of the Intl data the runtime+ * happens to ship.*/export const memberSince = (iso?: string): string => {- if (!iso) return '—'+ if (!iso) return UNKNOWN_DAYconst d = new Date(iso)- if (Number.isNaN(d.getTime()) || d.getUTCFullYear() < 2000) return '—'- return `${MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCFullYear()}`+ if (Number.isNaN(d.getTime()) || d.getUTCFullYear() < 2000) return UNKNOWN_DAY+ return formatDate(new Date(d.getUTCFullYear(), d.getUTCMonth(), 1, 12), 'monthYearLong')}++/**+ * Today / Yesterday for the diary's day picker, else the weekday and date. Looked up when+ * called so it follows a language switch; callers must render under useTranslation().+ */+export const relativeDayLabel = (day: string): string => {+ if (day === todayStr()) return i18n.t('common.day.today')+ if (day === daysAgoStr(1)) return i18n.t('common.day.yesterday')+ return formatDay(day, 'weekdayMonthDay')+}++/** The name a quick-start workout gets: "Workout — Oct 10". Stored, so never re-translated. */+export const defaultWorkoutName = (now: Date = new Date()): string =>+ i18n.t('workouts.defaultName', { date: formatDate(now, 'monthDay') })diff --git a/packages/shared/src/utils/exerciseUtils.test.ts b/packages/shared/src/utils/exerciseUtils.test.tsindex 79e6db4..35aa328 100644--- a/packages/shared/src/utils/exerciseUtils.test.ts+++ b/packages/shared/src/utils/exerciseUtils.test.ts@@ -1,4 +1,5 @@-import { EQUIPMENT_LABEL, resolveMuscleSlugs } from './exerciseUtils'+import { i18n } from '../i18n'+import { categoryLabel, equipmentLabel, 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.@@ -31,9 +32,84 @@ describe('resolveMuscleSlugs', () => {})})-describe('EQUIPMENT_LABEL', () => {- it('maps the exercise DB\'s raw equipment strings to friendly labels', () => {- expect(EQUIPMENT_LABEL['body only']).toBe('Bodyweight')- expect(EQUIPMENT_LABEL['kettlebells']).toBe('Kettlebell')+// The table equipmentLabel replaced, kept here so English is pinned to what it rendered.+const OLD_EQUIPMENT_LABEL: Record<string, string> = {+ 'body-only': 'Bodyweight', 'barbell': 'Barbell', 'dumbbell': 'Dumbbell', 'machine': 'Machine',+ 'cable': 'Cable', 'kettlebells': 'Kettlebell', 'bands': 'Bands', 'medicine-ball': 'Med Ball',+ 'e-z-curl-bar': 'EZ Bar', 'exercise-ball': 'Exercise Ball', 'foam-roll': 'Foam Roll',+ 'none': 'None', 'other': 'Other',+ 'body only': 'Bodyweight', 'medicine ball': 'Med Ball', 'e-z curl bar': 'EZ Bar',+ 'exercise ball': 'Exercise Ball', 'foam roll': 'Foam Roll',+}++afterEach(async () => { await i18n.changeLanguage('en') })++describe('equipmentLabel', () => {+ it('gives every raw key and pre-migration alias the label the old table did (en)', () => {+ for (const [raw, label] of Object.entries(OLD_EQUIPMENT_LABEL)) {+ expect({ raw, label: equipmentLabel(raw) }).toEqual({ raw, label })+ }+ })++ it('passes an unknown or empty value through as it came', () => {+ expect(equipmentLabel('sandbag')).toBe('sandbag')+ expect(equipmentLabel('')).toBe('')+ expect(equipmentLabel(undefined)).toBe('')+ })++ it('reads in the active language (es), spaced and hyphenated spellings alike', async () => {+ await i18n.changeLanguage('es')+ expect(equipmentLabel('body-only')).toBe('Peso corporal')+ expect(equipmentLabel('body only')).toBe('Peso corporal')+ expect(equipmentLabel('sandbag')).toBe('sandbag')+ })+})++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']) {+ expect(muscleLabel(slug)).toBe(slug)+ }+ })++ 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')+ expect(muscleLabel('Chest')).toBe('Chest')+ expect(muscleLabel('')).toBe('')+ expect(muscleLabel(undefined)).toBe('')+ })++ it('reads in the active language (es)', async () => {+ await i18n.changeLanguage('es')+ expect(muscleLabel('lower-back')).toBe('espalda baja')+ expect(muscleLabel('chest')).toBe('pecho')+ })+})++describe('categoryLabel', () => {+ it('gives the slug back unchanged in en, as the screens rendered it before the catalog', () => {+ for (const slug of ['strength', 'stretching', 'plyometrics', 'strongman', 'powerlifting', 'cardio', 'olympic-weightlifting']) {+ expect(categoryLabel(slug)).toBe(slug)+ }+ })++ it('reads the pre-migration spaced spelling as the hyphenated slug', () => {+ expect(categoryLabel('olympic weightlifting')).toBe('olympic-weightlifting')+ })++ it('passes an unknown or empty value through as it came', () => {+ expect(categoryLabel('flexibility')).toBe('flexibility')+ expect(categoryLabel('')).toBe('')+ expect(categoryLabel(undefined)).toBe('')+ })++ it('reads in the active language (es), spaced and hyphenated spellings alike', async () => {+ await i18n.changeLanguage('es')+ expect(categoryLabel('strength')).toBe('fuerza')+ expect(categoryLabel('plyometrics')).toBe('pliometría')+ expect(categoryLabel('olympic-weightlifting')).toBe('halterofilia')+ expect(categoryLabel('olympic weightlifting')).toBe('halterofilia')+ expect(categoryLabel('flexibility')).toBe('flexibility')})})diff --git a/packages/shared/src/utils/exerciseUtils.ts b/packages/shared/src/utils/exerciseUtils.tsindex dc47073..392805b 100644--- a/packages/shared/src/utils/exerciseUtils.ts+++ b/packages/shared/src/utils/exerciseUtils.ts@@ -14,34 +14,55 @@//// The *lookup rule* over those tables is identical on both sides, so it lives here.-// Keys are open-exercise-db's equipment slugs, which is what the API now serves.+import { i18n } from '../i18n'++// 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+// (a custom exercise, a value upstream added since) is shown as it came rather than dropped.+//+// Equipment keeps the spaced spellings ("body only", "medicine ball", "e-z curl bar") that+// free-exercise-db wrote: a self-hosted instance that has not yet run the taxonomy migration+// still holds rows spelled that way, so the lookup reads a space as the hyphen rather than+// letting those rows degrade to raw values with nothing to explain why.//-// The spaced spellings below them are the same vocabulary as free-exercise-db wrote-// it, and they stay as aliases rather than being replaced: a self-hosted instance-// that has not yet run the taxonomy migration still holds rows spelled that way, and-// a label table that silently stopped matching them would degrade to raw values in-// the UI with nothing to explain why.-export const EQUIPMENT_LABEL: Record<string, string> = {- 'body-only': 'Bodyweight',- 'barbell': 'Barbell',- 'dumbbell': 'Dumbbell',- 'machine': 'Machine',- 'cable': 'Cable',- 'kettlebells': 'Kettlebell',- 'bands': 'Bands',- 'medicine-ball': 'Med Ball',- 'e-z-curl-bar': 'EZ Bar',- 'exercise-ball': 'Exercise Ball',- 'foam-roll': 'Foam Roll',- 'none': 'None',- 'other': 'Other',-- // Pre-migration spellings.- 'body only': 'Bodyweight',- 'medicine ball': 'Med Ball',- 'e-z curl bar': 'EZ Bar',- 'exercise ball': 'Exercise Ball',- 'foam roll': 'Foam Roll',+// The English muscle labels are the slugs themselves, not title-cased: that is what the+// screens always rendered, and the ones that capitalised did it in CSS. So a muscle is+// matched exactly, and each screen keeps whatever casing it already applied.+const EQUIPMENT_SLUGS = [+ 'body-only', 'barbell', 'dumbbell', 'machine', 'cable', 'kettlebells', 'bands',+ 'medicine-ball', 'e-z-curl-bar', 'exercise-ball', 'foam-roll', 'none', 'other',+] as const++const MUSCLE_SLUGS = [+ 'abdominals', 'abductors', 'abs', 'adductors', 'back', 'biceps', 'calves', 'chest', 'core',+ 'forearms', 'full-body', 'glutes', 'hamstrings', 'lats', 'legs', 'lower-back', 'middle-back',+ 'neck', 'obliques', 'other', 'quadriceps', 'shoulders', 'traps', 'triceps',+] as const++const CATEGORY_SLUGS = [+ 'strength', 'stretching', 'plyometrics', 'strongman', 'powerlifting', 'cardio', 'olympic-weightlifting',+] as const++const slugOf = (raw: string | undefined | null): string => (raw ?? '').trim().toLowerCase().replace(/\s+/g, '-')++const isOneOf = <T extends string>(list: readonly T[], s: string): s is T => (list as readonly string[]).includes(s)++export function equipmentLabel(raw: string | undefined | null): string {+ const slug = slugOf(raw)+ return isOneOf(EQUIPMENT_SLUGS, slug) ? i18n.t(`exercises.equipment.${slug}`) : (raw ?? '')+}++// Category reads like equipment: the pre-migration "olympic weightlifting" spelling is still+// held by instances that have not run the taxonomy migration. English is the slug itself, as+// with muscles; the screens keep their CSS capitalize.+export function categoryLabel(raw: string | undefined | null): string {+ const slug = slugOf(raw)+ return isOneOf(CATEGORY_SLUGS, slug) ? i18n.t(`exercises.category.${slug}`) : (raw ?? '')+}++export function muscleLabel(raw: string | undefined | null): string {+ const slug = raw ?? ''+ return isOneOf(MUSCLE_SLUGS, slug) ? i18n.t(`exercises.muscle.${slug}`) : slug}// Resolve a muscle name to body-diagram slugs against the caller's table: exact matchdiff --git a/packages/shared/src/utils/food.test.ts b/packages/shared/src/utils/food.test.tsindex 42fd343..6ad3a88 100644--- a/packages/shared/src/utils/food.test.ts+++ b/packages/shared/src/utils/food.test.ts@@ -1,4 +1,5 @@-import { amountForServings, MAX_SERVINGS, maxAmountFor, eanModules, entryToResult, findSavedFood, foodResultKey, formatBarcode, formatLoggedAmount, formatServings, isDailyStats, normaliseFoodKey, savedToResult, scaledFigures, scaleServing, servingBasis, servingsForAmount } from './food'+import { i18n } from '../i18n'+import { storedFoodName, storedServingSize, amountForServings, MAX_SERVINGS, maxAmountFor, eanModules, entryToResult, findSavedFood, foodResultKey, formatBarcode, formatLoggedAmount, formatServings, isDailyStats, normaliseFoodKey, savedToResult, scaledFigures, scaleServing, servingBasis, servingsForAmount } from './food'import type { FoodLog, SavedFood } from '../types'const log = (over: Partial<FoodLog> = {}): FoodLog => ({@@ -378,3 +379,15 @@ describe('formatServings', () => {expect(formatServings(0)).toBe(0)})})++describe('stored defaults', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('stay English while the UI is Spanish, so saved rows and favourite matching do not depend on the language', async () => {+ await i18n.changeLanguage('es')+ expect(i18n.t('food.servings', { count: 1 })).not.toBe('1 serving')+ expect(storedServingSize()).toBe('1 serving')+ expect(storedFoodName()).toBe('Custom entry')+ expect(scaleServing({ name: '', calories: 100, protein: 1, carbs: 1, fat: 1, fiber: 0 } as never, 1).name).toBe('Custom entry')+ })+})diff --git a/packages/shared/src/utils/food.ts b/packages/shared/src/utils/food.tsindex 53ca035..f024da4 100644--- a/packages/shared/src/utils/food.ts+++ b/packages/shared/src/utils/food.ts@@ -1,4 +1,13 @@import type { FoodLog, FoodSearchResult, SavedFood } from '../types'+import { i18n } from '../i18n'++// Defaults that get POSTed (diary entries, favourites) are written in English whatever the+// UI language is. A diary or favourite row outlives the language it was logged in, and+// favourites are matched on these fields, so a Spanish "1 porción" would never match the+// "1 serving" the same food was saved with. Anything merely displayed translates at render.+const storedT = () => i18n.getFixedT('en')+export const storedFoodName = () => storedT()('food.customEntry')+export const storedServingSize = () => storedT()('food.servings', { count: 1 })// A logged entry stores macros for the servings the user actually ate; a// FoodSearchResult is always per single serving, because the detail view multiplies@@ -37,7 +46,7 @@ export function entryToResult(e: FoodLog): FoodSearchResult {// toFixed(1) matches the 0.1 precision used everywhere else numbers are entered.export function scaleServing(r: FoodSearchResult, servings: number) {return {- name: r.name || 'Custom entry',+ name: r.name || storedFoodName(),// Carried onto the log so a diary entry still knows which product it was. Without// it every Recent row compares as brand '', so a branded favourite shows an empty// star there and starring it creates a second, brandless row.@@ -114,7 +123,7 @@ export function formatLoggedAmount(const basis = servingBasis(e)if (basis) return `${amountForServings(servings, basis)} ${basis.unit}`const n = formatServings(servings)- return `${n} ${n === 1 ? 'serving' : 'servings'}`+ return i18n.t('food.servings', { count: n })}// A saved food is already stored per serving, so it maps across untouched.@@ -170,7 +179,7 @@ export const MAX_SERVINGS = 100export function maxAmountFor(basis: ServingBasis | null): string {return basis? `${+(MAX_SERVINGS * basis.quantity).toFixed(1)} ${basis.unit}`- : `${MAX_SERVINGS} servings`+ : i18n.t('food.servings', { count: MAX_SERVINGS })}export interface ScaledFigures {diff --git a/packages/shared/src/utils/networkError.test.ts b/packages/shared/src/utils/networkError.test.tsindex bc3fa27..f226843 100644--- a/packages/shared/src/utils/networkError.test.ts+++ b/packages/shared/src/utils/networkError.test.ts@@ -1,4 +1,7 @@import { classifyNetworkError, nativeErrorDetail, networkFailureMessage } from './networkError'+import { i18n } from '../i18n'+import en from '../i18n/locales/en.json'+import es from '../i18n/locales/es.json'// Builds the shape axios actually produces on React Native: message is always the literal// 'Network Error' (RN dispatches a bare Event with no .message), and the real reason is@@ -175,3 +178,29 @@ describe('brief vs full', () => {expect(networkFailureMessage(odd, 'brief')).not.toMatch(/ENETUNREACH/)})})++// The wording is looked up when the message is built, not when the module loads: a reader+// who switches language between two failures gets each in the language they had chosen.+describe('networkFailureMessage in es', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reads the es catalog after a language switch, and en again after restoring', async () => {+ const timeout = { code: 'ECONNABORTED' }+ expect(networkFailureMessage(timeout)).toBe(en.errors.network.brief.timeout)+ await i18n.changeLanguage('es')+ expect(networkFailureMessage(timeout)).toBe(es.errors.network.brief.timeout)+ expect(networkFailureMessage(timeout, 'full')).toBe(es.errors.network.full.timeout)+ await i18n.changeLanguage('en')+ expect(networkFailureMessage(timeout)).toBe(en.errors.network.brief.timeout)+ })++ it('keeps the raw native reason after the translated sentence', async () => {+ await i18n.changeLanguage('es')+ const odd = { request: { _response: 'ENETUNREACH somewhere deep in okhttp' } }+ expect(networkFailureMessage(odd, 'full')).toBe(+ es.errors.network.full.withDetail+ .replace('{{message}}', es.errors.network.full.unknownNative)+ .replace('{{detail}}', 'ENETUNREACH somewhere deep in okhttp'),+ )+ })+})diff --git a/packages/shared/src/utils/networkError.ts b/packages/shared/src/utils/networkError.tsindex 734c236..b9ae303 100644--- a/packages/shared/src/utils/networkError.ts+++ b/packages/shared/src/utils/networkError.ts@@ -1,3 +1,5 @@+import { i18n } from '../i18n'+// Classifies transport-level failures (no HTTP response) into something actionable.//// Why this exists: axios reports every response-less failure identically. RN's XHR@@ -87,44 +89,44 @@ export type MessageDetail = 'brief' | 'full'// Each one names the cause and, where the fix is somewhere the user can go, points at it.// A short message that offers no way forward is not brief, it is unhelpful.-const BRIEF: Record<NetworkFailure, string> = {- 'cleartext-blocked': 'Blocked because the server URL uses http://. Check Server settings.',- 'certificate-untrusted': "The server's certificate isn't trusted by this device. Check Server settings.",- 'hostname-mismatch': "The server's certificate doesn't cover this address. Check Server settings.",- timeout: "The server didn't respond in time. Try again in a moment.",- unreachable: "Couldn't reach the server. Check that it's running.",+// Catalog keys, not text: the sentence is looked up when it is shown, so it follows the+// language the reader has chosen by then rather than the one the module loaded in.+const BRIEF = {+ 'cleartext-blocked': 'errors.network.brief.cleartextBlocked',+ 'certificate-untrusted': 'errors.network.brief.certificateUntrusted',+ 'hostname-mismatch': 'errors.network.brief.hostnameMismatch',+ timeout: 'errors.network.brief.timeout',+ unreachable: 'errors.network.brief.unreachable',// No raw native string here: in full it is diagnostic gold, in a sheet it is noise.- unknown: "Can't reach the server right now.",-}+ unknown: 'errors.network.brief.unknown',+} as const satisfies Record<NetworkFailure, string>export const networkFailureMessage = (err: any, detail: MessageDetail = 'brief'): string => {- if (detail === 'brief') return BRIEF[classifyNetworkError(err)]+ if (detail === 'brief') return i18n.t(BRIEF[classifyNetworkError(err)])switch (classifyNetworkError(err)) {// Deliberately does NOT say "update the app". This build already permits cleartext, so// if the OS still blocked it the cause is something an update can't fix — most likely// iOS, where NSAllowsLocalNetworking covers LAN IPs, `.local` and unqualified names but// NOT a custom TLD like `.lan`. Promising an update would send that user in circles.case 'cleartext-blocked':- return 'This device blocked the connection because the URL uses plain http://. Switch the server to https:// — a reverse proxy can issue a certificate for a LAN-only hostname with no ports open.'+ return i18n.t('errors.network.full.cleartextBlocked')// Leads with the real-certificate path on purpose. Installing a CA is a device-wide// action — it affects every app that trusts the user store, not just Lyftr — so it is// offered as the fallback it is, not as the headline fix.case 'certificate-untrusted':- return "The server's certificate isn't trusted by this device. Best fix: give the server a real certificate — a reverse proxy can issue one for a LAN-only hostname with no ports open. Or install your own CA under Settings → Security → Encryption & credentials, which trusts it for every app on the device, not just Lyftr."+ return i18n.t('errors.network.full.certificateUntrusted')case 'hostname-mismatch':- return "The server's certificate doesn't cover this address. Reissue it with this hostname or IP listed in the certificate's Subject Alternative Name (SAN)."+ return i18n.t('errors.network.full.hostnameMismatch')case 'timeout':- return "The server didn't respond in time. Check that it's running and reachable from this device."+ return i18n.t('errors.network.full.timeout')case 'unreachable':- return "Couldn't connect to the server. Check the URL and that the backend is running."+ return i18n.t('errors.network.full.unreachable')default: {- const base = isWeb()- ? "Can't reach the server. Check the URL, that the backend is running, and that it allows this app's origin (CORS)."- : "Can't reach the server. Check the URL and that the backend is running and reachable from this device."+ const base = i18n.t(isWeb() ? 'errors.network.full.unknownWeb' : 'errors.network.full.unknownNative')// Surface the raw native reason rather than guessing: an unmatched string is exactly// the case where our copy would otherwise be confidently wrong.const detail = nativeErrorDetail(err)- return detail ? `${base} (${detail})` : base+ return detail ? i18n.t('errors.network.full.withDetail', { message: base, detail }) : base}}}diff --git a/packages/shared/src/utils/passwordRules.ts b/packages/shared/src/utils/passwordRules.tsindex 325cf30..2506ba0 100644--- a/packages/shared/src/utils/passwordRules.ts+++ b/packages/shared/src/utils/passwordRules.ts@@ -10,6 +10,8 @@// The server is still the authority. This exists so the user learns the answer while// typing instead of after a round trip.+import { i18n } from '../i18n'+/*** Mirrors the backend's `min=8` on RegisterRequest and ChangePasswordRequest. That tag* counts runes, so this minimum does too — see `characterLength`.@@ -105,13 +107,13 @@ export function newPasswordRules({ password, confirm, current }: NewPasswordInpu*/export function lengthRuleLabel(password = ''): string {if (byteLength(password) > MAX_PASSWORD_BYTES) {- return `At most ${MAX_PASSWORD_BYTES} characters (accents and emoji count for more)`+ return i18n.t('auth.passwordRules.maxBytes', { count: MAX_PASSWORD_BYTES })}- return `At least ${MIN_PASSWORD_LENGTH} characters`+ return i18n.t('auth.passwordRules.minLength', { count: MIN_PASSWORD_LENGTH })}export function differentRuleLabel(): string {- return 'Different from your current password'+ return i18n.t('auth.passwordRules.different')}/**@@ -122,10 +124,10 @@ export function differentRuleLabel(): string {export function matchRuleLabel(state: RuleState): string {switch (state) {case 'ok':- return 'Passwords match'+ return i18n.t('auth.passwordRules.match')case 'bad':- return 'Passwords do not match'+ return i18n.t('auth.passwordRules.mismatch')default:- return 'Repeat the new password'+ return i18n.t('auth.passwordRules.repeat')}}diff --git a/packages/shared/src/utils/profile.ts b/packages/shared/src/utils/profile.tsindex b11c351..0931007 100644--- a/packages/shared/src/utils/profile.ts+++ b/packages/shared/src/utils/profile.ts@@ -1,3 +1,5 @@+import { i18n } from '../i18n'+// An independently maintained mirror of models.MaxDisplayNameLen. Not an identity: Go's// `max` counts runes and these fields count UTF-16 units, so the client cuts off earlier// for astral characters — the safe direction, never a 400 on a name it let you finish.@@ -14,7 +16,7 @@ export function displayName(name?: string, email?: string): string {const given = (name ?? '').trim()if (given) return givenconst local = (email ?? '').split('@')[0].trim()- return local || 'there'+ return local || i18n.t('common.there')}// Whether the typed address differs from the current one. A letter-case change counts:diff --git a/packages/shared/src/utils/programUtils.ts b/packages/shared/src/utils/programUtils.tsindex 11582f5..92bae14 100644--- a/packages/shared/src/utils/programUtils.ts+++ b/packages/shared/src/utils/programUtils.ts@@ -1,6 +1,7 @@// Program day/cycle helpers. Ported verbatim from web/src/utils/programUtils.ts so// web and mobile share one implementation of the multi-day-program logic.import type { ActiveSessionExercise, Program, ProgramDay, ProgramExercise } from '../types'+import { i18n } from '../i18n'// Workout days only — rest days carry no exercises and can't be "started" or// "loaded". Used everywhere a picker needs to offer a day to load/start from.@@ -14,7 +15,7 @@ export const todaysDay = (program: Program): ProgramDay | undefined =>(program.days ?? [])[program.current_day_index]export const dayLabel = (day: ProgramDay, idx: number): string =>- day.name?.trim() || (day.is_rest_day ? 'Rest Day' : `Day ${idx + 1}`)+ day.name?.trim() || (day.is_rest_day ? i18n.t('programs.day.rest') : i18n.t('programs.day.numbered', { number: idx + 1 }))// A day is startable/loadable only if it's a workout day that actually has// exercises — a rest day or an empty day is never "due" and can't seed a session.diff --git a/packages/shared/src/utils/serverUrl.ts b/packages/shared/src/utils/serverUrl.tsindex 4dbc258..f1e630d 100644--- a/packages/shared/src/utils/serverUrl.ts+++ b/packages/shared/src/utils/serverUrl.ts@@ -34,12 +34,6 @@ const LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[?::1\]?)$/i//// Pass the *saved* server URL, not an input buffer: a half-typed "http" would otherwise// flash a warning while the user is still typing.-// One wording for every surface (login server row, Settings, web) so the risk reads the-// same wherever it appears. Names the concrete consequence rather than "not secure" —-// a vague warning is the kind users learn to scroll past.-export const INSECURE_SERVER_WARNING =- 'Not encrypted — anyone on this network can read your login and stay signed in as you. Use https:// if you can.'-export const isInsecureServerUrl = (serverUrl: string): boolean => {if (!serverUrl) return false // '' = same-origin/default backend, not a user choicetry {@@ -73,6 +67,3 @@ export const isMixedContentBlocked = (serverUrl: string): boolean => {return false}}--export const MIXED_CONTENT_WARNING =- "This browser will block it — an HTTPS page can't call an http:// server. Use https:// for the server too, or leave this blank to use this site's own backend."diff --git a/packages/shared/src/utils/weight.ts b/packages/shared/src/utils/weight.tsindex d1a2ba0..a2401b0 100644--- a/packages/shared/src/utils/weight.ts+++ b/packages/shared/src/utils/weight.ts@@ -1,6 +1,8 @@// Pure weight helpers — ported verbatim from web/src/stores/settings.ts. Backend// always stores lbs; use these everywhere weight values are read/written/shown.+import { i18n } from '../i18n'+export const weightShort = (unit: string) => (unit === 'kg' ? 'kg' : 'lb')export const lbsToDisplay = (lbs: number, unit: string): number =>@@ -20,7 +22,7 @@ export const displayWeight = (lbs: number, unit: string): number => round1(lbsTo// A target weight for display: the converted number with its unit, or "BW" when the// target is 0 — a bodyweight movement has no load, and showing "0 lb" reads as a bug.export const targetWeightLabel = (lbs: number, unit: string): string =>- lbs > 0 ? `${displayWeight(lbs, unit)} ${unit}` : 'BW'+ lbs > 0 ? `${displayWeight(lbs, unit)} ${unit}` : i18n.t('weight.bodyweightShort')// Volume/aggregate (sum of reps×weight) in the user's unit, as a whole number.export const displayVolume = (lbs: number, unit: string): number => Math.round(lbsToDisplay(lbs, unit))@@ -34,9 +36,9 @@ export const maxWeight = (unit: string): number => round1(lbsToDisplay(MAX_WEIGH// `value` is in the user's display unit. Returns an error message, or null if valid.export const weightError = (value: number, unit: string): string | null => {- if (!Number.isFinite(value) || value <= 0) return 'Enter a valid weight'+ if (!Number.isFinite(value) || value <= 0) return i18n.t('weight.errors.invalid')if (displayToLbs(value, unit) > MAX_WEIGHT_LBS) {- return `Weight must be under ${Math.round(maxWeight(unit))} ${weightShort(unit)}`+ return i18n.t('weight.errors.tooHigh', { max: Math.round(maxWeight(unit)), unit: weightShort(unit) })}return null}diff --git a/packages/shared/src/utils/workoutSets.ts b/packages/shared/src/utils/workoutSets.tsindex d52db72..8f83517 100644--- a/packages/shared/src/utils/workoutSets.ts+++ b/packages/shared/src/utils/workoutSets.ts@@ -1,3 +1,5 @@+import { i18n } from '../i18n'+// Format whole seconds as m:ss (e.g. 90 → "1:30"). Shared by the rest banner and// the minimized session-pill chip.export function fmtClock(totalSeconds: number): string {@@ -26,7 +28,10 @@ export function formatElapsed(seconds: number): string {// Rest interval as a compact label: whole minutes collapse to "2m", anything else// stays in seconds ("90s"). Shown on program and workout set rows.-export const restLabel = (s: number): string => (s % 60 === 0 && s >= 60 ? `${s / 60}m` : `${s}s`)+export const restLabel = (s: number): string =>+ s % 60 === 0 && s >= 60+ ? i18n.t('common.duration.minutes', { value: s / 60 })+ : i18n.t('common.duration.seconds', { value: s })// "8", "8–12", or an em dash when there's nothing to show. Used for the planned// reps/weight spread across an exercise's sets in gym mode.diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex dbe0388..64b7527 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -38,6 +38,7 @@ export default defineConfig({reporter: 'list',use: {baseURL,+ locale: 'en-US',ignoreHTTPSErrors: true,trace: 'on-first-retry',screenshot: 'only-on-failure',diff --git a/web/src/components/BarcodeLookup.test.tsx b/web/src/components/BarcodeLookup.test.tsxindex cb8f1d6..13c0175 100644--- a/web/src/components/BarcodeLookup.test.tsx+++ b/web/src/components/BarcodeLookup.test.tsx@@ -1,8 +1,12 @@import { describe, it, expect, vi, afterEach } from 'vitest'import { render, screen, act } from '@testing-library/react'+import { i18n } from '@lyftr/shared'import BarcodeLookup from './BarcodeLookup'-afterEach(() => vi.useRealTimers())+afterEach(async () => {+ vi.useRealTimers()+ await i18n.changeLanguage('en')+})describe('BarcodeLookup', () => {// The silence past a few seconds is what made people rescan (#164), so a slow lookup@@ -15,4 +19,14 @@ describe('BarcodeLookup', () => {act(() => { vi.advanceTimersByTime(4000) })expect(screen.getByText('Still looking. This can take a few seconds.')).toBeTruthy()})++ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ vi.useFakeTimers()+ render(<BarcodeLookup code="3017620422003" />)++ expect(screen.getByText('Buscando este producto…')).toBeTruthy()+ act(() => { vi.advanceTimersByTime(4000) })+ expect(screen.getByText('Sigo buscando. Esto puede tardar unos segundos.')).toBeTruthy()+ })})diff --git a/web/src/components/BarcodeLookup.tsx b/web/src/components/BarcodeLookup.tsxindex 996abf0..79615a0 100644--- a/web/src/components/BarcodeLookup.tsx+++ b/web/src/components/BarcodeLookup.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from 'react'import { Barcode } from 'lucide-react'-import { eanModules, formatBarcode } from '@lyftr/shared'+import { eanModules, formatBarcode, useTranslation } from '@lyftr/shared'// When a lookup has run this long, say so: the silence past this point is what made// people rescan (#164). Open Food Facts routinely takes a few seconds.@@ -31,6 +31,7 @@ function Bars({ code }: { code: string }) {// Shown in place of the results while a scanned code is looked up: the barcode and its// digits, as printed on the pack, so the scan visibly landed.export default function BarcodeLookup({ code }: { code: string }) {+ const { t } = useTranslation()const [slow, setSlow] = useState(false)useEffect(() => {const t = setTimeout(() => setSlow(true), SLOW_AFTER_MS)@@ -47,7 +48,7 @@ export default function BarcodeLookup({ code }: { code: string }) {{formatBarcode(code)}</p><p className="mt-3 text-sm text-tx-muted">- {slow ? 'Still looking. This can take a few seconds.' : 'Looking up this product…'}+ {slow ? t('food.lookup.slow') : t('food.lookup.looking')}</p></div>)diff --git a/web/src/components/BarcodeScanner.tsx b/web/src/components/BarcodeScanner.tsxindex 09f0899..32ce867 100644--- a/web/src/components/BarcodeScanner.tsx+++ b/web/src/components/BarcodeScanner.tsx@@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useZxing } from 'react-zxing'import { X, AlertCircle } from 'lucide-react'+import { Trans, useTranslation } from '@lyftr/shared'interface Props {onResult: (code: string) => void@@ -9,6 +10,7 @@ interface Props {}export default function BarcodeScanner({ onResult, onClose }: Props) {+ const { t } = useTranslation()const resolvedRef = useRef(false)const [cameraError, setCameraError] = useState<string | null>(null)@@ -49,11 +51,11 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {return createPortal(<div className="fixed inset-0 z-50 bg-black/95 flex flex-col"><div className="flex items-center justify-between p-4">- <p className="text-white text-sm font-medium">Scan barcode</p>+ <p className="text-white text-sm font-medium">{t('food.scan.title')}</p><buttononClick={onClose}className="p-2 rounded-lg hover:bg-white/10 transition-colors"- aria-label="Close scanner"+ aria-label={t('food.scan.close')}><X className="w-5 h-5 text-white" /></button>@@ -65,23 +67,24 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {{insecureContext ? (<div className="flex flex-col items-center gap-3 px-6 text-center"><AlertCircle className="w-8 h-8 text-error-400" />- <p className="text-white text-sm font-medium">Camera needs HTTPS</p>+ <p className="text-white text-sm font-medium">{t('food.scan.httpsTitle')}</p><p className="text-white/60 text-xs leading-relaxed">- Browsers only allow camera access on secure pages. This site is served over- plain <span className="font-mono">http://</span> — put it behind a reverse proxy- with HTTPS to scan barcodes.+ <Trans+ i18nKey="food.scan.httpsBody"+ components={{ mono: <span className="font-mono" /> }}+ /></p><button onClick={onClose} className="btn-primary btn-sm mt-2">- Search by name instead+ {t('food.scan.searchByName')}</button></div>) : cameraError ? (<div className="flex flex-col items-center gap-3 px-6 text-center"><AlertCircle className="w-8 h-8 text-error-400" />- <p className="text-white text-sm font-medium">Camera unavailable</p>+ <p className="text-white text-sm font-medium">{t('food.scan.unavailable')}</p><p className="text-white/50 text-xs font-mono break-all">{cameraError}</p><button onClick={onClose} className="btn-primary btn-sm mt-2">- Search by name instead+ {t('food.scan.searchByName')}</button></div>) : null}@@ -112,7 +115,7 @@ export default function BarcodeScanner({ onResult, onClose }: Props) {{!insecureContext && !cameraError && (<p className="text-center text-white/60 text-xs pb-8 px-4">- Point camera at barcode — it will scan automatically+ {t('food.scan.hint')}</p>)}diff --git a/web/src/components/ErrorBoundary.tsx b/web/src/components/ErrorBoundary.tsxindex 2debc78..2049702 100644--- a/web/src/components/ErrorBoundary.tsx+++ b/web/src/components/ErrorBoundary.tsx@@ -1,4 +1,5 @@import { Component, type ReactNode } from 'react'+import { i18n } from '@lyftr/shared'import ErrorState from './ui/ErrorState'// The last net under a PR whose whole subject is that a failure must be visible.@@ -43,8 +44,8 @@ export default class ErrorBoundary extends Component<Props, State> {return (<ErrorStatesize={this.props.size ?? 'page'}- title={`Couldn't show ${this.props.subject ?? 'this page'}`}- message="Something went wrong on our side. Try again, and if it keeps happening reload the page."+ title={i18n.t('errors.boundary.title', { subject: this.props.subject ?? i18n.t('errors.boundary.thisPage') })}+ message={i18n.t('errors.boundary.message')}// Remounting the subtree is the retry: state that got us into the bad// render is thrown away with it.onRetry={() => this.setState({ failed: false })}diff --git a/web/src/components/ExercisePicker.test.tsx b/web/src/components/ExercisePicker.test.tsxindex a6c4f2a..679f871 100644--- a/web/src/components/ExercisePicker.test.tsx+++ b/web/src/components/ExercisePicker.test.tsx@@ -1,7 +1,7 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'import ExercisePicker from './ExercisePicker'-import { types } from '@lyftr/shared'+import { types, i18n } from '@lyftr/shared'type ListParams = {q?: string@@ -47,6 +47,8 @@ beforeEach(() => {listMock.mockReset()})+afterEach(async () => { await i18n.changeLanguage('en') })+describe('ExercisePicker', () => {// The picker opens with an unfiltered first page in flight. If typing a query// while that request is outstanding is treated as "a load is already running,@@ -137,4 +139,22 @@ describe('ExercisePicker', () => {await waitFor(() => expect(screen.getByText('Barbell Squat')).toBeTruthy())expect(screen.queryByRole('button', { name: /try again/i })).toBeNull()})++ it('names the title, count, muscle and equipment from the catalog, and follows a switch to Spanish', async () => {+ listMock.mockResolvedValue([exercise(1, 'Barbell Squat')])+ render(<ExercisePicker selectedIds={[]} onSelect={() => {}} onClose={() => {}} />)+ await screen.findByText('Barbell Squat')+ expect(screen.getByText('Add Exercise')).toBeTruthy()+ expect(screen.getByText('1 loaded')).toBeTruthy()+ expect(screen.getByText('quadriceps')).toBeTruthy()+ expect(screen.getByText('Barbell')).toBeTruthy()++ await act(async () => { await i18n.changeLanguage('es') })++ expect(screen.getByText('Añadir ejercicio')).toBeTruthy()+ expect(screen.getByText('1 cargado')).toBeTruthy()+ expect(screen.getByText('cuádriceps')).toBeTruthy()+ expect(screen.getByText('Barra')).toBeTruthy()+ expect(screen.getByPlaceholderText('Buscar ejercicios…')).toBeTruthy()+ })})diff --git a/web/src/components/ExercisePicker.tsx b/web/src/components/ExercisePicker.tsxindex b0766da..3da9c92 100644--- a/web/src/components/ExercisePicker.tsx+++ b/web/src/components/ExercisePicker.tsx@@ -2,10 +2,10 @@ import { useState, useEffect, useRef, useCallback } from 'react'import { createPortal } from 'react-dom'import { ArrowLeft, Search, Dumbbell } from 'lucide-react'import { useVirtualizer } from '@tanstack/react-virtual'-import { useServerList, types } from '@lyftr/shared'+import { useServerList, types, useTranslation } from '@lyftr/shared'import { ListError } from './ui'import { exerciseAPI } from '../services/api'-import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'+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.@@ -22,13 +22,14 @@ interface Props {}export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props) {+ const { t } = useTranslation()const [query, setQuery] = useState('')const [debouncedQuery, setDebouncedQuery] = useState('')const scrollRef = useRef<HTMLDivElement>(null)useEffect(() => {- const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)- return () => clearTimeout(t)+ const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ return () => clearTimeout(timer)}, [query])// Results come a page at a time from the server, which queries open-exercise-db.@@ -82,14 +83,14 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props<ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h2 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h2>+ <h2 className="font-display font-bold text-xl text-tx-primary">{t('exercises.picker.title')}</h2>{/* Derived from the rows we actually hold, so it is only true if the fetchlanded. On a failure `available` is empty and this read "0 loaded" directlyabove a message saying we could not load anything — the same claim theerror state exists to stop. */}{!error && (<p className="text-xs text-tx-muted">- {available.length} loaded{hasMore ? '…' : ''}+ {t(hasMore ? 'exercises.picker.loadedMore' : 'exercises.picker.loaded', { count: available.length })}</p>)}</div>@@ -103,7 +104,7 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Propstype="text"value={query}onChange={e => setQuery(e.target.value)}- placeholder="Search exercises…"+ placeholder={t('exercises.picker.search')}className="input pl-10 w-full"autoFocus/>@@ -115,18 +116,18 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props{initialLoading ? (<div className="flex items-center justify-center py-16 text-tx-muted text-sm"><Dumbbell className="w-5 h-5 mr-2 animate-pulse text-brand-500" />- Loading exercises…+ {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="these exercises" message={error} onRetry={retry} />+ <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">- No exercises found+ {t('exercises.picker.empty')}</div>)) : (@@ -170,11 +171,11 @@ export default function ExercisePicker({ selectedIds, onSelect, onClose }: Props<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 ${muscleColorBordered(ex.muscle_group)}`}>- {ex.muscle_group}+ {muscleLabel(ex.muscle_group)}</span>{ex.equipment && ex.equipment !== 'other' && (<span className="text-xs text-tx-muted">- {EQUIPMENT_LABEL[ex.equipment] || ex.equipment}+ {equipmentLabel(ex.equipment)}</span>)}</div>diff --git a/web/src/components/FavoriteStar.tsx b/web/src/components/FavoriteStar.tsxindex 459cdf6..a865829 100644--- a/web/src/components/FavoriteStar.tsx+++ b/web/src/components/FavoriteStar.tsx@@ -1,4 +1,5 @@import { Star } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'// Shared by the food rows, the food detail header and the diary so they cannot drift.// aria-pressed carries the toggle state that the fill conveys visually.@@ -8,6 +9,7 @@ export default function FavoriteStar() {// `compact` is IconButton's `sm`, box and icon, for rows whose other actions are// IconButtons (the diary). `sm` and `md` are the Log Food rows and detail header.+ const { t } = useTranslation()const box = size === 'md' ? 'w-10 h-10' : 'w-8 h-8'const icon = size === 'compact' ? 'w-3.5 h-3.5' : size === 'sm' ? 'w-[18px] h-[18px]' : 'w-[22px] h-[22px]'return (@@ -16,7 +18,7 @@ export default function FavoriteStar(onClick={onClick}disabled={busy}aria-pressed={favorited}- aria-label={favorited ? `Remove ${name} from Favorites` : `Add ${name} to Favorites`}+ aria-label={t(favorited ? 'food.favorites.remove' : 'food.favorites.add', { name })}className={`${box} flex items-center justify-center rounded-lg flex-shrink-0 transition-colors hover:bg-surface-muted active:scale-95 disabled:opacity-40 ${favorited ? 'text-brand-500' : 'text-tx-muted'}`}><Star className={icon} fill={favorited ? 'currentColor' : 'none'} strokeWidth={2.2} />diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsxindex 1c12d68..a4702f4 100644--- a/web/src/components/Layout.tsx+++ b/web/src/components/Layout.tsx@@ -9,7 +9,7 @@ import { useAuthStore } from '../stores/auth'import { useTheme } from '../hooks/useTheme'import { useWorkoutSession } from '../stores/workoutSession'import { useRestTimer } from '../hooks/useRestTimer'-import { fmtClock, formatElapsed, useElapsedSeconds, nameInitial } from '@lyftr/shared'+import { fmtClock, formatElapsed, useElapsedSeconds, nameInitial, useTranslation } from '@lyftr/shared'import { useDisplayName } from '../lib/lyftr'import { useSettingsStore, weightShort } from '../stores/settings'import GymModeWorkout from '../pages/GymModeWorkout'@@ -17,14 +17,15 @@ import Logo from './Logo'import ErrorBoundary from './ErrorBoundary'const NAV = [- { path: '/', label: 'Home', icon: Home },- { path: '/workouts', label: 'Workouts', icon: Dumbbell },- { path: '/programs', label: 'Programs', icon: BookOpen },- { path: '/food', label: 'Food', icon: Apple },- { path: '/weight', label: 'Weight', icon: Scale },-]+ { path: '/', label: 'nav.home', icon: Home },+ { path: '/workouts', label: 'nav.workouts', icon: Dumbbell },+ { path: '/programs', label: 'nav.programs', icon: BookOpen },+ { path: '/food', label: 'nav.food', icon: Apple },+ { path: '/weight', label: 'nav.weight', icon: Scale },+] as constfunction ActiveSessionBar() {+ const { t } = useTranslation()const { session, gymOpen, openGym } = useWorkoutSession()const { settings } = useSettingsStore()const navigate = useNavigate()@@ -62,12 +63,12 @@ function ActiveSessionBar() {</div><div className="text-left"><p className="text-xs font-bold text-white leading-tight truncate max-w-[140px]">{session.name}</p>- <p className="text-[11px] text-white/70 leading-tight">{completedSets}/{totalSets} sets · {formatElapsed(elapsed)}</p>+ <p className="text-[11px] text-white/70 leading-tight">{t('nav.session.sets', { done: completedSets, total: totalSets })} · {formatElapsed(elapsed)}</p></div>{resting && (<div className="flex items-center gap-1.5 pl-2.5 py-1 pr-1 rounded-full bg-white/15 flex-shrink-0"><span className="text-[10px] font-semibold uppercase tracking-wide text-white/70 leading-none">- {done ? 'Rest over' : paused ? 'Paused' : 'Rest'}+ {done ? t('nav.session.restOver') : paused ? t('nav.session.paused') : t('nav.session.rest')}</span>{!done && <span className="text-xs font-bold text-white tabular-nums leading-none">{fmtClock(left)}</span>}</div>@@ -79,6 +80,7 @@ function ActiveSessionBar() {}function UserMenu() {+ const { t } = useTranslation()const { user, logout } = useAuthStore()const { theme, toggleTheme } = useTheme()const [open, setOpen] = useState(false)@@ -104,7 +106,7 @@ function UserMenu() {? 'ring-2 ring-brand-500 ring-offset-2 ring-offset-surface-base': 'hover:ring-2 hover:ring-surface-border hover:ring-offset-2 hover:ring-offset-surface-base'}`}- aria-label="User menu"+ aria-label={t('nav.userMenu')}><div className="w-9 h-9 rounded-full flex items-center justify-center" style={{ background: 'linear-gradient(135deg, #0891b2, #00b8d9)' }}><span className="text-sm font-bold text-white leading-none">{initial}</span>@@ -127,15 +129,15 @@ function UserMenu() {className="flex items-center gap-3 px-4 py-2.5 text-sm text-tx-secondary hover:text-tx-primary hover:bg-surface-muted/50 transition-colors"><User className="w-4 h-4 text-tx-muted flex-shrink-0" />- Settings+ {t('nav.settings')}</Link><buttononClick={toggleTheme}className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-tx-secondary hover:text-tx-primary hover:bg-surface-muted/50 transition-colors">{theme === 'dark'- ? <><Sun className="w-4 h-4 text-tx-muted flex-shrink-0" />Light mode</>- : <><Moon className="w-4 h-4 text-tx-muted flex-shrink-0" />Dark mode</>+ ? <><Sun className="w-4 h-4 text-tx-muted flex-shrink-0" />{t('nav.lightMode')}</>+ : <><Moon className="w-4 h-4 text-tx-muted flex-shrink-0" />{t('nav.darkMode')}</>}</button></div>@@ -147,7 +149,7 @@ function UserMenu() {className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-error-400 hover:bg-error-500/10 transition-colors"><LogOut className="w-4 h-4 flex-shrink-0" />- Sign out+ {t('nav.signOut')}</button></div></div>@@ -157,6 +159,7 @@ function UserMenu() {}export default function Layout() {+ const { t } = useTranslation()const { pathname } = useLocation()const { session, gymOpen } = useWorkoutSession()const { settings } = useSettingsStore()@@ -189,7 +192,7 @@ export default function Layout() {{/* Keyed on the path so the boundary RESETS on navigation: without the key acrash on one route would follow the user to every other one, turning a badrow on /workouts into an app that looks broken everywhere. */}- <ErrorBoundary key={pathname} subject="this page">+ <ErrorBoundary key={pathname}><Outlet /></ErrorBoundary></main>@@ -209,7 +212,7 @@ export default function Layout() {return (<Link key={path} to={path} className={`nav-item flex-1 ${active ? 'active' : ''}`}><Icon className="w-5 h-5" strokeWidth={active ? 2.5 : 1.75} />- <span>{label}</span>+ <span>{t(label)}</span></Link>)})}diff --git a/web/src/components/Loading.tsx b/web/src/components/Loading.tsxindex 1de65b3..14a8967 100644--- a/web/src/components/Loading.tsx+++ b/web/src/components/Loading.tsx@@ -1,4 +1,7 @@+import { useTranslation } from '@lyftr/shared'+export default function Loading() {+ const { t } = useTranslation()return (<div className="fixed inset-0 flex items-center justify-center bg-surface-base"><div className="flex flex-col items-center gap-11">@@ -88,7 +91,7 @@ export default function Loading() {lyftr</div><div className="text-xs font-semibold text-tx-muted uppercase tracking-widest mt-2">- Loading+ {t('common.loading')}</div></div></div>diff --git a/web/src/components/PeriodSelector.tsx b/web/src/components/PeriodSelector.tsxindex bc9772e..3461298 100644--- a/web/src/components/PeriodSelector.tsx+++ b/web/src/components/PeriodSelector.tsx@@ -2,9 +2,11 @@ interface PeriodSelectorProps<T extends string> {options: readonly T[]value: TonChange: (value: T) => void+ /** What a chip says, when that differs from the value it selects. */+ label?: (value: T) => string}-export default function PeriodSelector<T extends string>({ options, value, onChange }: PeriodSelectorProps<T>) {+export default function PeriodSelector<T extends string>({ options, value, onChange, label }: PeriodSelectorProps<T>) {return (<div className="flex gap-1 bg-surface-overlay rounded-lg p-1">{options.map(opt => (@@ -17,7 +19,7 @@ export default function PeriodSelector<T extends string>({ options, value, onCha: 'text-tx-muted hover:text-tx-primary'}`}>- {opt}+ {label ? label(opt) : opt}</button>))}</div>diff --git a/web/src/components/ProgramPicker.test.tsx b/web/src/components/ProgramPicker.test.tsxindex 82c8191..987856b 100644--- a/web/src/components/ProgramPicker.test.tsx+++ b/web/src/components/ProgramPicker.test.tsx@@ -1,7 +1,7 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'import ProgramPicker from './ProgramPicker'-import { types } from '@lyftr/shared'+import { types, i18n } from '@lyftr/shared'const listMock = vi.fn()vi.mock('../services/api', () => ({@@ -39,6 +39,18 @@ const multiDay = () =>describe('ProgramPicker', () => {beforeEach(() => listMock.mockReset())+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ listMock.mockResolvedValue([multiDay()])+ render(<ProgramPicker onSelect={() => {}} onClose={() => {}} />)+ expect(screen.getByText('Cargar desde un programa')).toBeTruthy()+ fireEvent.click(await screen.findByText('PPL'))+ expect(screen.getByText('Elige un día para rellenar los ejercicios')).toBeTruthy()+ expect(screen.getByText('HOY')).toBeTruthy()+ expect(screen.getByText('← Volver a programas')).toBeTruthy()+ })it('a program with zero workout days renders disabled (nothing to load)', async () => {listMock.mockResolvedValue([program([day({ is_rest_day: true })])])diff --git a/web/src/components/ProgramPicker.tsx b/web/src/components/ProgramPicker.tsxindex 79280a5..b7afd71 100644--- a/web/src/components/ProgramPicker.tsx+++ b/web/src/components/ProgramPicker.tsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react'import { createPortal } from 'react-dom'import { X, BookOpen, ChevronRight, Dumbbell, AlertCircle, Moon } from 'lucide-react'import { programAPI } from '../services/api'-import { apiErrorMessage, workoutDays, dayLabel, todaysDay, types } from '@lyftr/shared'+import { workoutDays, dayLabel, todaysDay, uiMessage, useTranslation, types, type UiMessage } from '@lyftr/shared'interface Props {onSelect: (program: types.Program, day: types.ProgramDay) => void@@ -13,15 +13,17 @@ interface Props {// Day to load — a single-workout-day program skips straight through, so the common// case stays a one-tap flow exactly like before the multi-day rework.export default function ProgramPicker({ onSelect, onClose }: Props) {+ const { t } = useTranslation()const [programs, setPrograms] = useState<types.Program[]>([])const [loading, setLoading] = useState(true)- const [error, setError] = useState('')+ // A UiMessage rather than a sentence, so a failure already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [dayPickFor, setDayPickFor] = useState<types.Program | null>(null)useEffect(() => {programAPI.list().then(data => setPrograms(data || []))- .catch(err => setError(apiErrorMessage(err, "Couldn't load your programs.")))+ .catch(err => setError({ key: 'workouts.form.programPicker.loadFailed', cause: err })).finally(() => setLoading(false))}, [])@@ -32,8 +34,8 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {setDayPickFor(p)}- const title = dayPickFor ? dayPickFor.name : 'Load from Program'- const subtitle = dayPickFor ? 'Pick a day to pre-fill exercises' : 'Pick a program to pre-fill exercises'+ const title = dayPickFor ? dayPickFor.name : t('workouts.form.programPicker.title')+ const subtitle = dayPickFor ? t('workouts.form.programPicker.pickDay') : t('workouts.form.programPicker.pickProgram')// Portalled to document.body like every other overlay here (ExercisePicker,// ConfirmSheet, QuickWeighInSheet, BarcodeScanner, Toast). Rendered inline it@@ -59,12 +61,12 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {{loading ? (<div className="flex items-center justify-center p-8 text-tx-muted text-sm"><BookOpen className="w-5 h-5 mr-2 animate-pulse text-brand-500" />- Loading programs…+ {t('workouts.start.loadingPrograms')}</div>) : error ? (<div className="flex items-center gap-2 p-4 text-error-400 text-sm"><AlertCircle className="w-4 h-4 flex-shrink-0" />- {error}+ {uiMessage(error)}</div>) : dayPickFor ? (<div>@@ -73,7 +75,7 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {onClick={() => setDayPickFor(null)}className="w-full text-left px-4 py-2 text-xs text-tx-muted hover:text-tx-secondary transition-colors">- ← Back to programs+ {t('workouts.form.programPicker.back')}</button><div className="divide-y divide-surface-border">{workoutDays(dayPickFor).map((day, i) => {@@ -91,10 +93,10 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {<div className="flex-1 min-w-0"><p className="text-sm font-medium text-tx-primary truncate flex items-center gap-1.5">{dayLabel(day, day.order_index)}- {isToday && <span className="text-[10px] font-bold text-brand-400 bg-brand-500/15 px-1.5 py-0.5 rounded-full">TODAY</span>}+ {isToday && <span className="text-[10px] font-bold text-brand-400 bg-brand-500/15 px-1.5 py-0.5 rounded-full">{t('workouts.form.programPicker.today')}</span>}</p><span className="text-xs text-tx-muted">- {(day.exercises ?? []).length} exercise{(day.exercises ?? []).length === 1 ? '' : 's'}+ {t('workouts.form.exerciseCount', { count: (day.exercises ?? []).length })}</span></div><ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity" />@@ -106,8 +108,8 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {) : programs.length === 0 ? (<div className="flex flex-col items-center justify-center p-8 text-center"><BookOpen className="w-8 h-8 text-tx-muted mb-2 opacity-50" />- <p className="text-sm text-tx-muted">No programs yet</p>- <p className="text-xs text-tx-muted mt-1">Create a program first</p>+ <p className="text-sm text-tx-muted">{t('workouts.start.noPrograms')}</p>+ <p className="text-xs text-tx-muted mt-1">{t('workouts.form.programPicker.createFirst')}</p></div>) : (<div className="divide-y divide-surface-border">@@ -129,10 +131,10 @@ export default function ProgramPicker({ onSelect, onClose }: Props) {<div className="flex items-center gap-2 mt-0.5"><span className="text-xs text-tx-muted"><Dumbbell className="w-3 h-3 inline mr-1" />- {days.length === 0 ? 'No exercises yet' : `${days.length} workout day${days.length === 1 ? '' : 's'}`}+ {days.length === 0 ? t('workouts.form.programPicker.noExercises') : t('workouts.form.programPicker.workoutDays', { count: days.length })}</span>{(p.days ?? []).some(d => d.is_rest_day) && (- <span className="text-xs text-tx-muted"><Moon className="w-3 h-3 inline mr-0.5" />rest days</span>+ <span className="text-xs text-tx-muted"><Moon className="w-3 h-3 inline mr-0.5" />{t('workouts.form.programPicker.restDays')}</span>)}</div></div>diff --git a/web/src/components/QuickWeighInSheet.tsx b/web/src/components/QuickWeighInSheet.tsxindex e084781..c6e94a4 100644--- a/web/src/components/QuickWeighInSheet.tsx+++ b/web/src/components/QuickWeighInSheet.tsx@@ -5,7 +5,7 @@ import { weightAPI } from '../services/api'import { useSettingsStore, weightShort, displayToLbs , weightError, maxWeight } from '../stores/settings'import { useBodyScrollLock } from '../hooks/useBodyScrollLock'import { useEscapeKey } from '../hooks/useEscapeKey'-import { useAsyncAction, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types } from '@lyftr/shared'+import { useAsyncAction, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, useTranslation, types } from '@lyftr/shared'import StepperTile from './ui/StepperTile'import NumberField from './ui/NumberField'@@ -18,6 +18,7 @@ interface Props {}export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose, onSuccess }: Props) {+ const { t } = useTranslation()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)@@ -25,7 +26,9 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,const [date, setDate] = useState(todayStr())const [notes, setNotes] = useState('')const [showExtras, setShowExtras] = useState(false)- const [error, setError] = useState('')+ // The rejected weight, not the sentence about it: the text is made at render from the current+ // unit and language, so a banner already on screen follows a switch of either.+ const [rejected, setRejected] = useState<number | null>(null)const [showDuplicateWarning, setShowDuplicateWarning] = useState(false)const duplicateWarningDismissedRef = useRef(false)const formRef = useRef<HTMLFormElement>(null)@@ -36,7 +39,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,setDate(todayStr())setNotes('')setShowExtras(false)- setError('')+ setRejected(null)setShowDuplicateWarning(false)duplicateWarningDismissedRef.current = false}, [isOpen, lastValue])@@ -49,22 +52,24 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,})onSuccess(log)onClose()- }, 'Failed to save')+ }, t('home.quickWeighIn.saveFailed'))- const handleClose = () => { setError(''); onClose() }+ const handleClose = () => { setRejected(null); onClose() }useBodyScrollLock(isOpen)useEscapeKey(isOpen, handleClose)if (!isOpen) return null+ const error = rejected === null ? '' : weightError(rejected, settings.weight_unit) ?? ''+const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()if (save.busy) returnconst w = parseFloat(value)const wErr = weightError(w, settings.weight_unit)if (wErr) {- setError(wErr)+ setRejected(w)return}@@ -73,7 +78,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,return}- setError('')+ setRejected(null)setShowDuplicateWarning(false)void save.run(w)}@@ -99,7 +104,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,<div className="w-8 h-8 rounded-lg bg-brand-500/10 border border-brand-500/20 flex items-center justify-center"><Scale className="w-4 h-4 text-brand-500" /></div>- <h2 id="qws-title" className="font-display font-bold text-lg text-tx-primary">Log Weight</h2>+ <h2 id="qws-title" className="font-display font-bold text-lg text-tx-primary">{t('home.quickWeighIn.title')}</h2></div><button onClick={handleClose} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors"><X className="w-5 h-5 text-tx-muted" />@@ -118,14 +123,14 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,<div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert"><AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" /><div className="flex-1 min-w-0">- <p className="font-medium">Already logged today ({Math.round(lastValue ?? 0)} {wUnit}). Log again anyway?</p>+ <p className="font-medium">{t('home.quickWeighIn.duplicateToday', { weight: Math.round(lastValue ?? 0), unit: wUnit })}</p><div className="flex gap-2 mt-2"><buttontype="button"onClick={() => setShowDuplicateWarning(false)}className="px-3 py-1 rounded-lg text-xs font-medium bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors">- Cancel+ {t('common.cancel')}</button><buttontype="button"@@ -136,7 +141,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,}}className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-500/20 border border-amber-500/30 text-amber-300 hover:bg-amber-500/30 transition-colors">- Log Anyway+ {t('home.quickWeighIn.logAnyway')}</button></div></div>@@ -145,12 +150,12 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,<StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('home.quickWeighIn.weightWithUnit', { unit: wUnit })}+ name={t('home.quickWeighIn.weightName')}step={BODYWEIGHT_STEP}onStep={d => setValue(String(clampStep(parseFloat(value) || 0, d, { max: maxWeight(settings.weight_unit) })))}>- <NumberField value={value} onChange={setValue} autoFocus aria-label="Weight" />+ <NumberField value={value} onChange={setValue} autoFocus aria-label={t('home.quickWeighIn.weight')} /></StepperTile>{!showExtras ? (@@ -159,13 +164,13 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,onClick={() => setShowExtras(true)}className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-1">- + Change date or add a note+ {t('home.quickWeighIn.changeDateOrNote')}</button>) : (<div className="space-y-3 pt-1"><div><label className="label">- <Calendar className="w-3 h-3" /> Date+ <Calendar className="w-3 h-3" /> {t('home.quickWeighIn.date')}</label><inputtype="date"@@ -177,13 +182,13 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,</div><div><label className="label">- <FileText className="w-3 h-3" /> Note <span className="text-tx-muted font-normal normal-case tracking-normal">(optional)</span>+ <FileText className="w-3 h-3" /> {t('home.quickWeighIn.note')} <span className="text-tx-muted font-normal normal-case tracking-normal">{t('home.quickWeighIn.optional')}</span></label><inputtype="text"value={notes}onChange={e => setNotes(e.target.value)}- placeholder="e.g., morning, post-workout"+ placeholder={t('home.quickWeighIn.notePlaceholder')}maxLength={200}className="input mt-1"/>@@ -197,7 +202,7 @@ export default function QuickWeighInSheet({ isOpen, lastValue, lastLog, onClose,className="btn-primary btn-lg w-full"><Save className="w-4 h-4" />- {save.busy ? 'Saving…' : 'Save'}+ {save.busy ? t('common.saving') : t('common.save')}</button></form></div>diff --git a/web/src/components/RestPicker.tsx b/web/src/components/RestPicker.tsxindex 2f0b997..97fffa3 100644--- a/web/src/components/RestPicker.tsx+++ b/web/src/components/RestPicker.tsx@@ -1,5 +1,6 @@import { useState } from 'react'import { Clock, TimerOff, Pencil, Minus, Plus } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'interface Props {value: number@@ -8,16 +9,17 @@ interface Props {const PRESETS = [0, 60, 90, 120, 180]const SEGMENTS = [- { v: 0, label: 'Off', Icon: TimerOff },- { v: 60, label: '60s', Icon: Clock },- { v: 90, label: '90s', Icon: Clock },- { v: 120, label: '120s', Icon: Clock },- { v: 180, label: '180s', Icon: Clock },+ { v: 0, Icon: TimerOff },+ { v: 60, Icon: Clock },+ { v: 90, Icon: Clock },+ { v: 120, Icon: Clock },+ { v: 180, Icon: Clock },]// Per-exercise rest control: one connected segmented bar (Off · presets · Custom),// each segment icon-labelled. Custom reveals a seconds field when chosen.export default function RestPicker({ value, onChange }: Props) {+ const { t } = useTranslation()const isCustom = !PRESETS.includes(value)const [showCustom, setShowCustom] = useState(false)const customActive = isCustom || showCustom@@ -30,20 +32,20 @@ export default function RestPicker({ value, onChange }: Props) {return (<div><div className="flex rounded-xl border border-surface-border overflow-hidden divide-x divide-surface-border">- {SEGMENTS.map(({ v, label, Icon }) => (+ {SEGMENTS.map(({ v, Icon }) => (<button key={v} type="button" onClick={() => { setShowCustom(false); onChange(v) }} className={seg(!customActive && value === v)}><Icon className="w-3.5 h-3.5 flex-shrink-0" />- <span className="text-[11px] font-semibold leading-none">{label}</span>+ <span className="text-[11px] font-semibold leading-none">{v === 0 ? t('workouts.rest.off') : t('common.duration.seconds', { value: v })}</span></button>))}<button type="button" onClick={() => setShowCustom(true)} className={seg(customActive)}><Pencil className="w-3.5 h-3.5 flex-shrink-0" />- <span className="text-[11px] font-semibold leading-none">{isCustom ? `${value}s` : 'Custom'}</span>+ <span className="text-[11px] font-semibold leading-none">{isCustom ? t('common.duration.seconds', { value }) : t('workouts.rest.custom')}</span></button></div>{customActive && (<div className="flex items-center justify-center gap-2 mt-3">- <button type="button" aria-label="−5 seconds" onClick={() => onChange(Math.max(0, value - 5))}+ <button type="button" aria-label={t('workouts.rest.stepDown5')} onClick={() => onChange(Math.max(0, value - 5))}className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary"><Minus className="w-4 h-4" /></button>@@ -55,11 +57,11 @@ export default function RestPicker({ value, onChange }: Props) {value={value}onChange={e => onChange(Math.max(0, Math.min(3600, Number(e.target.value) || 0)))}className="input w-28 text-center py-2.5 pr-9 text-base font-semibold tabular-nums"- aria-label="Rest seconds"+ aria-label={t('workouts.rest.secondsLabel')}/>- <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">sec</span>+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">{t('workouts.rest.secondsUnit')}</span></div>- <button type="button" aria-label="+5 seconds" onClick={() => onChange(Math.min(3600, value + 5))}+ <button type="button" aria-label={t('workouts.rest.stepUp5')} onClick={() => onChange(Math.min(3600, value + 5))}className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary"><Plus className="w-4 h-4" /></button>diff --git a/web/src/components/RestTimerBanner.tsx b/web/src/components/RestTimerBanner.tsxindex ed9eeae..d904c88 100644--- a/web/src/components/RestTimerBanner.tsx+++ b/web/src/components/RestTimerBanner.tsx@@ -2,7 +2,7 @@ import { useCallback } from 'react'import { Pause, Play, SkipForward, Check } from 'lucide-react'import { useWorkoutSession } from '../stores/workoutSession'import { useRestTimer } from '../hooks/useRestTimer'-import { fmtClock, nextIncompleteSet } from '@lyftr/shared'+import { fmtClock, nextIncompleteSet, useTranslation } from '@lyftr/shared'import { IconButton } from './ui'// Hevy/Strong-style rest panel: a thin draining progress line, a big centred@@ -13,6 +13,7 @@ import { IconButton } from './ui'// pill (see Layout's ActiveSessionBar) instead of following you around the app.// Haptics/sound are left to a future native app.export default function RestTimerBanner() {+ const { t } = useTranslation()const {restEndsAt, restDurationSec, restPausedRemainingMs, restExIdx, restSetIdx,session, adjustRest, clearRest, pauseRest, resumeRest,@@ -55,14 +56,14 @@ export default function RestTimerBanner() {// Once rest is over the headline says "Rest over", so the caption carries the// thing you actually need next instead of repeating it.const label = doneSetNum == null- ? (done ? 'Ready' : paused ? 'Paused' : 'Rest')+ ? (done ? t('workouts.rest.label.ready') : paused ? t('workouts.rest.label.paused') : t('workouts.rest.label.resting')): done- ? (nextIdx !== -1 ? `Set ${nextIdx + 1} up next` : `Set ${doneSetNum} done`)+ ? (nextIdx !== -1 ? t('workouts.rest.label.upNext', { next: nextIdx + 1 }) : t('workouts.rest.label.setDone', { done: doneSetNum })): paused- ? `Set ${doneSetNum} done · paused`+ ? t('workouts.rest.label.setDonePaused', { done: doneSetNum }): nextIdx !== -1- ? `Set ${doneSetNum} done · set ${nextIdx + 1} next`- : `Set ${doneSetNum} done · resting`+ ? t('workouts.rest.label.setDoneNext', { done: doneSetNum, next: nextIdx + 1 })+ : t('workouts.rest.label.setDoneResting', { done: doneSetNum })const secBtn = 'flex-1 flex items-center justify-center py-2.5 rounded-xl text-sm font-semibold tabular-nums bg-surface-muted border border-surface-border text-tx-secondary active:scale-95'const brandBtn = 'flex-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl text-sm font-semibold bg-brand-500 text-white active:scale-95'@@ -92,13 +93,13 @@ export default function RestTimerBanner() {{done ? (<><Check className="w-7 h-7 text-success-500" />- <span className="font-display text-3xl font-black text-tx-primary leading-none">Rest over</span>+ <span className="font-display text-3xl font-black text-tx-primary leading-none">{t('workouts.rest.label.over')}</span></>) : (<><IconButtonicon={paused ? Play : Pause}- label={paused ? 'Resume rest timer' : 'Pause rest timer'}+ label={paused ? t('workouts.rest.resume') : t('workouts.rest.pause')}onClick={paused ? resumeRest : pauseRest}variant="ghost" size="lg"className="!text-brand-500 hover:!text-brand-500"@@ -109,12 +110,12 @@ export default function RestTimerBanner() {</div>{/* full-width actions */}{done ? (- <button onClick={() => clearRest()} className={doneBtn}><Check className="w-4 h-4" />Done</button>+ <button onClick={() => clearRest()} className={doneBtn}><Check className="w-4 h-4" />{t('common.done')}</button>) : (<div className="flex gap-2">- <button onClick={() => adjustRest(-15)} aria-label="Shorten rest by 15 seconds" className={secBtn}>−15</button>- <button onClick={() => adjustRest(15)} aria-label="Extend rest by 15 seconds" className={secBtn}>+15</button>- <button onClick={() => clearRest()} className={brandBtn}><SkipForward className="w-4 h-4" />Skip</button>+ <button onClick={() => adjustRest(-15)} aria-label={t('workouts.rest.shorten')} className={secBtn}>−15</button>+ <button onClick={() => adjustRest(15)} aria-label={t('workouts.rest.extend')} className={secBtn}>+15</button>+ <button onClick={() => clearRest()} className={brandBtn}><SkipForward className="w-4 h-4" />{t('workouts.rest.skip')}</button></div>)}</div>diff --git a/web/src/components/ServerSettings.tsx b/web/src/components/ServerSettings.tsxindex 7780ec8..0c58ac8 100644--- a/web/src/components/ServerSettings.tsx+++ b/web/src/components/ServerSettings.tsx@@ -4,24 +4,24 @@ import {useServerStore,normalizeServerUrl,isInsecureServerUrl,- INSECURE_SERVER_WARNING,isMixedContentBlocked,- MIXED_CONTENT_WARNING,} from '../stores/server'+import { Trans, useTranslation, uiMessage, type UiMessage } from '@lyftr/shared'import { testServerConnection } from '../services/api'type Status =| { kind: 'idle' }| { kind: 'testing' }- | { kind: 'ok'; message: string }- | { kind: 'warn'; message: string }- | { kind: 'error'; message: string }+ | { kind: 'ok'; name: string; version: string }+ | { kind: 'warn'; failure: UiMessage }+ | { kind: 'error'; key: 'server.status.invalidUrlExample' | 'server.status.storageBlocked' }// Bitwarden-style server selector shared by Login and Register: validates and// normalizes the URL, tests connectivity against the backend's public /info, and// saves regardless of the result (a server may be temporarily down) while showing// clear status. Empty means "use this site's own origin via the reverse proxy".export default function ServerSettings() {+ const { t } = useTranslation()const { serverUrl, setServerUrl } = useServerStore()const [open, setOpen] = useState(false)const [input, setInput] = useState(serverUrl)@@ -35,10 +35,7 @@ export default function ServerSettings() {const raw = input.trim()const normalized = normalizeServerUrl(raw) // '' = same origin (reverse proxy)if (raw && !normalized) {- setStatus({- kind: 'error',- message: 'Include http:// or https:// — e.g. http://192.168.1.10:3000',- })+ setStatus({ kind: 'error', key: 'server.status.invalidUrlExample' })return}// Save immediately (warn-but-save): the choice is authoritative right away;@@ -51,7 +48,7 @@ export default function ServerSettings() {try {await setServerUrl(normalized)} catch {- setStatus({ kind: 'error', message: "Couldn't save the server URL — this browser is blocking storage." })+ setStatus({ kind: 'error', key: 'server.status.storageBlocked' })return}setInput(normalized)@@ -59,8 +56,8 @@ export default function ServerSettings() {const result = await testServerConnection(normalized)setStatus(result.ok- ? { kind: 'ok', message: `Connected · ${result.info.name} ${result.info.version}` }- : { kind: 'warn', message: `Saved — ${result.message}` },+ ? { kind: 'ok', name: result.info.name, version: result.info.version }+ : { kind: 'warn', failure: result.failure },)}@@ -72,18 +69,18 @@ export default function ServerSettings() {className="flex items-center gap-2 px-3 py-2 w-full text-xs text-tx-muted hover:text-tx-secondary rounded-lg hover:bg-surface-muted/40 transition-colors"><Server className="w-3.5 h-3.5" />- <span>Server settings</span>+ <span>{t('server.settingsTitle')}</span>{/* Stays visible while the panel is collapsed — the problem outlives the moment of entry. */}{blocked && (- <span className="flex items-center gap-1 text-error-400" title={MIXED_CONTENT_WARNING}>+ <span className="flex items-center gap-1 text-error-400" title={t('server.mixedContentWarning')}><AlertTriangle className="w-3 h-3" />- Blocked+ {t('server.blocked')}</span>)}{insecure && (- <span className="flex items-center gap-1 text-warning-400" title={INSECURE_SERVER_WARNING}>+ <span className="flex items-center gap-1 text-warning-400" title={t('server.insecureWarning')}><AlertTriangle className="w-3 h-3" />- Not encrypted+ {t('server.notEncrypted')}</span>)}<ChevronDown className={`w-3 h-3 ml-auto transition-transform ${open ? 'rotate-180' : ''}`} />@@ -91,12 +88,12 @@ export default function ServerSettings() {{open && (<div className="mt-2 p-3 bg-surface-muted/30 border border-surface-border rounded-lg space-y-2">- <label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">Server URL</label>+ <label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">{t('settings.server.url.label')}</label><inputtype="text"value={input}onChange={e => { setInput(e.target.value); setStatus({ kind: 'idle' }) }}- placeholder="Leave blank to use this site"+ placeholder={t('server.blankPlaceholder')}className="input text-sm"autoComplete="off"autoCapitalize="off"@@ -104,33 +101,36 @@ export default function ServerSettings() {/><p className="text-[11px] leading-relaxed text-tx-muted">- Full URL, e.g. <span className="font-mono text-tx-secondary">https://lyftr.example.com</span>+ <Trans+ i18nKey="server.fullUrlHint"+ components={{ url: <span className="font-mono text-tx-secondary" /> }}+ /></p>{blocked && (<p className="flex items-start gap-1.5 text-xs text-error-400"><AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />- <span>{MIXED_CONTENT_WARNING}</span>+ <span>{t('server.mixedContentWarning')}</span></p>)}{insecure && (<p className="flex items-start gap-1.5 text-xs text-warning-400"><AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />- <span>{INSECURE_SERVER_WARNING}</span>+ <span>{t('server.insecureWarning')}</span></p>)}- {status.kind === 'error' && <p className="text-xs text-error-400">{status.message}</p>}+ {status.kind === 'error' && <p className="text-xs text-error-400">{t(status.key)}</p>}{status.kind === 'warn' && (<p className="flex items-start gap-1.5 text-xs text-warning-400"><AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />- <span>{status.message}</span>+ <span>{t('settings.server.savedWithWarning', { message: uiMessage(status.failure) })}</span></p>)}{status.kind === 'ok' && (<p className="flex items-center gap-1.5 text-xs text-success-500"><CheckCircle2 className="w-3.5 h-3.5 flex-shrink-0" />- <span>{status.message}</span>+ <span>{t('server.status.connected', { name: status.name, version: status.version })}</span></p>)}@@ -142,20 +142,20 @@ export default function ServerSettings() {className="flex-1 px-2 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-1.5">{status.kind === 'testing'- ? (<><Loader className="w-3.5 h-3.5 animate-spin" /> Testing…</>)- : 'Test & Save'}+ ? (<><Loader className="w-3.5 h-3.5 animate-spin" /> {t('server.testing')}</>)+ : t('server.testAndSave')}</button><buttontype="button"onClick={() => setOpen(false)}className="flex-1 px-2 py-1.5 text-xs bg-surface-border text-tx-secondary hover:bg-surface-border/80 rounded-lg transition-colors">- Close+ {t('common.close')}</button></div><p className="text-xs text-tx-muted pt-1">- {serverUrl ? `Current: ${serverUrl}` : 'Using this site’s address (reverse proxy)'}+ {serverUrl ? t('server.current', { url: serverUrl }) : t('server.usingSite')}</p></div>)}diff --git a/web/src/components/programs/DayExercisesEditor.tsx b/web/src/components/programs/DayExercisesEditor.tsxindex 2d74f1a..6438037 100644--- a/web/src/components/programs/DayExercisesEditor.tsx+++ b/web/src/components/programs/DayExercisesEditor.tsx@@ -3,7 +3,7 @@ import { Plus, Trash2, Zap, Timer } from 'lucide-react'import WeightInput from '../WeightInput'import ExercisePicker from '../ExercisePicker'import RestPicker from '../RestPicker'-import { types } from '@lyftr/shared'+import { types, useTranslation, muscleLabel, equipmentLabel } from '@lyftr/shared'import type { DayExerciseDraft } from './types'interface Props {@@ -19,6 +19,7 @@ interface Props {// pre-multi-day flat editor, just parameterized so each Day in ProgramDaysEditor// gets its own instance instead of the page owning one flat exercises array.export default function DayExercisesEditor({ exercises, onChange, pickerExercises, onCacheExercise, wUnit, restSecondsDefault }: Props) {+ const { t } = useTranslation()const [showPicker, setShowPicker] = useState(false)const addExercise = (exercise: types.Exercise) => {@@ -78,7 +79,7 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExercise<div className="flex items-center justify-between mb-3"><div className="flex items-center gap-2"><Zap className="w-4 h-4 text-brand-500" />- <label className="label">Exercises</label>+ <label className="label">{t('workouts.form.exercises')}</label></div><buttontype="button"@@ -86,7 +87,7 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExerciseclassName="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"><Plus className="w-3.5 h-3.5" />- Add Exercise+ {t('workouts.form.addExercise')}</button></div>@@ -99,7 +100,7 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExercise)}{exercises.length === 0 ? (- <p className="text-xs text-tx-muted text-center py-4">No exercises yet — add one above.</p>+ <p className="text-xs text-tx-muted text-center py-4">{t('programs.form.dayEditor.emptyInline')}</p>) : (<div className="space-y-4">{exercises.map((workoutEx, exIdx) => {@@ -114,20 +115,20 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExercise</div><p className="font-semibold text-tx-primary">{exercise?.name}</p></div>- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>+ <p className="text-xs text-tx-muted ml-8">{muscleLabel(exercise?.muscle_group)} • {equipmentLabel(exercise?.equipment)}</p></div>- <button type="button" aria-label="Remove exercise" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeExercise')} onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div><div className="mb-4">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.notes')}</label><inputtype="text"value={workoutEx.notes}onChange={e => updateNotes(exIdx, e.target.value)}- placeholder="e.g., Focus on controlled eccentric"+ placeholder={t('programs.form.dayEditor.notesPlaceholder')}className="input text-sm"/></div>@@ -135,31 +136,31 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExercise<div className="mb-4"><div className="flex items-center gap-1.5 mb-1"><Timer className="w-3.5 h-3.5 text-brand-500" />- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">{t('workouts.form.restBetweenSets')}</label></div><RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} /></div><div className="space-y-2 mb-3"><div className="flex items-center justify-between">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Target Sets</label>- <span className="text-xs text-tx-muted">{workoutEx.sets.length} set{workoutEx.sets.length === 1 ? '' : 's'}</span>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">{t('programs.form.targetSets')}</label>+ <span className="text-xs text-tx-muted">{t('programs.count.sets', { count: workoutEx.sets.length })}</span></div>{workoutEx.sets.map((set, setIdx) => (<div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50"><div className="flex-shrink-0 w-12">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">{t('workouts.form.set')}</label><div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Reps</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('programs.form.dayEditor.targetReps')}</label><input type="number" inputMode="numeric" value={set.target_reps || ''} onChange={e => updateSet(exIdx, setIdx, 'target_reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" /></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Target Weight</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('programs.form.dayEditor.targetWeight')}</label><WeightInput size="sm" value={set.target_weight ? String(set.target_weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'target_weight', v)} unit={wUnit} placeholder="135" /></div>- <button type="button" aria-label="Remove set" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeSet')} onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div>@@ -168,7 +169,7 @@ export default function DayExercisesEditor({ exercises, onChange, pickerExercise<button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"><Plus className="w-3.5 h-3.5" />- Add Set+ {t('workouts.form.addSet')}</button></div>)diff --git a/web/src/components/programs/ProgramDaysEditor.test.tsx b/web/src/components/programs/ProgramDaysEditor.test.tsxindex db8179a..570d22a 100644--- a/web/src/components/programs/ProgramDaysEditor.test.tsx+++ b/web/src/components/programs/ProgramDaysEditor.test.tsx@@ -1,6 +1,7 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, it, expect, vi, afterEach } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'import ProgramDaysEditor from './ProgramDaysEditor'+import { i18n } from '@lyftr/shared'import type { DayDraft } from './types'const dayDraft = (overrides: Partial<DayDraft> = {}): DayDraft => ({@@ -26,6 +27,20 @@ const renderEditor = (days: DayDraft[], onChange = vi.fn()) => {}describe('ProgramDaysEditor', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ renderEditor([dayDraft({ exercises: [{ exercise_id: 1, notes: '', rest_seconds: 90, sets: [] }] }), dayDraft({ order_index: 1, is_rest_day: true })])+ expect(screen.getByText('Agregar día de entrenamiento')).toBeTruthy()+ expect(screen.getByText('Agregar día de descanso')).toBeTruthy()+ expect(screen.getByText('1 ejercicio')).toBeTruthy()+ expect(screen.getAllByLabelText('Quitar día')).toHaveLength(2)+ expect(screen.getByPlaceholderText('Día 1')).toBeTruthy()+ expect(screen.getByPlaceholderText('Día de descanso 2')).toBeTruthy()+ expect(screen.queryByText('Add Workout Day')).toBeNull()+ })+it('renders the empty state when there are no days', () => {renderEditor([])expect(screen.getByText(/No days yet/)).toBeTruthy()diff --git a/web/src/components/programs/ProgramDaysEditor.tsx b/web/src/components/programs/ProgramDaysEditor.tsxindex a8f3328..a2685c6 100644--- a/web/src/components/programs/ProgramDaysEditor.tsx+++ b/web/src/components/programs/ProgramDaysEditor.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { Plus, Trash2, ChevronUp, ChevronDown, Dumbbell, Moon, ChevronRight, ChevronLeft as ChevronCollapse } from 'lucide-react'import DayExercisesEditor from './DayExercisesEditor'-import { types, appendDay, removeDayAt, moveDayBy, patchDayAt } from '@lyftr/shared'+import { types, appendDay, removeDayAt, moveDayBy, patchDayAt, useTranslation } from '@lyftr/shared'import type { DayDraft } from './types'interface Props {@@ -17,6 +17,7 @@ interface Props {// workout day expands to the (unchanged) per-day exercise editor. The array operations// come from @lyftr/shared — only the `expanded` row bookkeeping below is web's.export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCacheExercise, wUnit, restSecondsDefault }: Props) {+ const { t } = useTranslation()const [expanded, setExpanded] = useState<number | null>(days.findIndex(d => !d.is_rest_day))const addDay = (isRest: boolean) => {@@ -49,7 +50,7 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCreturn (<div className="space-y-3">{days.length === 0 && (- <p className="text-xs text-tx-muted text-center py-4">No days yet — add a workout or rest day below.</p>+ <p className="text-xs text-tx-muted text-center py-4">{t('programs.form.daysEditor.empty')}</p>)}{days.map((day, idx) => {@@ -58,10 +59,10 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onC<div key={idx} className={`border rounded-lg overflow-hidden ${day.is_rest_day ? 'border-surface-border bg-surface-muted/20' : 'border-surface-border bg-surface-muted/30'}`}><div className="flex items-center gap-2 p-3"><div className="flex flex-col flex-shrink-0">- <button type="button" aria-label="Move day up" onClick={() => moveDay(idx, -1)} disabled={idx === 0} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors">+ <button type="button" aria-label={t('programs.form.daysEditor.moveUp')} onClick={() => moveDay(idx, -1)} disabled={idx === 0} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors"><ChevronUp className="w-3.5 h-3.5" /></button>- <button type="button" aria-label="Move day down" onClick={() => moveDay(idx, 1)} disabled={idx === days.length - 1} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors">+ <button type="button" aria-label={t('programs.form.daysEditor.moveDown')} onClick={() => moveDay(idx, 1)} disabled={idx === days.length - 1} className="p-0.5 text-tx-muted hover:text-tx-primary disabled:opacity-20 transition-colors"><ChevronDown className="w-3.5 h-3.5" /></button></div>@@ -74,7 +75,7 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCtype="text"value={day.name}onChange={e => updateDay(idx, { name: e.target.value })}- placeholder={day.is_rest_day ? `Rest Day ${idx + 1}` : `Day ${idx + 1}`}+ placeholder={day.is_rest_day ? t('programs.form.daysEditor.restPlaceholder', { number: idx + 1 }) : t('programs.day.numbered', { number: idx + 1 })}className="input text-sm flex-1 min-w-0"/>@@ -84,31 +85,31 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onConClick={() => day.is_rest_day && toggleRest(idx)}className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${!day.is_rest_day ? 'bg-brand-500 text-white' : 'bg-transparent text-tx-muted hover:text-tx-secondary'}`}>- Workout+ {t('programs.form.daysEditor.workout')}</button><buttontype="button"onClick={() => !day.is_rest_day && toggleRest(idx)}className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${day.is_rest_day ? 'bg-surface-muted text-tx-primary' : 'bg-transparent text-tx-muted hover:text-tx-secondary'}`}>- Rest+ {t('programs.form.daysEditor.rest')}</button></div>{!day.is_rest_day && (- <button type="button" aria-label={isOpen ? 'Collapse day' : 'Expand day'} aria-expanded={isOpen} onClick={() => setExpanded(isOpen ? null : idx)} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors flex-shrink-0">+ <button type="button" aria-label={isOpen ? t('programs.form.daysEditor.collapse') : t('programs.form.daysEditor.expand')} aria-expanded={isOpen} onClick={() => setExpanded(isOpen ? null : idx)} className="p-1.5 hover:bg-surface-muted rounded-lg transition-colors flex-shrink-0">{isOpen ? <ChevronCollapse className="w-4 h-4 text-tx-muted rotate-90" /> : <ChevronRight className="w-4 h-4 text-tx-muted" />}</button>)}- <button type="button" aria-label="Remove day" onClick={() => removeDay(idx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('programs.form.daysEditor.remove')} onClick={() => removeDay(idx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div>{!day.is_rest_day && (<div className="px-3 pb-3 flex items-center gap-2 -mt-1">- <span className="text-[11px] text-tx-muted">{day.exercises.length} exercise{day.exercises.length === 1 ? '' : 's'}</span>+ <span className="text-[11px] text-tx-muted">{t('programs.count.exercises', { count: day.exercises.length })}</span></div>)}@@ -135,7 +136,7 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCclassName="flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs bg-brand-500/10 hover:bg-brand-500/15 text-brand-400 border border-brand-500/20 rounded-lg transition-colors font-medium"><Plus className="w-3.5 h-3.5" />- Add Workout Day+ {t('programs.form.daysEditor.addWorkoutDay')}</button><buttontype="button"@@ -143,7 +144,7 @@ export default function ProgramDaysEditor({ days, onChange, pickerExercises, onCclassName="flex-1 flex items-center justify-center gap-1.5 py-2.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border rounded-lg transition-colors font-medium"><Moon className="w-3.5 h-3.5" />- Add Rest Day+ {t('programs.form.daysEditor.addRestDay')}</button></div></div>diff --git a/web/src/components/ui/ConfirmSheet.tsx b/web/src/components/ui/ConfirmSheet.tsxindex 641c9d6..aec07e9 100644--- a/web/src/components/ui/ConfirmSheet.tsx+++ b/web/src/components/ui/ConfirmSheet.tsx@@ -1,6 +1,7 @@import type { ComponentType } from 'react'import { createPortal } from 'react-dom'import { AlertCircle } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'import { useEscapeKey } from '../../hooks/useEscapeKey'import { useBodyScrollLock } from '../../hooks/useBodyScrollLock'@@ -34,9 +35,10 @@ interface Props {// Mirrors mobile's ConfirmSheet prop-for-prop, `error` included, so a fix to how a failed// confirmation behaves is one change on each platform rather than eight.export default function ConfirmSheet({- open, title, message, confirmLabel, busyLabel, cancelLabel = 'Cancel',+ open, title, message, confirmLabel, busyLabel, cancelLabel,destructive = false, icon: Icon, busy = false, error, onConfirm, onCancel,}: Props) {+ const { t } = useTranslation()useBodyScrollLock(open)// Escape dismisses — always the non-destructive choice — but not while the confirmed// action is in flight: dismissing then leaves the request to fail into a sheet that is@@ -69,7 +71,7 @@ export default function ConfirmSheet({disabled={busy}className="flex-1 py-3 disabled:opacity-50 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm">- {cancelLabel}+ {cancelLabel ?? t('common.cancel')}</button><buttononClick={onConfirm}diff --git a/web/src/components/ui/ErrorState.test.tsx b/web/src/components/ui/ErrorState.test.tsxindex 0d40dfb..ede93fc 100644--- a/web/src/components/ui/ErrorState.test.tsx+++ b/web/src/components/ui/ErrorState.test.tsx@@ -1,5 +1,6 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, it, expect, vi, afterEach } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'+import { i18n } from '@lyftr/shared'import ErrorState from './ErrorState'import ListError from './ListError'@@ -41,6 +42,19 @@ describe('ErrorState', () => {})})+describe('ErrorState in Spanish', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reads its retry label and the list title from the catalog, and follows a language switch', async () => {+ const { rerender } = render(<ListError subject="workouts" message="No answer." onRetry={() => {}} />)+ expect(screen.getByRole('button', { name: 'Try again' })).toBeTruthy()+ await i18n.changeLanguage('es')+ rerender(<ListError subject="entrenos" message="No answer." onRetry={() => {}} />)+ expect(screen.getByText('Error al cargar entrenos')).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Intentar de nuevo' })).toBeTruthy()+ })+})+describe('ListError', () => {// A failed list is section-scoped: the search box and the create button above it still// work, so the state replaces the rows and says which rows they were.diff --git a/web/src/components/ui/ErrorState.tsx b/web/src/components/ui/ErrorState.tsxindex 412f70c..240e312 100644--- a/web/src/components/ui/ErrorState.tsx+++ b/web/src/components/ui/ErrorState.tsx@@ -1,5 +1,6 @@import type React from 'react'import { RotateCw } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'import BarbellBrokenSVG from '../BarbellBrokenSVG'// A load that failed, said as a state rather than as a banner over the wreckage.@@ -37,9 +38,10 @@ export default function ErrorState({message,size = 'section',onRetry,- retryLabel = 'Try again',+ retryLabel,secondary,}: Props) {+ const { t } = useTranslation()const page = size === 'page'return (<div@@ -66,7 +68,7 @@ export default function ErrorState({<div className="flex flex-wrap items-center justify-center gap-2 mt-1">{onRetry && (<button onClick={onRetry} className="btn-primary btn-sm flex items-center gap-1.5">- <RotateCw className="w-3.5 h-3.5" /> {retryLabel}+ <RotateCw className="w-3.5 h-3.5" /> {retryLabel ?? t('common.tryAgain')}</button>)}{secondary}diff --git a/web/src/components/ui/ListError.tsx b/web/src/components/ui/ListError.tsxindex ca47a8e..4e321f7 100644--- a/web/src/components/ui/ListError.tsx+++ b/web/src/components/ui/ListError.tsx@@ -1,3 +1,4 @@+import { useTranslation } from '@lyftr/shared'import ErrorState from './ErrorState'// A page of a list that never arrived.@@ -17,10 +18,11 @@ import ErrorState from './ErrorState'export default function ListError({ subject, message, onRetry }: { subject: string; message: string; onRetry: () => void },) {+ const { t } = useTranslation()return (<ErrorStatesize="section"- title={`Couldn't load ${subject}`}+ title={t('errors.list.title', { subject })}message={message}onRetry={onRetry}/>diff --git a/web/src/components/ui/PasswordField.tsx b/web/src/components/ui/PasswordField.tsxindex cfafa6f..618fbe7 100644--- a/web/src/components/ui/PasswordField.tsx+++ b/web/src/components/ui/PasswordField.tsx@@ -1,6 +1,6 @@import { useState } from 'react'import { AlertCircle, Check, Eye, EyeOff, X } from 'lucide-react'-import type { RuleState } from '@lyftr/shared'+import { useTranslation, type RuleState } from '@lyftr/shared'export function Rule({ state, children }: { state: RuleState; children: React.ReactNode }) {const tone =@@ -36,6 +36,7 @@ interface Props {export default function PasswordField({id, label, value, onChange, autoComplete, placeholder, children,}: Props) {+ const { t } = useTranslation()const [visible, setVisible] = useState(false)const [caps, setCaps] = useState(false)@@ -64,7 +65,7 @@ export default function PasswordField({// tabIndex -1 keeps Tab running straight down the fields to the submit button,// which is the path someone filling this form actually wants.tabIndex={-1}- aria-label={visible ? `Hide ${label.toLowerCase()}` : `Show ${label.toLowerCase()}`}+ aria-label={t(visible ? 'common.password.hide' : 'common.password.show', { label: label.toLowerCase() })}className="absolute inset-y-0 right-0 px-3 flex items-center text-tx-muted hover:text-tx-primary transition-colors">{visible ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}@@ -72,7 +73,7 @@ export default function PasswordField({</div>{caps && (<p className="flex items-center gap-1.5 text-xs mt-1.5 text-warning-400">- <AlertCircle className="w-3 h-3 flex-shrink-0" /> Caps Lock is on+ <AlertCircle className="w-3 h-3 flex-shrink-0" /> {t('common.capsLockOn')}</p>)}{children}diff --git a/web/src/components/ui/StatFailure.tsx b/web/src/components/ui/StatFailure.tsxindex 44f58b3..352a178 100644--- a/web/src/components/ui/StatFailure.tsx+++ b/web/src/components/ui/StatFailure.tsx@@ -1,3 +1,4 @@+import { useTranslation } from '@lyftr/shared'import BarbellBrokenSVG from '../BarbellBrokenSVG'// A figure that never arrived, in a slot too small to say so in words.@@ -22,9 +23,10 @@ import BarbellBrokenSVG from '../BarbellBrokenSVG'//// It repeats when several tiles in a row fail, and that is intended: each tile makes its// own claim, so each has to withdraw its own.-export default function StatFailure({ label = "Couldn't load this figure" }: { label?: string }) {+export default function StatFailure({ label }: { label?: string }) {+ const { t } = useTranslation()return (- <span className="inline-flex items-center" role="img" aria-label={label}>+ <span className="inline-flex items-center" role="img" aria-label={label ?? t('common.figureFailed')}><BarbellBrokenSVG className="w-[26px] h-[26px] text-[color:var(--alert-error)]" /></span>)diff --git a/web/src/components/ui/StepperTile.test.tsx b/web/src/components/ui/StepperTile.test.tsxindex 4381a5b..a9d7f06 100644--- a/web/src/components/ui/StepperTile.test.tsx+++ b/web/src/components/ui/StepperTile.test.tsx@@ -1,6 +1,7 @@-import { describe, it, expect, vi } from 'vitest'+import { describe, it, expect, vi, afterEach } from 'vitest'import { render, screen, fireEvent } from '@testing-library/react'import { Scale } from 'lucide-react'+import { i18n } from '@lyftr/shared'import StepperTile from './StepperTile'import NumberField from './NumberField'@@ -17,6 +18,15 @@ const renderTile = (props: Partial<React.ComponentProps<typeof StepperTile>> = {}describe('StepperTile', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('names its step buttons from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ renderTile()+ expect(screen.getByLabelText('Disminuir weight')).toBeTruthy()+ expect(screen.getByLabelText('Aumentar weight')).toBeTruthy()+ })+it('renders the label and the value field between the two buttons', () => {renderTile()expect(screen.getByText('Weight (lbs)')).toBeTruthy()diff --git a/web/src/components/ui/StepperTile.tsx b/web/src/components/ui/StepperTile.tsxindex ba58761..53c4c1d 100644--- a/web/src/components/ui/StepperTile.tsx+++ b/web/src/components/ui/StepperTile.tsx@@ -1,5 +1,6 @@import { Minus, Plus } from 'lucide-react'import type { LucideIcon } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'interface Props {icon: LucideIcon@@ -17,6 +18,7 @@ interface Props {// increment footer. Shared by the gym reps + weight inputs so the layout and the// stepper buttons live in one place.export default function StepperTile({ icon: Icon, label, name, step, onStep, disabled = false, children }: Props) {+ const { t } = useTranslation()const btn = 'flex-1 py-2.5 flex items-center justify-center text-tx-secondary hover:bg-surface-muted active:scale-95 transition-all disabled:opacity-30'return (<div className="card overflow-hidden">@@ -27,10 +29,10 @@ export default function StepperTile({ icon: Icon, label, name, step, onStep, dis{children}</div><div className="flex border-t border-surface-border divide-x divide-surface-border">- <button type="button" aria-label={`Decrease ${name}`} disabled={disabled} onClick={() => onStep(-step)} className={btn}>+ <button type="button" aria-label={t('common.stepper.decrease', { name })} disabled={disabled} onClick={() => onStep(-step)} className={btn}><Minus className="w-5 h-5" /></button>- <button type="button" aria-label={`Increase ${name}`} disabled={disabled} onClick={() => onStep(step)} className={btn}>+ <button type="button" aria-label={t('common.stepper.increase', { name })} disabled={disabled} onClick={() => onStep(step)} className={btn}><Plus className="w-5 h-5" /></button></div>diff --git a/web/src/components/ui/Toast.tsx b/web/src/components/ui/Toast.tsxindex d567368..f855648 100644--- a/web/src/components/ui/Toast.tsx+++ b/web/src/components/ui/Toast.tsx@@ -2,6 +2,7 @@ import { useEffect } from 'react'import { createPortal } from 'react-dom'import { X, ChevronRight } from 'lucide-react'import type { LucideIcon } from 'lucide-react'+import { useTranslation } from '@lyftr/shared'export type ToastVariant = 'default' | 'success' | 'brand' | 'warning' | 'error'@@ -31,6 +32,7 @@ const VARIANTS: Record<ToastVariant, { border: string; chip: string; icon: strin// bottom-24 to clear the nav; callers that fire it after a session ends don't// collide with session-gated UI.export default function Toast({ title, description, icon: Icon, variant = 'default', onClick, onDismiss, autoDismissMs = 4000 }: Props) {+ const { t } = useTranslation()// Armed once on mount — parent re-renders must not extend the window (0 disables).useEffect(() => {if (!autoDismissMs) return@@ -71,7 +73,7 @@ export default function Toast({ title, description, icon: Icon, variant = 'defau<buttontype="button"onClick={onDismiss}- aria-label="Dismiss"+ aria-label={t('common.dismiss')}className="p-1.5 -m-1.5 text-tx-muted hover:text-tx-primary flex-shrink-0"><X className="w-4 h-4" />diff --git a/web/src/hooks/useServerInfo.test.ts b/web/src/hooks/useServerInfo.test.tsindex 0ae79aa..5fa7995 100644--- a/web/src/hooks/useServerInfo.test.ts+++ b/web/src/hooks/useServerInfo.test.ts@@ -27,7 +27,7 @@ describe('useServerInfo', () => {it('stays null when the server is unreachable', async () => {useServerStore.setState({ serverUrl: 'http://unreachable-server' })- mockTest.mockResolvedValue({ ok: false, message: "Can't reach the server." })+ mockTest.mockResolvedValue({ ok: false, failure: { key: 'server.test.unreachable' } })const { result } = renderHook(() => useServerInfo())await waitFor(() => expect(mockTest).toHaveBeenCalled())diff --git a/web/src/lib/lyftr.test.ts b/web/src/lib/lyftr.test.tsindex b2a470f..344f3dc 100644--- a/web/src/lib/lyftr.test.ts+++ b/web/src/lib/lyftr.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeEach } from 'vitest'import { hydrateStores, useAuthStore, useServerStore, useSettingsStore, useThemeStore, useWorkoutSession } from './lyftr'import { storage } from './storage'-import { surfaces } from '@lyftr/shared'+import { surfaces, i18n } from '@lyftr/shared'// main.tsx awaits hydrateStores() before the first render. Everything that depends on// that ordering is invisible from the store code itself, so this pins the contract:@@ -23,6 +23,19 @@ describe('hydrateStores', () => {useWorkoutSession.setState({ session: null })})+ it('sets html lang and document.title, and both follow a language switch', async () => {+ await hydrateStores()+ expect(document.documentElement.lang).toBe('en')+ expect(document.title).toBe('Lyftr — Workout & Nutrition Tracker')+ try {+ await i18n.changeLanguage('es')+ expect(document.documentElement.lang).toBe('es')+ expect(document.title).toBe('Lyftr — Registro de entrenamiento y nutrición')+ } finally {+ await i18n.changeLanguage('en')+ }+ })+it('settles the auth store — the one the catch-all route depends on', async () => {localStorage.setItem('access_token', 'tok')localStorage.setItem('user', JSON.stringify({ id: 1, email: '[email protected]' }))diff --git a/web/src/lib/lyftr.ts b/web/src/lib/lyftr.tsindex d619743..d83b7d9 100644--- a/web/src/lib/lyftr.ts+++ b/web/src/lib/lyftr.ts@@ -6,6 +6,8 @@ import {createServerStore,createSettingsStore,createThemeStore,+ createLanguageStore,+ i18n,createWorkoutSession,surfaces,} from '@lyftr/shared'@@ -39,6 +41,11 @@ export const useWorkoutSession = createWorkoutSession(storage)// Dark-first on web (mobile is light-first, per product).export const useThemeStore = createThemeStore(storage, 'dark')+// Raw device tags only; shared resolveLanguage() decides which supported language they mean.+const detectLanguages = () =>+ (navigator.languages?.length ? navigator.languages : [navigator.language]).filter(Boolean)+export const useLanguageStore = createLanguageStore(storage, detectLanguages)+// Replaces the theme-color tag rather than editing it. Browsers diff this value to decide// whether to repaint their chrome, and setAttribute('content', …) on the existing element// is not always seen as a change — which is why the address bar used to lag until a@@ -85,11 +92,20 @@ export const hydrateStores = async () => {// screen is a mount-only effect, so workout_layout must be right on first render.useSettingsStore.getState().hydratePrefs(),useThemeStore.getState().hydrate(),+ useLanguageStore.getState().hydrate(),])// Paint the theme before React renders, so there is no flash of the default. This is// why theme could only move to the shared store once hydration gated the first render.applyThemeClass(useThemeStore.getState().mode)useThemeStore.subscribe((s) => applyThemeClass(s.mode))+ // Both follow the language: the static <title> in index.html is only the pre-hydration+ // English fallback.+ const applyLanguage = (lang: string) => {+ document.documentElement.lang = lang+ document.title = i18n.t('app.documentTitle')+ }+ applyLanguage(i18n.language)+ i18n.on('languageChanged', applyLanguage)}// Rest-timer state derived from the session store above. The logic lives indiff --git a/web/src/pages/ActiveWorkout.tsx b/web/src/pages/ActiveWorkout.tsxindex c7a1c1f..5e4489e 100644--- a/web/src/pages/ActiveWorkout.tsx+++ b/web/src/pages/ActiveWorkout.tsx@@ -8,11 +8,12 @@ import { useWorkoutSession } from '../stores/workoutSession'import { useSettingsStore, weightShort, displayToLbs, displayWeight } from '../stores/settings'import WeightInput from '../components/WeightInput'import { workoutAPI } from '../services/api'-import { muscleColor } from '../utils/exerciseUtils'-import { formatElapsed, useAsyncAction, useElapsedSeconds } from '@lyftr/shared'+import { muscleColor, muscleLabel } from '../utils/exerciseUtils'+import { formatElapsed, useAsyncAction, useElapsedSeconds, useTranslation } from '@lyftr/shared'import { ConfirmSheet } from '../components/ui'function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {+ const { t } = useTranslation()const [editing, setEditing] = useState(false)const [val, setVal] = useState(notes)@@ -28,7 +29,7 @@ function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string;onChange={e => setVal(e.target.value)}onBlur={commit}onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setVal(notes); setEditing(false) } }}- placeholder="Add a note…"+ placeholder={t('workouts.active.notes.placeholder')}className="input text-sm w-full"/></div>@@ -41,13 +42,14 @@ function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string;onClick={() => { setVal(notes); setEditing(true) }}className="text-xs text-tx-muted hover:text-tx-secondary transition-colors">- {notes ? <span className="italic">{notes}</span> : <span className="opacity-50">+ Add note</span>}+ {notes ? <span className="italic">{notes}</span> : <span className="opacity-50">{t('workouts.active.notes.add')}</span>}</button></div>)}export default function ActiveWorkout() {+ const { t } = useTranslation()const navigate = useNavigate()const { session, updateSet, updateExerciseNotes, completeSet, addSet, removeSet, removeExercise, buildPayload, cancelSession, openGym } =useWorkoutSession()@@ -74,7 +76,7 @@ export default function ActiveWorkout() {cancelSession()// Surface the routine auto-progression as a toast on the workouts list (#40).navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)- }, 'Failed to save workout')+ }, t('workouts.active.saveFailed'))// Workout elapsed timerif (!session) {@@ -83,9 +85,9 @@ export default function ActiveWorkout() {<div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4"><Dumbbell className="w-6 h-6 text-tx-muted" /></div>- <p className="text-sm font-medium text-tx-primary mb-1">No active workout</p>- <p className="text-xs text-tx-muted mb-4">Start one from the home page</p>- <button onClick={() => navigate('/')} className="btn-primary btn-sm">Go Home</button>+ <p className="text-sm font-medium text-tx-primary mb-1">{t('workouts.active.noWorkout.title')}</p>+ <p className="text-xs text-tx-muted mb-4">{t('workouts.active.noWorkout.hintHome')}</p>+ <button onClick={() => navigate('/')} className="btn-primary btn-sm">{t('workouts.active.noWorkout.goHome')}</button></div>)}@@ -129,7 +131,7 @@ export default function ActiveWorkout() {<Timer className="w-3.5 h-3.5" />{formatElapsed(elapsed)}</span>- <span className="text-xs text-tx-muted">{completedSets}/{totalSets} sets done</span>+ <span className="text-xs text-tx-muted">{t('workouts.active.setsDone', { done: completedSets, total: totalSets })}</span></div></div><button@@ -141,7 +143,7 @@ export default function ActiveWorkout() {}`}><Flag className="w-4 h-4" />- Finish+ {t('workouts.active.finish')}</button></div>@@ -196,8 +198,8 @@ export default function ActiveWorkout() {<div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4"><Dumbbell className="w-6 h-6 text-tx-muted" /></div>- <p className="text-sm font-medium text-tx-primary mb-1">No exercises yet</p>- <p className="text-xs text-tx-muted">Add exercises below</p>+ <p className="text-sm font-medium text-tx-primary mb-1">{t('workouts.active.empty.title')}</p>+ <p className="text-xs text-tx-muted">{t('workouts.active.empty.hint')}</p></div>) : (session.exercises.map((ex, exIdx) => {@@ -250,9 +252,9 @@ export default function ActiveWorkout() {</div><div className="flex items-center gap-2 mt-1"><span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span>- <span className="text-xs text-tx-muted tabular-nums">{completedHere}/{ex.sets.length} sets</span>+ <span className="text-xs text-tx-muted tabular-nums">{t('workouts.active.setProgress', { done: completedHere, total: ex.sets.length })}</span></div></button>@@ -265,7 +267,7 @@ export default function ActiveWorkout() {<buttononClick={() => removeExercise(exIdx)}className="w-9 h-9 flex items-center justify-center hover:bg-error-500/10 rounded-xl transition-colors flex-shrink-0 group/rm"- aria-label="Remove exercise"+ aria-label={t('workouts.active.removeExercise')}><X className="w-4 h-4 text-tx-muted group-hover/rm:text-error-400 transition-colors" /></button>@@ -279,10 +281,10 @@ export default function ActiveWorkout() {<div className="px-3 pb-3 space-y-2">{/* Column labels */}<div className="grid grid-cols-[2rem_1fr_1fr_3.5rem_2rem] gap-2 px-1">- <span className="text-xs text-tx-muted font-medium text-center">Set</span>- <span className="text-xs text-tx-muted font-medium text-center">Reps</span>- <span className="text-xs text-tx-muted font-medium text-center">Weight</span>- <span className="text-xs text-tx-muted font-medium text-center">Done</span>+ <span className="text-xs text-tx-muted font-medium text-center">{t('workouts.active.columns.set')}</span>+ <span className="text-xs text-tx-muted font-medium text-center">{t('workouts.active.columns.reps')}</span>+ <span className="text-xs text-tx-muted font-medium text-center">{t('workouts.active.columns.weight')}</span>+ <span className="text-xs text-tx-muted font-medium text-center">{t('workouts.active.columns.done')}</span><span /></div>@@ -332,7 +334,7 @@ export default function ActiveWorkout() {"button" with no way to tell a done set from a pending one.aria-pressed carries what the fill colour conveys visually. */}<button- aria-label={`Set ${set.set_number}, mark done`}+ aria-label={t('workouts.active.completeSetWeb', { number: set.set_number })}aria-pressed={!!set.completed}onClick={() => handleCompleteSet(exIdx, setIdx)}className={`flex items-center justify-center transition-colors min-h-[3rem] ${@@ -352,7 +354,7 @@ export default function ActiveWorkout() {<buttononClick={() => removeSet(exIdx, setIdx)}className="flex items-center justify-center rounded-r-xl hover:bg-error-500/10 transition-colors group/del"- aria-label="Remove set"+ aria-label={t('workouts.active.removeSet')}><X className="w-3.5 h-3.5 text-tx-muted/40 group-hover/del:text-error-400 transition-colors" /></button>@@ -366,7 +368,7 @@ export default function ActiveWorkout() {<buttononClick={() => jumpToExercise(exIdx - 1)}className="py-2.5 px-3 flex items-center justify-center rounded-xl bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border transition-colors"- aria-label="Previous exercise"+ aria-label={t('workouts.active.previous')}><ChevronLeft className="w-3.5 h-3.5" /></button>@@ -377,7 +379,7 @@ export default function ActiveWorkout() {className="flex-1 py-2.5 flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border hover:border-brand-500/40 hover:bg-brand-500/5 text-xs font-medium text-tx-muted hover:text-brand-400 transition-colors"><Plus className="w-3.5 h-3.5" />- Add Set+ {t('workouts.active.addSet')}</button>{isActive && exIdx < session.exercises.length - 1 && (@@ -389,7 +391,7 @@ export default function ActiveWorkout() {: 'bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border'}`}>- Next+ {t('workouts.active.next')}<ChevronRight className="w-3.5 h-3.5" /></button>)}@@ -403,7 +405,7 @@ export default function ActiveWorkout() {}`}><Flag className="w-3.5 h-3.5" />- Finish+ {t('workouts.active.finish')}</button>)}</div>@@ -421,14 +423,14 @@ export default function ActiveWorkout() {className="w-full py-3.5 bg-surface-muted/60 hover:bg-surface-muted border border-surface-border hover:border-brand-500/40 rounded-2xl text-sm font-medium text-tx-secondary hover:text-brand-400 transition-colors flex items-center justify-center gap-2"><Plus className="w-4 h-4" />- Add Exercise+ {t('workouts.active.addExercise')}</button><buttononClick={() => setConfirmCancel(true)}className="w-full py-2.5 text-xs text-tx-muted hover:text-error-400 transition-colors">- Cancel Workout+ {t('workouts.active.cancelWorkout')}</button></div></>@@ -437,11 +439,11 @@ export default function ActiveWorkout() {<ConfirmSheetopen={confirmFinish}icon={Flag}- title="Finish Workout?"- message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}- confirmLabel="Finish"- busyLabel="Saving…"- cancelLabel="Keep Going"+ title={t('workouts.active.finishConfirm.title')}+ message={t('workouts.active.finishConfirm.message', { done: completedSets, total: totalSets })}+ confirmLabel={t('workouts.active.finish')}+ busyLabel={t('common.saving')}+ cancelLabel={t('workouts.active.keepGoing')}busy={finish.busy}error={finish.error}onConfirm={() => { void finish.run() }}@@ -453,10 +455,10 @@ export default function ActiveWorkout() {open={confirmCancel}icon={Trash2}destructive- title="Cancel Workout?"- message="All progress will be lost."- confirmLabel="Cancel"- cancelLabel="Keep Going"+ title={t('workouts.active.cancelConfirm.title')}+ message={t('workouts.active.cancelConfirm.message')}+ confirmLabel={t('common.cancel')}+ cancelLabel={t('workouts.active.keepGoing')}onConfirm={() => { cancelSession(); navigate('/') }}onCancel={() => setConfirmCancel(false)}/>diff --git a/web/src/pages/AddProgram.tsx b/web/src/pages/AddProgram.tsxindex cd0f257..9ee5f08 100644--- a/web/src/pages/AddProgram.tsx+++ b/web/src/pages/AddProgram.tsx@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'import { ArrowLeft, AlertCircle, BookOpen, FileText, CalendarDays } from 'lucide-react'import { programAPI } from '../services/api'import { useSettingsStore, weightShort, displayToLbs } from '../stores/settings'-import { useAsyncAction, hasWorkoutExercises, types } from '@lyftr/shared'+import { useAsyncAction, hasWorkoutExercises, types, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'import type { DayDraft } from '../components/programs/types'@@ -14,13 +14,14 @@ interface ProgramFormData {}export default function AddProgram() {+ const { t } = useTranslation()const navigate = useNavigate()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)// `error` is for what the FORM can tell the user before anything is sent (a missing// name, an empty day). What the SERVER says lives on the hook below — different// questions, kept apart on purpose, and rendered in the same place.- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })@@ -41,17 +42,17 @@ export default function AddProgram() {}await programAPI.create(payload)navigate('/programs')- }, 'Failed to create program')+ }, t('programs.form.createFailed'))- useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.failureKey])const handleSubmit = (e: React.FormEvent) => {e.preventDefault()- if (!formData.name.trim()) { setError('Program name required'); return }- if (formData.days.length === 0) { setError('Add at least one day'); return }+ if (!formData.name.trim()) { setError({ key: 'programs.form.errors.nameRequired' }); return }+ if (formData.days.length === 0) { setError({ key: 'programs.form.errors.noDays' }); return }const hasAnyExercise = hasWorkoutExercises(formData.days)- if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }- setError('')+ if (!hasAnyExercise) { setError({ key: 'programs.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -61,13 +62,13 @@ export default function AddProgram() {return (<div className="space-y-6 animate-slide-up pb-10"><div className="flex items-center gap-3">- <button aria-label="Go back" onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors">+ <button aria-label={t('common.goBack')} onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h1 className="font-display font-bold text-2xl text-tx-primary">New Program</h1>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('programs.form.newTitle')}</h1><p className="text-xs text-tx-muted">- {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}+ {t('programs.form.summary', { days: t('programs.count.days', { count: formData.days.length }), exercises: t('programs.count.exercises', { count: totalExercises }), sets: t('programs.count.sets', { count: totalSets }) })}</p></div></div>@@ -76,21 +77,21 @@ export default function AddProgram() {{(error || save.error) && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error || save.error}</span>+ <span>{error ? uiMessage(error) : save.error}</span></div>)}<div><div className="flex items-center gap-2 mb-2"><BookOpen className="w-4 h-4 text-brand-500" />- <label className="label">Program Name</label>- <span className="text-xs text-tx-muted">(required)</span>+ <label className="label">{t('programs.form.name')}</label>+ <span className="text-xs text-tx-muted">{t('programs.form.required')}</span></div><inputtype="text"value={formData.name}onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))}- placeholder="e.g., Push Pull Legs, Upper Lower"+ placeholder={t('programs.form.namePlaceholder')}className="input mt-1"/></div>@@ -98,12 +99,12 @@ export default function AddProgram() {<div><div className="flex items-center gap-2 mb-2"><FileText className="w-4 h-4 text-brand-500" />- <label className="label">Notes</label>+ <label className="label">{t('workouts.form.notes')}</label></div><textareavalue={formData.notes}onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))}- placeholder="Program description or goals…"+ placeholder={t('programs.form.notesPlaceholder')}className="input mt-1 min-h-16 resize-none"/></div>@@ -112,15 +113,15 @@ export default function AddProgram() {<div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg"><div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.days.length}</div>- <div className="text-xs text-tx-muted">Days</div>+ <div className="text-xs text-tx-muted">{t('programs.form.days')}</div></div><div className="text-center"><div className="text-sm font-bold text-brand-500">{totalExercises}</div>- <div className="text-xs text-tx-muted">Exercises</div>+ <div className="text-xs text-tx-muted">{t('workouts.form.exercises')}</div></div><div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div>- <div className="text-xs text-tx-muted">Target Sets</div>+ <div className="text-xs text-tx-muted">{t('programs.form.targetSets')}</div></div></div>)}@@ -128,8 +129,8 @@ export default function AddProgram() {<div><div className="flex items-center gap-2 mb-3"><CalendarDays className="w-4 h-4 text-brand-500" />- <label className="label">Days</label>- <span className="text-xs text-tx-muted">(required — repeats in this order)</span>+ <label className="label">{t('programs.form.days')}</label>+ <span className="text-xs text-tx-muted">{t('programs.form.daysHintNew')}</span></div><ProgramDaysEditordays={formData.days}@@ -143,11 +144,11 @@ export default function AddProgram() {<div className="flex gap-3 pt-2"><button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">- Cancel+ {t('common.cancel')}</button><button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"><BookOpen className="w-4 h-4" />- {save.busy ? 'Saving…' : 'Save Program'}+ {save.busy ? t('common.saving') : t('programs.form.saveProgram')}</button></div></form>diff --git a/web/src/pages/AddWorkout.tsx b/web/src/pages/AddWorkout.tsxindex 8f1006e..ac26471 100644--- a/web/src/pages/AddWorkout.tsx+++ b/web/src/pages/AddWorkout.tsx@@ -7,7 +7,7 @@ import WeightInput from '../components/WeightInput'import ExercisePicker from '../components/ExercisePicker'import ProgramPicker from '../components/ProgramPicker'import RestPicker from '../components/RestPicker'-import { useAsyncAction, types, todayStr, dayToInstant } from '@lyftr/shared'+import { useAsyncAction, types, muscleLabel, equipmentLabel, todayStr, dayToInstant, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'interface WorkoutFormData {name: string@@ -18,6 +18,7 @@ interface WorkoutFormData {}export default function AddWorkout() {+ const { t } = useTranslation()const navigate = useNavigate()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)@@ -25,8 +26,9 @@ export default function AddWorkout() {const [showProgramPicker, setShowProgramPicker] = useState(false)// `error` is for what the FORM can tell the user before anything is sent (a missing// name, an empty day). What the SERVER says lives on the hook below — different- // questions, kept apart on purpose, and rendered in the same place.- const [error, setError] = useState('')+ // questions, kept apart on purpose, and rendered in the same place. Kept as a UiMessage+ // rather than a sentence, so a banner already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, date: todayStr(), exercises: [] })@@ -40,14 +42,14 @@ export default function AddWorkout() {setPickerExercises(newMap)setFormData(prev => ({ ...prev, exercises: newExercises }))setShowProgramPicker(false)- setError('')+ setError(null)}const addExercise = (exercise: types.Exercise) => {setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))setFormData(prev => ({ ...prev, exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', rest_seconds: settings.rest_seconds_default ?? 90, sets: [{ set_number: 1, reps: 0, weight: 0 }] }] }))setShowPicker(false)- setError('')+ setError(null)}const removeExercise = (index: number) => setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))@@ -96,15 +98,15 @@ export default function AddWorkout() {}await workoutAPI.create(payload)navigate('/workouts')- }, 'Failed to create workout')+ }, t('workouts.form.createFailed'))- useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.failureKey])const handleSubmit = (e: React.FormEvent) => {e.preventDefault()- if (!formData.name.trim()) { setError('Workout name required'); return }- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }- setError('')+ if (!formData.name.trim()) { setError({ key: 'workouts.form.errors.nameRequired' }); return }+ if (formData.exercises.length === 0) { setError({ key: 'workouts.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -115,12 +117,12 @@ export default function AddWorkout() {return (<div className="space-y-6 animate-slide-up pb-10"><div className="flex items-center gap-3">- <button aria-label="Go back" onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors">+ <button aria-label={t('common.goBack')} onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Log Workout</h1>- <p className="text-xs text-tx-muted">{formData.exercises.length} exercise{formData.exercises.length === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}</p>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('workouts.form.logTitle')}</h1>+ <p className="text-xs text-tx-muted">{t('workouts.form.summary', { exercises: t('workouts.form.exerciseCount', { count: formData.exercises.length }), sets: t('workouts.form.setCount', { count: totalSets }) })}</p></div></div>@@ -128,23 +130,23 @@ export default function AddWorkout() {{(error || save.error) && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error || save.error}</span>+ <span>{error ? uiMessage(error) : save.error}</span></div>)}<div><div className="flex items-center gap-2 mb-2"><Dumbbell className="w-4 h-4 text-brand-500" />- <label className="label">Workout Name</label>- <span className="text-xs text-tx-muted">(required)</span>+ <label className="label">{t('workouts.form.name')}</label>+ <span className="text-xs text-tx-muted">{t('workouts.form.required')}</span></div>- <input type="text" value={formData.name} onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))} placeholder="e.g., Leg Day, Push Day" className="input mt-1" />+ <input type="text" value={formData.name} onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))} placeholder={t('workouts.form.namePlaceholder')} className="input mt-1" /></div><div><div className="flex items-center gap-2 mb-2"><CalendarDays className="w-4 h-4 text-brand-500" />- <label className="label">Date</label>+ <label className="label">{t('workouts.form.date')}</label></div><input type="date" value={formData.date} onChange={e => setFormData(prev => ({ ...prev, date: e.target.value }))} className="input" max={todayStr()} /></div>@@ -152,12 +154,12 @@ export default function AddWorkout() {<div><div className="flex items-center gap-2 mb-2"><Clock className="w-4 h-4 text-brand-500" />- <label className="label">Duration (minutes)</label>+ <label className="label">{t('workouts.form.durationMinutes')}</label></div><div className="grid grid-cols-2 gap-3"><input type="number" value={formData.duration || ''} onChange={e => setFormData(prev => ({ ...prev, duration: Number(e.target.value) || 0 }))} placeholder="0" className="input" min="0" /><div className="flex items-center px-3 bg-surface-muted/30 rounded-lg text-sm text-tx-muted font-medium">- {Math.floor(formData.duration / 60)}h {formData.duration % 60}m+ {t('workouts.form.durationHm', { hours: Math.floor(formData.duration / 60), minutes: formData.duration % 60 })}</div></div></div>@@ -165,16 +167,16 @@ export default function AddWorkout() {<div><div className="flex items-center gap-2 mb-2"><FileText className="w-4 h-4 text-brand-500" />- <label className="label">Notes</label>+ <label className="label">{t('workouts.form.notes')}</label></div>- <textarea value={formData.notes} onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))} placeholder="How did it feel? Any PRs?" className="input mt-1 min-h-20 resize-none" />+ <textarea value={formData.notes} onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))} placeholder={t('workouts.form.notesPlaceholder')} className="input mt-1 min-h-20 resize-none" /></div>{formData.exercises.length > 0 && (<div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">- <div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div><div className="text-xs text-tx-muted">Exercises</div></div>- <div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div><div className="text-xs text-tx-muted">Sets</div></div>- <div className="text-center"><div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div><div className="text-xs text-tx-muted">Total {wUnit}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div><div className="text-xs text-tx-muted">{t('workouts.form.exercises')}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div><div className="text-xs text-tx-muted">{t('workouts.form.sets')}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div><div className="text-xs text-tx-muted">{t('workouts.form.totalUnit', { unit: wUnit })}</div></div></div>)}@@ -182,17 +184,17 @@ export default function AddWorkout() {<div className="flex items-center justify-between mb-3"><div className="flex items-center gap-2"><Zap className="w-4 h-4 text-brand-500" />- <label className="label">Exercises</label>- <span className="text-xs text-tx-muted">(required)</span>+ <label className="label">{t('workouts.form.exercises')}</label>+ <span className="text-xs text-tx-muted">{t('workouts.form.required')}</span></div><div className="flex items-center gap-2"><button type="button" onClick={() => setShowProgramPicker(true)} className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border rounded-lg transition-colors font-medium"><BookOpen className="w-3.5 h-3.5" />- Load Program+ {t('workouts.form.loadProgram')}</button><button type="button" onClick={() => setShowPicker(true)} className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"><Plus className="w-3.5 h-3.5" />- Add Exercise+ {t('workouts.form.addExercise')}</button></div></div>@@ -213,46 +215,46 @@ export default function AddWorkout() {</div><p className="font-semibold text-tx-primary">{exercise?.name}</p></div>- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>+ <p className="text-xs text-tx-muted ml-8">{muscleLabel(exercise?.muscle_group)} • {equipmentLabel(exercise?.equipment)}</p></div>- <button type="button" aria-label="Remove exercise" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeExercise')} onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div><div className="mb-4">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>- <input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} placeholder="e.g., Felt strong" className="input text-sm" />+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.notes')}</label>+ <input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} placeholder={t('workouts.form.exerciseNotesPlaceholder')} className="input text-sm" /></div><div className="mb-4"><div className="flex items-center gap-1.5 mb-1"><Timer className="w-3.5 h-3.5 text-brand-500" />- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Rest between sets</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">{t('workouts.form.restBetweenSets')}</label></div><RestPicker value={workoutEx.rest_seconds ?? 90} onChange={secs => setExRest(exIdx, secs)} /></div><div className="space-y-2 mb-3"><div className="flex items-center justify-between">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Sets</label>- <span className="text-xs text-tx-muted">{workoutEx.sets.length} set{workoutEx.sets.length === 1 ? '' : 's'}</span>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">{t('workouts.form.sets')}</label>+ <span className="text-xs text-tx-muted">{t('workouts.form.setCount', { count: workoutEx.sets.length })}</span></div>{workoutEx.sets.map((set, setIdx) => (<div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50"><div className="flex-shrink-0 w-12">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">{t('workouts.form.set')}</label><div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Reps</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.reps')}</label><input type="number" inputMode="numeric" value={set.reps || ''} onChange={e => updateSet(exIdx, setIdx, 'reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" /></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Weight</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.weight')}</label><WeightInput size="sm" value={set.weight ? String(set.weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'weight', v)} unit={wUnit} placeholder="225" /></div>- <button type="button" aria-label="Remove set" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeSet')} onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div>@@ -261,7 +263,7 @@ export default function AddWorkout() {<button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"><Plus className="w-3.5 h-3.5" />- Add Set+ {t('workouts.form.addSet')}</button></div>)@@ -271,11 +273,11 @@ export default function AddWorkout() {<div className="flex gap-3 pt-2"><button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">- Cancel+ {t('common.cancel')}</button><button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"><Dumbbell className="w-4 h-4" />- {save.busy ? 'Saving…' : 'Save Workout'}+ {save.busy ? t('common.saving') : t('workouts.form.saveWorkout')}</button></div></form>diff --git a/web/src/pages/ChangeEmail.test.tsx b/web/src/pages/ChangeEmail.test.tsxindex c54f33f..1433c69 100644--- a/web/src/pages/ChangeEmail.test.tsx+++ b/web/src/pages/ChangeEmail.test.tsx@@ -1,7 +1,8 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, fireEvent, waitFor } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'import ChangeEmail from './ChangeEmail'+import { i18n } from '@lyftr/shared'const changeEmail = vi.fn()@@ -89,3 +90,22 @@ describe('ChangeEmail', () => {expect((screen.getByLabelText('New email') as HTMLInputElement).value).toBe('[email protected]')})})++describe('ChangeEmail in Spanish', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ it('reads the form and the confirmation from the catalog, address kept intact (es)', async () => {+ await i18n.changeLanguage('es')+ changeEmail.mockResolvedValue({ id: 1, email: '[email protected]', created_at: '2026-07-01T00:00:00Z' })+ renderPage()++ expect(screen.getByRole('heading', { name: 'Cambiar correo' })).toBeTruthy()+ fireEvent.change(screen.getByLabelText('Correo nuevo'), { target: { value: '[email protected]' } })+ fireEvent.change(screen.getByLabelText('Contraseña actual'), { target: { value: 'password123' } })+ fireEvent.click(screen.getByRole('button', { name: 'Actualizar correo' }))++ await waitFor(() => expect(screen.getByRole('heading', { name: 'Correo cambiado' })).toBeTruthy())+ expect(screen.getByText('[email protected]').tagName).toBe('SPAN')+ expect(screen.getByText(/en tus otros dispositivos se cerró la sesión/)).toBeTruthy()+ })+})diff --git a/web/src/pages/ChangeEmail.tsx b/web/src/pages/ChangeEmail.tsxindex 48bc018..5b361ab 100644--- a/web/src/pages/ChangeEmail.tsx+++ b/web/src/pages/ChangeEmail.tsx@@ -2,7 +2,7 @@ import { useState } from 'react'import { Link } from 'react-router-dom'import { ArrowLeft, AlertCircle, Loader, MailCheck } from 'lucide-react'import { useAuthStore } from '../stores/auth'-import { useAsyncAction, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'+import { Trans, useAsyncAction, useTranslation, emailChanged, onlyLetterCaseChanged } from '@lyftr/shared'import PageHeader from '../components/ui/PageHeader'import PasswordField from '../components/ui/PasswordField'@@ -10,6 +10,7 @@ import PasswordField from '../components/ui/PasswordField'// It confirms with a card rather than a toast because the sign-in identifier changed:// that is a consequence the user has to be told about, not just a saved field.export default function ChangeEmail() {+ const { t } = useTranslation()const user = useAuthStore(s => s.user)const changeEmail = useAuthStore(s => s.changeEmail)const [email, setEmail] = useState('')@@ -23,7 +24,7 @@ export default function ChangeEmail() {setCurrent('')setCaseOnly(onlyCase)setChangedTo(updated.email)- }, "Couldn't change your email. Please try again.")+ }, t('settings.account.email.failedFallback'))const ready = emailChanged(email, user?.email) && !!current@@ -37,7 +38,7 @@ export default function ChangeEmail() {return (<div className="space-y-5 animate-slide-up max-w-lg"><Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Settings+ <ArrowLeft className="w-4 h-4" /> {t('settings.account.backLink')}</Link><div className="card p-6 flex flex-col items-center text-center gap-3">@@ -45,15 +46,19 @@ export default function ChangeEmail() {<MailCheck className="w-6 h-6 text-success-400" /></div><div>- <h1 className="font-display font-bold text-xl text-tx-primary">Email changed</h1>+ <h1 className="font-display font-bold text-xl text-tx-primary">{t('settings.account.email.changedTitle')}</h1><p className="text-sm text-tx-muted mt-1">- Sign in with <span className="break-all text-tx-secondary">{changedTo}</span> from now on.{' '}+ <Trans+ i18nKey="settings.account.email.signInWith"+ values={{ email: changedTo }}+ components={{ email: <span className="break-all text-tx-secondary" /> }}+ />{' '}{caseOnly- ? 'Only the letter case changed, so your other devices stay signed in.'- : 'You stay signed in here; your other devices are signed out.'}+ ? t('settings.account.email.caseOnly')+ : t('settings.account.email.signedOutElsewhere')}</p></div>- <Link to="/settings" className="btn-secondary btn-sm mt-1">Back to settings</Link>+ <Link to="/settings" className="btn-secondary btn-sm mt-1">{t('settings.account.backToSettings')}</Link></div></div>)@@ -62,23 +67,23 @@ export default function ChangeEmail() {return (<div className="space-y-5 animate-slide-up max-w-lg"><Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Settings+ <ArrowLeft className="w-4 h-4" /> {t('settings.account.backLink')}</Link><PageHeader- title="Change email"- subtitle="You will sign in with the new address. Changing more than the letter case signs out your other devices."+ title={t('settings.account.email.pageTitle')}+ subtitle={t('settings.account.email.pageSubtitle')}/><form onSubmit={submit} className="card p-4 space-y-4"><div>- <p className="text-xs text-tx-muted">Current email</p>+ <p className="text-xs text-tx-muted">{t('settings.account.email.current')}</p><p className="text-sm text-tx-primary font-mono break-all">{user?.email}</p></div><div><label htmlFor="new-email" className="label">- New email+ {t('settings.account.email.new')}</label><inputid="new-email"@@ -95,7 +100,7 @@ export default function ChangeEmail() {<PasswordFieldid="current-password"- label="Current password"+ label={t('settings.account.password.current')}value={current}onChange={setCurrent}autoComplete="current-password"@@ -114,10 +119,10 @@ export default function ChangeEmail() {disabled={save.busy || !ready}className="btn-primary btn-sm flex-1 flex items-center justify-center gap-2">- {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update email'}+ {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> {t('settings.account.saving')}</> : t('settings.account.email.submit')}</button><Link to="/settings" className="btn-secondary btn-sm flex-1 flex items-center justify-center">- Cancel+ {t('common.cancel')}</Link></div></form>diff --git a/web/src/pages/ChangePassword.tsx b/web/src/pages/ChangePassword.tsxindex bcdfdbc..f577a5e 100644--- a/web/src/pages/ChangePassword.tsx+++ b/web/src/pages/ChangePassword.tsx@@ -3,7 +3,7 @@ import { Link } from 'react-router-dom'import { ArrowLeft, AlertCircle, Loader, ShieldCheck } from 'lucide-react'import { userAPI } from '../services/api'import { useAuthStore } from '../stores/auth'-import { useAsyncAction, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'+import { useAsyncAction, useTranslation, differentRuleLabel, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'import PageHeader from '../components/ui/PageHeader'import PasswordField, { Rule } from '../components/ui/PasswordField'@@ -12,6 +12,7 @@ import PasswordField, { Rule } from '../components/ui/PasswordField'// here. That contract needs a URL that lands on the form itself; a collapsed panel on// /settings would drop the user on a settings list with nothing open.export default function ChangePassword() {+ const { t } = useTranslation()const user = useAuthStore(s => s.user)const [current, setCurrent] = useState('')const [next, setNext] = useState('')@@ -24,7 +25,7 @@ export default function ChangePassword() {await userAPI.changePassword({ current_password: current, new_password: next })setCurrent(''); setNext(''); setConfirm('')setDone(true)- }, "Couldn't change your password. Please try again.")+ }, t('settings.account.password.failedFallback'))const submit = async (e: React.FormEvent) => {e.preventDefault()@@ -43,7 +44,7 @@ export default function ChangePassword() {return (<div className="space-y-5 animate-slide-up max-w-lg"><Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Settings+ <ArrowLeft className="w-4 h-4" /> {t('settings.account.backLink')}</Link><div className="card p-6 flex flex-col items-center text-center gap-3">@@ -51,13 +52,12 @@ export default function ChangePassword() {<ShieldCheck className="w-6 h-6 text-success-400" /></div><div>- <h1 className="font-display font-bold text-xl text-tx-primary">Password changed</h1>+ <h1 className="font-display font-bold text-xl text-tx-primary">{t('settings.account.password.changedTitle')}</h1><p className="text-sm text-tx-muted mt-1">- You are still signed in here. Every other device has been signed out and will- need the new password.+ {t('settings.account.password.changedBody')}</p></div>- <Link to="/settings" className="btn-secondary btn-sm mt-1">Back to settings</Link>+ <Link to="/settings" className="btn-secondary btn-sm mt-1">{t('settings.account.backToSettings')}</Link></div></div>)@@ -66,12 +66,12 @@ export default function ChangePassword() {return (<div className="space-y-5 animate-slide-up max-w-lg"><Link to="/settings" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Settings+ <ArrowLeft className="w-4 h-4" /> {t('settings.account.backLink')}</Link><PageHeader- title="Change password"- subtitle="You will stay signed in here. Every other device is signed out."+ title={t('settings.account.password.pageTitle')}+ subtitle={t('settings.account.password.pageSubtitle')}/><form onSubmit={submit} className="card p-4 space-y-4">@@ -92,7 +92,7 @@ export default function ChangePassword() {<PasswordFieldid="current-password"- label="Current password"+ label={t('settings.account.password.current')}value={current}onChange={setCurrent}autoComplete="current-password"@@ -100,7 +100,7 @@ export default function ChangePassword() {<PasswordFieldid="new-password"- label="New password"+ label={t('settings.account.password.new')}value={next}onChange={setNext}autoComplete="new-password"@@ -111,7 +111,7 @@ export default function ChangePassword() {<PasswordFieldid="confirm-password"- label="Confirm new password"+ label={t('settings.account.password.confirmNew')}value={confirm}onChange={setConfirm}autoComplete="new-password"@@ -135,10 +135,10 @@ export default function ChangePassword() {disabled={save.busy || !rules.ready}className="btn-primary btn-sm flex-1 flex items-center justify-center gap-2">- {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Saving</> : 'Update password'}+ {save.busy ? <><Loader className="w-3.5 h-3.5 animate-spin" /> {t('settings.account.saving')}</> : t('settings.account.password.submit')}</button><Link to="/settings" className="btn-secondary btn-sm flex-1 flex items-center justify-center">- Cancel+ {t('common.cancel')}</Link></div></form>diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsxindex da9f4fb..13495bb 100644--- a/web/src/pages/Dashboard.tsx+++ b/web/src/pages/Dashboard.tsx@@ -18,9 +18,9 @@ import { useWorkoutSession } from '../stores/workoutSession'import { useAuthStore } from '../stores/auth'import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'import { useDisplayName } from '../lib/lyftr'-import { apiErrorMessage, isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, lifterQuip } from '@lyftr/shared'+import { isDailyStats, workoutDay, entryDay, types, activeSessionExercisesForDay, dayLabel, sessionNameForDay, nextStartableDay, muscleRoast, muscleHex, calcVolume, greeting, formatDay, lifterQuip, formatDate, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { useNavigate, Link } from 'react-router-dom'-import { muscleColor } from '../utils/exerciseUtils'+import { muscleColor, muscleLabel } from '../utils/exerciseUtils'const DEFAULT_FOOD: types.DailyStats = {date: '',@@ -62,6 +62,9 @@ function MuscleSparkline({ values, color, isTop }: { values: number[], color: st)}+// The seven weekday rows of the heatmap; every other one carries a letter.+const WEEKDAY_ROWS = [0, 1, 2, 3, 4, 5, 6] as const+const TOOLTIP_STYLE = {background: 'var(--color-surface-raised, #1e1e2e)',border: '1px solid var(--color-surface-border, #2d2d3a)',@@ -71,6 +74,7 @@ const TOOLTIP_STYLE = {}export default function Dashboard() {+ const { t } = useTranslation()// Sampled per mount, not at module load. As a module constant this went stale the// moment the tab outlived the day it was opened on — a tab left open across midnight// kept yesterday's date header, week boundary and heatmap "today" until a reload.@@ -92,7 +96,9 @@ export default function Dashboard() {const [weightStats, setWeightStats] = useState<types.WeightStats | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // Failures are kept as a UiMessage (a key and the failure that caused it), not as a sentence,+ // so a banner already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Bumping this re-runs the load effect. A lifted useCallback would be the tidier// shape, but it would mean restructuring a working effect to gain a retry button;// this does the same job in three lines.@@ -106,8 +112,7 @@ export default function Dashboard() {// Name -> what the server actually said. Keeping the message matters for the two// areas big enough to show one: a card that never loaded can say why, and a generic// sentence there would be us inventing a cause we were handed.- const [missing, setMissing] = useState<Record<string, string>>({})- const FALLBACK = "The server didn't say what went wrong."+ const [missing, setMissing] = useState<Record<string, UiMessage>>({})const foodMissing = "today's food" in missingconst weightMissing = 'your weight' in missing@@ -118,21 +123,21 @@ export default function Dashboard() {useEffect(() => {void fetchSettings()- const absent: Record<string, string> = {}+ const absent: Record<string, UiMessage> = {}Promise.all([workoutAPI.list({ limit: 84 }), // 12 weeks × 7 days max// backend's max — Up Next must see every programprogramAPI.list({ limit: 100 })- .catch(err => { absent['your programs'] = apiErrorMessage(err, FALLBACK); return [] }),+ .catch(err => { absent['your programs'] = { key: 'settings.unknownError', cause: err }; return [] }),foodAPI.stats(format(TODAY, 'yyyy-MM-dd'))// A 200 carrying the wrong shape never reaches the catch. Unchecked, the missing// field went through Math.round and the ring read "NaN"..then(fs => isDailyStats(fs) ? fs : Promise.reject(new Error('unreadable')))- .catch(err => { absent["today's food"] = apiErrorMessage(err, FALLBACK); return DEFAULT_FOOD }),+ .catch(err => { absent["today's food"] = { key: 'settings.unknownError', cause: err }; return DEFAULT_FOOD }),weightAPI.list({ limit: 14 })- .catch(err => { absent['your weight'] = apiErrorMessage(err, FALLBACK); return [] }),+ .catch(err => { absent['your weight'] = { key: 'settings.unknownError', cause: err }; return [] }),weightAPI.stats()- .catch(err => { absent['your weight'] = apiErrorMessage(err, FALLBACK); return null }),+ .catch(err => { absent['your weight'] = { key: 'settings.unknownError', cause: err }; return null }),]).then(([ws, ps, fs, wl, wst]) => {setWorkouts(ws || [])@@ -142,7 +147,7 @@ export default function Dashboard() {setWeightStats(wst)setMissing(absent)})- .catch(err => setError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ .catch(err => setError({ key: 'settings.unknownError', cause: err })).finally(() => setLoading(false))}, [TODAY, retryKey, fetchSettings])@@ -159,8 +164,8 @@ export default function Dashboard() {return (<ErrorStatesize="page"- title="Couldn't load your dashboard"- message={error}+ title={t('home.loadFailed')}+ message={uiMessage(error)}onRetry={() => { setError(null); setLoading(true); setRetryKey(k => k + 1) }}/>)@@ -189,7 +194,7 @@ export default function Dashboard() {// Volume chart: slice by selected period, oldest→newestconst chartData = workouts.slice(0, Number(volumePeriod)).reverse().map(w => ({- date: formatDay(workoutDay(w), 'M/d'),+ date: formatDay(workoutDay(w), 'numericMonthDay'),volume: displayVolume(calcVolume(w), settings.weight_unit),name: w.name,}))@@ -216,9 +221,9 @@ export default function Dashboard() {}// month labels: show month name on first week that starts in that monthconst monthLabels: (string | null)[] = heatmapWeeks.map((week, i) => {- const m = format(week[0], 'MMM')+ const m = formatDate(week[0], 'monthShort')if (i === 0) return m- const prev = format(heatmapWeeks[i - 1][0], 'MMM')+ const prev = formatDate(heatmapWeeks[i - 1][0], 'monthShort')return m !== prev ? m : null})@@ -256,7 +261,7 @@ export default function Dashboard() {// Weight sparklineconst sparkData = [...weightLogs].reverse().map(l => ({- date: formatDay(entryDay(l), 'M/d'),+ date: formatDay(entryDay(l), 'numericMonthDay'),weight: displayWeight(l.weight, settings.weight_unit),}))@@ -267,7 +272,7 @@ export default function Dashboard() {<div className="flex justify-between items-start gap-3"><div className="min-w-0"><p className="text-[11px] text-tx-muted uppercase tracking-wider font-medium">- {format(TODAY, 'EEEE, MMMM d')}+ {formatDate(TODAY, 'weekdayMonthDayLong')}</p>{/* Never clipped: a name is the one string here that is the user's own, andits length is bounded at the input instead (MaxDisplayNameLen). text-balance@@ -275,7 +280,7 @@ export default function Dashboard() {wrap. Mobile wraps too, but gets no text-balance and deliberately noleading-tight — an imposed lineHeight clips descenders on iOS (ui/Field.tsx). */}<h1 className="font-display font-bold text-2xl text-tx-primary mt-0.5 leading-tight text-balance">- {greeting(TODAY)}, {username}+ {greeting(TODAY, username)}</h1><p className="text-xs text-tx-muted mt-1">{lifterQuip(user?.id ?? '')}</p></div>@@ -284,7 +289,7 @@ export default function Dashboard() {className="btn-primary btn-sm flex-shrink-0"><Play className="w-3.5 h-3.5" />- {session ? 'Resume' : 'Start'}+ {t(session ? 'home.header.resume' : 'home.header.start')}</button></div>@@ -299,8 +304,8 @@ export default function Dashboard() {<Timer className="w-4 h-4 text-amber-400 animate-pulse" /></div><div>- <p className="text-sm font-semibold text-amber-300">Workout in progress</p>- <p className="text-xs text-amber-400/70">{session.name} — tap to resume</p>+ <p className="text-sm font-semibold text-amber-300">{t('home.activeSession.title')}</p>+ <p className="text-xs text-amber-400/70">{t('home.activeSession.tapToResume', { name: session.name })}</p></div></div><ArrowRight className="w-4 h-4 text-amber-400 flex-shrink-0" />@@ -321,7 +326,7 @@ export default function Dashboard() {<div className="flex items-center gap-3 card p-3 hover:bg-surface-muted/40 transition-colors"><Linkto={`/programs/${upNext.program.id}`}- aria-label={`View ${upNext.program.name} routine`}+ aria-label={t('home.upNext.viewRoutine', { name: upNext.program.name })}className="flex items-center gap-3 flex-1 min-w-0">{upNext.day.exercises?.[0]?.exercise?.image_url ? (@@ -337,14 +342,14 @@ export default function Dashboard() {</div>)}<div className="flex-1 min-w-0">- <p className="text-[10px] text-tx-muted uppercase tracking-wide font-medium truncate">Up next · {upNext.program.name}</p>+ <p className="text-[10px] text-tx-muted uppercase tracking-wide font-medium truncate">{t('home.upNext.label', { name: upNext.program.name })}</p><p className="text-sm font-semibold text-tx-primary truncate mt-0.5">{dayLabel(upNext.day, upNext.day.order_index)}</p>- <p className="text-xs text-tx-muted mt-0.5">{(upNext.day.exercises ?? []).length} exercise{(upNext.day.exercises ?? []).length === 1 ? '' : 's'}</p>+ <p className="text-xs text-tx-muted mt-0.5">{t('home.upNext.exercises', { count: (upNext.day.exercises ?? []).length })}</p></div></Link><buttononClick={startUpNext}- aria-label={`Start ${dayLabel(upNext.day, upNext.day.order_index)}`}+ aria-label={t('home.upNext.start', { name: dayLabel(upNext.day, upNext.day.order_index) })}className="flex items-center justify-center w-9 h-9 bg-brand-500 hover:bg-brand-600 text-white rounded-xl transition-colors flex-shrink-0"><Play className="w-4 h-4" />@@ -356,20 +361,20 @@ export default function Dashboard() {<div className="grid grid-cols-3 gap-2"><div className="card p-3 flex flex-col gap-1.5"><div className="flex items-center justify-between">- <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">Week</span>+ <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('home.kpi.week')}</span><Dumbbell className="w-3 h-3 text-tx-muted" /></div><p className="text-xl font-bold text-tx-primary leading-none">{weekWorkouts.length}</p>- <p className="text-[10px] text-tx-muted">sessions</p>+ <p className="text-[10px] text-tx-muted">{t('home.kpi.sessions')}</p></div><div className="card p-3 flex flex-col gap-1.5"><div className="flex items-center justify-between">- <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">Cals</span>+ <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('home.kpi.cals')}</span><Flame className="w-3 h-3 text-tx-muted" /></div>{foodMissing ? (- <StatFailure label="Couldn't load today's calories" />+ <StatFailure label={t('home.kpi.caloriesFailed')} />) : (<><p className="text-xl font-bold text-tx-primary leading-none">{Math.round(food.total_calories)}</p>@@ -382,11 +387,11 @@ export default function Dashboard() {<div className="card p-3 flex flex-col gap-1.5"><div className="flex items-center justify-between">- <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">Protein</span>+ <span className="text-[10px] text-tx-muted uppercase tracking-wide font-medium">{t('home.macro.protein')}</span><Beef className="w-3 h-3 text-tx-muted" /></div>{foodMissing ? (- <StatFailure label="Couldn't load today's protein" />+ <StatFailure label={t('home.kpi.proteinFailed')} />) : (<><p className="text-xl font-bold text-tx-primary leading-none">@@ -404,7 +409,7 @@ export default function Dashboard() {<div className="card p-4"><SectionHeadericon={TrendingUp}- title="Volume Trend"+ title={t('home.volume.title')}right={<PeriodSelector options={['7', '14', '30'] as const} value={volumePeriod} onChange={setVolumePeriod} />}className="mb-3"/>@@ -412,7 +417,7 @@ export default function Dashboard() {{chartData.length === 0 ? (<div className="flex flex-col items-center justify-center py-8 gap-2"><Dumbbell className="w-6 h-6 text-tx-muted opacity-40" />- <p className="text-xs text-tx-muted">Log workouts to see trends</p>+ <p className="text-xs text-tx-muted">{t('home.volume.empty')}</p></div>) : (<>@@ -428,7 +433,7 @@ export default function Dashboard() {<YAxis hide /><TooltipcontentStyle={TOOLTIP_STYLE}- formatter={(v: number) => [`${v.toLocaleString()} ${wUnit}`, 'Volume']}+ formatter={(v: number) => [`${v.toLocaleString()} ${wUnit}`, t('home.volume.tooltip')]}labelFormatter={(label: string) => chartData.find(d => d.date === label)?.name || label}cursor={{ fill: 'rgba(99,102,241,0.08)', radius: 4 }}/>@@ -450,7 +455,7 @@ export default function Dashboard() {return (<div key={i} className="flex flex-col items-center gap-1.5"><span className={`text-[10px] font-semibold ${isToday ? 'text-brand-400' : 'text-tx-muted'}`}>- {format(day, 'EEEEE')}+ {formatDate(day, 'weekdayNarrow')}</span><div className={`w-3 h-3 rounded-full transition-all ${hasWorkout ? 'bg-brand-500 shadow-sm shadow-brand-500/50' :@@ -470,14 +475,14 @@ export default function Dashboard() {<div className="card p-4"><SectionHeadericon={Activity}- title="Consistency"- right={<span className="text-xs text-tx-muted">12 weeks</span>}+ title={t('home.consistency.title')}+ right={<span className="text-xs text-tx-muted">{t('home.consistency.range')}</span>}className="mb-3"/>{workouts.length === 0 ? (<div className="flex flex-col items-center justify-center py-6 gap-2">- <p className="text-xs text-tx-muted">Start working out to build your streak</p>+ <p className="text-xs text-tx-muted">{t('home.consistency.empty')}</p></div>) : (<>@@ -495,10 +500,10 @@ export default function Dashboard() {))}{/* Rows 1–7: day label + cells */}- {(['M', '', 'W', '', 'F', '', 'S'] as const).map((lbl, dayIdx) => (+ {WEEKDAY_ROWS.map((dayIdx) => ([<div key={`lbl-${dayIdx}`} className="text-[9px] text-tx-muted/60 font-medium flex items-center leading-none">- {lbl}+ {dayIdx % 2 === 0 ? formatDate(heatmapWeeks[0][dayIdx], 'weekdayNarrow') : ''}</div>,...heatmapWeeks.map((week, wi) => {const day = week[dayIdx]@@ -508,7 +513,7 @@ export default function Dashboard() {return (<divkey={`${wi}-${dayIdx}`}- title={`${format(day, 'MMM d')}${count > 0 ? ` · ${count} workout${count > 1 ? 's' : ''}` : ''}`}+ title={count > 0 ? t('home.heatmap.workouts', { date: formatDate(day, 'monthDay'), count }) : formatDate(day, 'monthDay')}className={`h-3 rounded-[2px] transition-colors ${future ? 'bg-surface-muted/20' :count === 0 ? 'bg-surface-muted/50' :@@ -524,11 +529,11 @@ export default function Dashboard() {{/* Legend */}<div className="flex items-center gap-1.5 mt-2 justify-end">- <span className="text-[9px] text-tx-muted">Less</span>+ <span className="text-[9px] text-tx-muted">{t('home.heatmap.less')}</span>{['bg-surface-muted/50', 'bg-brand-500/30', 'bg-brand-500/60', 'bg-brand-500'].map((cls, i) => (<div key={i} className={`w-3 h-3 rounded-[3px] ${cls}`} />))}- <span className="text-[9px] text-tx-muted">More</span>+ <span className="text-[9px] text-tx-muted">{t('home.heatmap.more')}</span></div></>)}@@ -549,14 +554,16 @@ export default function Dashboard() {<div className="min-w-0"><p className="text-sm font-semibold text-tx-primary truncate">{lastWorkout.name}</p><p className="text-xs text-tx-muted mt-0.5">- {formatDay(workoutDay(lastWorkout), 'MMM d')}- {mins > 0 && ` · ${mins} min`}- {totalSets > 0 && ` · ${totalSets} set${totalSets === 1 ? '' : 's'}`}- {totalVolume > 0 && ` · ${totalVolume.toLocaleString()} ${wUnit}`}+ {[+ formatDay(workoutDay(lastWorkout), 'monthDay'),+ mins > 0 && t('home.lastWorkout.minutes', { mins }),+ totalSets > 0 && t('home.lastWorkout.sets', { count: totalSets }),+ totalVolume > 0 && `${totalVolume.toLocaleString()} ${wUnit}`,+ ].filter(Boolean).join(' · ')}</p></div><Link to="/workouts" className="flex items-center gap-0.5 text-xs text-brand-400 hover:text-brand-300 flex-shrink-0 transition-colors">- All <ArrowRight className="w-3 h-3" />+ {t('home.lastWorkout.all')} <ArrowRight className="w-3 h-3" /></Link></div>@@ -584,12 +591,12 @@ export default function Dashboard() {<div className="flex-1 min-w-0"><p className="text-sm text-tx-secondary truncate">{ex.exercise.name}</p><span className={`text-[10px] px-1 py-0.5 rounded ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span></div>{best && (<span className="text-xs text-tx-muted tabular-nums flex-shrink-0">- {sets.length}×{best.weight > 0 ? ` ${displayWeight(best.weight, settings.weight_unit)}${wUnit}` : ' BW'}+ {sets.length}×{best.weight > 0 ? ` ${displayWeight(best.weight, settings.weight_unit)}${wUnit}` : ` ${t('weight.bodyweightShort')}`}</span>)}</div>@@ -599,7 +606,7 @@ export default function Dashboard() {{exs.length > 4 && (<p className="text-xs text-tx-muted text-center pt-2">- +{exs.length - 4} more exercises+ {t('home.lastWorkout.moreExercises', { count: exs.length - 4 })}</p>)}</div>@@ -607,7 +614,7 @@ export default function Dashboard() {})() : (<div className="card p-4 flex flex-col items-center justify-center min-h-36 gap-2"><Dumbbell className="w-7 h-7 text-tx-muted opacity-40" />- <p className="text-sm text-tx-muted">No workouts logged yet</p>+ <p className="text-sm text-tx-muted">{t('home.lastWorkout.empty')}</p>{/* Suppressed when the Up Next card is already showing above — thatcard is its own "start something" CTA; a second "start your firstworkout" link right under it is the redundant-buttons clutter this@@ -617,7 +624,7 @@ export default function Dashboard() {onClick={() => navigate('/workout/start')}className="text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors mt-1">- Start your first workout →+ {t('home.lastWorkout.startFirst')}</button>)}</div>@@ -626,9 +633,9 @@ export default function Dashboard() {{/* Nutrition */}<div className="card p-4 overflow-hidden min-w-0"><div className="flex items-center justify-between mb-3">- <h2 className="section-title">Today's Nutrition</h2>+ <h2 className="section-title">{t('home.nutrition.title')}</h2><Link to="/food" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex-shrink-0">- Log →+ {t('home.nutrition.log')}</Link></div>@@ -637,8 +644,8 @@ export default function Dashboard() {// sentence and the retry belong here, in the section that owns them.<ErrorStatesize="section"- title="Couldn't load today's food"- message={missing["today's food"]}+ title={t('home.nutrition.loadFailed')}+ message={uiMessage(missing["today's food"])}onRetry={retry}/>) : (@@ -659,11 +666,11 @@ export default function Dashboard() {{/* Macros */}<div className="space-y-2.5">{[- { label: 'Protein', val: food.total_protein, target: settings.protein_target, pct: protPct, color: '#3b82f6' },- { label: 'Carbs', val: food.total_carbs, target: settings.carb_target, pct: carbsPct, color: '#f59e0b' },- { label: 'Fat', val: food.total_fat, target: settings.fat_target, pct: fatPct, color: '#8b5cf6' },+ { id: 'protein', label: t('home.macro.protein'), val: food.total_protein, target: settings.protein_target, pct: protPct, color: '#3b82f6' },+ { id: 'carbs', label: t('home.macro.carbs'), val: food.total_carbs, target: settings.carb_target, pct: carbsPct, color: '#f59e0b' },+ { id: 'fat', label: t('home.macro.fat'), val: food.total_fat, target: settings.fat_target, pct: fatPct, color: '#8b5cf6' },].map(m => (- <div key={m.label}>+ <div key={m.id}><div className="flex justify-between items-center mb-1"><span className="text-xs text-tx-muted">{m.label}</span><span className="text-xs font-semibold text-tx-primary tabular-nums">@@ -686,8 +693,8 @@ export default function Dashboard() {<div className="card p-4"><SectionHeadericon={Dumbbell}- title="Muscle Balance"- right={<span className="text-xs text-tx-muted">{workouts.length} workout{workouts.length === 1 ? '' : 's'}</span>}+ title={t('home.muscle.title')}+ right={<span className="text-xs text-tx-muted">{t('home.muscle.workouts', { count: workouts.length })}</span>}className="mb-1"/>@@ -696,13 +703,13 @@ export default function Dashboard() {{muscleRoast(topMuscle)}</p>) : (- <p className="text-xs text-tx-muted mb-3">Log workouts to see which muscles you train most.</p>+ <p className="text-xs text-tx-muted mb-3">{t('home.muscle.empty')}</p>)}{muscleData.length === 0 ? (<div className="flex flex-col items-center justify-center py-6 gap-2"><Dumbbell className="w-6 h-6 text-tx-muted opacity-30" />- <p className="text-xs text-tx-muted">No workout data yet</p>+ <p className="text-xs text-tx-muted">{t('home.muscle.noData')}</p></div>) : (<div className="flex flex-col sm:flex-row items-center gap-4">@@ -727,8 +734,8 @@ export default function Dashboard() {<TooltipcontentStyle={TOOLTIP_STYLE}formatter={(v: number, _: string, props: { payload?: { name: string } }) => [- `${v} set${v === 1 ? '' : 's'} (${Math.round((v / totalMuscSets) * 100)}%)`,- props.payload?.name ?? '',+ t('home.muscle.tooltip', { count: v, percent: Math.round((v / totalMuscSets) * 100) }),+ muscleLabel(props.payload?.name),]}/></PieChart>@@ -747,8 +754,8 @@ export default function Dashboard() {<div className="flex items-center gap-2 mb-0.5"><div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: color }} /><span className={`text-xs capitalize flex-1 min-w-0 truncate ${isTop ? 'font-semibold text-tx-primary' : 'text-tx-secondary'}`}>- {d.name}- {isTop && <span className="ml-1 text-[9px] font-normal text-tx-muted uppercase tracking-wide">top</span>}+ {muscleLabel(d.name)}+ {isTop && <span className="ml-1 text-[9px] font-normal text-tx-muted uppercase tracking-wide">{t('home.muscle.top')}</span>}</span><MuscleSparkline values={values} color={color} isTop={isTop} /><span className="text-xs text-tx-muted tabular-nums w-16 text-right flex-shrink-0">@@ -770,10 +777,10 @@ export default function Dashboard() {<div className="card p-4"><SectionHeadericon={Scale}- title="Weight"+ title={t('home.weight.title')}right={<Link to="/weight" className="text-xs text-brand-400 hover:text-brand-300 transition-colors flex items-center gap-0.5">- View <ArrowRight className="w-3 h-3" />+ {t('home.weight.view')} <ArrowRight className="w-3 h-3" /></Link>}className="mb-2"@@ -785,8 +792,8 @@ export default function Dashboard() {// rather than the bare mark a stat tile has room for.<ErrorStatesize="section"- title="Couldn't load your weight"- message={missing['your weight']}+ title={t('home.weight.loadFailed')}+ message={uiMessage(missing['your weight'])}onRetry={retry}/>) : weightLogs.length === 0 ? (@@ -799,8 +806,8 @@ export default function Dashboard() {<Plus className="w-4 h-4 text-brand-500" /></div><div className="min-w-0">- <p className="text-sm font-semibold text-tx-primary">Log your first weight</p>- <p className="text-xs text-tx-muted">Tap to start tracking</p>+ <p className="text-sm font-semibold text-tx-primary">{t('home.weight.logFirst')}</p>+ <p className="text-xs text-tx-muted">{t('home.weight.logFirstHint')}</p></div></button>) : (@@ -808,7 +815,7 @@ export default function Dashboard() {type="button"onClick={() => setSheetOpen(true)}className="w-full text-left active:scale-[0.99] transition-transform"- aria-label="Log weight"+ aria-label={t('home.weight.logAria')}><div className="flex items-center justify-between mb-2"><div className="flex items-baseline gap-1.5">@@ -821,11 +828,11 @@ export default function Dashboard() {{(() => {const delta = weightStats?.change_7d ?? 0if (delta === 0) {- return <span className="text-xs text-tx-muted">7d · no change</span>+ return <span className="text-xs text-tx-muted">{t('home.weight.noChange7d')}</span>}return (<span className={`text-xs tabular-nums ${delta < 0 ? 'text-success-400' : 'text-error-400'}`}>- 7d · {delta < 0 ? '↓' : '↑'}{Math.abs(displayWeight(delta, settings.weight_unit))} {wUnit}+ {t(delta < 0 ? 'home.weight.trendDown' : 'home.weight.trendUp', { amount: Math.abs(displayWeight(delta, settings.weight_unit)), unit: wUnit })}</span>)})()}@@ -841,7 +848,7 @@ export default function Dashboard() {<Line dataKey="weight" dot={false} stroke="#6366f1" strokeWidth={2} type="monotone" /><TooltipcontentStyle={TOOLTIP_STYLE}- formatter={(v: number) => [`${v} ${wUnit}`, 'Weight']}+ formatter={(v: number) => [`${v} ${wUnit}`, t('home.weight.title')]}/></LineChart></ResponsiveContainer>diff --git a/web/src/pages/EditProgram.tsx b/web/src/pages/EditProgram.tsxindex 5cc7c8e..7a73d90 100644--- a/web/src/pages/EditProgram.tsx+++ b/web/src/pages/EditProgram.tsx@@ -3,7 +3,7 @@ import { useNavigate, useParams } from 'react-router-dom'import { ArrowLeft, AlertCircle, BookOpen, FileText, Dumbbell, CalendarDays } from 'lucide-react'import { programAPI } from '../services/api'import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'-import { apiErrorMessage, useAsyncAction, hasWorkoutExercises, types } from '@lyftr/shared'+import { useAsyncAction, hasWorkoutExercises, types, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { ErrorState } from '../components/ui'import ProgramDaysEditor from '../components/programs/ProgramDaysEditor'import type { DayDraft } from '../components/programs/types'@@ -16,6 +16,7 @@ interface ProgramFormData {export default function EditProgram() {const { id } = useParams<{ id: string }>()+ const { t } = useTranslation()const navigate = useNavigate()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)@@ -23,11 +24,11 @@ export default function EditProgram() {// `error` is for what the FORM can tell the user before anything is sent (a missing// name, an empty day). What the SERVER says lives on the hook below — different// questions, kept apart on purpose, and rendered in the same place.- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)// Separate from `error`, which is this form's own validation. A load that never// arrived is not a missing field: there is nothing to edit, and the header would// otherwise assert "0 exercises" about a workout that has several.- const [loadError, setLoadError] = useState<string | null>(null)+ const [loadError, setLoadError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})const [formData, setFormData] = useState<ProgramFormData>({ name: '', notes: '', days: [] })@@ -62,7 +63,7 @@ export default function EditProgram() {})),})})- .catch(err => { setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")); })+ .catch(err => { setLoadError({ key: 'settings.unknownError', cause: err }); }).finally(() => setInitialLoading(false))}, [id, retryKey])@@ -87,17 +88,17 @@ export default function EditProgram() {}await programAPI.update(Number(id), payload)navigate('/programs')- }, 'Failed to update program')+ }, t('programs.form.updateFailed'))- useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.failureKey])const handleSubmit = (e: React.FormEvent) => {e.preventDefault()- if (!formData.name.trim()) { setError('Program name required'); return }- if (formData.days.length === 0) { setError('Add at least one day'); return }+ if (!formData.name.trim()) { setError({ key: 'programs.form.errors.nameRequired' }); return }+ if (formData.days.length === 0) { setError({ key: 'programs.form.errors.noDays' }); return }const hasAnyExercise = hasWorkoutExercises(formData.days)- if (!hasAnyExercise) { setError('Add at least one exercise to a workout day'); return }- setError('')+ if (!hasAnyExercise) { setError({ key: 'programs.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -113,10 +114,10 @@ export default function EditProgram() {return (<ErrorStatesize="page"- title="Couldn't load this program"- message={loadError}+ title={t('programs.detail.loadFailed')}+ message={uiMessage(loadError)}onRetry={() => { setLoadError(null); setInitialLoading(true); setRetryKey(k => k + 1) }}- secondary={<button onClick={() => navigate('/programs')} className="btn-secondary btn-sm">Back to programs</button>}+ secondary={<button onClick={() => navigate('/programs')} className="btn-secondary btn-sm">{t('programs.detail.backToPrograms')}</button>}/>)}@@ -127,13 +128,13 @@ export default function EditProgram() {return (<div className="space-y-6 animate-slide-up pb-10"><div className="flex items-center gap-3">- <button aria-label="Go back" onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors">+ <button aria-label={t('common.goBack')} onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Edit Program</h1>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('programs.form.editTitle')}</h1><p className="text-xs text-tx-muted">- {formData.days.length} day{formData.days.length === 1 ? '' : 's'} • {totalExercises} exercise{totalExercises === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}+ {t('programs.form.summary', { days: t('programs.count.days', { count: formData.days.length }), exercises: t('programs.count.exercises', { count: totalExercises }), sets: t('programs.count.sets', { count: totalSets }) })}</p></div></div>@@ -142,14 +143,14 @@ export default function EditProgram() {{(error || save.error) && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error || save.error}</span>+ <span>{error ? uiMessage(error) : save.error}</span></div>)}<div><div className="flex items-center gap-2 mb-2"><BookOpen className="w-4 h-4 text-brand-500" />- <label className="label">Program Name</label>+ <label className="label">{t('programs.form.name')}</label></div><input type="text" value={formData.name} onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))} className="input mt-1" /></div>@@ -157,7 +158,7 @@ export default function EditProgram() {<div><div className="flex items-center gap-2 mb-2"><FileText className="w-4 h-4 text-brand-500" />- <label className="label">Notes</label>+ <label className="label">{t('workouts.form.notes')}</label></div><textarea value={formData.notes} onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))} className="input mt-1 min-h-16 resize-none" /></div>@@ -166,15 +167,15 @@ export default function EditProgram() {<div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg"><div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.days.length}</div>- <div className="text-xs text-tx-muted">Days</div>+ <div className="text-xs text-tx-muted">{t('programs.form.days')}</div></div><div className="text-center"><div className="text-sm font-bold text-brand-500">{totalExercises}</div>- <div className="text-xs text-tx-muted">Exercises</div>+ <div className="text-xs text-tx-muted">{t('workouts.form.exercises')}</div></div><div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div>- <div className="text-xs text-tx-muted">Target Sets</div>+ <div className="text-xs text-tx-muted">{t('programs.form.targetSets')}</div></div></div>)}@@ -182,8 +183,8 @@ export default function EditProgram() {<div><div className="flex items-center gap-2 mb-3"><CalendarDays className="w-4 h-4 text-brand-500" />- <label className="label">Days</label>- <span className="text-xs text-tx-muted">(repeats in this order)</span>+ <label className="label">{t('programs.form.days')}</label>+ <span className="text-xs text-tx-muted">{t('programs.form.daysHintEdit')}</span></div><ProgramDaysEditordays={formData.days}@@ -197,11 +198,11 @@ export default function EditProgram() {<div className="flex gap-3 pt-2"><button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">- Cancel+ {t('common.cancel')}</button><button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"><BookOpen className="w-4 h-4" />- {save.busy ? 'Saving…' : 'Save Changes'}+ {save.busy ? t('common.saving') : t('workouts.form.saveChanges')}</button></div></form>diff --git a/web/src/pages/EditWorkout.tsx b/web/src/pages/EditWorkout.tsxindex cf04bb2..de7f882 100644--- a/web/src/pages/EditWorkout.tsx+++ b/web/src/pages/EditWorkout.tsx@@ -5,7 +5,7 @@ import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, lbsToDisplay, displayToLbs } from '../stores/settings'import WeightInput from '../components/WeightInput'import ExercisePicker from '../components/ExercisePicker'-import { apiErrorMessage, useAsyncAction, types } from '@lyftr/shared'+import { useAsyncAction, types, muscleLabel, equipmentLabel, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import { ErrorState } from '../components/ui'interface WorkoutFormData {@@ -16,6 +16,7 @@ interface WorkoutFormData {}export default function EditWorkout() {+ const { t } = useTranslation()const { id } = useParams<{ id: string }>()const navigate = useNavigate()const { settings } = useSettingsStore()@@ -24,12 +25,14 @@ export default function EditWorkout() {const [initialLoading, setInitialLoading] = useState(true)// `error` is for what the FORM can tell the user before anything is sent (a missing// name, an empty day). What the SERVER says lives on the hook below — different- // questions, kept apart on purpose, and rendered in the same place.- const [error, setError] = useState('')+ // questions, kept apart on purpose, and rendered in the same place. Both messages below+ // are kept as a UiMessage rather than a sentence, so a banner already on screen follows a+ // language switch.+ const [error, setError] = useState<UiMessage | null>(null)// Separate from `error`, which is this form's own validation. A load that never// arrived is not a missing field: there is nothing to edit, and the header would// otherwise assert "0 exercises" about a workout that has several.- const [loadError, setLoadError] = useState<string | null>(null)+ const [loadError, setLoadError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)const [pickerExercises, setPickerExercises] = useState<Record<number, types.Exercise>>({})const [formData, setFormData] = useState<WorkoutFormData>({ name: '', notes: '', duration: 0, exercises: [] })@@ -61,7 +64,7 @@ export default function EditWorkout() {})),})})- .catch(err => setLoadError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ .catch(err => setLoadError({ key: 'settings.unknownError', cause: err })).finally(() => setInitialLoading(false))}, [id, retryKey])@@ -69,7 +72,7 @@ export default function EditWorkout() {setPickerExercises(prev => ({ ...prev, [exercise.id]: exercise }))setFormData(prev => ({ ...prev, exercises: [...prev.exercises, { exercise_id: exercise.id, notes: '', sets: [{ set_number: 1, reps: 0, weight: 0 }] }] }))setShowPicker(false)- setError('')+ setError(null)}const removeExercise = (index: number) => setFormData(prev => ({ ...prev, exercises: prev.exercises.filter((_, i) => i !== index) }))@@ -111,15 +114,15 @@ export default function EditWorkout() {}await workoutAPI.update(Number(id), payload)navigate('/workouts')- }, 'Failed to update workout')+ }, t('workouts.form.updateFailed'))- useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.error])+ useEffect(() => { if (error || save.error) window.scrollTo({ top: 0, behavior: 'smooth' }) }, [error, save.failureKey])const handleSubmit = (e: React.FormEvent) => {e.preventDefault()- if (!formData.name.trim()) { setError('Workout name required'); return }- if (formData.exercises.length === 0) { setError('Add at least one exercise'); return }- setError('')+ if (!formData.name.trim()) { setError({ key: 'workouts.form.errors.nameRequired' }); return }+ if (formData.exercises.length === 0) { setError({ key: 'workouts.form.errors.noExercises' }); return }+ setError(null)void save.run()}@@ -135,10 +138,10 @@ export default function EditWorkout() {return (<ErrorStatesize="page"- title="Couldn't load this workout"- message={loadError}+ title={t('workouts.detail.loadFailed')}+ message={uiMessage(loadError)}onRetry={() => { setLoadError(null); setInitialLoading(true); setRetryKey(k => k + 1) }}- secondary={<button onClick={() => navigate('/workouts')} className="btn-secondary btn-sm">Back to workouts</button>}+ secondary={<button onClick={() => navigate('/workouts')} className="btn-secondary btn-sm">{t('workouts.detail.backToWorkouts')}</button>}/>)}@@ -150,19 +153,19 @@ export default function EditWorkout() {return (<div className="space-y-6 animate-slide-up pb-10"><div className="flex items-center gap-3">- <button aria-label="Go back" onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors">+ <button aria-label={t('common.goBack')} onClick={() => navigate(-1)} className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h1 className="font-display font-bold text-2xl text-tx-primary">Edit Workout</h1>- <p className="text-xs text-tx-muted">{formData.exercises.length} exercise{formData.exercises.length === 1 ? '' : 's'} • {totalSets} set{totalSets === 1 ? '' : 's'}</p>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('workouts.form.editTitle')}</h1>+ <p className="text-xs text-tx-muted">{t('workouts.form.summary', { exercises: t('workouts.form.exerciseCount', { count: formData.exercises.length }), sets: t('workouts.form.setCount', { count: totalSets }) })}</p></div></div>{(error || save.error) && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error || save.error}</span>+ <span>{error ? uiMessage(error) : save.error}</span></div>)}@@ -170,7 +173,7 @@ export default function EditWorkout() {<div><div className="flex items-center gap-2 mb-2"><Dumbbell className="w-4 h-4 text-brand-500" />- <label className="label">Workout Name</label>+ <label className="label">{t('workouts.form.name')}</label></div><input type="text" value={formData.name} onChange={e => setFormData(prev => ({ ...prev, name: e.target.value }))} className="input mt-1" /></div>@@ -178,12 +181,12 @@ export default function EditWorkout() {<div><div className="flex items-center gap-2 mb-2"><Clock className="w-4 h-4 text-brand-500" />- <label className="label">Duration (minutes)</label>+ <label className="label">{t('workouts.form.durationMinutes')}</label></div><div className="grid grid-cols-2 gap-3"><input type="number" value={formData.duration || ''} onChange={e => setFormData(prev => ({ ...prev, duration: Number(e.target.value) || 0 }))} placeholder="0" className="input" min="0" /><div className="flex items-center px-3 bg-surface-muted/30 rounded-lg text-sm text-tx-muted font-medium">- {Math.floor(formData.duration / 60)}h {formData.duration % 60}m+ {t('workouts.form.durationHm', { hours: Math.floor(formData.duration / 60), minutes: formData.duration % 60 })}</div></div></div>@@ -191,16 +194,16 @@ export default function EditWorkout() {<div><div className="flex items-center gap-2 mb-2"><FileText className="w-4 h-4 text-brand-500" />- <label className="label">Notes</label>+ <label className="label">{t('workouts.form.notes')}</label></div><textarea value={formData.notes} onChange={e => setFormData(prev => ({ ...prev, notes: e.target.value }))} className="input mt-1 min-h-20 resize-none" /></div>{formData.exercises.length > 0 && (<div className="grid grid-cols-3 gap-2 p-3 bg-brand-500/10 border border-brand-500/20 rounded-lg">- <div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div><div className="text-xs text-tx-muted">Exercises</div></div>- <div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div><div className="text-xs text-tx-muted">Sets</div></div>- <div className="text-center"><div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div><div className="text-xs text-tx-muted">Total {wUnit}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{formData.exercises.length}</div><div className="text-xs text-tx-muted">{t('workouts.form.exercises')}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{totalSets}</div><div className="text-xs text-tx-muted">{t('workouts.form.sets')}</div></div>+ <div className="text-center"><div className="text-sm font-bold text-brand-500">{Math.round(totalWeight)}</div><div className="text-xs text-tx-muted">{t('workouts.form.totalUnit', { unit: wUnit })}</div></div></div>)}@@ -208,11 +211,11 @@ export default function EditWorkout() {<div className="flex items-center justify-between mb-3"><div className="flex items-center gap-2"><Zap className="w-4 h-4 text-brand-500" />- <label className="label">Exercises</label>+ <label className="label">{t('workouts.form.exercises')}</label></div><button type="button" onClick={() => setShowPicker(true)} className="flex items-center gap-1.5 px-3 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 text-white rounded-lg transition-colors font-medium"><Plus className="w-3.5 h-3.5" />- Add Exercise+ {t('workouts.form.addExercise')}</button></div>@@ -231,38 +234,38 @@ export default function EditWorkout() {</div><p className="font-semibold text-tx-primary">{exercise?.name}</p></div>- <p className="text-xs text-tx-muted ml-8">{exercise?.muscle_group} • {exercise?.equipment}</p>+ <p className="text-xs text-tx-muted ml-8">{muscleLabel(exercise?.muscle_group)} • {equipmentLabel(exercise?.equipment)}</p></div>- <button type="button" aria-label="Remove exercise" onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeExercise')} onClick={() => removeExercise(exIdx)} className="p-1.5 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div><div className="mb-4">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Notes</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.notes')}</label><input type="text" value={workoutEx.notes} onChange={e => { const ex = [...formData.exercises]; ex[exIdx].notes = e.target.value; setFormData(p => ({ ...p, exercises: ex })) }} className="input text-sm" /></div><div className="space-y-2 mb-3"><div className="flex items-center justify-between">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">Sets</label>- <span className="text-xs text-tx-muted">{workoutEx.sets.length} set{workoutEx.sets.length === 1 ? '' : 's'}</span>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider">{t('workouts.form.sets')}</label>+ <span className="text-xs text-tx-muted">{t('workouts.form.setCount', { count: workoutEx.sets.length })}</span></div>{workoutEx.sets.map((set, setIdx) => (<div key={setIdx} className="flex gap-2 items-end bg-surface-raised/40 p-3 rounded-lg border border-surface-border/50"><div className="flex-shrink-0 w-12">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">Set</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block">{t('workouts.form.set')}</label><div className="text-sm font-bold text-tx-primary bg-surface-muted px-2 py-1 rounded text-center">{set.set_number}</div></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Reps</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.reps')}</label><input type="number" inputMode="numeric" value={set.reps || ''} onChange={e => updateSet(exIdx, setIdx, 'reps', e.target.value)} placeholder="10" className="input text-sm w-full" min="0" /></div><div className="flex-1 min-w-0">- <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">Weight</label>+ <label className="text-xs text-tx-muted font-medium uppercase tracking-wider block mb-1">{t('workouts.form.weight')}</label><WeightInput size="sm" value={set.weight ? String(set.weight) : ''} onChange={v => updateSet(exIdx, setIdx, 'weight', v)} unit={wUnit} placeholder="225" /></div>- <button type="button" aria-label="Remove set" onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0">+ <button type="button" aria-label={t('workouts.form.removeSet')} onClick={() => removeSet(exIdx, setIdx)} className="p-2 hover:bg-error-500/20 rounded transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></button></div>@@ -271,7 +274,7 @@ export default function EditWorkout() {<button type="button" onClick={() => addSet(exIdx)} className="flex items-center gap-1 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors"><Plus className="w-3.5 h-3.5" />- Add Set+ {t('workouts.form.addSet')}</button></div>)@@ -281,11 +284,11 @@ export default function EditWorkout() {<div className="flex gap-3 pt-2"><button type="button" onClick={() => navigate(-1)} className="flex-1 px-4 py-3 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">- Cancel+ {t('common.cancel')}</button><button type="submit" disabled={save.busy} className="flex-1 px-4 py-3 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"><Dumbbell className="w-4 h-4" />- {save.busy ? 'Saving…' : 'Save Changes'}+ {save.busy ? t('common.saving') : t('workouts.form.saveChanges')}</button></div></form>diff --git a/web/src/pages/ExerciseDetail.tsx b/web/src/pages/ExerciseDetail.tsxindex c0af36b..1e0a837 100644--- a/web/src/pages/ExerciseDetail.tsx+++ b/web/src/pages/ExerciseDetail.tsx@@ -1,7 +1,7 @@import { useState, useEffect, useMemo } from 'react'import { useNavigate, useParams } from 'react-router-dom'import { ArrowLeft, Dumbbell, Trophy } from 'lucide-react'-import { format, subDays } from 'date-fns'+import { subDays } from 'date-fns'import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts'import Model, { IExerciseData } from 'react-body-highlighter'import { exerciseAPI } from '../services/api'@@ -9,9 +9,9 @@ import { useWorkoutSession } from '../stores/workoutSession'import { useSettingsStore, weightShort, displayWeight } from '../stores/settings'import { useTheme } from '../hooks/useTheme'import PeriodSelector from '../components/PeriodSelector'-import { apiErrorMessage, isNotFound, types } from '@lyftr/shared'+import { uiMessage, isNotFound, types, formatDate, useTranslation, type UiMessage } from '@lyftr/shared'import { ErrorState } from '../components/ui'-import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'+import { muscleColor, muscleColorBordered, categoryLabel, equipmentLabel, muscleLabel, muscleToBodySlugs } from '../utils/exerciseUtils'const HISTORY_PERIODS = ['1m', '3m', '6m', 'All'] as consttype HistoryPeriod = typeof HISTORY_PERIODS[number]@@ -34,6 +34,7 @@ function buildBodyData(exercise: types.Exercise): IExerciseData[] {}export default function ExerciseDetail() {+ const { t } = useTranslation()const { exerciseId } = useParams<{ exerciseId: string }>()const navigate = useNavigate()const { session } = useWorkoutSession()@@ -46,7 +47,8 @@ export default function ExerciseDetail() {const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('3m')const [imgFailed, setImgFailed] = useState(false)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // A UiMessage rather than a sentence, so a failure already on screen follows a language switch.+ const [error, setError] = useState<UiMessage | null>(null)// A 404 is not a retryable failure: the row is gone, and a Try again button that// cannot ever succeed is worse than no button. Tracked separately from the message// because the message alone cannot say which kind of failure produced it.@@ -78,7 +80,7 @@ export default function ExerciseDetail() {}).catch(err => {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })}).finally(() => setLoading(false))}, [exerciseId, retryKey])@@ -99,10 +101,10 @@ export default function ExerciseDetail() {return (<ErrorStatesize="page"- title="Couldn't load this exercise"- message={error}+ title={t('exercises.detail.loadFailed')}+ message={uiMessage(error)}onRetry={gone ? undefined : () => { setError(null); setRetryKey(k => k + 1) }}- secondary={<button onClick={() => navigate(-1)} className="btn-secondary btn-sm">Go back</button>}+ secondary={<button onClick={() => navigate(-1)} className="btn-secondary btn-sm">{t('common.goBack')}</button>}/>)}@@ -116,7 +118,7 @@ export default function ExerciseDetail() {}const bodyData = buildBodyData(exercise)- const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment+ const equipLabel = equipmentLabel(exercise.equipment)const descLines = exercise.description? exercise.description.split('\n').filter(l => l.trim()): []@@ -126,7 +128,7 @@ export default function ExerciseDetail() {{/* Header */}<div className="flex items-start gap-3"><button- aria-label="Go back"+ aria-label={t('common.goBack')}onClick={() => navigate(-1)}className="p-2 hover:bg-surface-muted rounded-lg transition-colors mt-0.5 flex-shrink-0">@@ -135,14 +137,14 @@ export default function ExerciseDetail() {<div className="flex-1 min-w-0"><h1 className="font-display font-bold text-2xl text-tx-primary leading-tight">{exercise.name}</h1><span className={`inline-flex items-center mt-1.5 px-2 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(exercise.muscle_group)}`}>- {exercise.muscle_group}+ {muscleLabel(exercise.muscle_group)}</span></div></div>{/* Muscle diagram */}<div className="card p-4">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Muscles Worked</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.musclesWorked')}</p><div className="flex items-start justify-center gap-6"><div className="flex flex-col items-center gap-1">@@ -153,7 +155,7 @@ export default function ExerciseDetail() {highlightedColors={highlightColors}style={{ width: '140px' }}/>- <span className="text-xs text-tx-muted">Front</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.bodyFront')}</span></div><div className="flex flex-col items-center gap-1"><Model@@ -163,7 +165,7 @@ export default function ExerciseDetail() {highlightedColors={highlightColors}style={{ width: '140px' }}/>- <span className="text-xs text-tx-muted">Back</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.bodyBack')}</span></div></div>@@ -171,11 +173,11 @@ export default function ExerciseDetail() {<div className="flex items-center gap-4 mt-3 justify-center"><div className="flex items-center gap-1.5"><div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#22d3ee' }} />- <span className="text-xs text-tx-muted">Primary</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.primary')}</span></div><div className="flex items-center gap-1.5"><div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#0e7490' }} />- <span className="text-xs text-tx-muted">Secondary</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.secondary')}</span></div></div></div>@@ -200,7 +202,7 @@ export default function ExerciseDetail() {)}{exercise.category && (<span className="inline-flex items-center px-3 py-1 rounded-full bg-brand-500/10 border border-brand-500/20 text-xs font-medium text-brand-400 capitalize">- {exercise.category}+ {categoryLabel(exercise.category)}</span>)}</div>@@ -208,11 +210,11 @@ export default function ExerciseDetail() {{/* Secondary muscles */}{exercise.secondary_muscles?.length > 0 && (<div>- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">Also works</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">{t('exercises.detail.alsoWorks')}</p><div className="flex flex-wrap gap-1.5">{exercise.secondary_muscles.map(m => (<span key={m} className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${muscleColor(m)}`}>- {m}+ {muscleLabel(m)}</span>))}</div>@@ -224,14 +226,14 @@ export default function ExerciseDetail() {<div className="card p-4"><div className="flex items-center gap-2 mb-3"><Trophy className="w-4 h-4 text-warning-400" />- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Your Best</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">{t('exercises.detail.yourBest')}</p></div><div className="flex items-end gap-2"><span className="text-2xl font-bold text-tx-primary tabular-nums">{displayWeight(pr.weight, wUnit)}</span>- <span className="text-sm text-tx-muted mb-0.5">{wUnit} × {pr.reps} reps</span>+ <span className="text-sm text-tx-muted mb-0.5">{t('exercises.detail.bestSet', { unit: wUnit, count: pr.reps })}</span></div><p className="text-xs text-tx-muted mt-1">- Est. 1RM: {displayWeight(pr.estimated_1rm, wUnit)} {wUnit} · {format(new Date(pr.date), 'MMM d, yyyy')}+ {t('exercises.estimated1rm', { weight: displayWeight(pr.estimated_1rm, wUnit), unit: wUnit, date: formatDate(new Date(pr.date), 'monthDayYear') })}</p></div>)}@@ -239,19 +241,19 @@ export default function ExerciseDetail() {{/* History chart */}{history.length >= 2 && (() => {const chartData = [...filteredHistory].reverse().map(h => ({- date: format(new Date(h.date), 'M/d'),+ date: formatDate(new Date(h.date), 'numericMonthDay'),weight: displayWeight(h.max_weight, wUnit),}))return (<div className="card p-4"><div className="flex items-center justify-between mb-3 gap-2"><p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">- Weight Progression+ {t('exercises.detail.weightProgression')}</p>- <PeriodSelector options={HISTORY_PERIODS} value={historyPeriod} onChange={setHistoryPeriod} />+ <PeriodSelector options={HISTORY_PERIODS} value={historyPeriod} onChange={setHistoryPeriod} label={p => t(`exercises.detail.period.${p}`)} /></div>{chartData.length < 2 ? (- <div className="flex items-center justify-center h-[110px] text-tx-muted text-sm">No data for this period</div>+ <div className="flex items-center justify-center h-[110px] text-tx-muted text-sm">{t('exercises.detail.noPeriodData')}</div>) : (<ResponsiveContainer width="100%" height={110}><LineChart data={chartData}>@@ -269,7 +271,7 @@ export default function ExerciseDetail() {borderRadius: 8,fontSize: 11,}}- formatter={(v: number) => [`${v} ${wUnit}`, 'Max weight']}+ formatter={(v: number) => [`${v} ${wUnit}`, t('exercises.detail.maxWeight')]}/><Linetype="monotone"@@ -289,7 +291,7 @@ export default function ExerciseDetail() {{/* Instructions */}{descLines.length > 0 && (<div className="card p-4">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Instructions</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.instructions')}</p><div className="space-y-2.5">{descLines.map((line, i) => {const stepMatch = line.match(/^(\d+\.)\s*(.*)/)diff --git a/web/src/pages/Food.test.tsx b/web/src/pages/Food.test.tsxindex 818f643..8989e33 100644--- a/web/src/pages/Food.test.tsx+++ b/web/src/pages/Food.test.tsx@@ -1,6 +1,7 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, fireEvent, waitFor } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'+import { i18n } from '@lyftr/shared'import Food from './Food'// Starring from the diary (#138): a logged entry is starred as the food it is — one@@ -50,6 +51,24 @@ beforeEach(() => {list.mockResolvedValue([OATS])})+afterEach(async () => { await i18n.changeLanguage('en') })++describe('Diary copy', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ savedList.mockResolvedValue([])+ renderPage()++ expect(await screen.findByRole('button', { name: 'Agregar a Desayuno' })).toBeTruthy()+ expect(screen.getByText('Registrar comida')).toBeTruthy()+ expect(screen.getByText('Nutrición')).toBeTruthy()+ expect(screen.getByLabelText('Día anterior')).toBeTruthy()+ expect(screen.getByText('Almuerzo')).toBeTruthy()+ expect(screen.getByText('Historial de macros')).toBeTruthy()+ expect(screen.queryByText('Log Food')).toBeNull()+ })+})+describe('Starring from the diary', () => {it('adds the entry to Favorites as one serving of the food', async () => {savedList.mockResolvedValue([])diff --git a/web/src/pages/Food.tsx b/web/src/pages/Food.tsxindex 4813f6e..8eaf6e7 100644--- a/web/src/pages/Food.tsx+++ b/web/src/pages/Food.tsx@@ -15,14 +15,11 @@ import Loading from '../components/Loading'import PeriodSelector from '../components/PeriodSelector'import { foodAPI, savedFoodsAPI } from '../services/api'import { useSettingsStore } from '../stores/settings'-import { apiErrorMessage, entryToResult, formatLoggedAmount, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites } from '@lyftr/shared'+import { entryToResult, formatLoggedAmount, isDailyStats, todayStr, dayToLocalDate, MACRO_COLORS, types, formatDay, useFavorites, type Favorites, formatDate, relativeDayLabel, useTranslation, uiMessage, Trans, type UiMessage } from '@lyftr/shared'import { ErrorState, Toast } from '../components/ui'import FavoriteStar from '../components/FavoriteStar'const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const-const MEAL_LABELS: Record<string, string> = {- breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks',-}const MEAL_ICONS: Record<string, React.ElementType> = {breakfast: Coffee, lunch: Sun, dinner: Moon, snacks: Cookie,}@@ -84,6 +81,7 @@ function EntryStar({ entry, favorites }: { entry: types.FoodLog; favorites: Favo}export default function Food() {+ const { t } = useTranslation()const navigate = useNavigate()const location = useLocation()const [selectedDate, setSelectedDate] = useState(todayStr())@@ -93,18 +91,18 @@ export default function Food() {// caught so one of them cannot blank a working day — but caught silently they// substituted zeros and an empty chart, which is what "ate nothing" looks like.// Name -> what the server said, for the areas with room to show it.- const [missing, setMissing] = useState<Record<string, string>>({})+ const [missing, setMissing] = useState<Record<string, UiMessage>>({})const [historyKey, setHistoryKey] = useState(0)// From the store, not a page-local fetch: this page carried a fourth copy of the// fallback settings literal, invisible to the store's loadFailed flag. The store// fetch no-ops when loaded and retries when the last read fell back.const { settings, fetch: fetchSettings } = useSettingsStore()const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<UiMessage | null>(null)// Separate from `error`, which reports a failed action (a delete) while the day's// data is still on screen. This one means the day itself never arrived, so there is// no ring, no total and no meal list worth drawing.- const [loadError, setLoadError] = useState<string | null>(null)+ const [loadError, setLoadError] = useState<UiMessage | null>(null)const [historyPeriod, setHistoryPeriod] = useState<HistoryPeriod>('30d')const [historyData, setHistoryData] = useState<types.FoodHistoryPoint[]>([])@@ -132,7 +130,7 @@ export default function Food() {total_fat: 0, total_fiber: 0, workout_count: 0,}let statsFailed = false- let statsMessage = ''+ let statsMessage: UiMessage | null = nullconst [logData, statsData] = await Promise.all([foodAPI.list(date),foodAPI.stats(date)@@ -141,7 +139,7 @@ export default function Food() {.then(st => isDailyStats(st) ? st : Promise.reject(new Error('unreadable'))).catch(err => {statsFailed = true- statsMessage = apiErrorMessage(err, "The server didn't say what went wrong.")+ statsMessage = { key: 'settings.unknownError', cause: err }return defaultStats}),])@@ -149,12 +147,12 @@ export default function Food() {setStats(statsData)setMissing(m => {const next = { ...m }- if (statsFailed) next["today's totals"] = statsMessage+ if (statsFailed && statsMessage) next["today's totals"] = statsMessageelse delete next["today's totals"]return next})} catch (err: any) {- setLoadError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setLoadError({ key: 'settings.unknownError', cause: err })} finally {hasLoadedRef.current = truesetLoading(false)@@ -184,7 +182,7 @@ export default function Food() {.catch(err => {if (cancelled) returnsetMissing(m => ({- ...m, 'your history': apiErrorMessage(err, "The server didn't say what went wrong."),+ ...m, 'your history': { key: 'settings.unknownError', cause: err },}))}).finally(() => { if (!cancelled) setHistoryLoading(false) })@@ -203,7 +201,7 @@ export default function Food() {setDeleteConfirmId(null)foodAPI.stats(selectedDate).then(setStats).catch(() => {})} catch (err) {- setError(apiErrorMessage(err, "Couldn't delete that entry."))+ setError({ key: 'food.diary.deleteFailed', cause: err })} finally {setDeletingId(null)}@@ -216,11 +214,11 @@ export default function Food() {if (loadError) {return (<div className="space-y-4 animate-slide-up">- <PageHeader title="Nutrition" subtitle="Macros & meals" />+ <PageHeader title={t('food.page.title')} subtitle={t('food.page.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your food log"- message={loadError}+ title={t('food.diary.loadFailed')}+ message={uiMessage(loadError)}onRetry={() => loadDay(selectedDate)}/></div>@@ -242,20 +240,16 @@ export default function Food() {const nextDate = format(addDays(selectedDateObj, 1), 'yyyy-MM-dd')const canGoNext = selectedDate < todayStr()- const dayLabel = isToday- ? 'Today'- : selectedDate === format(subDays(new Date(), 1), 'yyyy-MM-dd')- ? 'Yesterday'- : format(selectedDateObj, 'EEE, MMM d')+ const dayLabel = relativeDayLabel(selectedDate)return (<div className="space-y-4 animate-slide-up"><PageHeader- title="Nutrition"- subtitle="Macros & meals"+ title={t('food.page.title')}+ subtitle={t('food.page.subtitle')}action={<button onClick={() => openLog('breakfast')} className="btn-primary btn-sm">- <Plus className="w-4 h-4" /> Log Food+ <Plus className="w-4 h-4" /> {t('food.diary.logFood')}</button>}/>@@ -263,7 +257,7 @@ export default function Food() {{error && (<div className="alert-error"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{error}</span>+ <span>{uiMessage(error)}</span></div>)}@@ -272,7 +266,7 @@ export default function Food() {{/* Date navigator */}<div className="flex items-center gap-2"><button- aria-label="Previous day"+ aria-label={t('food.diary.previousDay')}onClick={() => setSelectedDate(prevDate)}className="p-3 rounded-xl hover:bg-surface-muted active:scale-95 transition-all text-tx-muted">@@ -283,7 +277,7 @@ export default function Food() {<CalendarDays className="w-4 h-4 text-tx-muted" /><span className="text-sm font-semibold text-tx-primary">{dayLabel}</span>{!isToday && (- <span className="text-xs text-tx-muted">{format(selectedDateObj, 'yyyy')}</span>+ <span className="text-xs text-tx-muted">{formatDate(selectedDateObj, 'year')}</span>)}</div><input@@ -296,7 +290,7 @@ export default function Food() {/></div><button- aria-label="Next day"+ aria-label={t('food.diary.nextDay')}onClick={() => setSelectedDate(nextDate)}disabled={!canGoNext}className="p-3 rounded-xl hover:bg-surface-muted active:scale-95 transition-all text-tx-muted disabled:opacity-30 disabled:cursor-not-allowed"@@ -312,8 +306,8 @@ export default function Food() {<div className="card p-5"><ErrorStatesize="section"- title="Couldn't load today's totals"- message="Something went wrong on our end."+ title={t('food.diary.totalsFailed')}+ message={t('food.diary.totalsFailedMessage')}onRetry={() => void loadDay(selectedDate)}/></div>@@ -323,7 +317,7 @@ export default function Food() {{/* Calorie hero */}<div className="flex items-center justify-between"><div>- <p className="text-xs font-medium text-tx-muted uppercase tracking-wide mb-1">Calories</p>+ <p className="text-xs font-medium text-tx-muted uppercase tracking-wide mb-1">{t('food.diary.calories')}</p><div className="flex items-baseline gap-1.5"><span className="text-4xl font-bold tabular-nums text-tx-primary">{Math.round(totalCals)}</span><span className="text-sm text-tx-muted">/ {calTarget}</span>@@ -336,8 +330,8 @@ export default function Food() {}`}><Flame className="w-4 h-4" />{isOver- ? `${Math.round(Math.abs(remaining))} over`- : `${Math.round(remaining)} left`+ ? t('food.diary.over', { amount: Math.round(Math.abs(remaining)) })+ : t('food.diary.left', { amount: Math.round(remaining) })}</div></div>@@ -357,7 +351,7 @@ export default function Food() {</div><div className="flex justify-between text-[10px] text-tx-muted"><span>0</span>- <span>{calTarget} kcal goal</span>+ <span>{t('food.diary.goal', { amount: calTarget })}</span></div></div>@@ -367,19 +361,19 @@ export default function Food() {value={s?.total_protein ?? 0}target={settings.protein_target}color={MACRO_COLORS.protein}- label="Protein"+ label={t('food.macro.protein')}/><MacroRingvalue={s?.total_carbs ?? 0}target={settings.carb_target}color={MACRO_COLORS.carbs}- label="Carbs"+ label={t('food.macro.carbs')}/><MacroRingvalue={s?.total_fat ?? 0}target={settings.fat_target}color={MACRO_COLORS.fat}- label="Fat"+ label={t('food.macro.fat')}/></div></div>@@ -401,7 +395,7 @@ export default function Food() {<MealIcon className={`w-4 h-4 ${iconColor}`} /></div><div className="flex-1 min-w-0">- <span className="text-sm font-semibold text-tx-primary">{MEAL_LABELS[meal]}</span>+ <span className="text-sm font-semibold text-tx-primary">{t(`food.meal.${meal}`)}</span>{mealCals > 0 && (<span className="ml-2 text-xs text-tx-muted tabular-nums">{Math.round(mealCals)} kcal</span>)}@@ -409,7 +403,7 @@ export default function Food() {<IconButtonicon={Plus}variant="solid"- label={`Add to ${MEAL_LABELS[meal]}`}+ label={t('food.diary.addTo', { meal: t(`food.meal.${meal}`) })}onClick={() => openLog(meal)}/></div>@@ -420,7 +414,7 @@ export default function Food() {className="w-full px-4 py-4 text-center border-t border-surface-border hover:bg-surface-muted/50 transition-colors group"><p className="text-xs text-tx-muted group-hover:text-tx-secondary transition-colors">- + Tap to add food+ {t('food.diary.tapToAdd')}</p></button>) : (@@ -430,14 +424,18 @@ export default function Food() {{deleteConfirmId === entry.id ? (<div className="px-4 py-3 flex items-center justify-between gap-3 bg-error-500/5 border-l-2 border-error-500"><p className="text-xs text-tx-secondary flex-1 min-w-0">- Delete <span className="font-medium text-tx-primary">{entry.name}</span>?+ <Trans+ i18nKey="food.diary.deleteConfirm"+ values={{ name: entry.name }}+ components={{ name: <span className="font-medium text-tx-primary" /> }}+ /></p><div className="flex gap-2 flex-shrink-0"><button onClick={() => setDeleteConfirmId(null)} className="btn-secondary btn-sm">- Cancel+ {t('common.cancel')}</button><button onClick={() => handleDelete(entry.id)} disabled={deletingId === entry.id} className="btn-danger-solid btn-sm disabled:opacity-50">- {deletingId === entry.id ? '…' : 'Delete'}+ {deletingId === entry.id ? '…' : t('common.delete')}</button></div></div>@@ -461,11 +459,11 @@ export default function Food() {{Math.round(entry.calories)} kcal</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-emerald-400 tabular-nums">{entry.protein.toFixed(0)}g P</span>+ <span className="text-xs text-emerald-400 tabular-nums">{entry.protein.toFixed(0)}g {t('food.macro.proteinInitial')}</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-amber-400 tabular-nums">{entry.carbs.toFixed(0)}g C</span>+ <span className="text-xs text-amber-400 tabular-nums">{entry.carbs.toFixed(0)}g {t('food.macro.carbsInitial')}</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-violet-400 tabular-nums">{entry.fat.toFixed(0)}g F</span>+ <span className="text-xs text-violet-400 tabular-nums">{entry.fat.toFixed(0)}g {t('food.macro.fatInitial')}</span>{entry.servings !== 1 && (<span className="text-xs text-tx-muted">{formatLoggedAmount(entry)}</span>)}@@ -474,7 +472,7 @@ export default function Food() {<ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" /></button>{favoritesLoaded && <EntryStar entry={entry} favorites={favorites} />}- <IconButton icon={Trash2} variant="danger" label="Delete" onClick={() => setDeleteConfirmId(entry.id)} />+ <IconButton icon={Trash2} variant="danger" label={t('common.delete')} onClick={() => setDeleteConfirmId(entry.id)} /></div>)}</div>@@ -489,13 +487,13 @@ export default function Food() {{/* Macro history */}<div className="card p-5"><SectionHeader- title="Macro History"+ title={t('food.history.title')}right={<PeriodSelector options={HISTORY_PERIODS} value={historyPeriod} onChange={setHistoryPeriod} />}className="mb-5"/>{historyLoading ? (- <div className="flex items-center justify-center h-48 text-xs text-tx-muted">Loading…</div>+ <div className="flex items-center justify-center h-48 text-xs text-tx-muted">{t('food.history.loading')}</div>) : historyData.length === 0 ? (<div className="flex flex-col items-center justify-center h-48 gap-2">{historyMissing ? (@@ -504,14 +502,14 @@ export default function Food() {// unrelated icons for one condition.<ErrorStatesize="section"- title="Couldn't load your history"- message={missing['your history']}+ title={t('food.history.loadFailed')}+ message={uiMessage(missing['your history'])}onRetry={() => setHistoryKey(k => k + 1)}/>) : (<><CalendarDays className="w-8 h-8 text-tx-muted opacity-40" />- <p className="text-xs text-tx-muted">No data yet — start logging meals</p>+ <p className="text-xs text-tx-muted">{t('food.history.empty')}</p></>)}</div>@@ -534,7 +532,7 @@ export default function Food() {</defs><XAxisdataKey="date"- tickFormatter={d => formatDay(d, 'M/d')}+ tickFormatter={d => formatDay(d, 'numericMonthDay')}tick={{ fontSize: 10, fill: 'var(--color-tx-muted)' }}axisLine={false}tickLine={false}@@ -555,26 +553,26 @@ export default function Food() {fontSize: '12px',color: 'var(--color-tx-primary)',}}- labelFormatter={d => formatDay(d, 'MMM d')}+ labelFormatter={d => formatDay(d, 'monthDay')}formatter={(val: number, name: string) => [`${Math.round(val)}g`, name]}cursor={{ stroke: 'rgba(99,102,241,0.15)', strokeWidth: 1 }}/>- <Area type="monotone" dataKey="fat" stackId="macros" stroke={MACRO_COLORS.fat} strokeWidth={1.5} fill="url(#gFat)" name="Fat" dot={false} />- <Area type="monotone" dataKey="carbs" stackId="macros" stroke={MACRO_COLORS.carbs} strokeWidth={1.5} fill="url(#gCarbs)" name="Carbs" dot={false} />- <Area type="monotone" dataKey="protein" stackId="macros" stroke={MACRO_COLORS.protein} strokeWidth={1.5} fill="url(#gProtein)" name="Protein" dot={false} />+ <Area type="monotone" dataKey="fat" stackId="macros" stroke={MACRO_COLORS.fat} strokeWidth={1.5} fill="url(#gFat)" name={t('food.macro.fat')} dot={false} />+ <Area type="monotone" dataKey="carbs" stackId="macros" stroke={MACRO_COLORS.carbs} strokeWidth={1.5} fill="url(#gCarbs)" name={t('food.macro.carbs')} dot={false} />+ <Area type="monotone" dataKey="protein" stackId="macros" stroke={MACRO_COLORS.protein} strokeWidth={1.5} fill="url(#gProtein)" name={t('food.macro.protein')} dot={false} /></AreaChart></ResponsiveContainer>)}<div className="flex gap-4 justify-center mt-4">- {[- { color: MACRO_COLORS.protein, label: 'Protein' },- { color: MACRO_COLORS.carbs, label: 'Carbs' },- { color: MACRO_COLORS.fat, label: 'Fat' },- ].map(m => (- <div key={m.label} className="flex items-center gap-1.5">+ {([+ { color: MACRO_COLORS.protein, key: 'protein' },+ { color: MACRO_COLORS.carbs, key: 'carbs' },+ { color: MACRO_COLORS.fat, key: 'fat' },+ ] as const).map(m => (+ <div key={m.key} className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 rounded-sm flex-shrink-0" style={{ background: m.color }} />- <span className="text-xs text-tx-muted">{m.label}</span>+ <span className="text-xs text-tx-muted">{t(`food.macro.${m.key}`)}</span></div>))}</div>diff --git a/web/src/pages/GymModeWorkout.tsx b/web/src/pages/GymModeWorkout.tsxindex 5f2892e..5d80f1c 100644--- a/web/src/pages/GymModeWorkout.tsx+++ b/web/src/pages/GymModeWorkout.tsx@@ -5,8 +5,8 @@ import {Minimize2, Trash2, Repeat, Check, Layers, Timer,} from 'lucide-react'import Model, { IExerciseData } from 'react-body-highlighter'-import { useAsyncAction, types, PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange } from '@lyftr/shared'-import { muscleColor, muscleColorBordered, EQUIPMENT_LABEL, muscleToBodySlugs } from '../utils/exerciseUtils'+import { useAsyncAction, types, PLATE_STEP, REP_STEP, clampStep, clampValue, nextIncompleteSet, numericRange, useTranslation } from '@lyftr/shared'+import { muscleColor, muscleColorBordered, categoryLabel, equipmentLabel, muscleLabel, muscleToBodySlugs } from '../utils/exerciseUtils'import { useTheme } from '../hooks/useTheme'import { useWorkoutSession } from '../stores/workoutSession'import { useSettingsStore } from '../stores/settings'@@ -30,6 +30,7 @@ function buildBodyData(exercise: types.Exercise): IExerciseData[] {}function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string; onSave: (i: number, v: string) => void }) {+ const { t } = useTranslation()const [editing, setEditing] = useState(false)const [val, setVal] = useState(notes)const commit = () => { onSave(exIdx, val); setEditing(false) }@@ -40,7 +41,7 @@ function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string;onChange={e => setVal(e.target.value)}onBlur={commit}onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setVal(notes); setEditing(false) } }}- placeholder="Add a note…"+ placeholder={t('workouts.active.notes.placeholder')}className="input text-sm w-full"/>)@@ -50,7 +51,7 @@ function ExerciseNotes({ exIdx, notes, onSave }: { exIdx: number; notes: string;onClick={() => { setVal(notes); setEditing(true) }}className="text-xs text-tx-muted hover:text-tx-secondary transition-colors text-left w-full">- {notes ? <span className="italic">{notes}</span> : <span className="opacity-50">+ Add note</span>}+ {notes ? <span className="italic">{notes}</span> : <span className="opacity-50">{t('workouts.active.notes.add')}</span>}</button>)}@@ -60,6 +61,8 @@ interface GymModeWorkoutProps {}export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {+ // Also re-renders on a language switch for the labels read from the catalog.+ const { t } = useTranslation()const navigate = useNavigate()const { isDark } = useTheme()const {@@ -101,7 +104,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {minimizeGym()// Surface the routine auto-progression as a toast on the workouts list (#40).navigate('/workouts', saved?.progression ? { state: { progression: saved.progression } } : undefined)- }, 'Failed to save workout')+ }, t('workouts.active.saveFailed'))if (!session) return null@@ -135,7 +138,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<buttonkey={i}onClick={() => setGymState('exercise-info', i, 0)}- aria-label={`Go to exercise ${i + 1}`}+ aria-label={t('gym.goToExercise', { number: i + 1 })}className={`h-1.5 rounded-full flex-shrink-0 transition-all duration-200 ${i === activeIdx ? 'w-6 bg-brand-500' :s.exercises[i].sets.every(st => st.completed) && s.exercises[i].sets.length > 0@@ -156,21 +159,21 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {}`}><Flag className="w-3.5 h-3.5" />- Finish+ {t('workouts.active.finish')}</button><buttononClick={handleMinimize}className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted"- aria-label="Minimize workout"- title="Minimize"+ aria-label={t('gym.minimizeWorkout')}+ title={t('gym.minimize')}><Minimize2 className="w-4 h-4" /></button><buttononClick={() => setConfirmCancel(true)}className="p-2 hover:bg-error-500/10 rounded-xl transition-colors text-tx-muted hover:text-error-400"- aria-label="Discard workout"- title="Discard workout"+ aria-label={t('gym.discardWorkout')}+ title={t('gym.discardWorkout')}><X className="w-5 h-5" /></button>@@ -188,11 +191,11 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<ConfirmSheetopen={confirmFinish}icon={Flag}- title="Finish Workout?"- message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}- confirmLabel="Finish"- busyLabel="Saving…"- cancelLabel="Keep Going"+ title={t('workouts.active.finishConfirm.title')}+ message={t('workouts.active.finishConfirm.message', { done: completedSets, total: totalSets })}+ confirmLabel={t('workouts.active.finish')}+ busyLabel={t('common.saving')}+ cancelLabel={t('workouts.active.keepGoing')}busy={finish.busy}error={finish.error}onConfirm={() => { void finish.run() }}@@ -202,10 +205,10 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {open={confirmCancel}icon={Trash2}destructive- title="Discard workout?"- message="This ends the workout without saving — all progress is lost."- confirmLabel="Discard"- cancelLabel="Keep Going"+ title={t('gym.discard.title')}+ message={t('gym.discard.message')}+ confirmLabel={t('gym.discard.confirm')}+ cancelLabel={t('workouts.active.keepGoing')}onConfirm={() => { cancelSession(); handleMinimize() }}onCancel={() => setConfirmCancel(false)}/>@@ -215,17 +218,17 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {// ── Overview ──────────────────────────────────────────────────────────if (phase === 'overview') {return (- <div role="dialog" aria-modal="true" aria-label="Workout" className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">+ <div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col"><div className="flex items-center justify-between px-5 pt-5 pb-4 border-b border-surface-border flex-shrink-0"><div>- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-0.5">Workout</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-0.5">{t('gym.workout')}</p><h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{session.name}</h1></div><div className="flex items-center gap-1">- <button onClick={handleMinimize} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted" aria-label="Minimize">+ <button onClick={handleMinimize} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted" aria-label={t('gym.minimize')}><Minimize2 className="w-4 h-4" /></button>- <button onClick={() => setConfirmCancel(true)} aria-label="Discard workout" title="Discard workout" className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted hover:text-error-400">+ <button onClick={() => setConfirmCancel(true)} aria-label={t('gym.discardWorkout')} title={t('gym.discardWorkout')} className="p-2 hover:bg-surface-muted rounded-xl transition-colors text-tx-muted hover:text-error-400"><X className="w-5 h-5" /></button></div>@@ -235,17 +238,17 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<div className="grid grid-cols-3 gap-3 px-5 py-4 border-b border-surface-border flex-shrink-0"><div className="text-center"><p className="text-xl font-bold text-tx-primary tabular-nums">{session.exercises.length}</p>- <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Exercises</p>+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.exercises')}</p></div><div className="text-center"><p className="text-xl font-bold text-tx-primary tabular-nums">{totalSets}</p>- <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Total Sets</p>+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.totalSets')}</p></div><div className="text-center"><p className="text-xl font-bold text-tx-primary tabular-nums">{[...new Set(session.exercises.map(e => e.exercise.muscle_group))].length}</p>- <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">Muscles</p>+ <p className="text-[10px] text-tx-muted uppercase tracking-wide mt-0.5">{t('gym.overview.muscles')}</p></div></div>@@ -254,7 +257,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {{session.exercises.length === 0 ? (<div className="flex flex-col items-center justify-center py-16 gap-3"><Dumbbell className="w-10 h-10 text-tx-muted/30" />- <p className="text-sm text-tx-muted">No exercises added yet</p>+ <p className="text-sm text-tx-muted">{t('gym.overview.empty')}</p></div>) : (<div className="space-y-2">@@ -279,9 +282,9 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<p className="text-sm font-semibold text-tx-primary truncate">{ex.exercise.name}</p><div className="flex items-center gap-2 mt-0.5"><span className={`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span>- <span className="text-[10px] text-tx-muted">{ex.sets.length} set{ex.sets.length === 1 ? '' : 's'}</span>+ <span className="text-[10px] text-tx-muted">{t('workouts.detail.setCount', { count: ex.sets.length })}</span></div></div>{done && <CheckCircle2 className="w-4 h-4 text-brand-400 flex-shrink-0" />}@@ -299,7 +302,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {className="w-full py-3 bg-surface-muted/60 hover:bg-surface-muted border border-surface-border hover:border-brand-500/40 rounded-2xl text-sm font-medium text-tx-secondary hover:text-brand-400 transition-colors flex items-center justify-center gap-2"><Plus className="w-4 h-4" />- Add Exercise+ {t('workouts.active.addExercise')}</button>{session.exercises.length > 0 && (<button@@ -307,7 +310,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"><Play className="w-5 h-5 fill-current" />- Start Workout+ {t('gym.overview.startWorkout')}</button>)}</div>@@ -326,7 +329,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {// ── Exercise info ─────────────────────────────────────────────────────if (phase === 'exercise-info') {const exercise = ex.exercise- const equipLabel = EQUIPMENT_LABEL[exercise.equipment?.toLowerCase()] || exercise.equipment+ const equipLabel = equipmentLabel(exercise.equipment)const descLines = exercise.description? exercise.description.split('\n').filter(l => l.trim()): []@@ -335,13 +338,13 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {const repsVals = ex.sets.map(s => s.target_reps).filter(r => r > 0)const wtVals = ex.sets.map(s => displayWeight(s.target_weight, wUnit)).filter(w => w > 0)const planStats = [- { icon: Layers, label: 'Sets', value: <>{ex.sets.length}</> },- { icon: Repeat, label: 'Reps', value: <>{numericRange(repsVals)}</> },- { icon: Dumbbell, label: 'Weight', value: <>{numericRange(wtVals)}<span className="text-xs font-semibold text-tx-muted ml-0.5">{wUnit}</span></> },+ { icon: Layers, label: t('gym.labels.sets'), value: <>{ex.sets.length}</> },+ { icon: Repeat, label: t('gym.labels.reps'), value: <>{numericRange(repsVals)}</> },+ { icon: Dumbbell, label: t('gym.labels.weight'), value: <>{numericRange(wtVals)}<span className="text-xs font-semibold text-tx-muted ml-0.5">{wUnit}</span></> },]return (- <div role="dialog" aria-modal="true" aria-label="Workout" className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col">+ <div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base overflow-y-auto flex flex-col"><TopBar s={session} onBack={() => isFirst ? setPhase('overview') : setGymState('exercise', activeIdx - 1, 0)} /><div className="flex-1 overflow-y-auto">@@ -361,7 +364,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<h2 className="font-display font-bold text-2xl text-tx-primary leading-tight">{exercise.name}</h2><div className="flex flex-wrap items-center gap-2 mt-2"><span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium border ${muscleColorBordered(exercise.muscle_group)}`}>- {exercise.muscle_group}+ {muscleLabel(exercise.muscle_group)}</span>{equipLabel && exercise.equipment !== 'other' && (<span className="inline-flex items-center px-3 py-1 rounded-full bg-surface-muted border border-surface-border text-xs font-medium text-tx-secondary">@@ -370,7 +373,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {)}{exercise.category && (<span className="inline-flex items-center px-3 py-1 rounded-full bg-surface-muted border border-surface-border text-xs font-medium text-tx-secondary capitalize">- {exercise.category}+ {categoryLabel(exercise.category)}</span>)}</div>@@ -391,19 +394,19 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<div className="card p-4"><div className="flex items-center gap-2"><Timer className="w-4 h-4 text-brand-500" />- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">Rest between sets</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider">{t('gym.info.restTitle')}</p></div>- <p className="text-[11px] text-tx-muted mt-1 mb-3">Auto-starts when you complete a set</p>+ <p className="text-[11px] text-tx-muted mt-1 mb-3">{t('gym.info.restHint')}</p><RestPicker value={ex.rest_seconds ?? (settings.rest_seconds_default ?? 90)} onChange={secs => setExerciseRest(activeIdx, secs)} /></div>{/* Secondary muscles */}{exercise.secondary_muscles?.length > 0 && (<div>- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">Also works</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-2">{t('exercises.detail.alsoWorks')}</p><div className="flex flex-wrap gap-1.5">{exercise.secondary_muscles.map(m => (- <span key={m} className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${muscleColor(m)}`}>{m}</span>+ <span key={m} className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${muscleColor(m)}`}>{muscleLabel(m)}</span>))}</div></div>@@ -412,25 +415,25 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {{/* Muscle diagram */}{bodyData.length > 0 && (<div className="card p-4">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Muscles Worked</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.musclesWorked')}</p><div className="flex items-start justify-center gap-6"><div className="flex flex-col items-center gap-1"><Model data={bodyData} type="anterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />- <span className="text-xs text-tx-muted">Front</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.bodyFront')}</span></div><div className="flex flex-col items-center gap-1"><Model data={bodyData} type="posterior" bodyColor={bodyColor} highlightedColors={highlightColors} style={{ width: '120px' }} />- <span className="text-xs text-tx-muted">Back</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.bodyBack')}</span></div></div><div className="flex items-center gap-4 mt-3 justify-center"><div className="flex items-center gap-1.5"><div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#22d3ee' }} />- <span className="text-xs text-tx-muted">Primary</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.primary')}</span></div><div className="flex items-center gap-1.5"><div className="w-3 h-3 rounded-full" style={{ backgroundColor: '#0e7490' }} />- <span className="text-xs text-tx-muted">Secondary</span>+ <span className="text-xs text-tx-muted">{t('exercises.detail.secondary')}</span></div></div></div>@@ -439,7 +442,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {{/* Instructions */}{descLines.length > 0 && (<div className="card p-4">- <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">Instructions</p>+ <p className="text-xs font-semibold text-tx-muted uppercase tracking-wider mb-3">{t('exercises.detail.instructions')}</p><div className="space-y-2.5">{descLines.map((line, i) => {const stepMatch = line.match(/^(\d+\.)\s*(.*)/)@@ -465,7 +468,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {className="w-full py-4 bg-brand-500 hover:bg-brand-600 text-white rounded-2xl text-base font-bold flex items-center justify-center gap-2 shadow-lg shadow-brand-500/30 transition-colors"><Play className="w-5 h-5 fill-current" />- Begin Exercise+ {t('gym.info.begin')}</button></div>@@ -521,7 +524,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {const hideCompleteForRest = restingHere && clampedSetIdx === restNextSetreturn (- <div role="dialog" aria-modal="true" aria-label="Workout" className="fixed inset-0 z-[60] bg-surface-base flex flex-col">+ <div role="dialog" aria-modal="true" aria-label={t('gym.workout')} className="fixed inset-0 z-[60] bg-surface-base flex flex-col"><TopBar s={session} onBack={() => setPhase('exercise-info')} />{/* Exercise name + muscle (compact) */}@@ -531,13 +534,13 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<h2 className="font-display font-bold text-lg text-tx-primary leading-tight truncate">{ex.exercise.name}</h2><div className="flex items-center gap-2 mt-1"><span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span>- <span className="text-xs text-tx-muted tabular-nums">{completedHere}/{ex.sets.length} sets done</span>+ <span className="text-xs text-tx-muted tabular-nums">{t('workouts.active.setsDone', { done: completedHere, total: ex.sets.length })}</span></div></div>{!allSetsComplete && (- <button onClick={handleRemoveExercise} aria-label="Remove this exercise" title="Remove exercise" className="p-1.5 hover:bg-error-500/10 rounded-lg transition-colors flex-shrink-0">+ <button onClick={handleRemoveExercise} aria-label={t('gym.removeExercise')} title={t('workouts.active.removeExercise')} className="p-1.5 hover:bg-error-500/10 rounded-lg transition-colors flex-shrink-0"><Trash2 className="w-4 h-4 text-tx-muted hover:text-error-400 transition-colors" /></button>)}@@ -569,7 +572,12 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<buttonkey={i}onClick={() => setActiveSetIdx(i)}- aria-label={`Set ${i + 1}${s.completed ? ', done' : ''}${resting ? ', resting' : ''}`}+ aria-label={t(+ s.completed+ ? (resting ? 'gym.set.chipDoneResting' : 'gym.set.chipDone')+ : (resting ? 'gym.set.chipResting' : 'gym.set.chip'),+ { number: i + 1 },+ )}aria-current={i === clampedSetIdx}className={`flex items-center justify-center gap-1 min-w-[2.75rem] h-10 px-3 rounded-full text-sm font-bold tabular-nums transition-all active:scale-95 ${i === clampedSetIdx ? 'bg-brand-500 text-white shadow-sm shadow-brand-500/30' :@@ -587,8 +595,8 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {{/* Target reference for this set (the goal to hit) */}{(set.target_reps > 0 || set.target_weight > 0) && (<p className="text-sm text-tx-muted text-center">- Target{' '}- <span className="font-semibold text-tx-secondary tabular-nums">{set.target_reps > 0 ? set.target_reps : '—'} reps</span>+ {t('gym.target.label')}{' '}+ <span className="font-semibold text-tx-secondary tabular-nums">{set.target_reps > 0 ? t('gym.target.reps', { count: set.target_reps }) : t('gym.target.repsUnknown')}</span>{set.target_weight > 0 && (<> · <span className="font-semibold text-tx-secondary tabular-nums">{displayWeight(set.target_weight, wUnit)} {wUnit}</span></>)}@@ -601,7 +609,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {<div className="w-full grid grid-cols-2 gap-3">{/* Reps — key by set so a half-typed value can't bleed to the next set */}<StepperTile- icon={Repeat} label="Reps" name="reps" step={REP_STEP} disabled={set.completed}+ icon={Repeat} label={t('gym.labels.reps')} name={t('gym.labels.repsName')} step={REP_STEP} disabled={set.completed}onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_reps', clampStep(set.actual_reps || 0, d, { min: 0 }))}><NumberField@@ -611,13 +619,13 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_reps', Math.round(clampValue(v)))}placeholder={set.target_reps > 0 ? String(set.target_reps) : '0'}disabled={set.completed}- aria-label="Reps"+ aria-label={t('gym.labels.reps')}/></StepperTile>{/* Weight */}<StepperTile- icon={Dumbbell} label={`Weight (${wUnit})`} name="weight" step={PLATE_STEP} disabled={set.completed}+ icon={Dumbbell} label={t('workouts.form.weightWithUnit', { unit: wUnit })} name={t('weight.log.weightName')} step={PLATE_STEP} disabled={set.completed}onStep={d => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampStep(displayWeight(set.actual_weight, wUnit), d, { min: 0 }), wUnit))}><NumberField@@ -627,7 +635,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {onChange={v => updateSet(activeIdx, clampedSetIdx, 'actual_weight', displayToLbs(clampValue(v), wUnit))}placeholder={set.target_weight > 0 ? String(displayWeight(set.target_weight, wUnit)) : '0'}disabled={set.completed}- aria-label="Weight"+ aria-label={t('gym.labels.weight')}/></StepperTile></div>@@ -650,7 +658,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {}`}><CheckCircle2 className="w-6 h-6" />- {set.completed ? 'Completed' : 'Complete Set'}+ {set.completed ? t('gym.completed') : t('gym.completeSet')}</button>{/* Remove set — hidden on the last set (removing it would empty the exercise@@ -660,7 +668,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {onClick={() => handleRemoveSet(clampedSetIdx)}className="text-xs text-tx-muted/50 hover:text-error-400 transition-colors">- Remove this set+ {t('gym.removeSet')}</button>)}</div>@@ -683,7 +691,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {className="flex-1 py-3 flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-surface-border hover:border-brand-500/40 hover:bg-brand-500/5 text-xs font-medium text-tx-muted hover:text-brand-400 transition-colors"><Plus className="w-3.5 h-3.5" />- Add Set+ {t('workouts.active.addSet')}</button><buttononClick={() => setActiveSetIdx(clampedSetIdx + 1)}@@ -701,7 +709,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {className="flex items-center gap-1.5 px-4 py-3 rounded-xl bg-surface-muted hover:bg-surface-muted/80 border border-surface-border text-tx-secondary text-sm font-medium transition-colors"><ChevronLeft className="w-4 h-4" />- Info+ {t('gym.nav.info')}</button>{isLast ? (<button@@ -713,7 +721,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {}`}><Flag className="w-4 h-4" />- Finish Workout+ {t('gym.nav.finishWorkout')}</button>) : (<button@@ -724,7 +732,7 @@ export default function GymModeWorkout({ wUnit }: GymModeWorkoutProps) {: 'bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary border border-surface-border'}`}>- Next Exercise+ {t('gym.nav.nextExercise')}<ChevronRight className="w-4 h-4" /></button>)}diff --git a/web/src/pages/LogFood.test.tsx b/web/src/pages/LogFood.test.tsxindex 0d9a28c..c83ee92 100644--- a/web/src/pages/LogFood.test.tsx+++ b/web/src/pages/LogFood.test.tsx@@ -1,8 +1,8 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, fireEvent, waitFor } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'import LogFood from './LogFood'-import type { FoodSearchResult } from '@lyftr/shared'+import { i18n, type FoodSearchResult } from '@lyftr/shared'// What the page sends to the API: scaleServing's fields plus where and when.type LoggedPayload = ReturnType<typeof import('@lyftr/shared').scaleServing> & {@@ -60,6 +60,22 @@ beforeEach(() => {vi.clearAllMocks()})+afterEach(async () => { await i18n.changeLanguage('en') })++describe('Log Food copy', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ renderPage()++ expect(await screen.findByRole('heading', { name: 'Registrar comida' })).toBeTruthy()+ expect(screen.getByPlaceholderText('Buscar comida…')).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Escanear código de barras' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Favoritos' })).toBeTruthy()+ expect(screen.getByLabelText('Volver')).toBeTruthy()+ expect(screen.queryByText('Search food…')).toBeNull()+ })+})+describe('Barcode lookup', () => {it('shows the scanned code while it is looked up, and blocks a second scan', async () => {barcode.mockReturnValue(new Promise(() => {}))diff --git a/web/src/pages/LogFood.tsx b/web/src/pages/LogFood.tsxindex 667762c..43a993b 100644--- a/web/src/pages/LogFood.tsx+++ b/web/src/pages/LogFood.tsx@@ -6,7 +6,7 @@ import {Coffee, Sun, Moon, Cookie, ChevronRight, Loader2,} from 'lucide-react'import { foodAPI, savedFoodsAPI } from '../services/api'-import { apiErrorMessage, isNotFound, useAsyncAction, todayStr, dayToInstant, entryDay, foodResultKey, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'+import { isNotFound, useAsyncAction, useTranslation, uiMessage, type UiMessage, todayStr, dayToInstant, entryDay, foodResultKey, MACRO_COLORS, types, entryToResult, savedToResult, scaleServing, storedServingSize, scaledFigures, useFavorites, useFoodAmount } from '@lyftr/shared'import { ErrorState, ListError, Toast } from '../components/ui'import BarcodeScanner from '../components/BarcodeScanner'import BarcodeLookup from '../components/BarcodeLookup'@@ -20,9 +20,6 @@ type Phase = 'search' | 'detail' | 'scan'type SearchTab = 'recent' | 'myfoods' | 'all'const MEALS = ['breakfast', 'lunch', 'dinner', 'snacks'] as const-const MEAL_LABELS: Record<string, string> = {- breakfast: 'Breakfast', lunch: 'Lunch', dinner: 'Dinner', snacks: 'Snacks',-}const MEAL_ICONS: Record<string, React.ElementType> = {breakfast: Coffee, lunch: Sun, dinner: Moon, snacks: Cookie,}@@ -53,6 +50,7 @@ function FoodResultRow(loading?: boolean},) {+ const { t } = useTranslation()const content = (<><FoodThumb src={item.image_url} />@@ -62,11 +60,11 @@ function FoodResultRow(<div className="flex items-center gap-1.5 mt-1 flex-wrap"><span className="text-xs font-semibold text-tx-secondary tabular-nums">{Math.round(item.calories)} kcal</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-emerald-400 tabular-nums">{item.protein.toFixed(0)}g P</span>+ <span className="text-xs text-emerald-400 tabular-nums">{item.protein.toFixed(0)}g {t('food.macro.proteinInitial')}</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-amber-400 tabular-nums">{item.carbs.toFixed(0)}g C</span>+ <span className="text-xs text-amber-400 tabular-nums">{item.carbs.toFixed(0)}g {t('food.macro.carbsInitial')}</span><span className="text-[10px] text-tx-muted">·</span>- <span className="text-xs text-violet-400 tabular-nums">{item.fat.toFixed(0)}g F</span>+ <span className="text-xs text-violet-400 tabular-nums">{item.fat.toFixed(0)}g {t('food.macro.fatInitial')}</span>{item.serving_size && (<><span className="text-[10px] text-tx-muted">·</span>@@ -97,6 +95,7 @@ function FoodResultRow(}export default function LogFood() {+ const { t } = useTranslation()const navigate = useNavigate()const [searchParams] = useSearchParams()@@ -115,17 +114,17 @@ export default function LogFood() {// Each list's own failure. Kept separate from the page: one of these failing is not a// reason to withhold search, and an empty list that failed to load must not draw the// same "nothing here" as a list that really is empty.- const [recentError, setRecentError] = useState<string | null>(null)- const [savedError, setSavedError] = useState<string | null>(null)+ const [recentError, setRecentError] = useState<UiMessage | null>(null)+ const [savedError, setSavedError] = useState<UiMessage | null>(null)const [listReload, setListReload] = useState(0)const [searching, setSearching] = useState(false)- const [searchError, setSearchError] = useState<string | null>(null)+ const [searchError, setSearchError] = useState<UiMessage | null>(null)const [rateLimited, setRateLimited] = useState(false)// A barcode lookup goes through Open Food Facts and routinely takes seconds (the// server allows it 5). The scanner closes the moment it reads a code, so without// this the screen sat unchanged and people rescanned, thinking it had failed (#164).// null: no lookup. error null: in flight. error set: failed, in the server's words.- const [lookup, setLookup] = useState<{ code: string; error: string | null } | null>(null)+ const [lookup, setLookup] = useState<{ code: string; error: UiMessage | null } | null>(null)const lookingUp = lookup !== null && lookup.error === nullconst [selected, setSelected] = useState<types.FoodSearchResult | null>(null)@@ -137,12 +136,12 @@ export default function LogFood() {// search index answers with per-100g figures and no serving at all, so a hit has to// be read again through the product endpoint before it can be trusted (#171).const [upgrading, setUpgrading] = useState<string | null>(null)- const [staleServing, setStaleServing] = useState<string | null>(null)+ const [staleServing, setStaleServing] = useState<UiMessage | null>(null)const [meal, setMeal] = useState<types.FoodLog['meal']>(initMeal)const [date, setDate] = useState(initDate)- const [editError, setEditError] = useState<string | null>(null)+ const [editError, setEditError] = useState<UiMessage | null>(null)const [editRetry, setEditRetry] = useState(0)const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)@@ -157,7 +156,7 @@ export default function LogFood() {setMeal(entry.meal)setDate(entryDay(entry))setPhase('detail')- }).catch(err => setEditError(apiErrorMessage(err, "The server didn't say what went wrong.")))+ }).catch(err => setEditError({ key: 'settings.unknownError', cause: err }))}, [editId, navigate, editRetry, openOnEntry])useEffect(() => {@@ -174,10 +173,10 @@ export default function LogFood() {}setRecentItems(items)setRecentError(null)- }).catch(err => setRecentError(apiErrorMessage(err, "Couldn't load what you logged today.")))+ }).catch(err => setRecentError({ key: 'food.log.recent.loadFailed', cause: err }))savedFoodsAPI.list().then(list => { setSavedFoods(list); setSavedError(null) })- .catch(err => setSavedError(apiErrorMessage(err, "Couldn't load your favourites.")))+ .catch(err => setSavedError({ key: 'food.favorites.loadFailed', cause: err }))}, [listReload, setSavedFoods])useEffect(() => {@@ -192,7 +191,7 @@ export default function LogFood() {setSearchResults(await foodAPI.search(query.trim()) ?? [])} catch (err: any) {if (err?.response?.status === 429) setRateLimited(true)- else setSearchError('Food search unavailable — enter details manually')+ else setSearchError({ key: 'food.log.searchUnavailable' })setSearchResults([])} finally {setSearching(false)@@ -201,7 +200,7 @@ export default function LogFood() {return () => { if (debounceRef.current) clearTimeout(debounceRef.current) }}, [query, tab])- const selectResult = (result: types.FoodSearchResult, note: string | null = null) => {+ const selectResult = (result: types.FoodSearchResult, note: UiMessage | null = null) => {setSelected(result)amount.openOn(result)setStaleServing(note)@@ -220,7 +219,7 @@ export default function LogFood() {} catch (err) {// The search row is still real data, so log against it rather than dead-ending —// but say which figures these are, because they are the ones that read wrong.- selectResult(result, apiErrorMessage(err, "Couldn't re-read this product."))+ selectResult(result, { key: 'food.log.rereadFailed', cause: err })} finally {setUpgrading(null)}@@ -228,7 +227,7 @@ export default function LogFood() {const enterManually = () => {setLookup(null)- selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'manual' })+ selectResult({ name: '', calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'manual' })}const lookUpBarcode = async (code: string) => {@@ -242,7 +241,7 @@ export default function LogFood() {// unreachable upstream is not an answer, and saying "not found" for it sent// people to type in a product that does exist.if (isNotFound(err)) enterManually()- else setLookup({ code, error: apiErrorMessage(err, "Couldn't look up that barcode.") })+ else setLookup({ code, error: { key: 'food.log.lookupFailed', cause: err } })}}@@ -258,7 +257,7 @@ export default function LogFood() {await foodAPI.log(payload)}navigate('/food', { replace: true })- }, 'Failed to save')+ }, t('food.log.saveFailed'))const handleLog = async () => {if (!selected || save.busy) return@@ -280,10 +279,10 @@ export default function LogFood() {return (<ErrorStatesize="page"- title="Couldn't load this entry"- message={editError}+ title={t('food.entry.loadFailed')}+ message={uiMessage(editError)}onRetry={() => { setEditError(null); setEditRetry(k => k + 1) }}- secondary={<button onClick={() => navigate('/food')} className="btn-secondary btn-sm">Back to food</button>}+ secondary={<button onClick={() => navigate('/food')} className="btn-secondary btn-sm">{t('food.log.backToFood')}</button>}/>)}@@ -299,7 +298,7 @@ export default function LogFood() {{/* Header with breadcrumb */}<div className="flex items-center gap-3 mb-5"><button- aria-label="Go back"+ aria-label={t('common.goBack')}onClick={() => phase === 'detail' && !editId ? setPhase('search') : navigate(-1)}className="w-10 h-10 flex items-center justify-center rounded-xl hover:bg-surface-muted active:scale-95 transition-all flex-shrink-0">@@ -309,17 +308,17 @@ export default function LogFood() {{phase === 'detail' && selected ? (<><div className="flex items-center gap-1.5 text-xs text-tx-muted mb-0.5">- <span>{editId ? 'Edit Food' : 'Log Food'}</span>+ <span>{editId ? t('food.log.editTitle') : t('food.log.title')}</span><ChevronRight className="w-3 h-3" />- <span className="text-tx-secondary">Details</span>+ <span className="text-tx-secondary">{t('food.log.details')}</span></div><h1 className="font-display font-bold text-xl text-tx-primary truncate">- {selected.name || 'New Entry'}+ {selected.name || t('food.log.newEntry')}</h1>{selected.brand && <p className="text-xs text-tx-muted mt-0.5">{selected.brand}</p>}</>) : (- <h1 className="font-display font-bold text-2xl text-tx-primary">Log Food</h1>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('food.log.title')}</h1>)}</div>{/* Favouriting is decoupled from logging, so the star sits beside the food rather@@ -354,7 +353,7 @@ export default function LogFood() {type="text"value={query}onChange={e => { setQuery(e.target.value); if (e.target.value.trim()) setTab('all'); if (lookup?.error) setLookup(null) }}- placeholder="Search food…"+ placeholder={t('food.log.searchPlaceholder')}className="input pl-10 pr-10 w-full h-12 text-base"/>{query && (@@ -370,34 +369,34 @@ export default function LogFood() {onClick={() => setPhase('scan')}disabled={lookingUp}className="flex items-center gap-1.5 px-3.5 h-12 rounded-xl bg-surface-muted hover:bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors flex-shrink-0 disabled:opacity-40 disabled:pointer-events-none"- aria-label="Scan barcode"+ aria-label={t('food.log.scanLabel')}><Scan className="w-5 h-5" />- <span className="text-xs font-medium">Scan</span>+ <span className="text-xs font-medium">{t('food.log.scan')}</span></button></div>{/* Tabs */}<SegmentedControloptions={[- { value: 'recent', label: 'Recent' },- { value: 'myfoods', label: 'Favorites' },- { value: 'all', label: 'Search' },+ { value: 'recent', label: t('food.log.tab.recent') },+ { value: 'myfoods', label: t('food.log.tab.favorites') },+ { value: 'all', label: t('food.log.tab.search') },] as const}value={tab}- onChange={t => { setTab(t); if (lookup?.error) setLookup(null) }}+ onChange={v => { setTab(v); if (lookup?.error) setLookup(null) }}/>{rateLimited && (<div className="flex items-center gap-2 rounded-xl border border-amber-500/20 bg-amber-500/10 px-3.5 py-3 text-xs text-amber-400"><AlertCircle className="w-4 h-4 flex-shrink-0" />- Too many requests — wait a moment and try again+ {t('food.log.rateLimited')}</div>)}{searchError && (<div className="flex items-center gap-2 rounded-xl border border-error-500/20 bg-error-500/10 px-3.5 py-3 text-xs text-error-400"><AlertCircle className="w-4 h-4 flex-shrink-0" />- {searchError}+ {uiMessage(searchError)}</div>)}@@ -409,25 +408,25 @@ export default function LogFood() {// what failed, and both ways forward keep the code already scanned.<div className="card"><ErrorState- title="Couldn't look up this barcode"- message={lookup.error}+ title={t('food.log.lookupFailedTitle')}+ message={uiMessage(lookup.error)}onRetry={() => lookUpBarcode(lookup.code)}- secondary={<button onClick={enterManually} className="btn-secondary btn-sm">Enter it manually</button>}+ secondary={<button onClick={enterManually} className="btn-secondary btn-sm">{t('food.log.enterManually')}</button>}/></div>) : (<div className="card overflow-hidden">{tab === 'all' && quickAddCals !== null && (<button- onClick={() => selectResult({ name: `${quickAddCals} kcal`, calories: quickAddCals, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ onClick={() => selectResult({ name: `${quickAddCals} kcal`, calories: quickAddCals, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'off' })}className="flex items-center gap-3 w-full px-4 py-3.5 hover:bg-surface-muted transition-colors border-b border-surface-border"><div className="w-11 h-11 rounded-xl bg-brand-500/10 border border-brand-500/20 flex items-center justify-center flex-shrink-0"><Zap className="w-5 h-5 text-brand-500" /></div><div className="flex-1 text-left min-w-0">- <p className="text-sm font-semibold text-tx-primary">Quick add {quickAddCals} kcal</p>- <p className="text-xs text-tx-muted mt-0.5">No macro breakdown</p>+ <p className="text-sm font-semibold text-tx-primary">{t('food.log.quickAdd', { kcal: quickAddCals })}</p>+ <p className="text-xs text-tx-muted mt-0.5">{t('food.log.noMacroBreakdown')}</p></div><ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" /></button>@@ -435,13 +434,13 @@ export default function LogFood() {{tab === 'recent' && (recentError- ? <ListError subject="what you logged today" message={recentError} onRetry={() => { setRecentError(null); setListReload(n => n + 1) }} />+ ? <ListError subject={t('food.log.recent.subject')} message={uiMessage(recentError)} onRetry={() => { setRecentError(null); setListReload(n => n + 1) }} />: recentItems.length === 0? (<div className="px-4 py-14 text-center"><Utensils className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />- <p className="text-sm text-tx-muted">No recent items today</p>- <p className="text-xs text-tx-muted mt-1 opacity-60">Search or scan to log food</p>+ <p className="text-sm text-tx-muted">{t('food.log.recent.empty.title')}</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">{t('food.log.recent.empty.hint')}</p></div>): recentItems.map((item, i) => (@@ -458,13 +457,13 @@ export default function LogFood() {{tab === 'myfoods' && (savedError- ? <ListError subject="your favourites" message={savedError} onRetry={() => { setSavedError(null); setListReload(n => n + 1) }} />+ ? <ListError subject={t('food.favorites.subject')} message={uiMessage(savedError)} onRetry={() => { setSavedError(null); setListReload(n => n + 1) }} />: savedFoods.length === 0? (<div className="px-4 py-14 text-center"><Star className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />- <p className="text-sm text-tx-muted">No favorites yet</p>- <p className="text-xs text-tx-muted mt-1 opacity-60">Star foods while logging to find them here</p>+ <p className="text-sm text-tx-muted">{t('food.favorites.empty.title')}</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">{t('food.favorites.empty.hint')}</p></div>): savedFoods.map(sf => {@@ -485,21 +484,21 @@ export default function LogFood() {{tab === 'all' && !query.trim() && (<div className="px-4 py-14 text-center"><Search className="w-8 h-8 text-tx-muted opacity-30 mx-auto mb-2" />- <p className="text-sm text-tx-muted">Search millions of foods</p>- <p className="text-xs text-tx-muted mt-1 opacity-60">Or scan a barcode</p>+ <p className="text-sm text-tx-muted">{t('food.log.search.emptyTitle')}</p>+ <p className="text-xs text-tx-muted mt-1 opacity-60">{t('food.log.search.emptyHint')}</p></div>)}{tab === 'all' && query.trim() && searching && (- <div className="px-4 py-14 text-center text-sm text-tx-muted">Searching…</div>+ <div className="px-4 py-14 text-center text-sm text-tx-muted">{t('food.log.search.searching')}</div>)}{tab === 'all' && query.trim() && !searching && searchResults.length === 0 && !searchError && !rateLimited && (<div className="px-4 py-14 text-center space-y-3">- <p className="text-sm text-tx-muted">No results for "{query}"</p>+ <p className="text-sm text-tx-muted">{t('food.log.search.noResults', { query })}</p><button- onClick={() => selectResult({ name: query.trim(), calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: '1 serving', source: 'off' })}+ onClick={() => selectResult({ name: query.trim(), calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0, serving_size: storedServingSize(), source: 'off' })}className="btn-secondary text-xs">- + Enter "{query.trim()}" manually+ {t('food.log.search.manualEntry', { query: query.trim() })}</button></div>)}@@ -535,7 +534,7 @@ export default function LogFood() {{staleServing && (<div className="alert-warning"><AlertCircle className="w-4 h-4 flex-shrink-0" />- <span>{staleServing} Showing search results, which are always per {selected.serving_size}.</span>+ <span>{t('food.log.staleServing', { note: uiMessage(staleServing), serving: selected.serving_size })}</span></div>)}@@ -556,24 +555,23 @@ export default function LogFood() {{/* The label comes from OpenFoodFacts, which is free text — and rowslogged before the backend stopped prefixing it still read "per100g". Supplying a second "per" gave "per per 100g". */}- per {servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}- {selected.serving_size.replace(/^per\s+/i, '')}+ {t('food.log.per', { serving: `${servingsLabel === 1 || !figures ? '' : `${servingsLabel} × `}${selected.serving_size.replace(/^per\s+/i, '')}` })}</p>)}</div>{/* Macro composition mini-bars */}{(pro + carb + fat_) > 0 && (<div className="flex flex-col gap-1 items-end w-20 flex-shrink-0">- {[- { label: 'P', value: pro, color: MACRO_COLORS.protein },- { label: 'C', value: carb, color: MACRO_COLORS.carbs },- { label: 'F', value: fat_, color: MACRO_COLORS.fat },- ].map(m => {+ {([+ { key: 'protein', value: pro, color: MACRO_COLORS.protein },+ { key: 'carbs', value: carb, color: MACRO_COLORS.carbs },+ { key: 'fat', value: fat_, color: MACRO_COLORS.fat },+ ] as const).map(m => {const total = pro + carb + fat_const pct = total > 0 ? Math.round((m.value / total) * 100) : 0return (- <div key={m.label} className="flex items-center gap-1.5 w-full">- <span className="text-[10px] text-tx-muted w-3 text-right flex-shrink-0">{m.label}</span>+ <div key={m.key} className="flex items-center gap-1.5 w-full">+ <span className="text-[10px] text-tx-muted w-3 text-right flex-shrink-0">{t(`food.macro.${m.key}Initial`)}</span><div className="flex-1 h-1.5 bg-surface-muted rounded-full overflow-hidden"><div className="h-full rounded-full transition-all duration-500" style={{ width: `${pct}%`, background: m.color }} /></div>@@ -587,15 +585,15 @@ export default function LogFood() {{/* Macro grid */}<div className="grid grid-cols-4 gap-2">- {[- { label: 'Protein', value: figures ? `${pro}g` : '—', color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },- { label: 'Carbs', value: figures ? `${carb}g` : '—', color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },- { label: 'Fat', value: figures ? `${fat_}g` : '—', color: 'text-violet-400', bg: 'bg-violet-500/10 border-violet-500/20' },- { label: 'Fiber', value: figures ? `${figures.fiber}g` : '—', color: 'text-tx-secondary', bg: 'bg-surface-muted border-surface-border' },- ].map(m => (- <div key={m.label} className={`rounded-xl border p-2.5 text-center ${m.bg}`}>+ {([+ { key: 'protein', value: figures ? `${pro}g` : '—', color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },+ { key: 'carbs', value: figures ? `${carb}g` : '—', color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },+ { key: 'fat', value: figures ? `${fat_}g` : '—', color: 'text-violet-400', bg: 'bg-violet-500/10 border-violet-500/20' },+ { key: 'fiber', value: figures ? `${figures.fiber}g` : '—', color: 'text-tx-secondary', bg: 'bg-surface-muted border-surface-border' },+ ] as const).map(m => (+ <div key={m.key} className={`rounded-xl border p-2.5 text-center ${m.bg}`}><p className={`text-sm font-bold tabular-nums ${m.color}`}>{m.value}</p>- <p className="text-[10px] text-tx-muted mt-0.5">{m.label}</p>+ <p className="text-[10px] text-tx-muted mt-0.5">{t(`food.macro.${m.key}`)}</p></div>))}</div>@@ -605,13 +603,13 @@ export default function LogFood() {{/* Amount */}<div className="card p-4 space-y-3"><div className="flex items-baseline gap-2">- <label className="label" htmlFor="food-amount">{basis ? 'Amount' : 'Servings'}</label>+ <label className="label" htmlFor="food-amount">{basis ? t('food.entry.amount') : t('food.log.servings')}</label>{selected.serving_size && !basis && (- <span className="text-xs text-tx-muted">({selected.serving_size} each)</span>+ <span className="text-xs text-tx-muted">{t('food.log.servingEach', { serving: selected.serving_size })}</span>)}</div><div className="flex items-center gap-3">- <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? 'Decrease amount' : 'Decrease servings'} onClick={() => amount.step(-1)} />+ <IconButton icon={Minus} variant="secondary" size="lg" label={basis ? t('food.log.decreaseAmount') : t('food.log.decreaseServings')} onClick={() => amount.step(-1)} /><div className="relative flex-1"><inputid="food-amount"@@ -624,7 +622,7 @@ export default function LogFood() {// bottle unloggable (#171). The server has never had a floor.min="0"step="any"- aria-label={basis ? `Amount in ${basis.unit}` : 'Servings'}+ aria-label={basis ? t('food.log.amountIn', { unit: basis.unit }) : t('food.log.servings')}className={`input input-no-spin text-center h-12 text-lg font-semibold tabular-nums ${basis ? 'pr-9' : ''}`}/>{basis && (@@ -633,20 +631,20 @@ export default function LogFood() {</span>)}</div>- <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? 'Increase amount' : 'Increase servings'} onClick={() => amount.step(1)} />+ <IconButton icon={Plus} variant="secondary" size="lg" label={basis ? t('food.log.increaseAmount') : t('food.log.increaseServings')} onClick={() => amount.step(1)} /></div>{/* The readout doubles as the reason the Log button is disabled. Deleting the0.5-serving floor made an empty or nonsense amount reachable for the firsttime, and "0 servings" beside a dead button says what, not why. */}{servings <= 0 ? (<p className="text-xs text-tx-muted text-center">- Enter an amount{basis ? ` in ${basis.unit}` : ''} to log this+ {basis ? t('food.log.enterAmountIn', { unit: basis.unit }) : t('food.log.enterAmount')}</p>) : limitHint ? (<p className="text-xs text-warning-400 text-center" role="status">{limitHint}</p>) : basis && (<p className="text-xs text-tx-muted text-center">- {servingsLabel} {servingsLabel === 1 ? 'serving' : 'servings'} of {selected.serving_size}+ {t('food.log.servingsOf', { count: servingsLabel, serving: selected.serving_size })}</p>)}</div>@@ -655,7 +653,7 @@ export default function LogFood() {<div className="card p-4 space-y-5">{/* Meal */}<div className="space-y-3">- <label className="label">Meal</label>+ <label className="label">{t('food.entry.meal')}</label><div className="grid grid-cols-2 gap-2">{MEALS.map(m => {const MealIcon = MEAL_ICONS[m]@@ -672,7 +670,7 @@ export default function LogFood() {}`}><MealIcon className={`w-4 h-4 flex-shrink-0 ${active ? iconColor : 'text-tx-muted'}`} />- {MEAL_LABELS[m]}+ {t(`food.meal.${m}`)}</button>)})}@@ -681,7 +679,7 @@ export default function LogFood() {<div className="border-t border-surface-border" />- <DateInput label="When" value={date} onChange={setDate} max={todayStr()} />+ <DateInput label={t('food.log.when')} value={date} onChange={setDate} max={todayStr()} /></div></div>@@ -696,7 +694,7 @@ export default function LogFood() {disabled={save.busy || servings <= 0 || overLimit}className="btn-primary btn-lg w-full">- {save.busy ? 'Saving…' : editId ? 'Save Changes' : 'Log Food'}+ {save.busy ? t('common.saving') : editId ? t('food.log.saveChanges') : t('food.log.submit')}</button></div>)}diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsxindex 1fc93ca..eeb2afb 100644--- a/web/src/pages/Login.tsx+++ b/web/src/pages/Login.tsx@@ -2,32 +2,32 @@ import { useState } from 'react'import { useNavigate, Link } from 'react-router-dom'import { AlertCircle, Zap, Dumbbell, Apple, TrendingUp, LogIn } from 'lucide-react'import { useAuthStore } from '../stores/auth'-import { apiErrorMessage } from '../services/api'import { useServerInfo } from '../hooks/useServerInfo'-import { formatVersion, registrationOpen, demoMode } from '@lyftr/shared'+import { formatVersion, registrationOpen, demoMode, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'import Logo from '../components/Logo'import ServerSettings from '../components/ServerSettings'import PasswordField from '../components/ui/PasswordField'export default function Login() {+ const { t } = useTranslation()const navigate = useNavigate()const { login } = useAuthStore()const serverInfo = useServerInfo()const [email, setEmail] = useState('')const [password, setPassword] = useState('')- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)const [isLoading, setLoading] = useState(false)const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()- setError('')+ setError(null)setLoading(true)try {await login(email, password)navigate('/')} catch (err: any) {- setError(apiErrorMessage(err, 'Invalid email or password.'))+ setError({ key: 'auth.login.failed', cause: err })} finally {setLoading(false)}@@ -39,7 +39,7 @@ export default function Login() {await login('[email protected]', 'password123')navigate('/')} catch (err: any) {- setError(apiErrorMessage(err, "Couldn't sign in to the demo account."))+ setError({ key: 'auth.login.demoFailed', cause: err })} finally {setLoading(false)}@@ -69,27 +69,27 @@ export default function Login() {{/* Headline and features */}<div className="relative space-y-8"><h1 className="font-display font-bold text-5xl leading-tight tracking-tight">- Log. Lift.+ {t('auth.hero.headline')}<br /><span className="bg-gradient-to-r from-brand-500 to-violet-500 bg-clip-text text-transparent">- Progress.+ {t('auth.hero.headlineAccent')}</span></h1><p className="text-tx-secondary text-base leading-relaxed max-w-sm">- Your self-hosted fitness tracker. Track workouts, log food, monitor weight — all under your control, running on your own server.+ {t('auth.hero.description')}</p>{/* Features */}<div className="space-y-4">- {[- { icon: Dumbbell, label: 'Track workouts' },- { icon: Apple, label: 'Log food + macros' },- { icon: TrendingUp, label: 'See progress' },- ].map(({ icon: Icon, label }) => (+ {([+ { icon: Dumbbell, label: 'auth.hero.features.workouts' },+ { icon: Apple, label: 'auth.hero.features.food' },+ { icon: TrendingUp, label: 'auth.hero.features.progress' },+ ] as const).map(({ icon: Icon, label }) => (<div key={label} className="flex items-center gap-3 text-tx-muted text-sm"><Icon className="w-4 h-4 text-brand-500" strokeWidth={2} />- {label}+ {t(label)}</div>))}</div>@@ -112,10 +112,10 @@ export default function Login() {{/* Heading */}<div className="mb-8"><h2 className="font-display font-bold text-3xl text-tx-primary tracking-tight">- Welcome back+ {t('auth.login.heading')}</h2><p className="text-tx-muted text-sm mt-2">- Sign in to continue training.+ {t('auth.login.subtitle')}</p></div>@@ -126,14 +126,14 @@ export default function Login() {<form onSubmit={handleSubmit} className="space-y-4">{/* Email */}<div>- <label htmlFor="email" className="label">Email</label>+ <label htmlFor="email" className="label">{t('auth.field.email')}</label><inputid="email"type="email"value={email}onChange={e => setEmail(e.target.value)}className="input mt-2"- placeholder="[email protected]"+ placeholder={t('auth.field.emailPlaceholder')}autoComplete="email"required/>@@ -142,7 +142,7 @@ export default function Login() {{/* Password */}<PasswordFieldid="password"- label="Password"+ label={t('auth.field.password')}value={password}onChange={setPassword}autoComplete="current-password"@@ -153,7 +153,7 @@ export default function Login() {{error && (<div className="alert-error"><AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />- <span>{error}</span>+ <span>{uiMessage(error)}</span></div>)}@@ -164,7 +164,7 @@ export default function Login() {className="btn-primary btn-lg w-full mt-6 flex items-center justify-center gap-2"><LogIn className="w-4 h-4" />- {isLoading ? 'Signing in…' : 'Sign in'}+ {isLoading ? t('auth.login.submitting') : t('auth.login.submit')}</button>{/* Divider — only when something follows it that is genuinely an alternative@@ -174,7 +174,7 @@ export default function Login() {{(demoMode(serverInfo) || registrationOpen(serverInfo)) && (<div className="relative flex items-center my-6"><div className="flex-1 h-px bg-surface-border" />- <span className="px-3 text-xs text-tx-muted uppercase tracking-wider">or</span>+ <span className="px-3 text-xs text-tx-muted uppercase tracking-wider">{t('auth.divider.orLower')}</span><div className="flex-1 h-px bg-surface-border" /></div>)}@@ -191,7 +191,7 @@ export default function Login() {className="btn-secondary btn-lg w-full flex items-center justify-center gap-2"><Zap className="w-4 h-4 text-warning-400" />- Try demo account+ {t('auth.login.demo')}</button>)}</form>@@ -202,17 +202,17 @@ export default function Login() {(mastodon/mastodon#21556); a line of text answers them where they are. */}{registrationOpen(serverInfo) ? (<p className="mt-8 text-center text-sm text-tx-muted">- New here?{' '}+ {t('auth.login.newHere')}{' '}<Linkto="/register"className="text-brand-400 font-medium hover:text-brand-300 transition-colors">- Create account+ {t('auth.login.createAccountLink')}</Link></p>) : (<p className="mt-8 text-center text-sm text-tx-muted">- This server is not accepting new accounts.+ {t('auth.closed.notice')}</p>)}</div>diff --git a/web/src/pages/ProgramDetail.tsx b/web/src/pages/ProgramDetail.tsxindex b116878..1b4069d 100644--- a/web/src/pages/ProgramDetail.tsx+++ b/web/src/pages/ProgramDetail.tsx@@ -1,7 +1,6 @@import { ConfirmSheet, ErrorState } from '../components/ui'import { useState, useEffect } from 'react'import { useParams, useNavigate, Link } from 'react-router-dom'-import { format } from 'date-fns'import {ArrowLeft, BookOpen, Dumbbell, Edit2, Trash2, Play, AlertCircle, Loader, ChevronRight, Pause, TimerOff,Award, TrendingUp, Check, X, ChevronDown, ChevronUp, Moon, CalendarDays,@@ -9,13 +8,14 @@ import {import { programAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'import { useSettingsStore, weightShort, displayWeight } from '../stores/settings'-import { apiErrorMessage, isNotFound, useAsyncAction, types, allExercises, activeSessionExercisesForDay, dayLabel, sessionNameForDay, targetWeightLabel, restLabel } from '@lyftr/shared'-import { muscleColor } from '../utils/exerciseUtils'+import { isNotFound, useAsyncAction, types, allExercises, activeSessionExercisesForDay, dayLabel, sessionNameForDay, targetWeightLabel, restLabel, formatDate, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'+import { muscleColor, muscleLabel } from '../utils/exerciseUtils'// Rows shown before the review banner collapses behind a "Show all" toggle (#40).const SUGGESTION_CAP = 3export default function ProgramDetail() {+ const { t } = useTranslation()const { id } = useParams<{ id: string }>()const navigate = useNavigate()const { session, startSession } = useWorkoutSession()@@ -24,7 +24,8 @@ export default function ProgramDetail() {const restOn = settings.rest_enabled ?? trueconst [program, setProgram] = useState<types.Program | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // UiMessages, not their sentences, so the banners follow a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)// A 404 is not a retryable failure: the row is gone, and a Try again button that// cannot ever succeed is worse than no button. Tracked separately from the message// because the message alone cannot say which kind of failure produced it.@@ -37,7 +38,7 @@ export default function ProgramDetail() {const [resolving, setResolving] = useState(false)// Separate from `error`, which replaces the whole page: a failed resolve must leave the// program on screen so the same buttons are still under the finger to retry.- const [resolveError, setResolveError] = useState<string | null>(null)+ const [resolveError, setResolveError] = useState<UiMessage | null>(null)const [showAllSuggestions, setShowAllSuggestions] = useState(false)const [selectedDayIdx, setSelectedDayIdx] = useState(0)@@ -51,7 +52,7 @@ export default function ProgramDetail() {const updated = await programAPI.resolveSuggestions(program.id, { accept, dismiss })setProgram(updated)} catch (err) {- setResolveError(apiErrorMessage(err, "Couldn't save those targets."))+ setResolveError({ key: 'programs.detail.suggestions.saveFailed', cause: err })} finally {setResolving(false)}@@ -65,7 +66,7 @@ export default function ProgramDetail() {setSelectedDayIdx(data.current_day_index || 0)} catch (err: any) {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })} finally {setLoading(false)}@@ -91,7 +92,7 @@ export default function ProgramDetail() {if (!program) returnawait programAPI.delete(program.id)navigate('/programs', { replace: true })- }, 'Failed to delete program')+ }, t('programs.deleteFailed'))if (loading) {return (@@ -105,10 +106,10 @@ export default function ProgramDetail() {return (<ErrorStatesize="page"- title="Couldn't load this program"- message={error ?? 'That program no longer exists.'}+ title={t('programs.detail.loadFailed')}+ message={error ? uiMessage(error) : t('programs.detail.gone')}onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}- secondary={<Link to="/programs" className="btn-secondary btn-sm">Back to programs</Link>}+ secondary={<Link to="/programs" className="btn-secondary btn-sm">{t('programs.detail.backToPrograms')}</Link>}/>)}@@ -138,11 +139,11 @@ export default function ProgramDetail() {newLabel = targetWeightLabel(sw, wUnit)} else {oldLabel = `${s.target_reps}`- newLabel = `${sr} reps`+ newLabel = t('programs.count.reps', { count: sr })}return {setId: s.id as number,- exName: ex.exercise?.name ?? 'Exercise',+ exName: ex.exercise?.name ?? t('programs.detail.suggestions.exerciseFallback'),setNumber: s.set_number,isPR: !!s.suggested_is_pr,oldLabel,@@ -157,26 +158,26 @@ export default function ProgramDetail() {{/* Back nav */}<div className="flex items-center justify-between"><Link to="/programs" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Programs+ <ArrowLeft className="w-4 h-4" /> {t('programs.detail.back')}</Link><div className="flex items-center gap-1"><buttononClick={handleStart}disabled={!selectedDay || selectedDay.is_rest_day}- title={selectedDay?.is_rest_day ? 'Rest day — nothing to start' : undefined}+ title={selectedDay?.is_rest_day ? t('programs.detail.restDayTitle') : undefined}className="flex items-center gap-1.5 px-3 py-2 bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:hover:bg-brand-500 text-white text-xs font-semibold rounded-xl transition-colors">- <Play className="w-3.5 h-3.5" /> Start Workout+ <Play className="w-3.5 h-3.5" /> {t('programs.startWorkout')}</button><button- aria-label="Edit program"+ aria-label={t('programs.detail.editLabel')}onClick={() => navigate(`/programs/${program.id}/edit`)}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><Edit2 className="w-4 h-4 text-brand-500" /></button><button- aria-label="Delete program"+ aria-label={t('programs.detail.deleteLabel')}onClick={() => setConfirming(true)}className="p-2 hover:bg-error-500/10 rounded-lg transition-colors">@@ -190,10 +191,10 @@ export default function ProgramDetail() {open={confirming}icon={Trash2}destructive- title="Delete Program?"- message={`"${program.name}" will be permanently deleted.`}- confirmLabel="Delete"- busyLabel="Deleting…"+ title={t('programs.deleteConfirmTitle')}+ message={t('common.deleteConfirmMessage', { subject: `"${program.name}"` })}+ confirmLabel={t('common.delete')}+ busyLabel={t('common.deleting')}busy={remove.busy}error={remove.error}onConfirm={() => { void remove.run() }}@@ -207,14 +208,14 @@ export default function ProgramDetail() {{suggestions.some(s => s.isPR)? <Award className="w-4 h-4 text-warning-400 flex-shrink-0" />: <TrendingUp className="w-4 h-4 text-warning-400 flex-shrink-0" />}- <span className="text-sm font-semibold text-tx-primary flex-1">New targets from your last workout</span>+ <span className="text-sm font-semibold text-tx-primary flex-1">{t('programs.detail.suggestions.title')}</span><span className="text-xs font-bold text-warning-400 bg-warning-500/15 px-2 py-0.5 rounded-full tabular-nums">{suggestions.length}</span></div>{(showAllSuggestions ? suggestions : suggestions.slice(0, SUGGESTION_CAP)).map(sg => (<div key={sg.setId} className="flex items-center gap-3 px-4 py-2.5 border-t border-surface-border/60"><span className="text-sm text-tx-secondary min-w-0 flex-1 truncate flex items-center gap-1.5">{sg.isPR && <Award className="w-3.5 h-3.5 text-warning-400 flex-shrink-0" />}- <span className="truncate"><span className="font-semibold text-tx-primary">{sg.exName}</span> · Set {sg.setNumber}</span>+ <span className="truncate"><span className="font-semibold text-tx-primary">{sg.exName}</span> · {t('programs.detail.suggestions.set', { number: sg.setNumber })}</span></span><span className="text-sm tabular-nums whitespace-nowrap flex-shrink-0"><span className="text-tx-muted line-through">{sg.oldLabel}</span>@@ -225,7 +226,7 @@ export default function ProgramDetail() {<buttononClick={() => resolveSuggestions([sg.setId], [])}disabled={resolving}- aria-label={`Accept ${sg.exName} set ${sg.setNumber}`}+ aria-label={t('programs.detail.suggestions.accept', { name: sg.exName, number: sg.setNumber })}className="w-7 h-7 rounded-lg bg-success-500/15 text-success-400 hover:bg-success-500/25 disabled:opacity-50 flex items-center justify-center transition-colors"><Check className="w-4 h-4" strokeWidth={3} />@@ -233,7 +234,7 @@ export default function ProgramDetail() {<buttononClick={() => resolveSuggestions([], [sg.setId])}disabled={resolving}- aria-label={`Dismiss ${sg.exName} set ${sg.setNumber}`}+ aria-label={t('programs.detail.suggestions.dismiss', { name: sg.exName, number: sg.setNumber })}className="w-7 h-7 rounded-lg bg-surface-muted text-tx-muted hover:text-tx-primary disabled:opacity-50 flex items-center justify-center transition-colors"><X className="w-4 h-4" strokeWidth={3} />@@ -247,14 +248,14 @@ export default function ProgramDetail() {className="w-full flex items-center justify-center gap-1.5 py-2 border-t border-surface-border/60 text-warning-400 hover:text-warning-300 text-xs font-semibold transition-colors">{showAllSuggestions- ? <>Show less <ChevronUp className="w-3.5 h-3.5" /></>- : <>Show all {suggestions.length} <ChevronDown className="w-3.5 h-3.5" /></>}+ ? <>{t('programs.detail.suggestions.showLess')} <ChevronUp className="w-3.5 h-3.5" /></>+ : <>{t('programs.detail.suggestions.showAll', { total: suggestions.length })} <ChevronDown className="w-3.5 h-3.5" /></>}</button>)}{resolveError && (<div className="flex items-start gap-2 px-4 py-2.5 border-t border-surface-border/60 text-sm text-error-400"><AlertCircle className="w-4 h-4 flex-shrink-0 mt-0.5" />- <span className="flex-1">{resolveError}</span>+ <span className="flex-1">{uiMessage(resolveError)}</span></div>)}<div className="flex gap-2 px-4 py-3 border-t border-surface-border/60">@@ -263,14 +264,14 @@ export default function ProgramDetail() {disabled={resolving}className="flex-1 py-2 rounded-lg bg-surface-muted border border-surface-border text-tx-secondary hover:text-tx-primary disabled:opacity-50 text-sm font-medium transition-colors">- Dismiss all+ {t('programs.detail.suggestions.dismissAll')}</button><buttononClick={() => resolveSuggestions(suggestedSetIds, [])}disabled={resolving}className="flex-1 py-2 rounded-lg bg-warning-500 hover:bg-warning-400 disabled:opacity-50 text-[#1a1400] text-sm font-semibold transition-colors">- Apply all ({suggestions.length})+ {t('programs.detail.suggestions.applyAll', { total: suggestions.length })}</button></div></div>@@ -294,7 +295,7 @@ export default function ProgramDetail() {<div className="min-w-0 flex-1"><h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{program.name}</h1><p className="text-sm text-tx-muted mt-0.5">- Created {format(new Date(program.created_at), 'MMM d, yyyy')}+ {t('programs.createdOn', { date: formatDate(new Date(program.created_at), 'monthDayYear') })}</p></div></div>@@ -303,21 +304,21 @@ export default function ProgramDetail() {<div className="text-center"><div className="flex items-center justify-center gap-1 mb-0.5"><CalendarDays className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Cycle</p>+ <p className="text-xs text-tx-muted">{t('programs.detail.stats.cycle')}</p></div><p className="text-lg font-bold text-tx-primary tabular-nums">{days.length || '—'}</p></div><div className="text-center border-l border-surface-border"><div className="flex items-center justify-center gap-1 mb-0.5"><Dumbbell className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Exercises</p>+ <p className="text-xs text-tx-muted">{t('programs.detail.stats.exercises')}</p></div><p className="text-lg font-bold text-tx-primary tabular-nums">{allExs.length}</p></div><div className="text-center border-l border-surface-border"><div className="flex items-center justify-center gap-1 mb-0.5"><BookOpen className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Total Sets</p>+ <p className="text-xs text-tx-muted">{t('programs.detail.stats.totalSets')}</p></div><p className="text-lg font-bold text-tx-primary tabular-nums">{totalSets}</p></div>@@ -334,12 +335,12 @@ export default function ProgramDetail() {{days.length === 0 ? (<div className="card p-6 text-center"><CalendarDays className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />- <p className="text-sm text-tx-muted">No days yet</p>+ <p className="text-sm text-tx-muted">{t('programs.detail.noDays')}</p><buttononClick={() => navigate(`/programs/${program.id}/edit`)}className="mt-2 text-xs text-brand-400 hover:text-brand-300 font-medium transition-colors">- Add a day →+ {t('programs.detail.addDay')}</button></div>) : (@@ -364,7 +365,7 @@ export default function ProgramDetail() {{/* Textual chip, not a bare dot — a color-only marker isn'tdistinguishable by shape/text (a11y) and reads as decoration. */}{isToday && (- <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${isSelected ? 'bg-white/20 text-white' : 'bg-brand-500/15 text-brand-400'}`}>TODAY</span>+ <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded-full ${isSelected ? 'bg-white/20 text-white' : 'bg-brand-500/15 text-brand-400'}`}>{t('programs.detail.todayChip')}</span>)}</button>)@@ -376,26 +377,30 @@ export default function ProgramDetail() {{selectedDay?.is_rest_day ? (<div className="card p-8 text-center"><Moon className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-60" />- <p className="text-sm font-medium text-tx-primary">Rest Day</p>- <p className="text-xs text-tx-muted mt-1">No exercises scheduled — recover and come back stronger.</p>+ <p className="text-sm font-medium text-tx-primary">{t('programs.day.rest')}</p>+ <p className="text-xs text-tx-muted mt-1">{t('programs.detail.restDayHint')}</p></div>) : selectedDay ? (<>{!restOn && (<div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">- <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings+ <TimerOff className="w-3.5 h-3.5" /> {t('workouts.detail.restOff')}</div>)}<div className="space-y-2">{(selectedDay.exercises ?? []).length === 0 ? (<div className="card p-6 text-center"><Dumbbell className="w-8 h-8 text-tx-muted mx-auto mb-2 opacity-50" />- <p className="text-sm text-tx-muted">No exercises on this day yet</p>+ <p className="text-sm text-tx-muted">{t('programs.detail.noExercises')}</p></div>) : (selectedDay.exercises ?? []).map((ex) => {const sets = ex.sets ?? []const maxTargetLbs = sets.length > 0 ? Math.max(...sets.map(s => s.target_weight || 0)) : 0const maxTarget = displayWeight(maxTargetLbs, wUnit)+ const setsSummary = [+ t('programs.count.sets', { count: sets.length }),+ ...(maxTarget > 0 ? [t('programs.detail.target', { weight: maxTarget, unit: wUnit })] : []),+ ].join(' · ')return (<button@@ -421,10 +426,10 @@ export default function ProgramDetail() {<div className="flex items-center gap-2 mt-0.5">{ex.exercise?.muscle_group && (<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span>)}- <span className="text-xs text-tx-muted truncate">{sets.length} set{sets.length === 1 ? '' : 's'}{maxTarget > 0 ? ` · target ${maxTarget} ${wUnit}` : ''}</span>+ <span className="text-xs text-tx-muted truncate">{setsSummary}</span></div></div><ChevronRight className="w-4 h-4 text-tx-muted flex-shrink-0" />@@ -441,13 +446,13 @@ export default function ProgramDetail() {hasSuggestion ? 'bg-warning-500/10 text-tx-secondary ring-1 ring-warning-500/40': isBest ? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25' : 'bg-surface-raised text-tx-secondary'}`}>- {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : 'BW'}+ {set.target_reps > 0 ? set.target_reps : '—'} × {set.target_weight > 0 ? `${displayWeight(set.target_weight, wUnit)} ${wUnit}` : t('weight.bodyweightShort')}</div>)})}</div>{restOn && (ex.rest_seconds === 0- ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>+ ? <span className="text-xs text-tx-muted flex-shrink-0">{t('workouts.detail.noRest')}</span>: <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>)}</div>diff --git a/web/src/pages/Programs.tsx b/web/src/pages/Programs.tsxindex 473c1fc..552e6d8 100644--- a/web/src/pages/Programs.tsx+++ b/web/src/pages/Programs.tsx@@ -1,6 +1,5 @@import { useState, useEffect, useRef } from 'react'import { createPortal } from 'react-dom'-import { format } from 'date-fns'import { BookOpen, Plus, Dumbbell, Edit2, Trash2, Search, Play, ChevronRight, MoreVertical, Moon, Sun } from 'lucide-react'import { useNavigate } from 'react-router-dom'import Loading from '../components/Loading'@@ -9,7 +8,7 @@ import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { ErrorState, ListError } from '../components/ui'import { programAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'-import { useAsyncAction, types } from '@lyftr/shared'+import { useAsyncAction, types, formatDate, useTranslation } from '@lyftr/shared'import {todaysDay, dayLabel, isDayStartable, programExerciseCount, programSetCount, sessionNameForDay,@@ -25,6 +24,7 @@ function ProgramCard({onEdit: (id: number) => voidonDelete: (id: number) => void}) {+ const { t } = useTranslation()const navigate = useNavigate()const { session, startSession } = useWorkoutSession()const [menuOpen, setMenuOpen] = useState(false)@@ -64,7 +64,7 @@ function ProgramCard({const remove = useAsyncAction(async () => {await programAPI.delete(program.id)onDelete(program.id)- }, 'Failed to delete program')+ }, t('programs.deleteFailed'))if (confirming) {return (@@ -75,8 +75,8 @@ function ProgramCard({<Trash2 className="w-4 h-4 text-error-400" /></div><div>- <p className="text-sm font-semibold text-tx-primary">Delete "{program.name}"?</p>- <p className="text-xs text-tx-muted">This cannot be undone</p>+ <p className="text-sm font-semibold text-tx-primary">{t('programs.card.deleteTitle', { name: program.name })}</p>+ <p className="text-xs text-tx-muted">{t('programs.card.cannotUndo')}</p>{remove.error && <p className="text-xs text-error-400 mt-1">{remove.error}</p>}</div></div>@@ -85,7 +85,7 @@ function ProgramCard({onClick={() => setConfirming(false)}className="px-3 py-1.5 text-xs bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-lg transition-colors font-medium">- Cancel+ {t('common.cancel')}</button><buttononClick={() => { void remove.run() }}@@ -93,7 +93,7 @@ function ProgramCard({className="px-3 py-1.5 text-xs bg-error-500 hover:bg-error-600 disabled:opacity-50 text-white rounded-lg transition-colors font-medium flex items-center gap-1"><Trash2 className="w-3 h-3" />- {remove.busy ? 'Deleting…' : 'Delete'}+ {remove.busy ? t('common.deleting') : t('common.delete')}</button></div></div>@@ -127,20 +127,20 @@ function ProgramCard({)}<div className="min-w-0 flex-1"><p className="text-sm font-semibold text-tx-primary truncate">{program.name}</p>- <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{format(new Date(program.created_at), 'MMM d, yyyy')}</p>+ <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{formatDate(new Date(program.created_at), 'monthDayYear')}</p><div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">- <span className="text-xs text-tx-muted whitespace-nowrap">{totalExercises} exercise{totalExercises === 1 ? '' : 's'}</span>+ <span className="text-xs text-tx-muted whitespace-nowrap">{t('programs.count.exercises', { count: totalExercises })}</span><span className="text-tx-muted/40 text-xs">·</span>- <span className="text-xs text-tx-muted whitespace-nowrap">{totalSets} set{totalSets === 1 ? '' : 's'}</span>+ <span className="text-xs text-tx-muted whitespace-nowrap">{t('programs.count.sets', { count: totalSets })}</span>{dayCount > 1 && today && (<><span className="text-tx-muted/40 text-xs">·</span>{today.is_rest_day ? (- <span className="text-xs text-tx-muted whitespace-nowrap flex items-center gap-1"><Moon className="w-3 h-3" />Rest today</span>+ <span className="text-xs text-tx-muted whitespace-nowrap flex items-center gap-1"><Moon className="w-3 h-3" />{t('programs.card.restToday')}</span>) : (// Sun, not Dumbbell — Dumbbell already means "exercises" earlier on// this same row; Sun/Moon reads as a natural due/rest pair instead.- <span className="text-xs text-brand-400 font-medium whitespace-nowrap flex items-center gap-1"><Sun className="w-3 h-3" />Today: {dayLabel(today, today.order_index)}</span>+ <span className="text-xs text-brand-400 font-medium whitespace-nowrap flex items-center gap-1"><Sun className="w-3 h-3" />{t('programs.card.today', { day: dayLabel(today, today.order_index) })}</span>)}</>)}@@ -155,7 +155,7 @@ function ProgramCard({<buttononClick={e => { e.stopPropagation(); setMenuOpen(o => !o) }}className={`sm:hidden p-2 rounded-lg transition-colors ${menuOpen ? 'bg-surface-muted' : 'hover:bg-surface-muted'}`}- aria-label="Options"+ aria-label={t('programs.card.options')}><MoreVertical className="w-4 h-4 text-tx-muted" /></button>@@ -169,7 +169,7 @@ function ProgramCard({/><div ref={portalRef} className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 bg-surface-overlay border border-surface-border/60 rounded-2xl shadow-2xl z-50 overflow-hidden"><div className="px-4 pt-4 pb-3">- <p className="text-[10px] font-semibold text-tx-muted uppercase tracking-wider text-center">Program</p>+ <p className="text-[10px] font-semibold text-tx-muted uppercase tracking-wider text-center">{t('programs.card.menuHeading')}</p><p className="text-sm font-semibold text-tx-primary text-center mt-0.5 truncate">{program.name}</p></div><div className="border-t border-surface-border/40 py-1.5">@@ -180,7 +180,7 @@ function ProgramCard({<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0"><Play className="w-4 h-4 text-brand-500" /></div>- {canQuickStart ? 'Start Workout' : 'View Program'}+ {canQuickStart ? t('programs.startWorkout') : t('programs.card.viewProgram')}</button><div className="mx-4 border-t border-surface-border/30" /><button@@ -190,7 +190,7 @@ function ProgramCard({<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0"><Edit2 className="w-4 h-4 text-brand-500" /></div>- Edit Program+ {t('programs.card.editProgram')}</button><div className="mx-4 border-t border-surface-border/30" /><button@@ -200,7 +200,7 @@ function ProgramCard({<div className="w-8 h-8 rounded-xl bg-error-500/10 flex items-center justify-center flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></div>- Delete Program+ {t('programs.card.deleteProgram')}</button></div><div className="border-t border-surface-border/40 p-3">@@ -208,7 +208,7 @@ function ProgramCard({onClick={e => { e.stopPropagation(); setMenuOpen(false) }}className="w-full py-2.5 text-sm font-semibold text-tx-muted bg-surface-muted/60 hover:bg-surface-muted rounded-xl transition-colors">- Cancel+ {t('common.cancel')}</button></div></div>@@ -219,14 +219,14 @@ function ProgramCard({{/* Desktop hover icons */}<div className="hidden sm:flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity"><button onClick={handleStart}- className="p-2 hover:bg-brand-500/10 rounded-lg transition-colors" title={canQuickStart ? 'Start workout' : 'Rest day today — open program'}>+ className="p-2 hover:bg-brand-500/10 rounded-lg transition-colors" title={canQuickStart ? t('programs.card.startTitle') : t('programs.card.restDayTitle')}><Play className="w-4 h-4 text-brand-500" /></button>- <button aria-label={`Edit ${program.name}`} onClick={e => { e.stopPropagation(); onEdit(program.id) }}+ <button aria-label={t('programs.card.editNamed', { name: program.name })} onClick={e => { e.stopPropagation(); onEdit(program.id) }}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><Edit2 className="w-4 h-4 text-brand-500" /></button>- <button aria-label="Delete" onClick={e => { e.stopPropagation(); setConfirming(true) }}+ <button aria-label={t('common.delete')} onClick={e => { e.stopPropagation(); setConfirming(true) }}className="p-2 hover:bg-error-500/10 rounded-lg transition-colors"><Trash2 className="w-4 h-4 text-error-400" /></button>@@ -238,6 +238,7 @@ function ProgramCard({}export default function Programs() {+ const { t } = useTranslation()const navigate = useNavigate()const [search, setSearch] = useState('')const [debouncedSearch, setDebouncedSearch] = useState('')@@ -266,10 +267,10 @@ export default function Programs() {if (listError && programs.length === 0) {return (<div className="space-y-5 animate-slide-up">- <PageHeader title="Programs" subtitle="Reusable workout templates" />+ <PageHeader title={t('programs.title')} subtitle={t('programs.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your programs"+ title={t('programs.list.loadFailed')}message={listError}onRetry={retryList}/>@@ -296,19 +297,19 @@ export default function Programs() {return (<div className="space-y-5 animate-slide-up"><PageHeader- title="Programs"- subtitle="Reusable workout templates"+ title={t('programs.title')}+ subtitle={t('programs.subtitle')}action={<button onClick={() => navigate('/programs/new')} className="btn-primary btn-sm">- <Plus className="w-4 h-4" /> New Program+ <Plus className="w-4 h-4" /> {t('programs.newProgram')}</button>}/><div className="grid grid-cols-2 gap-3">{[- { label: 'Total', value: totalLabel, unit: 'programs', icon: BookOpen },- { label: 'Avg Exercises', value: avgLabel, unit: 'per program', icon: Dumbbell },+ { label: t('programs.stats.total'), value: totalLabel, unit: t('programs.stats.totalUnit'), icon: BookOpen },+ { label: t('programs.stats.avgExercises'), value: avgLabel, unit: t('programs.stats.perProgram'), icon: Dumbbell },].map(s => (<div key={s.label} className="card p-4"><div className="flex items-center gap-1.5 mb-2">@@ -328,7 +329,7 @@ export default function Programs() {value={search}onChange={e => setSearch(e.target.value)}className="input pl-10"- placeholder="Search programs…"+ placeholder={t('programs.list.searchPlaceholder')}/></div>@@ -340,8 +341,8 @@ export default function Programs() {<div className="w-12 h-12 rounded-xl bg-surface-muted border border-surface-border flex items-center justify-center mb-4"><BookOpen className="w-6 h-6 text-tx-muted" /></div>- <p className="text-sm font-medium text-tx-primary mb-1">No programs found</p>- <p className="text-xs text-tx-muted">{search ? 'Try a different search' : 'Create a program to get started'}</p>+ <p className="text-sm font-medium text-tx-primary mb-1">{t('programs.list.empty.title')}</p>+ <p className="text-xs text-tx-muted">{search ? t('programs.list.empty.searchHint') : t('programs.list.empty.startHint')}</p></div>) : (<>@@ -354,9 +355,9 @@ export default function Programs() {/>))}<div ref={sentinelRef} />- {listError && <ListError subject="your programs" message={listError} onRetry={retryList} />}+ {listError && <ListError subject={t('programs.list.errorSubject')} message={listError} onRetry={retryList} />}{hasMore && loading && (- <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>+ <p className="text-center text-xs text-tx-muted py-2">{t('programs.list.loadingMore')}</p>)}</>)}diff --git a/web/src/pages/Register.tsx b/web/src/pages/Register.tsxindex 59adce0..7ccfc30 100644--- a/web/src/pages/Register.tsx+++ b/web/src/pages/Register.tsx@@ -2,14 +2,17 @@ import { useState } from 'react'import { useNavigate, Link } from 'react-router-dom'import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus, Lock } from 'lucide-react'import { useAuthStore } from '../stores/auth'-import { apiErrorMessage } from '../services/api'import { useServerInfo } from '../hooks/useServerInfo'-import { formatVersion, registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules } from '@lyftr/shared'+import {+ formatVersion, registrationOpen, lengthRuleLabel, matchRuleLabel, newPasswordRules,+ uiMessage, useTranslation, type UiMessage,+} from '@lyftr/shared'import Logo from '../components/Logo'import ServerSettings from '../components/ServerSettings'import PasswordField, { Rule } from '../components/ui/PasswordField'export default function Register() {+ const { t } = useTranslation()const navigate = useNavigate()const { register } = useAuthStore()const serverInfo = useServerInfo()@@ -18,14 +21,14 @@ export default function Register() {const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [passwordConfirm, setPasswordConfirm] = useState('')- const [error, setError] = useState('')+ const [error, setError] = useState<UiMessage | null>(null)const [isLoading, setLoading] = useState(false)const rules = newPasswordRules({ password, confirm: passwordConfirm })const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()- setError('')+ setError(null)// The rules render under the fields as they type and the button is disabled until// they pass, so this is a backstop. The banner below is now server failures only.if (!rules.ready) return@@ -34,7 +37,7 @@ export default function Register() {await register(email, password)navigate('/')} catch (err: any) {- setError(apiErrorMessage(err, 'Registration failed.'))+ setError({ key: 'auth.register.failed', cause: err })} finally {setLoading(false)}@@ -64,27 +67,27 @@ export default function Register() {{/* Headline and features */}<div className="relative space-y-8"><h1 className="font-display font-bold text-5xl leading-tight tracking-tight">- Log. Lift.+ {t('auth.hero.headline')}<br /><span className="bg-gradient-to-r from-brand-500 to-violet-500 bg-clip-text text-transparent">- Progress.+ {t('auth.hero.headlineAccent')}</span></h1><p className="text-tx-secondary text-base leading-relaxed max-w-sm">- Your self-hosted fitness tracker. Track workouts, log food, monitor weight — all under your control, running on your own server.+ {t('auth.hero.description')}</p>{/* Features */}<div className="space-y-4">- {[- { icon: Dumbbell, label: 'Track workouts' },- { icon: Apple, label: 'Log food + macros' },- { icon: TrendingUp, label: 'See progress' },- ].map(({ icon: Icon, label }) => (+ {([+ { icon: Dumbbell, label: 'auth.hero.features.workouts' },+ { icon: Apple, label: 'auth.hero.features.food' },+ { icon: TrendingUp, label: 'auth.hero.features.progress' },+ ] as const).map(({ icon: Icon, label }) => (<div key={label} className="flex items-center gap-3 text-tx-muted text-sm"><Icon className="w-4 h-4 text-brand-500" strokeWidth={2} />- {label}+ {t(label)}</div>))}</div>@@ -107,12 +110,12 @@ export default function Register() {{/* Heading */}<div className="mb-8"><h2 className="font-display font-bold text-3xl text-tx-primary tracking-tight">- {isOpen ? 'Create account' : 'Registration closed'}+ {isOpen ? t('auth.register.heading') : t('auth.register.closedHeading')}</h2><p className="text-tx-muted text-sm mt-2">{isOpen- ? 'Start tracking your fitness today.'- : 'This server is not accepting new accounts.'}+ ? t('auth.register.subtitle')+ : t('auth.closed.notice')}</p></div>@@ -127,12 +130,11 @@ export default function Register() {<div className="flex gap-3 rounded-xl border border-surface-border bg-surface-raised p-4"><Lock className="w-4 h-4 mt-0.5 flex-shrink-0 text-tx-muted" /><p className="text-sm text-tx-secondary leading-relaxed">- The owner of this Lyftr instance has turned off new signups. If you should- have an account here, ask them to create one for you.+ {t('auth.register.closedBody')}</p></div><Link to="/login" className="btn-primary btn-lg w-full flex items-center justify-center gap-2">- Back to sign in+ {t('auth.register.backToSignIn')}</Link></div>) : (@@ -141,14 +143,14 @@ export default function Register() {<form onSubmit={handleSubmit} className="space-y-4">{/* Email */}<div>- <label htmlFor="email" className="label">Email</label>+ <label htmlFor="email" className="label">{t('auth.field.email')}</label><inputid="email"type="email"value={email}onChange={e => setEmail(e.target.value)}className="input mt-2"- placeholder="[email protected]"+ placeholder={t('auth.field.emailPlaceholder')}autoComplete="email"required/>@@ -157,7 +159,7 @@ export default function Register() {{/* Password */}<PasswordFieldid="password"- label="Password"+ label={t('auth.field.password')}value={password}onChange={setPassword}autoComplete="new-password"@@ -169,7 +171,7 @@ export default function Register() {{/* Confirm password */}<PasswordFieldid="password-confirm"- label="Confirm password"+ label={t('auth.field.confirmPassword')}value={passwordConfirm}onChange={setPasswordConfirm}autoComplete="new-password"@@ -182,7 +184,7 @@ export default function Register() {{error && (<div className="alert-error"><AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />- <span>{error}</span>+ <span>{uiMessage(error)}</span></div>)}@@ -193,18 +195,18 @@ export default function Register() {className="btn-primary btn-lg w-full mt-6 flex items-center justify-center gap-2"><UserPlus className="w-4 h-4" />- {isLoading ? 'Creating account…' : 'Create account'}+ {isLoading ? t('auth.register.submitting') : t('auth.register.submit')}</button></form>{/* Sign in link */}<p className="mt-8 text-center text-sm text-tx-muted">- Already have an account?{' '}+ {t('auth.register.haveAccount')}{' '}<Linkto="/login"className="text-brand-400 font-medium hover:text-brand-300 transition-colors">- Sign in+ {t('auth.register.signInLink')}</Link></p></>diff --git a/web/src/pages/Settings.test.tsx b/web/src/pages/Settings.test.tsxindex fa6c4c2..9c797a2 100644--- a/web/src/pages/Settings.test.tsx+++ b/web/src/pages/Settings.test.tsx@@ -1,7 +1,9 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'import Settings from './Settings'+import { i18n } from '@lyftr/shared'+import { useLanguageStore } from '../lib/lyftr'// What these pin is the shape of the WRITES this page makes, which is where #170 went// wrong twice. The name began life inside `formData`, and the only button that commits@@ -138,3 +140,60 @@ describe('the Name row', () => {expect(document.getElementById(described!)?.textContent).toMatch(/use your email/)})})++describe('the exercise library banner', () => {+ afterEach(async () => { await i18n.changeLanguage('en') })++ // The banner is state that outlives the click that raised it. It keeps the key and the+ // failure, not the sentence, so a language switch while it is showing re-words it.+ it('re-renders a visible failure in the new language without a reload (es)', async () => {+ const { exerciseAPI } = await import('../services/api')+ vi.mocked(exerciseAPI.refreshCache).mockRejectedValue({ response: { status: 400, data: { error: '' } } })+ renderPage()++ fireEvent.click(await screen.findByRole('button', { name: 'Refresh cached' }))+ await waitFor(() => expect(screen.getByText("Couldn't refresh the cache.")).toBeTruthy())++ await act(async () => { await i18n.changeLanguage('es') })+ expect(screen.getByText('No se pudo actualizar la caché.')).toBeTruthy()+ expect(screen.queryByText("Couldn't refresh the cache.")).toBeNull()+ })+})++describe('language', () => {+ afterEach(async () => {+ await i18n.changeLanguage('en')+ useLanguageStore.setState({ preference: 'system' })+ localStorage.clear()+ })++ const picker = () => screen.getByRole('combobox', { name: /Language|Idioma/ }) as HTMLSelectElement++ it('lists System first, then languages by their own names', async () => {+ renderPage()+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())+ const options = Array.from(picker().options)+ expect(options.map(o => o.value)).toEqual(['system', 'en', 'es'])+ expect(options[0].textContent).toBe('System (English)')+ expect(options[1].textContent).toBe('English')+ expect(options[1].getAttribute('translate')).toBe('no')+ expect(options[2].getAttribute('lang')).toBe('es')+ expect(options[2].getAttribute('translate')).toBe('no')+ // The name stays short so the selected value never clips; the marker is said below.+ expect(options[2].textContent).toBe('Español')+ })++ it('switches the whole page live and remembers the choice', async () => {+ renderPage()+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())++ fireEvent.change(picker(), { target: { value: 'es' } })+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Ajustes' })).toBeTruthy())+ expect(localStorage.getItem('lyftr_language')).toBe('es')+ expect(picker().value).toBe('es')+ expect(picker().getAttribute('aria-label')).toBe('Idioma')++ fireEvent.change(picker(), { target: { value: 'system' } })+ await waitFor(() => expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy())+ })+})diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex ae8085f..40d3645 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -1,5 +1,10 @@import { useState, useEffect, useCallback } from 'react'-import { apiErrorMessage, useAsyncAction, memberSince, displayName, MAX_DISPLAY_NAME_LEN } from '@lyftr/shared'+import {+ uiMessage, useAsyncAction, memberSince, displayName, MAX_DISPLAY_NAME_LEN,+ useTranslation, LANGUAGE_ORDER, LANGUAGE_NAMES, languageChoiceLabel,+ type LanguagePreference, type UiMessage,+} from '@lyftr/shared'+import { useLanguageStore } from '../lib/lyftr'import { useAuthStore } from '../stores/auth'import { useServerStore } from '../stores/server'import { useServerInfo } from '../hooks/useServerInfo'@@ -13,9 +18,13 @@ import ServerSettings from '../components/ServerSettings'import { Link } from 'react-router-dom'import {Moon, Sun, LogOut, Trash2, Check, AlertCircle, Loader,- RefreshCw, Pencil, Clock, Minus, Plus, KeyRound, Mail,+ RefreshCw, Pencil, Clock, Minus, Plus, KeyRound, Mail, Languages,} from 'lucide-react'+// The two-way switches below are keyed by their value; the label is translated where it is drawn.+const LAYOUT_MODES = ['list', 'gym'] as const+const WEIGHT_UNITS = ['lbs', 'kg'] as const+// Wraps per row, on content rather than on viewport width.//// Originally this was side-by-side at every width with `flex-shrink-0` on the value.@@ -66,14 +75,19 @@ function Section({ title, children }: { title: string; children: React.ReactNode}export default function Settings() {+ const { t } = useTranslation()const { user, logout } = useAuthStore()+ const languagePreference = useLanguageStore(s => s.preference)+ const setLanguagePreference = useLanguageStore(s => s.setPreference)const serverUrl = useServerStore(s => s.serverUrl)const serverInfo = useServerInfo()const { theme, toggleTheme } = useTheme()const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout, setRestEnabled, setRestSeconds } = useSettingsStore()const settingsLoadFailed = useSettingsStore(s => s.loadFailed)const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)- const [error, setError] = useState<string | null>(null)+ // Failures are kept as a UiMessage (a key and the failure that caused it), not as a+ // sentence, so a banner already on screen follows a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)const [success, setSuccess] = useState(false)const [showCustomRest, setShowCustomRest] = useState(false)const [confirmDelete, setConfirmDelete] = useState(false)@@ -81,14 +95,14 @@ export default function Settings() {// toggle sits ~800px down a long settings page. Measured in a browser — the toggle// flicked back to lbs while the explanation was off-screen above, which is the// "say it where the tap was" failure this whole branch exists to stop.- const [unitError, setUnitError] = useState<string | null>(null)+ const [unitError, setUnitError] = useState<UiMessage | null>(null)const [cacheStatus, setCacheStatus] = useState<{ count: number } | null>(null)const [seedAction, setSeedAction] = useState<'refresh' | 'clear' | null>(null)// Carries whether it FAILED, not just what it said. Both outcomes used to land in// one muted grey line, so "Refreshed 812 exercises" and "Can't reach the server// right now." were the same small grey text — a failure that does not read as one.- const [seedMsg, setSeedMsg] = useState<{ text: string; failed: boolean } | null>(null)+ const [seedMsg, setSeedMsg] = useState<{ message: UiMessage; failed: boolean } | null>(null)// Deliberately NOT in formData: the only button that commits formData is labelled// "Save targets", lives in Goals & Units ~900px below, and is removed entirely when@@ -129,7 +143,7 @@ export default function Settings() {fat_target: s.fat_target,})} catch (err: any) {- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })} finally {setLoading(false)}@@ -148,10 +162,10 @@ export default function Settings() {setSeedMsg(null)try {const res = await exerciseAPI.refreshCache()- setSeedMsg({ text: `Refreshed ${res.refreshed.toLocaleString()} exercise${res.refreshed === 1 ? '' : 's'}`, failed: false })+ setSeedMsg({ message: { key: 'settings.library.refreshed', params: { count: res.refreshed, amount: res.refreshed.toLocaleString() } }, failed: false })loadCacheStatus()} catch (err: any) {- setSeedMsg({ text: apiErrorMessage(err, "Couldn't refresh the cache."), failed: true })+ setSeedMsg({ message: { key: 'settings.library.refreshFailed', cause: err }, failed: true })} finally {setSeedAction(null)}@@ -162,10 +176,10 @@ export default function Settings() {setSeedMsg(null)try {const res = await exerciseAPI.clearCacheOnServer()- setSeedMsg({ text: `Cleared ${res.cleared.toLocaleString()} unused exercises`, failed: false })+ setSeedMsg({ message: { key: 'settings.library.cleared', params: { count: res.cleared, amount: res.cleared.toLocaleString() } }, failed: false })loadCacheStatus()} catch (err) {- setSeedMsg({ text: apiErrorMessage(err, "Couldn't clear the cache."), failed: true })+ setSeedMsg({ message: { key: 'settings.library.clearFailed', cause: err }, failed: true })} finally {setSeedAction(null)}@@ -185,7 +199,7 @@ export default function Settings() {await updateSettings({ weight_unit: unit })} catch (err) {setFormData(prev => ({ ...prev, weight_unit: previous }))- setUnitError(apiErrorMessage(err, "Couldn't change the weight unit."))+ setUnitError({ key: 'settings.targets.weightUnit.changeFailed', cause: err })}}@@ -195,7 +209,7 @@ export default function Settings() {await updateSettings(formData)setSuccess(true)setTimeout(() => setSuccess(false), 3000)- }, 'Failed to save settings')+ }, t('settings.targets.saveFailedFallback'))// Mobile has had this since it shipped; web rendered the button and wired nothing to// it, so "Delete account" was a control that did nothing at all — worse than absent,@@ -206,7 +220,7 @@ export default function Settings() {const deleteAccount = useAsyncAction(async () => {await userAPI.deleteAccount()await logout()- }, 'Could not delete account')+ }, t('settings.deleteAccount.failed'))// Its own commit, like handleUnitChange above and unlike the targets block: one// scoped patch, trimmed at the call site the way mobile's screen does it, and the@@ -217,7 +231,7 @@ export default function Settings() {const display_name = name.trim()await updateSettings({ display_name })setName(display_name)- }, "Couldn't save your name.")+ }, t('settings.account.name.saveFailed'))const handleSaveName = () => { void saveName.run() }@@ -238,33 +252,33 @@ export default function Settings() {return (<div className="space-y-5 animate-slide-up max-w-2xl">- <PageHeader title="Settings" subtitle="Preferences and account configuration" />+ <PageHeader title={t('settings.title')} subtitle={t('settings.subtitle')} />{(error || save.error) && (<div className="alert-error"><AlertCircle className="w-5 h-5 flex-shrink-0" />- <span>{error || save.error}</span>+ <span>{error ? uiMessage(error) : save.error}</span></div>)}{success && (<div className="alert-success"><Check className="w-5 h-5 flex-shrink-0" />- <span>Settings saved successfully</span>+ <span>{t('settings.saved')}</span></div>)}{/* Account */}- <Section title="Account">+ <Section title={t('settings.account.title')}>{/* aria-label because SettingRow's label is a <p>, not a <label>, so the rowtext names nothing — the same reason the custom-rest input carries one.autoComplete is "nickname", not "name": this is a chosen label, and "name"invites the browser to fill in a legal name. */}<SettingRow- label="Name"+ label={t('settings.account.name.label')}description={settingsLoadFailed- ? "Couldn't load your name, so we won't offer to overwrite it."- : saveName.error || "The name the app greets you by. Leave it empty and we'll use your email instead."}+ ? t('settings.account.name.loadFailed')+ : saveName.error || t('settings.account.name.description')}descriptionTone={settingsLoadFailed || saveName.error ? 'error' : undefined}descriptionId="name-help">@@ -274,7 +288,7 @@ export default function Settings() {<div className="flex items-center gap-2"><inputtype="text"- aria-label="Name"+ aria-label={t('settings.account.name.label')}aria-describedby="name-help"value={name}onChange={e => { setName(e.target.value); saveName.reset() }}@@ -292,47 +306,64 @@ export default function Settings() {"Saving…" state with it. */}{(nameDirty || saveName.busy) && (<button onClick={handleSaveName} disabled={saveName.busy} className="btn-secondary btn-sm flex-shrink-0">- {saveName.busy ? 'Saving…' : 'Save'}+ {saveName.busy ? t('settings.account.name.saving') : t('settings.account.name.save')}</button>)}</div>)}</SettingRow>- <SettingRow label="Email" description="Your login email address">+ <SettingRow label={t('settings.account.email.label')} description={t('settings.account.email.description')}><div className="flex flex-wrap items-center justify-end gap-2"><span className="text-sm text-tx-muted font-mono break-all">{user?.email}</span>- <Link to="/settings/email" aria-label="Change email" className="btn-secondary btn-sm">- <Mail className="w-3.5 h-3.5" /> Change+ <Link to="/settings/email" aria-label={t('settings.account.email.changeLabel')} className="btn-secondary btn-sm">+ <Mail className="w-3.5 h-3.5" /> {t('settings.account.email.change')}</Link></div></SettingRow>- <SettingRow label="Member since">+ <SettingRow label={t('settings.account.memberSince.label')}><span className="text-sm text-tx-muted">{memberSince(user?.created_at)}</span></SettingRow>- <SettingRow label="Password" description="Changing it signs you out on your other devices">+ <SettingRow label={t('settings.account.password.label')} description={t('settings.account.password.description')}><Link to="/settings/password" className="btn-secondary btn-sm">- <KeyRound className="w-3.5 h-3.5" /> Change+ <KeyRound className="w-3.5 h-3.5" /> {t('settings.account.password.change')}</Link></SettingRow></Section>{/* Appearance */}- <Section title="Appearance">- <SettingRow label="Theme" description="Interface color scheme">+ <Section title={t('settings.appearance.title')}>+ <SettingRow label={t('settings.appearance.theme.label')} description={t('settings.appearance.theme.description')}><button onClick={toggleTheme} className="btn-secondary btn-sm">{theme === 'dark'- ? <><Moon className="w-3.5 h-3.5" /> Dark</>- : <><Sun className="w-3.5 h-3.5" /> Light</>+ ? <><Moon className="w-3.5 h-3.5" /> {t('settings.appearance.theme.dark')}</>+ : <><Sun className="w-3.5 h-3.5" /> {t('settings.appearance.theme.light')}</>}</button></SettingRow>+ <SettingRow label={t('settings.language.label')} description={t('settings.language.description')} descriptionId="language-help">+ <div className="flex items-center gap-2">+ <Languages className="w-4 h-4 text-tx-muted flex-shrink-0" aria-hidden />+ <select+ className="input w-auto py-2"+ aria-label={t('settings.language.label')}+ aria-describedby="language-help"+ value={languagePreference}+ onChange={e => { void setLanguagePreference(e.target.value as LanguagePreference) }}+ >+ <option value="system">{languageChoiceLabel('system')}</option>+ {LANGUAGE_ORDER.map(code => (+ <option key={code} value={code} lang={code} translate="no">{LANGUAGE_NAMES[code]}</option>+ ))}+ </select>+ </div>+ </SettingRow></Section>{/* Workout */}- <Section title="Workout">- <SettingRow label="Active workout layout" description="How exercises are shown during a workout">+ <Section title={t('settings.workout.title')}>+ <SettingRow label={t('settings.workout.layout.label')} description={t('settings.workout.layout.description')}><div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">- {(['list', 'gym'] as const).map(mode => (+ {LAYOUT_MODES.map(mode => (<buttonkey={mode}onClick={() => setWorkoutLayout(mode)}@@ -342,15 +373,15 @@ export default function Settings() {: 'text-tx-muted hover:text-tx-primary'}`}>- {mode === 'list' ? 'List' : 'Gym Mode'}+ {mode === 'list' ? t('settings.workout.layout.list') : t('settings.workout.layout.gym')}</button>))}</div></SettingRow>- <SettingRow label="Rest timer" description="Auto-start a countdown between sets in gym mode">+ <SettingRow label={t('settings.workout.restTimer.label')} description={t('settings.workout.restTimer.gymDescription')}><div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">- {([['Off', false], ['On', true]] as const).map(([label, val]) => (+ {([[t('settings.workout.restTimer.off'), false], [t('settings.workout.restTimer.on'), true]] as const).map(([label, val]) => (<buttonkey={label}onClick={() => setRestEnabled(val)}@@ -378,23 +409,23 @@ export default function Settings() {}`return (<div className={`py-4 transition-opacity ${enabled ? '' : 'opacity-40 pointer-events-none select-none'}`} aria-disabled={!enabled}>- <p className="text-sm font-medium text-tx-primary">Default rest</p>- <p className="text-xs text-tx-muted mt-0.5 mb-3">Seeds new exercises · per-exercise rest overrides it</p>+ <p className="text-sm font-medium text-tx-primary">{t('settings.workout.defaultRest.label')}</p>+ <p className="text-xs text-tx-muted mt-0.5 mb-3">{t('settings.workout.defaultRest.description')}</p><div className="flex rounded-xl border border-surface-border overflow-hidden divide-x divide-surface-border">{presets.map(sec => (<button key={sec} disabled={!enabled} onClick={() => { setShowCustomRest(false); setRestSeconds(sec) }} className={seg(!customActive && cur === sec)}><Clock className="w-3.5 h-3.5 flex-shrink-0" />- <span className="text-[11px] font-semibold leading-none">{sec}s</span>+ <span className="text-[11px] font-semibold leading-none">{t('settings.workout.defaultRest.preset', { seconds: sec })}</span></button>))}<button disabled={!enabled} onClick={() => setShowCustomRest(true)} className={seg(customActive)}><Pencil className="w-3.5 h-3.5 flex-shrink-0" />- <span className="text-[11px] font-semibold leading-none">{isCustom ? `${cur}s` : 'Custom'}</span>+ <span className="text-[11px] font-semibold leading-none">{isCustom ? t('settings.workout.defaultRest.preset', { seconds: cur }) : t('settings.workout.defaultRest.custom')}</span></button></div>{customActive && (<div className="flex items-center justify-center gap-2 mt-3">- <button type="button" disabled={!enabled} aria-label="−5 seconds" onClick={() => setRestSeconds(Math.max(0, cur - 5))}+ <button type="button" disabled={!enabled} aria-label={t('settings.workout.defaultRest.minusFive')} onClick={() => setRestSeconds(Math.max(0, cur - 5))}className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary"><Minus className="w-4 h-4" /></button>@@ -407,11 +438,11 @@ export default function Settings() {value={cur}onChange={e => setRestSeconds(Math.max(0, Math.min(3600, Number(e.target.value) || 0)))}className="input w-28 text-center py-2.5 pr-9 text-base font-semibold tabular-nums"- aria-label="Custom rest seconds"+ aria-label={t('settings.workout.defaultRest.customLabel')}/>- <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">sec</span>+ <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-tx-muted pointer-events-none">{t('settings.workout.defaultRest.secondsUnit')}</span></div>- <button type="button" disabled={!enabled} aria-label="+5 seconds" onClick={() => setRestSeconds(Math.min(3600, cur + 5))}+ <button type="button" disabled={!enabled} aria-label={t('settings.workout.defaultRest.plusFive')} onClick={() => setRestSeconds(Math.min(3600, cur + 5))}className="p-2.5 rounded-xl bg-surface-muted border border-surface-border text-tx-secondary active:scale-95 hover:text-tx-primary"><Plus className="w-4 h-4" /></button>@@ -434,23 +465,23 @@ export default function Settings() {defaults, so the inputs showed 2000/150/250/65 and Save PUT them over realtargets of 3175/205/310/88. Measured, not theorised. */}{settingsLoadFailed ? (- <Section title="Goals & Units">+ <Section title={t('settings.goalsUnits.title')}><ErrorStatesize="section"- title="Couldn't load your goals"- message="These are your saved targets and units, so we won't guess at them. Everything else on this page still works."+ title={t('settings.targets.loadFailedTitle')}+ message={t('settings.goalsUnits.loadFailedMessage')}onRetry={() => { void load() }}/></Section>) : (- <Section title="Goals & Units">+ <Section title={t('settings.goalsUnits.title')}><SettingRow- label="Weight unit"- description={unitError ?? 'Changes apply immediately across the app'}+ label={t('settings.targets.weightUnit.label')}+ description={unitError ? uiMessage(unitError) : t('settings.targets.weightUnit.description')}descriptionTone={unitError ? 'error' : undefined}><div className="flex gap-1 bg-surface-overlay rounded-lg p-1 border border-surface-border">- {(['lbs', 'kg'] as const).map(unit => (+ {WEIGHT_UNITS.map(unit => (<buttonkey={unit}onClick={() => handleUnitChange(unit)}@@ -466,7 +497,7 @@ export default function Settings() {</div></SettingRow>- <SettingRow label="Calorie target" description="Daily calorie goal">+ <SettingRow label={t('settings.targets.calorie.label')} description={t('settings.targets.calorie.description')}><div className="flex items-center gap-2"><inputtype="number"@@ -480,7 +511,7 @@ export default function Settings() {</div></SettingRow>- <SettingRow label="Protein target" description="Daily protein goal">+ <SettingRow label={t('settings.targets.protein.label')} description={t('settings.targets.protein.description')}><div className="flex items-center gap-2"><inputtype="number"@@ -492,7 +523,7 @@ export default function Settings() {</div></SettingRow>- <SettingRow label="Carb target" description="Daily carb goal">+ <SettingRow label={t('settings.targets.carb.label')} description={t('settings.targets.carb.description')}><div className="flex items-center gap-2"><inputtype="number"@@ -504,7 +535,7 @@ export default function Settings() {</div></SettingRow>- <SettingRow label="Fat target" description="Daily fat goal">+ <SettingRow label={t('settings.targets.fat.label')} description={t('settings.targets.fat.description')}><div className="flex items-center gap-2"><inputtype="number"@@ -517,24 +548,24 @@ export default function Settings() {</SettingRow><div className="py-3 flex items-center justify-between">- <p className="text-xs text-tx-muted">Save calorie and macro targets</p>+ <p className="text-xs text-tx-muted">{t('settings.targets.saveHint')}</p><buttononClick={handleSave}disabled={save.busy}className="btn-primary btn-sm">- <Check className="w-3.5 h-3.5" /> {save.busy ? 'Saving...' : 'Save targets'}+ <Check className="w-3.5 h-3.5" /> {save.busy ? t('settings.targets.saving') : t('settings.targets.save')}</button></div></Section>)}{/* Server info */}- <Section title="Self-Hosted Instance">- <SettingRow label="API server" description="Backend server this client is connected to">+ <Section title={t('settings.server.webTitle')}>+ <SettingRow label={t('settings.server.api.label')} description={t('settings.server.api.description')}><div className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-success-500 flex-shrink-0" />- <span className="text-xs font-mono text-tx-muted">{serverUrl || 'This site (reverse proxy)'}</span>+ <span className="text-xs font-mono text-tx-muted">{serverUrl || t('settings.server.api.default')}</span></div></SettingRow>{/* #17: same Server Settings editor as the sign-in screens, so a logged-in@@ -542,29 +573,31 @@ export default function Settings() {<div className="py-2"><ServerSettings /></div>- <SettingRow label="Database" description="Storage backend">+ <SettingRow label={t('settings.server.database.label')} description={t('settings.server.database.description')}><span className="badge-dim">SQLite</span></SettingRow>- <SettingRow label="Version" description="lyftr backend version">+ <SettingRow label={t('settings.server.version.label')} description={t('settings.server.version.description')}><span className="text-xs text-tx-muted font-mono">{serverInfo?.version || '—'}</span></SettingRow></Section>{/* Exercise Library */}- <Section title="Exercise Library">+ <Section title={t('settings.library.title')}><SettingRow- label="Exercise database"- description="Exercises come from open-exercise-db, queried as you search. This server keeps a copy of the ones it has shown."+ label={t('settings.library.database.label')}+ description={t('settings.library.database.description')}><span className="text-sm font-mono text-tx-muted">- {cacheStatus ? cacheStatus.count.toLocaleString() : '—'} cached+ {cacheStatus+ ? t('settings.library.cached', { count: cacheStatus.count, amount: cacheStatus.count.toLocaleString() })+ : t('settings.library.cachedUnknown')}</span></SettingRow>{seedMsg && (<div className="py-2 px-1"><p className={`text-xs ${seedMsg.failed ? 'text-[color:var(--alert-error)]' : 'text-tx-muted'}`}>- {seedMsg.text}+ {uiMessage(seedMsg.message)}</p></div>)}@@ -576,8 +609,8 @@ export default function Settings() {className="btn-secondary btn-sm">{seedAction === 'refresh'- ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Refreshing...</>- : <><RefreshCw className="w-3.5 h-3.5" /> Refresh cached</>+ ? <><Loader className="w-3.5 h-3.5 animate-spin" /> {t('settings.library.refreshing')}</>+ : <><RefreshCw className="w-3.5 h-3.5" /> {t('settings.library.refresh')}</>}</button><button@@ -586,23 +619,23 @@ export default function Settings() {className="btn-secondary btn-sm">{seedAction === 'clear'- ? <><Loader className="w-3.5 h-3.5 animate-spin" /> Clearing...</>- : <><Trash2 className="w-3.5 h-3.5" /> Clear unused</>+ ? <><Loader className="w-3.5 h-3.5 animate-spin" /> {t('settings.library.clearing')}</>+ : <><Trash2 className="w-3.5 h-3.5" /> {t('settings.library.clear')}</>}</button></div></Section>{/* Danger Zone */}- <Section title="Danger Zone">- <SettingRow label="Sign out" description="Log out of this device">+ <Section title={t('settings.danger.title')}>+ <SettingRow label={t('settings.signOut.label')} description={t('settings.signOut.description')}><button onClick={() => logout()} className="btn-secondary btn-sm">- <LogOut className="w-3.5 h-3.5" /> Sign out+ <LogOut className="w-3.5 h-3.5" /> {t('settings.signOut.button')}</button></SettingRow>- <SettingRow label="Delete account" description="Permanently delete all your data">+ <SettingRow label={t('settings.deleteAccount.label')} description={t('settings.deleteAccount.description')}><button onClick={() => setConfirmDelete(true)} className="btn-danger btn-sm">- <Trash2 className="w-3.5 h-3.5" /> Delete+ <Trash2 className="w-3.5 h-3.5" /> {t('settings.deleteAccount.button')}</button></SettingRow></Section>@@ -613,10 +646,10 @@ export default function Settings() {open={confirmDelete}icon={Trash2}destructive- title="Delete account?"- message="This permanently deletes your account and all of your data. This can't be undone."- confirmLabel="Delete account"- busyLabel="Deleting…"+ title={t('settings.deleteAccount.sheetTitle')}+ message={t('settings.deleteAccount.sheetMessage')}+ confirmLabel={t('settings.deleteAccount.confirm')}+ busyLabel={t('settings.deleteAccount.busy')}busy={deleteAccount.busy}error={deleteAccount.error ?? undefined}onConfirm={() => { void deleteAccount.run() }}diff --git a/web/src/pages/StartWorkout.tsx b/web/src/pages/StartWorkout.tsxindex a1a98d1..1fef122 100644--- a/web/src/pages/StartWorkout.tsx+++ b/web/src/pages/StartWorkout.tsx@@ -3,16 +3,16 @@ import { useNavigate } from 'react-router-dom'import { ArrowLeft, Zap, BookOpen, ChevronRight, Play, Timer, Trash2 } from 'lucide-react'import { useWorkoutSession } from '../stores/workoutSession'import ProgramPicker from '../components/ProgramPicker'-import { activeSessionExercisesForDay, sessionNameForDay, types } from '@lyftr/shared'+import { activeSessionExercisesForDay, sessionNameForDay, defaultWorkoutName, types, useTranslation } from '@lyftr/shared'export default function StartWorkout() {+ const { t } = useTranslation()const navigate = useNavigate()const { session, startSession, cancelSession } = useWorkoutSession()const [showProgramPicker, setShowProgramPicker] = useState(false)const startQuick = () => {- const name = `Workout — ${new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`- startSession(name, [])+ startSession(defaultWorkoutName(), [])navigate('/workout/active')}@@ -26,13 +26,13 @@ export default function StartWorkout() {<div className="space-y-6 animate-slide-up"><div className="flex items-center gap-3"><button- aria-label="Go back"+ aria-label={t('common.goBack')}onClick={() => navigate(-1)}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button>- <h1 className="font-display font-bold text-2xl text-tx-primary">Start Workout</h1>+ <h1 className="font-display font-bold text-2xl text-tx-primary">{t('workouts.start.title')}</h1></div>{/* Active session — resume or discard */}@@ -44,7 +44,7 @@ export default function StartWorkout() {</div><div><p className="text-sm font-bold text-tx-primary">{session.name}</p>- <p className="text-xs text-amber-400/80">Workout in progress</p>+ <p className="text-xs text-amber-400/80">{t('workouts.start.inProgress')}</p></div></div><div className="flex gap-2">@@ -52,13 +52,13 @@ export default function StartWorkout() {onClick={() => navigate('/workout/active')}className="flex-1 py-2.5 bg-brand-500 hover:bg-brand-600 text-white rounded-xl text-sm font-semibold transition-colors flex items-center justify-center gap-2">- <Play className="w-4 h-4" /> Resume+ <Play className="w-4 h-4" /> {t('workouts.start.resume')}</button><buttononClick={() => cancelSession()}className="flex-1 py-2.5 bg-surface-muted hover:bg-error-500/10 text-tx-secondary hover:text-error-400 rounded-xl text-sm font-semibold transition-colors flex items-center justify-center gap-2 border border-surface-border">- <Trash2 className="w-4 h-4" /> Discard+ <Trash2 className="w-4 h-4" /> {t('workouts.start.discard')}</button></div></div>@@ -73,8 +73,8 @@ export default function StartWorkout() {<Zap className="w-6 h-6 text-white" /></div><div className="text-left flex-1">- <p className="font-semibold text-tx-primary text-lg">Quick Start</p>- <p className="text-sm text-tx-muted mt-0.5">Start blank, add exercises as you go</p>+ <p className="font-semibold text-tx-primary text-lg">{t('workouts.start.quick')}</p>+ <p className="text-sm text-tx-muted mt-0.5">{t('workouts.start.quickHint')}</p></div><ChevronRight className="w-5 h-5 text-tx-muted opacity-0 group-hover:opacity-100 transition-opacity" /></button>@@ -88,8 +88,8 @@ export default function StartWorkout() {<BookOpen className="w-6 h-6 text-brand-500" /></div><div className="text-left flex-1">- <p className="font-semibold text-tx-primary text-lg">Start from Program</p>- <p className="text-sm text-tx-muted mt-0.5">Load a saved routine's day</p>+ <p className="font-semibold text-tx-primary text-lg">{t('workouts.start.fromProgram')}</p>+ <p className="text-sm text-tx-muted mt-0.5">{t('workouts.start.fromProgramHint')}</p></div><ChevronRight className="w-5 h-5 text-tx-muted opacity-0 group-hover:opacity-100 transition-opacity" /></button>diff --git a/web/src/pages/Weight.test.tsx b/web/src/pages/Weight.test.tsxindex c86a635..8df7bb9 100644--- a/web/src/pages/Weight.test.tsx+++ b/web/src/pages/Weight.test.tsx@@ -1,7 +1,8 @@-import { describe, it, expect, vi, beforeEach } from 'vitest'+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import { render, screen, waitFor, fireEvent } from '@testing-library/react'import { MemoryRouter } from 'react-router-dom'import Weight from './Weight'+import { i18n } from '@lyftr/shared'// Each figure on this screen comes from exactly one read: on "All" the server aggregate// from /weight/stats, on every other period the period-scoped trend list. The bug these@@ -41,6 +42,23 @@ beforeEach(() => {})})+afterEach(async () => { await i18n.changeLanguage('en') })++describe('Weight copy', () => {+ it('reads its copy from the catalog in Spanish', async () => {+ await i18n.changeLanguage('es')+ list.mockResolvedValue(HISTORY)+ renderPage()++ expect(await screen.findByRole('heading', { name: 'Registrar peso' })).toBeTruthy()+ expect(screen.getByRole('heading', { name: 'Tendencia' })).toBeTruthy()+ expect(screen.getByRole('heading', { name: 'Historial' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Todo' })).toBeTruthy()+ expect(screen.getByText('Mejor registrarlo por la mañana, después de ir al baño')).toBeTruthy()+ expect(screen.queryByText('Log Weight')).toBeNull()+ })+})+describe('Weight figures', () => {it('marks the tiles as failed when the read behind them died, instead of showing 0', async () => {list.mockImplementation((...args: unknown[]) =>diff --git a/web/src/pages/Weight.tsx b/web/src/pages/Weight.tsxindex 3a228bf..93e41c4 100644--- a/web/src/pages/Weight.tsx+++ b/web/src/pages/Weight.tsx@@ -1,6 +1,5 @@import { useState, useEffect, useMemo, useRef } from 'react'import { TrendingDown, TrendingUp, Minus, Plus, Calendar, Sunrise, AlertCircle, ChevronRight, Scale, Activity, ArrowDown, ArrowUp, X } from 'lucide-react'-import { format } from 'date-fns'import { Link } from 'react-router-dom'import { HelpTip } from '../components/Tooltip'import Loading from '../components/Loading'@@ -9,7 +8,7 @@ import DateInput from '../components/ui/DateInput'import PeriodSelector from '../components/PeriodSelector'import StepperTile from '../components/ui/StepperTile'import NumberField from '../components/ui/NumberField'-import { apiErrorMessage, useAsyncAction, BODYWEIGHT_STEP, clampStep, todayStr, daysAgoStr, dayToInstant, entryDay, dayToLocalDate, types, formatDay } from '@lyftr/shared'+import { uiMessage, useAsyncAction, BODYWEIGHT_STEP, clampStep, todayStr, daysAgoStr, dayToInstant, entryDay, dayToLocalDate, types, formatDay, formatDate, useTranslation, type UiMessage } from '@lyftr/shared'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { ErrorState, ListError, StatFailure } from '../components/ui'import { weightAPI } from '../services/api'@@ -51,6 +50,7 @@ function smoothPath(pts: [number, number][]): string {}function TrendChart({ points, wUnit }: { points: ChartPoint[]; wUnit: string }) {+ useTranslation()const [activeIdx, setActiveIdx] = useState<number | null>(null)const layout = useMemo(() => {@@ -123,7 +123,7 @@ function TrendChart({ points, wUnit }: { points: ChartPoint[]; wUnit: string })<p className="font-bold tabular-nums text-tx-primary text-sm">{round1(activePoint.weight)} <span className="font-normal text-tx-muted">{wUnit}</span></p>- <p className="text-tx-muted mt-0.5">{format(activePoint.date, 'MMM d, yyyy')}</p>+ <p className="text-tx-muted mt-0.5">{formatDate(activePoint.date, 'monthDayYear')}</p></div></div>)}@@ -187,10 +187,10 @@ function TrendChart({ points, wUnit }: { points: ChartPoint[]; wUnit: string }){/* Date range labels */}<text x={PL} y={H - 10} fontSize={12} fill="var(--color-tx-muted)" fillOpacity={0.6} textAnchor="start">- {format(points[0].date, 'MMM d')}+ {formatDate(points[0].date, 'monthDay')}</text><text x={W - PR} y={H - 10} fontSize={12} fill="var(--color-tx-muted)" fillOpacity={0.6} textAnchor="end">- {format(points[points.length - 1].date, 'MMM d')}+ {formatDate(points[points.length - 1].date, 'monthDay')}</text>{/* Hit area — only over chart region, not y-axis */}@@ -207,11 +207,14 @@ function TrendChart({ points, wUnit }: { points: ChartPoint[]; wUnit: string })}export default function Weight() {+ const { t } = useTranslation()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)const [period, setPeriod] = useState<Period>('30d')const [stats, setStats] = useState<types.WeightStats | null>(null)- const [error, setError] = useState<string | null>(null)+ // The value the weight box was rejected for, not the sentence: the sentence is made at+ // render, so a banner already on screen follows a language switch.+ const [badWeight, setBadWeight] = useState<number | null>(null)// Paginated history listconst {@@ -226,14 +229,14 @@ export default function Weight() {// Both of these used to swallow their failure. Nothing recorded it, so the aggregates// below fell back to 0 and the page rendered three measurements it had never received.- const [chartError, setChartError] = useState<string | null>(null)+ const [chartError, setChartError] = useState<UiMessage | null>(null)// Which window chartLogs answers, and whether the window now selected has been// answered at all. Keeping the series through a failure is right when the same// question was asked again; under a different period it is not stale data, it is// another window's answer wearing this window's label.const [chartPeriod, setChartPeriod] = useState<Period | null>(null)const [chartLoading, setChartLoading] = useState(true)- const [statsError, setStatsError] = useState<string | null>(null)+ const [statsError, setStatsError] = useState<UiMessage | null>(null)const [retryKey, setRetryKey] = useState(0)// `cancelled` is not tidiness, it is correctness. A wider window is a slower query, so@@ -255,7 +258,7 @@ export default function Weight() {setChartPeriod(period)setChartError(null)})- .catch(err => { if (!cancelled) setChartError(apiErrorMessage(err, "Couldn't load your weight trend.")) })+ .catch(err => { if (!cancelled) setChartError({ key: 'weight.errors.trendFailed', cause: err }) }).finally(() => { if (!cancelled) setChartLoading(false) })return () => { cancelled = true }}, [period, retryKey])@@ -264,7 +267,7 @@ export default function Weight() {let cancelled = falseweightAPI.stats().then(data => { if (!cancelled) { setStats(data); setStatsError(null) } })- .catch(err => { if (!cancelled) setStatsError(apiErrorMessage(err, "Couldn't load your weight stats.")) })+ .catch(err => { if (!cancelled) setStatsError({ key: 'weight.errors.statsFailed', cause: err }) })return () => { cancelled = true }}, [retryKey])@@ -323,7 +326,7 @@ export default function Weight() {const days = PERIOD_DAYS[period]const from = days != null ? daysAgoStr(days) : undefinedweightAPI.list({ limit: 1000, from }).then(data => setChartLogs(data || [])).catch(() => {})- }, 'Failed to log weight')+ }, t('weight.log.failed'))const handleLog = async (e: React.FormEvent) => {e.preventDefault()@@ -331,7 +334,7 @@ export default function Weight() {const w = parseFloat(newWeight)const wErr = weightError(w, settings.weight_unit)if (wErr) {- setError(wErr)+ setBadWeight(w)return}@@ -340,7 +343,7 @@ export default function Weight() {return}- setError(null)+ setBadWeight(null)setShowDuplicateWarning(false)void log.run(w)}@@ -379,6 +382,8 @@ export default function Weight() {// down is ONE problem, and four retry buttons for it are four ways to say "reload".const everythingFailed = chartError != null && statsError != null && listError != null&& items.length === 0 && periodValues.length === 0+ const error = badWeight == null ? null : weightError(badWeight, settings.weight_unit)+ const loadMessage = listError ?? (chartError ? uiMessage(chartError) : statsError ? uiMessage(statsError) : '')// Nothing to aggregate. Two different reasons, and they are not the same sentence:// an account with no entries yet reads "—", a section whose reads failed says so@@ -417,7 +422,7 @@ export default function Weight() {: change < 0? 'bg-success-500/10 border-success-500/20 text-success-400': 'bg-error-500/10 border-error-500/20 text-error-400'- const changeWord = change === 0 ? 'no change' : change < 0 ? 'lost' : 'gained'+ const changeKey = change === 0 ? 'weight.hero.changeNone' : change < 0 ? 'weight.hero.changeLost' : 'weight.hero.changeGained'// Title and subtitle stay, so the reader still knows where they are; the header's// action does not. On an error screen the primary action is the retry, and a@@ -425,11 +430,11 @@ export default function Weight() {if (everythingFailed) {return (<div className="space-y-5 animate-slide-up">- <PageHeader title="Weight" subtitle="Track your body weight over time" />+ <PageHeader title={t('weight.title')} subtitle={t('weight.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your weight"- message={listError ?? chartError ?? statsError ?? ''}+ title={t('weight.loadFailed')}+ message={loadMessage}onRetry={retryAll}/></div>@@ -439,8 +444,8 @@ export default function Weight() {return (<div className="space-y-5 animate-slide-up"><PageHeader- title="Weight"- subtitle="Track your body weight over time"+ title={t('weight.title')}+ subtitle={t('weight.subtitle')}action={<span className="badge-brand"><Calendar className="w-3 h-3" /> {wUnit}</span>}/>@@ -456,32 +461,32 @@ export default function Weight() {<div className="flex items-center justify-between mb-3"><div className="flex items-center gap-2"><Scale className="w-4 h-4 text-brand-500" />- <h2 className="section-title">Log Weight</h2>+ <h2 className="section-title">{t('weight.log.title')}</h2></div>{items.length > 0 && (- <span className="text-[11px] text-tx-muted">last: {displayWeight(items[0].weight, settings.weight_unit)} {wUnit}</span>+ <span className="text-[11px] text-tx-muted">{t('weight.log.last', { weight: displayWeight(items[0].weight, settings.weight_unit), unit: wUnit })}</span>)}</div><form ref={logFormRef} onSubmit={handleLog} className="space-y-3"><StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('weight.log.weightLabel', { unit: wUnit })}+ name={t('weight.log.weightName')}step={BODYWEIGHT_STEP}onStep={d => setNewWeight(String(clampStep(parseFloat(newWeight) || 0, d, { max: maxWeight(settings.weight_unit) })))}>- <NumberField value={newWeight} onChange={setNewWeight} aria-label="Weight" />+ <NumberField value={newWeight} onChange={setNewWeight} aria-label={t('weight.log.weightField')} /></StepperTile>{showNotes ? (<div className="space-y-2 bg-surface-overlay border border-surface-border rounded-xl p-3"><div className="flex items-center justify-between mb-1">- <span className="text-xs font-medium text-tx-secondary">Date & note</span>+ <span className="text-xs font-medium text-tx-secondary">{t('weight.log.dateAndNote')}</span><buttontype="button"onClick={() => setShowNotes(false)}className="p-1 hover:bg-surface-muted rounded-lg transition-colors"- aria-label="Collapse"+ aria-label={t('weight.log.collapse')}><X className="w-3.5 h-3.5 text-tx-muted" /></button>@@ -491,7 +496,7 @@ export default function Weight() {type="text"value={newNotes}onChange={e => setNewNotes(e.target.value)}- placeholder="Note — e.g. morning, post-run"+ placeholder={t('weight.log.notePlaceholder')}maxLength={200}className="input"/>@@ -503,7 +508,7 @@ export default function Weight() {className="w-full flex items-center justify-center gap-2 py-2.5 text-sm text-tx-secondary bg-surface-overlay border border-surface-border rounded-xl hover:bg-surface-muted active:scale-[0.98] transition-all"><Calendar className="w-4 h-4 text-tx-muted" />- Add date & note+ {t('weight.log.addDateAndNote')}</button>)}@@ -511,14 +516,14 @@ export default function Weight() {<div className="flex items-start gap-3 rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-400" role="alert"><AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" /><div className="flex-1 min-w-0">- <p className="font-medium">Already logged on {formatDay(entryDay(items[0]), 'MMM d')} ({displayWeight(items[0].weight, settings.weight_unit)} {wUnit}). Log again anyway?</p>+ <p className="font-medium">{t('weight.duplicateWarning', { date: formatDay(entryDay(items[0]), 'monthDay'), weight: displayWeight(items[0].weight, settings.weight_unit), unit: wUnit })}</p><div className="flex gap-2 mt-2"><buttontype="button"onClick={() => setShowDuplicateWarning(false)}className="px-3 py-1 rounded-lg text-xs font-medium bg-surface-overlay border border-surface-border text-tx-secondary hover:text-tx-primary transition-colors">- Cancel+ {t('common.cancel')}</button><buttontype="button"@@ -529,7 +534,7 @@ export default function Weight() {}}className="px-3 py-1 rounded-lg text-xs font-medium bg-amber-500/20 border border-amber-500/30 text-amber-300 hover:bg-amber-500/30 transition-colors">- Log Anyway+ {t('weight.log.logAnyway')}</button></div></div>@@ -541,11 +546,11 @@ export default function Weight() {disabled={!(parseFloat(newWeight) > 0) || log.busy}className="btn-primary btn-lg w-full">- <Plus className="w-4 h-4" /> {log.busy ? 'Logging…' : 'Log Weight'}+ <Plus className="w-4 h-4" /> {log.busy ? t('weight.log.submitting') : t('weight.log.submit')}</button><p className="input-help flex items-center justify-center gap-1.5 text-center"><Sunrise className="w-3.5 h-3.5 text-amber-400 flex-shrink-0" />- Best logged in the morning, after the bathroom+ {t('weight.log.tip')}</p></form></div>@@ -558,20 +563,20 @@ export default function Weight() {// weighed themselves, and invited them to fix it against a server that was down.<ErrorStatesize="section"- title="Couldn't load your weight"- message={listError ?? chartError ?? statsError ?? ''}+ title={t('weight.loadFailed')}+ message={loadMessage}onRetry={retryAll}/>) : items.length === 0 ? (<div className="text-center py-2">- <p className="stat-label mb-1">Current Weight</p>- <p className="text-tx-muted text-sm">The scale doesn't know you exist yet. Fix that.</p>+ <p className="stat-label mb-1">{t('weight.hero.current')}</p>+ <p className="text-tx-muted text-sm">{t('weight.hero.empty')}</p></div>) : (<><div className="flex items-start justify-between"><div>- <p className="stat-label mb-2">Current Weight</p>+ <p className="stat-label mb-2">{t('weight.hero.current')}</p><div className="flex items-end gap-2"><span className="stat-value text-5xl">{currentKnown ? current : '—'}</span>{currentKnown && <span className="text-tx-muted text-lg mb-1">{wUnit}</span>}@@ -584,7 +589,7 @@ export default function Weight() {</div>{changeKnown && (<p className="text-xs text-tx-muted mt-3">- {Math.abs(change)} {wUnit} {changeWord} over {period}+ {t(changeKey, { amount: Math.abs(change), unit: wUnit, period: t(`weight.period.span.${period}`) })}</p>)}</>@@ -594,20 +599,20 @@ export default function Weight() {{/* Stats row */}<div className="grid grid-cols-3 gap-3">{[- { label: 'Avg', value: avg, tip: 'Average weight for selected period', icon: Activity, color: 'text-brand-400' },- { label: 'Low', value: min, tip: 'Lowest recorded weight in period', icon: ArrowDown, color: 'text-success-400' },- { label: 'High', value: max, tip: 'Highest recorded weight in period', icon: ArrowUp, color: 'text-error-400' },+ { id: 'avg' as const, value: avg, icon: Activity, color: 'text-brand-400' },+ { id: 'low' as const, value: min, icon: ArrowDown, color: 'text-success-400' },+ { id: 'high' as const, value: max, icon: ArrowUp, color: 'text-error-400' },].map(s => (- <div key={s.label} className="card p-4">+ <div key={s.id} className="card p-4"><div className="flex items-center gap-1.5 mb-2"><s.icon className={`w-3.5 h-3.5 ${s.color}`} />- <span className="stat-label">{s.label}</span>- <HelpTip content={s.tip} />+ <span className="stat-label">{t(`weight.stats.${s.id}.label`)}</span>+ <HelpTip content={t(`weight.stats.${s.id}.tip`)} /></div>{chartPending ? (<span className="inline-block h-6 w-14 rounded bg-surface-muted animate-pulse align-middle" />) : figuresFailed ? (- <StatFailure label={`Couldn't load ${s.label.toLowerCase()} weight`} />+ <StatFailure label={t(`weight.stats.${s.id}.failed`)} />) : (<><span className="stat-value text-xl">{aggregatesUnknown ? '—' : Math.round(s.value)}</span>@@ -625,29 +630,29 @@ export default function Weight() {{figuresStale && (<div className="flex items-center gap-2 px-1 text-xs text-tx-muted" role="status"><AlertCircle className="w-3.5 h-3.5 flex-shrink-0 text-amber-400" />- <span>Couldn't refresh these — showing the last we loaded.</span>- <button onClick={retryAll} className="underline hover:text-tx-primary">Try again</button>+ <span>{t('weight.stale')}</span>+ <button onClick={retryAll} className="underline hover:text-tx-primary">{t('common.tryAgain')}</button></div>)}{/* Chart + period selector */}<div className="card p-5"><div className="flex items-center justify-between mb-4 gap-2">- <h2 className="section-title">Trend</h2>- <PeriodSelector options={PERIODS} value={period} onChange={setPeriod} />+ <h2 className="section-title">{t('weight.trend.title')}</h2>+ <PeriodSelector options={PERIODS} value={period} onChange={setPeriod} label={p => t(`weight.period.chip.${p}`)} /></div>{chartPending ? (- <div className="h-44 rounded-xl bg-surface-muted animate-pulse" role="status" aria-label="Loading your trend" />+ <div className="h-44 rounded-xl bg-surface-muted animate-pulse" role="status" aria-label={t('weight.trend.loading')} />) : chartPoints.length === 0 && chartError ? (- <ErrorState size="section" title="Couldn't load your trend" message={chartError} onRetry={retryAll} />+ <ErrorState size="section" title={t('weight.trend.loadFailed')} message={uiMessage(chartError)} onRetry={retryAll} />) : chartPoints.length === 0 ? (<div className="flex items-center justify-center h-44 text-tx-muted text-sm">- No data for this period+ {t('weight.trend.noData')}</div>) : chartPoints.length === 1 ? (<div className="flex items-center justify-center h-44 text-tx-muted text-sm">- Log another entry to see the trend+ {t('weight.trend.needMore')}</div>) : (<TrendChart points={chartPoints} wUnit={wUnit} />@@ -656,11 +661,11 @@ export default function Weight() {{/* History — the error sits outside the items guard on purpose: a failed firstpage leaves items empty, and the guard alone rendered nothing whatsoever. */}- {listError && <ListError subject="your weight history" message={listError} onRetry={retryList} />}+ {listError && <ListError subject={t('weight.history.subject')} message={listError} onRetry={retryList} />}{items.length > 0 && (<>- <h2 className="section-title px-1">History</h2>+ <h2 className="section-title px-1">{t('weight.history.title')}</h2><div className="space-y-2">{items.map((entry, i) => {const next = items[i + 1]@@ -681,7 +686,7 @@ export default function Weight() {{Math.round(displayW)} {wUnit}</p><p className="text-xs text-tx-muted mt-0.5">- {formatDay(entryDay(entry), 'MMM d, yyyy')}+ {formatDay(entryDay(entry), 'monthDayYear')}</p>{(deltaLbs !== 0 || entry.notes) && (<div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">@@ -705,7 +710,7 @@ export default function Weight() {</div><div ref={sentinelRef} />{hasMore && listLoading && (- <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>+ <p className="text-center text-xs text-tx-muted py-2">{t('weight.history.loadingMore')}</p>)}</>)}diff --git a/web/src/pages/WeightDetail.tsx b/web/src/pages/WeightDetail.tsxindex 06c78e5..ddecdaa 100644--- a/web/src/pages/WeightDetail.tsx+++ b/web/src/pages/WeightDetail.tsx@@ -5,12 +5,13 @@ import { ArrowLeft, Scale, Trash2, Edit2, Save, X, AlertCircle, Loader } from 'limport { weightAPI } from '../services/api'import { useSettingsStore, weightShort, displayWeight, weightError, maxWeight, resolveWeightLbs } from '../stores/settings'import { useEscapeKey } from '../hooks/useEscapeKey'-import { useAsyncAction, apiErrorMessage, isNotFound, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types, formatDay } from '@lyftr/shared'+import { useAsyncAction, uiMessage, isNotFound, todayStr, dayToInstant, entryDay, BODYWEIGHT_STEP, clampStep, types, formatDay, useTranslation, Trans, type UiMessage } from '@lyftr/shared'import { ErrorState } from '../components/ui'import StepperTile from '../components/ui/StepperTile'import NumberField from '../components/ui/NumberField'export default function WeightDetail() {+ const { t } = useTranslation()const { id } = useParams<{ id: string }>()const navigate = useNavigate()const { settings } = useSettingsStore()@@ -18,7 +19,7 @@ export default function WeightDetail() {const [log, setLog] = useState<types.WeightLog | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ const [error, setError] = useState<UiMessage | null>(null)const [gone, setGone] = useState(false)const [retryKey, setRetryKey] = useState(0)@@ -27,19 +28,20 @@ export default function WeightDetail() {const [editWeight, setEditWeight] = useState('')const [editDate, setEditDate] = useState('')const [editNotes, setEditNotes] = useState('')- const [editError, setEditError] = useState('')+ // The value the box was rejected for, not the sentence, so the banner follows a language switch.+ const [badWeight, setBadWeight] = useState<number | null>(null)// Delete confirmconst [confirming, setConfirming] = useState(false)- useEscapeKey(editing, () => { setEditing(false); setEditError('') })+ useEscapeKey(editing, () => { setEditing(false); setBadWeight(null) })useEffect(() => {weightAPI.get(Number(id)).then(setLog).catch(err => {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })}).finally(() => setLoading(false))}, [id, retryKey])@@ -49,7 +51,7 @@ export default function WeightDetail() {setEditWeight(String(displayWeight(log.weight, settings.weight_unit)))setEditDate(entryDay(log))setEditNotes(log.notes ?? '')- setEditError('')+ setBadWeight(null)setEditing(true)}@@ -61,9 +63,9 @@ export default function WeightDetail() {})setLog(updated)setEditing(false)- }, 'Failed to save')+ }, t('weight.detail.saveFailed'))- // `editError` is what this page can say about the value in the box; the hook carries+ // `badWeight` is what this page can say about the value in the box; the hook carries// what the server said. The entry is passed to run() because the guard below is what// proves it is not null.const handleSave = (e: React.FormEvent) => {@@ -72,10 +74,10 @@ export default function WeightDetail() {const w = parseFloat(editWeight)const wErr = weightError(w, settings.weight_unit)if (wErr) {- setEditError(wErr)+ setBadWeight(w)return}- setEditError('')+ setBadWeight(null)void saveEdit.run(log)}@@ -84,7 +86,9 @@ export default function WeightDetail() {const remove = useAsyncAction(async (entry: types.WeightLog) => {await weightAPI.delete(entry.id)navigate('/weight', { replace: true })- }, 'Failed to delete entry')+ }, t('weight.deleteFailed'))++ const editError = badWeight == null ? '' : weightError(badWeight, settings.weight_unit) ?? ''if (loading) {return (@@ -98,10 +102,10 @@ export default function WeightDetail() {return (<ErrorStatesize="page"- title="Couldn't load this entry"- message={error ?? 'That entry no longer exists.'}+ title={t('weight.detail.loadFailed')}+ message={error ? uiMessage(error) : t('weight.detail.gone')}onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}- secondary={<Link to="/weight" className="btn-secondary btn-sm">Back to weight</Link>}+ secondary={<Link to="/weight" className="btn-secondary btn-sm">{t('weight.detail.backToWeight')}</Link>}/>)}@@ -111,21 +115,21 @@ export default function WeightDetail() {{/* Back nav + actions */}<div className="flex items-center justify-between"><Link to="/weight" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Weight+ <ArrowLeft className="w-4 h-4" /> {t('weight.detail.back')}</Link>{!editing && (<div className="flex items-center gap-1"><buttononClick={startEdit}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"- aria-label="Edit entry"+ aria-label={t('weight.detail.editLabel')}><Edit2 className="w-4 h-4 text-brand-500" /></button><buttononClick={() => setConfirming(true)}className="p-2 hover:bg-error-500/10 rounded-lg transition-colors"- aria-label="Delete entry"+ aria-label={t('weight.detail.deleteLabel')}><Trash2 className="w-4 h-4 text-error-400" /></button>@@ -140,9 +144,9 @@ export default function WeightDetail() {<Scale className="w-7 h-7 text-brand-500" /></div><div className="min-w-0 flex-1">- <p className="stat-label mb-1">Weight Entry</p>+ <p className="stat-label mb-1">{t('weight.detail.entryLabel')}</p>{editing ? (- <p className="text-sm text-brand-400 font-medium">Editing…</p>+ <p className="text-sm text-brand-400 font-medium">{t('weight.detail.editing')}</p>) : (<><div className="flex items-end gap-2">@@ -150,7 +154,7 @@ export default function WeightDetail() {<span className="text-tx-muted text-lg mb-1">{wUnit}</span></div><p className="text-sm text-tx-muted mt-1">- {formatDay(entryDay(log), 'EEEE, MMMM d, yyyy')}+ {formatDay(entryDay(log), 'weekdayDate')}</p>{log.notes && (<p className="text-sm text-tx-secondary mt-2 italic">"{log.notes}"</p>@@ -164,7 +168,7 @@ export default function WeightDetail() {{/* Edit form */}{editing && (<div className="card p-5">- <h2 className="section-title mb-4">Edit Entry</h2>+ <h2 className="section-title mb-4">{t('weight.detail.editTitle')}</h2><form onSubmit={handleSave} className="space-y-4">{(editError || saveEdit.error) && (<div className="alert-error" role="alert">@@ -175,16 +179,16 @@ export default function WeightDetail() {<StepperTileicon={Scale}- label={`Weight (${wUnit})`}- name="weight"+ label={t('weight.log.weightLabel', { unit: wUnit })}+ name={t('weight.log.weightName')}step={BODYWEIGHT_STEP}onStep={d => setEditWeight(String(clampStep(parseFloat(editWeight) || 0, d, { max: maxWeight(settings.weight_unit) })))}>- <NumberField value={editWeight} onChange={setEditWeight} aria-label="Weight" />+ <NumberField value={editWeight} onChange={setEditWeight} aria-label={t('weight.log.weightField')} /></StepperTile><div>- <label className="label">Date</label>+ <label className="label">{t('weight.detail.date')}</label><inputtype="date"value={editDate}@@ -195,12 +199,14 @@ export default function WeightDetail() {</div><div>- <label className="label">Notes <span className="text-tx-muted font-normal">(optional)</span></label>+ <label className="label">+ <Trans i18nKey="weight.detail.notesOptional" components={{ hint: <span className="text-tx-muted font-normal" /> }} />+ </label><inputtype="text"value={editNotes}onChange={e => setEditNotes(e.target.value)}- placeholder="e.g., morning, post-workout"+ placeholder={t('weight.detail.notePlaceholder')}maxLength={200}className="input mt-1"/>@@ -209,10 +215,10 @@ export default function WeightDetail() {<div className="flex items-center gap-2 pt-1"><buttontype="button"- onClick={() => { setEditing(false); setEditError('') }}+ onClick={() => { setEditing(false); setBadWeight(null) }}className="flex-1 py-2.5 bg-surface-muted hover:bg-surface-muted/80 text-tx-secondary rounded-xl transition-colors font-medium text-sm flex items-center justify-center gap-1.5">- <X className="w-4 h-4" /> Cancel+ <X className="w-4 h-4" /> {t('common.cancel')}</button><buttontype="submit"@@ -220,7 +226,7 @@ export default function WeightDetail() {className="flex-1 btn-primary py-2.5 rounded-xl flex items-center justify-center gap-1.5"><Save className="w-4 h-4" />- {saveEdit.busy ? 'Saving…' : 'Save'}+ {saveEdit.busy ? t('common.saving') : t('common.save')}</button></div></form>@@ -232,10 +238,10 @@ export default function WeightDetail() {open={confirming}icon={Trash2}destructive- title="Delete Entry?"- message={`${formatDay(entryDay(log), 'MMMM d, yyyy')} · ${displayWeight(log.weight, settings.weight_unit)} ${wUnit} will be permanently deleted.`}- confirmLabel="Delete"- busyLabel="Deleting…"+ title={t('weight.deleteTitle')}+ message={t('common.deleteConfirmMessage', { subject: t('weight.deleteSubject', { date: formatDay(entryDay(log), 'longDate'), weight: displayWeight(log.weight, settings.weight_unit), unit: wUnit }) })}+ confirmLabel={t('common.delete')}+ busyLabel={t('common.deleting')}busy={remove.busy}error={remove.error}onConfirm={() => { if (!remove.busy) void remove.run(log) }}diff --git a/web/src/pages/WorkoutDetail.tsx b/web/src/pages/WorkoutDetail.tsxindex 1f721ce..94f81c4 100644--- a/web/src/pages/WorkoutDetail.tsx+++ b/web/src/pages/WorkoutDetail.tsx@@ -6,22 +6,24 @@ import {} from 'lucide-react'import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, displayWeight, displayVolume } from '../stores/settings'-import { apiErrorMessage, isNotFound, useAsyncAction, types, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay } from '@lyftr/shared'-import { muscleColor } from '../utils/exerciseUtils'+import { isNotFound, useAsyncAction, types, workoutDay, restLabel, calcVolume, countWorkingSets, exerciseVolume, formatDay, uiMessage, useTranslation, type UiMessage } from '@lyftr/shared'+import { muscleColor, muscleLabel } from '../utils/exerciseUtils'function SetChip({ set, isBest, unit }: { set: types.Set; isBest: boolean; unit: string }) {+ const { t } = useTranslation()return (<div className={`px-2.5 py-1.5 rounded-lg text-xs font-semibold tabular-nums leading-none ${isBest? 'bg-brand-500/15 text-brand-300 ring-1 ring-brand-500/25': 'bg-surface-raised text-tx-secondary'}`}>- {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${displayWeight(set.weight, unit)} ${unit}` : 'BW'}+ {set.reps > 0 ? set.reps : '—'} × {set.weight > 0 ? `${displayWeight(set.weight, unit)} ${unit}` : t('weight.bodyweightShort')}</div>)}export default function WorkoutDetail() {+ const { t } = useTranslation()const { id } = useParams<{ id: string }>()const navigate = useNavigate()const { settings } = useSettingsStore()@@ -29,7 +31,8 @@ export default function WorkoutDetail() {const restOn = settings.rest_enabled ?? trueconst [workout, setWorkout] = useState<types.Workout | null>(null)const [loading, setLoading] = useState(true)- const [error, setError] = useState<string | null>(null)+ // A UiMessage, not its sentence, so the banner follows a live language switch.+ const [error, setError] = useState<UiMessage | null>(null)// A 404 is not a retryable failure: the row is gone, and a Try again button that// cannot ever succeed is worse than no button. Tracked separately from the message// because the message alone cannot say which kind of failure produced it.@@ -47,7 +50,7 @@ export default function WorkoutDetail() {setWorkout(data)} catch (err: any) {setGone(isNotFound(err))- setError(apiErrorMessage(err, "The server didn't say what went wrong."))+ setError({ key: 'settings.unknownError', cause: err })} finally {setLoading(false)}@@ -62,7 +65,7 @@ export default function WorkoutDetail() {if (!workout) returnawait workoutAPI.delete(workout.id)navigate('/workouts', { replace: true })- }, 'Failed to delete workout')+ }, t('workouts.deleteFailed'))if (loading) {return (@@ -76,10 +79,10 @@ export default function WorkoutDetail() {return (<ErrorStatesize="page"- title="Couldn't load this workout"- message={error ?? 'That workout no longer exists.'}+ title={t('workouts.detail.loadFailed')}+ message={error ? uiMessage(error) : t('workouts.detail.gone')}onRetry={error && !gone ? () => { setError(null); setRetryKey(k => k + 1) } : undefined}- secondary={<Link to="/workouts" className="btn-secondary btn-sm">Back to workouts</Link>}+ secondary={<Link to="/workouts" className="btn-secondary btn-sm">{t('workouts.detail.backToWorkouts')}</Link>}/>)}@@ -94,18 +97,18 @@ export default function WorkoutDetail() {{/* Back nav */}<div className="flex items-center justify-between"><Link to="/workouts" className="flex items-center gap-1.5 text-sm text-tx-muted hover:text-tx-primary transition-colors">- <ArrowLeft className="w-4 h-4" /> Workouts+ <ArrowLeft className="w-4 h-4" /> {t('workouts.detail.back')}</Link><div className="flex items-center gap-1"><button- aria-label="Edit workout"+ aria-label={t('workouts.detail.editLabel')}onClick={() => navigate(`/workouts/${workout.id}/edit`)}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><Edit2 className="w-4 h-4 text-brand-500" /></button><button- aria-label="Delete workout"+ aria-label={t('workouts.detail.deleteLabel')}onClick={() => setConfirming(true)}className="p-2 hover:bg-error-500/10 rounded-lg transition-colors">@@ -119,10 +122,10 @@ export default function WorkoutDetail() {open={confirming}icon={Trash2}destructive- title="Delete Workout?"- message={`"${workout.name}" will be permanently deleted.`}- confirmLabel="Delete"- busyLabel="Deleting…"+ title={t('workouts.deleteConfirmTitle')}+ message={t('common.deleteConfirmMessage', { subject: `"${workout.name}"` })}+ confirmLabel={t('common.delete')}+ busyLabel={t('common.deleting')}busy={remove.busy}error={remove.error}onConfirm={() => { void remove.run() }}@@ -147,7 +150,7 @@ export default function WorkoutDetail() {<div className="min-w-0 flex-1"><h1 className="font-display font-bold text-xl text-tx-primary leading-tight">{workout.name}</h1><p className="text-sm text-tx-muted mt-0.5">- {formatDay(workoutDay(workout), 'EEEE, MMMM d, yyyy')}+ {formatDay(workoutDay(workout), 'weekdayDate')}</p></div></div>@@ -157,21 +160,21 @@ export default function WorkoutDetail() {<div className="text-center"><div className="flex items-center justify-center gap-1 mb-0.5"><Clock className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Duration</p>+ <p className="text-xs text-tx-muted">{t('workouts.detail.duration')}</p></div>- <p className="text-lg font-bold text-tx-primary tabular-nums">{durationMin}<span className="text-xs font-normal text-tx-muted ml-0.5">min</span></p>+ <p className="text-lg font-bold text-tx-primary tabular-nums">{durationMin}<span className="text-xs font-normal text-tx-muted ml-0.5">{t('workouts.detail.minutesUnit')}</span></p></div><div className="text-center border-x border-surface-border"><div className="flex items-center justify-center gap-1 mb-0.5"><Dumbbell className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Sets</p>+ <p className="text-xs text-tx-muted">{t('workouts.detail.sets')}</p></div><p className="text-lg font-bold text-tx-primary tabular-nums">{totalSets}</p></div><div className="text-center"><div className="flex items-center justify-center gap-1 mb-0.5"><TrendingUp className="w-3.5 h-3.5 text-tx-muted" />- <p className="text-xs text-tx-muted">Volume</p>+ <p className="text-xs text-tx-muted">{t('workouts.detail.volume')}</p></div><p className="text-lg font-bold text-tx-primary tabular-nums">{totalVolume > 0 ? `${totalVolume.toLocaleString()}` : '—'}@@ -188,7 +191,7 @@ export default function WorkoutDetail() {{/* Exercises */}{!restOn && (<div className="flex items-center gap-1.5 text-[11px] text-tx-muted px-1">- <TimerOff className="w-3.5 h-3.5" /> Rest timer is off — turn it on in Settings+ <TimerOff className="w-3.5 h-3.5" /> {t('workouts.detail.restOff')}</div>)}<div className="space-y-3">@@ -197,6 +200,10 @@ export default function WorkoutDetail() {const maxWeightLbs = sets.length > 0 ? Math.max(...sets.map(s => s.weight || 0)) : 0const maxWeight = displayWeight(maxWeightLbs, wUnit)const exVol = displayVolume(exerciseVolume(sets), wUnit)+ const setsSummary = [+ t('workouts.detail.setCount', { count: sets.length }),+ ...(exVol > 0 ? [`${exVol.toLocaleString()} ${wUnit}`] : []),+ ].join(' · ')return (<button@@ -222,15 +229,15 @@ export default function WorkoutDetail() {<div className="flex items-center gap-2 mt-0.5">{ex.exercise?.muscle_group && (<span className={`inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${muscleColor(ex.exercise.muscle_group)}`}>- {ex.exercise.muscle_group}+ {muscleLabel(ex.exercise.muscle_group)}</span>)}- <span className="text-xs text-tx-muted truncate">{sets.length} set{sets.length === 1 ? '' : 's'}{exVol > 0 ? ` · ${exVol.toLocaleString()} ${wUnit}` : ''}</span>+ <span className="text-xs text-tx-muted truncate">{setsSummary}</span></div></div>{maxWeight > 0 && (<div className="text-right flex-shrink-0 mr-1">- <p className="text-[10px] text-tx-muted uppercase tracking-wide">best</p>+ <p className="text-[10px] text-tx-muted uppercase tracking-wide">{t('workouts.detail.best')}</p><p className="text-sm font-bold text-brand-400 tabular-nums">{maxWeight} {wUnit}</p></div>)}@@ -245,7 +252,7 @@ export default function WorkoutDetail() {))}</div>{restOn && (ex.rest_seconds === 0- ? <span className="text-xs text-tx-muted flex-shrink-0">No rest</span>+ ? <span className="text-xs text-tx-muted flex-shrink-0">{t('workouts.detail.noRest')}</span>: <span className="flex items-center gap-1 text-xs text-tx-muted flex-shrink-0"><Pause className="w-3.5 h-3.5" />{restLabel(ex.rest_seconds ?? 90)}</span>)}</div>diff --git a/web/src/pages/WorkoutExercisePicker.tsx b/web/src/pages/WorkoutExercisePicker.tsxindex de30393..fdb2908 100644--- a/web/src/pages/WorkoutExercisePicker.tsx+++ b/web/src/pages/WorkoutExercisePicker.tsx@@ -1,25 +1,26 @@import { useState, useEffect, useCallback } from 'react'import { useNavigate } from 'react-router-dom'import { ArrowLeft, Search, Dumbbell } from 'lucide-react'-import { useServerList, types } from '@lyftr/shared'+import { useServerList, types, useTranslation } from '@lyftr/shared'import { ListError } from '../components/ui'import { exerciseAPI } from '../services/api'import { useWorkoutSession } from '../stores/workoutSession'-import { muscleColorBordered, EQUIPMENT_LABEL } from '../utils/exerciseUtils'+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 = 50const DEBOUNCE_MS = 250export default function WorkoutExercisePicker() {+ const { t } = useTranslation()const navigate = useNavigate()const { session, addExercise } = useWorkoutSession()const [query, setQuery] = useState('')const [debouncedQuery, setDebouncedQuery] = useState('')useEffect(() => {- const t = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)- return () => clearTimeout(t)+ const timer = setTimeout(() => setDebouncedQuery(query), DEBOUNCE_MS)+ return () => clearTimeout(timer)}, [query])const selectedIds = session?.exercises.map(e => e.exercise_id) ?? []@@ -69,21 +70,21 @@ export default function WorkoutExercisePicker() {{/* Header */}<div className="flex items-center gap-3 mb-4 flex-shrink-0"><button- aria-label="Back to workout"+ aria-label={t('exercises.picker.backToWorkout')}onClick={() => navigate('/workout/active')}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><ArrowLeft className="w-5 h-5 text-tx-muted" /></button><div>- <h1 className="font-display font-bold text-xl text-tx-primary">Add Exercise</h1>+ <h1 className="font-display font-bold text-xl text-tx-primary">{t('exercises.picker.title')}</h1>{/* Derived from the rows we actually hold, so it is only true if the fetchlanded. On a failure `available` is empty and this read "0 loaded" directlyabove a message saying we could not load anything — the same claim theerror state exists to stop. */}{!error && (<p className="text-xs text-tx-muted">- {available.length} loaded{hasMore ? '…' : ''}+ {t(hasMore ? 'exercises.picker.loadedMore' : 'exercises.picker.loaded', { count: available.length })}</p>)}</div>@@ -96,7 +97,7 @@ export default function WorkoutExercisePicker() {type="text"value={query}onChange={e => setQuery(e.target.value)}- placeholder="Search exercises…"+ placeholder={t('exercises.picker.search')}className="input pl-10 w-full"autoFocus/>@@ -107,18 +108,18 @@ export default function WorkoutExercisePicker() {{initialLoading ? (<div className="flex items-center justify-center py-12 text-tx-muted text-sm"><Dumbbell className="w-5 h-5 mr-2 animate-pulse text-brand-500" />- Loading…+ {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="these exercises" message={error} onRetry={retry} />+ <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">- No exercises found+ {t('exercises.picker.empty')}</div>)) : (@@ -146,11 +147,11 @@ export default function WorkoutExercisePicker() {<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 ${muscleColorBordered(ex.muscle_group)}`}>- {ex.muscle_group}+ {muscleLabel(ex.muscle_group)}</span>{ex.equipment && ex.equipment !== 'other' && (<span className="text-xs text-tx-muted">- {EQUIPMENT_LABEL[ex.equipment] || ex.equipment}+ {equipmentLabel(ex.equipment)}</span>)}</div>@@ -164,7 +165,7 @@ export default function WorkoutExercisePicker() {disabled={loading}className="btn-secondary btn-sm w-full my-3">- {loading ? 'Loading…' : 'Load more'}+ {loading ? t('exercises.picker.loadingShort') : t('exercises.picker.loadMore')}</button>)}</div>diff --git a/web/src/pages/Workouts.tsx b/web/src/pages/Workouts.tsxindex 09c2efa..f0d8b78 100644--- a/web/src/pages/Workouts.tsx+++ b/web/src/pages/Workouts.tsx@@ -11,9 +11,10 @@ import { Toast } from '../components/ui'import { useServerInfiniteList } from '../hooks/useServerInfiniteList'import { workoutAPI } from '../services/api'import { useSettingsStore, weightShort, displayVolume } from '../stores/settings'-import { useAsyncAction, types, workoutDay, calcVolume, formatDay } from '@lyftr/shared'+import { useAsyncAction, types, workoutDay, calcVolume, formatDay, useTranslation } from '@lyftr/shared'function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onEdit: (id: number) => void; onDelete: (id: number) => void }) {+ const { t } = useTranslation()const navigate = useNavigate()const { settings } = useSettingsStore()const wUnit = weightShort(settings.weight_unit)@@ -40,7 +41,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; onconst remove = useAsyncAction(async () => {await workoutAPI.delete(workout.id)onDelete(workout.id)- }, 'Failed to delete workout')+ }, t('workouts.deleteFailed'))if (confirming) {return (@@ -51,18 +52,18 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on<Trash2 className="w-4 h-4 text-error-400" /></div><div>- <p className="text-sm font-semibold text-tx-primary">Delete "{workout.name}"?</p>- <p className="text-xs text-tx-muted">This cannot be undone</p>+ <p className="text-sm font-semibold text-tx-primary">{t('workouts.card.deleteTitle', { name: workout.name })}</p>+ <p className="text-xs text-tx-muted">{t('workouts.card.cannotUndo')}</p>{remove.error && <p className="text-xs text-error-400 mt-1">{remove.error}</p>}</div></div><div className="flex items-center gap-2"><button onClick={() => setConfirming(false)} className="btn-secondary btn-sm">- Cancel+ {t('common.cancel')}</button><button onClick={() => { void remove.run() }} disabled={remove.busy} className="btn-danger-solid btn-sm disabled:opacity-50"><Trash2 className="w-3 h-3" />- {remove.busy ? 'Deleting…' : 'Delete'}+ {remove.busy ? t('common.deleting') : t('common.delete')}</button></div></div>@@ -92,15 +93,15 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on)}<div className="min-w-0 flex-1"><p className="text-sm font-semibold text-tx-primary truncate">{workout.name}</p>- <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{formatDay(workoutDay(workout), 'MMM d, yyyy')}</p>+ <p className="text-xs text-tx-muted mt-0.5 whitespace-nowrap">{formatDay(workoutDay(workout), 'monthDayYear')}</p><div className="flex items-center gap-x-2 mt-0.5 min-w-0 overflow-hidden">{durationMin > 0 && (<span className="flex items-center gap-1 text-xs text-tx-muted whitespace-nowrap">- <Clock className="w-3 h-3 flex-shrink-0" />{durationMin} min+ <Clock className="w-3 h-3 flex-shrink-0" />{t('workouts.card.minutes', { minutes: durationMin })}</span>)}{durationMin > 0 && <span className="text-tx-muted/40 text-xs">·</span>}- <span className="text-xs text-tx-muted whitespace-nowrap">{workout.exercises?.length || 0} exercise{(workout.exercises?.length || 0) === 1 ? '' : 's'}</span>+ <span className="text-xs text-tx-muted whitespace-nowrap">{t('workouts.card.exercises', { count: workout.exercises?.length || 0 })}</span>{totalVolume > 0 && (<><span className="text-tx-muted/40 text-xs">·</span>@@ -120,7 +121,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on<buttononClick={e => { e.stopPropagation(); setMenuOpen(o => !o) }}className={`sm:hidden p-2 rounded-lg transition-colors ${menuOpen ? 'bg-surface-muted' : 'hover:bg-surface-muted'}`}- aria-label="Options"+ aria-label={t('workouts.card.options')}><MoreVertical className="w-4 h-4 text-tx-muted" /></button>@@ -134,7 +135,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on/><div ref={portalRef} className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 bg-surface-overlay border border-surface-border/60 rounded-2xl shadow-2xl z-50 overflow-hidden"><div className="px-4 pt-4 pb-3">- <p className="text-[10px] font-semibold text-tx-muted uppercase tracking-wider text-center">Workout</p>+ <p className="text-[10px] font-semibold text-tx-muted uppercase tracking-wider text-center">{t('workouts.card.menuHeading')}</p><p className="text-sm font-semibold text-tx-primary text-center mt-0.5 truncate">{workout.name}</p></div><div className="border-t border-surface-border/40 py-1.5">@@ -145,7 +146,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on<div className="w-8 h-8 rounded-xl bg-brand-500/10 flex items-center justify-center flex-shrink-0"><Edit2 className="w-4 h-4 text-brand-500" /></div>- Edit Workout+ {t('workouts.card.editWorkout')}</button><div className="mx-4 border-t border-surface-border/30" /><button@@ -155,7 +156,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on<div className="w-8 h-8 rounded-xl bg-error-500/10 flex items-center justify-center flex-shrink-0"><Trash2 className="w-4 h-4 text-error-400" /></div>- Delete Workout+ {t('workouts.card.deleteWorkout')}</button></div><div className="border-t border-surface-border/40 p-3">@@ -163,7 +164,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; ononClick={e => { e.stopPropagation(); setMenuOpen(false) }}className="w-full py-2.5 text-sm font-semibold text-tx-muted bg-surface-muted/60 hover:bg-surface-muted rounded-xl transition-colors">- Cancel+ {t('common.cancel')}</button></div></div>@@ -174,14 +175,14 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on{/* Desktop hover icons */}<div className="hidden sm:flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity"><button- aria-label={`Edit ${workout.name}`}+ aria-label={t('workouts.card.editNamed', { name: workout.name })}onClick={e => { e.stopPropagation(); onEdit(workout.id) }}className="p-2 hover:bg-surface-muted rounded-lg transition-colors"><Edit2 className="w-4 h-4 text-brand-500" /></button><button- aria-label="Delete"+ aria-label={t('common.delete')}onClick={e => { e.stopPropagation(); setConfirming(true) }}className="p-2 hover:bg-error-500/10 rounded-lg transition-colors">@@ -195,6 +196,7 @@ function WorkoutCard({ workout, onEdit, onDelete }: { workout: types.Workout; on}export default function Workouts() {+ const { t } = useTranslation()const navigate = useNavigate()const location = useLocation()const [search, setSearch] = useState('')@@ -238,10 +240,10 @@ export default function Workouts() {if (listError && workouts.length === 0) {return (<div className="space-y-5 animate-slide-up">- <PageHeader title="Workouts" subtitle="Track and review your training sessions" />+ <PageHeader title={t('workouts.list.title')} subtitle={t('workouts.list.subtitle')} /><ErrorStatesize="page"- title="Couldn't load your workouts"+ title={t('workouts.list.loadFailed')}message={listError}onRetry={retryList}/>@@ -252,11 +254,11 @@ export default function Workouts() {return (<div className="space-y-5 animate-slide-up"><PageHeader- title="Workouts"- subtitle="Track and review your training sessions"+ title={t('workouts.list.title')}+ subtitle={t('workouts.list.subtitle')}action={<button onClick={() => navigate('/workouts/new')} className="btn-primary btn-sm">- <Plus className="w-4 h-4" /> Log Workout+ <Plus className="w-4 h-4" /> {t('workouts.list.logWorkout')}</button>}/>@@ -271,12 +273,12 @@ export default function Workouts() {// One page of an infinite list, so this is what has loaded, not how many exist:// with more pages outstanding it is a lower bound and says so, rather than// reporting a page size as a training history.- { label: 'Total', value: hasMore ? `${workouts.length}+` : workouts.length.toString(), unit: 'logged' },+ { label: t('workouts.stats.total'), value: hasMore ? `${workouts.length}+` : workouts.length.toString(), unit: t('workouts.stats.logged') },// The month the workout was logged in, not the month its UTC instant lands in —// a session near a month boundary belongs to the month the lifter trained in.- { label: 'This Month', value: workouts.filter(w => workoutDay(w).startsWith(format(new Date(), 'yyyy-MM'))).length.toString(), unit: 'sessions' },+ { label: t('workouts.stats.thisMonth'), value: workouts.filter(w => workoutDay(w).startsWith(format(new Date(), 'yyyy-MM'))).length.toString(), unit: t('workouts.stats.sessions') },// The mean of no sessions is not zero minutes.- { label: 'Avg Time', value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '—', unit: 'min' },+ { label: t('workouts.stats.avgTime'), value: workouts.length > 0 ? Math.round(workouts.reduce((sum, w) => sum + w.duration, 0) / workouts.length / 60).toString() : '—', unit: t('workouts.stats.min') },].map(s => (<div key={s.label} className="card p-4"><div className="flex items-center gap-1.5 mb-2">@@ -298,7 +300,7 @@ export default function Workouts() {value={search}onChange={e => setSearch(e.target.value)}className="input pl-10"- placeholder="Search workouts…"+ placeholder={t('workouts.list.searchPlaceholder')}/></div>@@ -309,8 +311,8 @@ export default function Workouts() {// so an empty list at this point really is empty.<EmptyStateicon={Dumbbell}- title="No workouts found"- subtitle={search ? 'Try a different search' : 'Log a workout to get started'}+ title={t('workouts.list.empty.title')}+ subtitle={search ? t('workouts.list.empty.searchHint') : t('workouts.list.empty.startHint')}/>) : (<>@@ -319,9 +321,9 @@ export default function Workouts() {onDelete={() => reload()}/>)}<div ref={sentinelRef} />- {listError && <ListError subject="your workouts" message={listError} onRetry={retryList} />}+ {listError && <ListError subject={t('workouts.list.errorSubject')} message={listError} onRetry={retryList} />}{hasMore && loading && (- <p className="text-center text-xs text-tx-muted py-2">Loading more…</p>+ <p className="text-center text-xs text-tx-muted py-2">{t('workouts.list.loadingMore')}</p>)}</>)}@@ -331,8 +333,8 @@ export default function Workouts() {<Toastvariant={progression.is_pr ? 'warning' : 'success'}icon={progression.is_pr ? Award : TrendingUp}- title={progression.is_pr ? `New PR in ${progression.program_name}` : `New targets in ${progression.program_name}`}- description={`Tap to review ${progression.count} ${progression.count === 1 ? 'update' : 'updates'}`}+ title={progression.is_pr ? t('workouts.toast.newPr', { name: progression.program_name }) : t('workouts.toast.newTargets', { name: progression.program_name })}+ description={t('workouts.toast.reviewUpdates', { count: progression.count })}onClick={() => { setProgression(null); navigate(`/programs/${progression.program_id}`) }}onDismiss={() => setProgression(null)}/>diff --git a/web/src/stores/server.ts b/web/src/stores/server.tsindex 8e52421..ad7ea48 100644--- a/web/src/stores/server.ts+++ b/web/src/stores/server.ts@@ -5,7 +5,5 @@ export { useServerStore } from '../lib/lyftr'export {normalizeServerUrl,isInsecureServerUrl,- INSECURE_SERVER_WARNING,isMixedContentBlocked,- MIXED_CONTENT_WARNING,} from '@lyftr/shared'diff --git a/web/src/utils/exerciseUtils.test.ts b/web/src/utils/exerciseUtils.test.tsindex d8155f3..f5c1ab4 100644--- a/web/src/utils/exerciseUtils.test.ts+++ b/web/src/utils/exerciseUtils.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest'import { muscleColor, muscleColorBordered, muscleToBodySlugs } from './exerciseUtils'-// The lookup rule and EQUIPMENT_LABEL are covered in+// The lookup rule and the equipment and muscle labels are covered in// packages/shared/src/utils/exerciseUtils.test.ts. What's left here is what is// genuinely web's: the Tailwind class output and the react-body-highlighter slugs.diff --git a/web/src/utils/exerciseUtils.ts b/web/src/utils/exerciseUtils.tsindex 308b275..c421b6a 100644--- a/web/src/utils/exerciseUtils.ts+++ b/web/src/utils/exerciseUtils.ts@@ -1,9 +1,9 @@import { resolveMuscleSlugs } from '@lyftr/shared'// Web's half of exercise presentation: the Tailwind colour table and the-// react-body-highlighter slug table. EQUIPMENT_LABEL and the lookup rule are shared —-// see packages/shared/src/utils/exerciseUtils.ts for why these two tables are not.-export { EQUIPMENT_LABEL } from '@lyftr/shared'+// react-body-highlighter slug table. The equipment and muscle labels and the lookup rule are+// shared — see packages/shared/src/utils/exerciseUtils.ts for why these two tables are not.+export { categoryLabel, equipmentLabel, muscleLabel } from '@lyftr/shared'const MUSCLE_COLORS: Record<string, string> = {chest: 'bg-red-500/20 text-red-400 border-red-500/30',