Skip to content

armgit / lyftr

Public Imported from GitHub
0

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

Fail lint on a new hard-coded UI string (web and mobile) (#200)

Carter6fe0520d6a3c
diff --git a/CLAUDE.md b/CLAUDE.md
index 19b6ec9..7fd1f4d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -183,6 +183,13 @@ true of one file. Do not document it here before it lands.
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.
+- **The guard is lint.** `eslint-plugin-i18next` (`no-literal-string`) plus three
+ `no-restricted-syntax` selectors fail web and mobile lint, as errors, on a hard-coded string
+ in JSX text or a string prop, and on copy passed to `apiErrorMessage`, `useAsyncAction`,
+ `useServerList`, a `set…Error` setter or a `label`/`placeholder`/`title` default. The rule
+ data is `packages/shared/i18n-lint.cjs`, imported by both ESLint configs: a prop or word
+ that is not copy is allowlisted there, once, never in one app. A hit is copy to migrate, not
+ something to silence (CONTRIBUTING.md, "Translations").
- Numbers and dates are never formatted through i18next (see Numbers & Locale).
- Details and key-naming rules: CONTRIBUTING.md, "Translations".
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1b38219..c72422a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -134,13 +134,34 @@ are listed in `locales/README.md`.
- 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.
+ language may not. Web and mobile share a key only when the role and the English are both
+ identical.
+- One catalog file per language; the area is the top-level key (`settings`, `food`, ...).
- 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.
+- Copy with inline markup or a link uses `<Trans>` with named components, not a sentence cut
+ into pieces around a tag.
+- Never translate at module load. A constant that calls `t()` is evaluated once, in English,
+ and never follows a language switch. Store the key (or a `UiMessage`) and call `t()` where
+ it renders.
+
+**When lint flags a string.** Web and mobile lint fail, as errors, on a literal in JSX text or
+a string prop (`eslint-plugin-i18next`), and on copy handed to `apiErrorMessage`,
+`useAsyncAction`, `useServerList`, a `set…Error` setter or a `label`/`placeholder`/`title`
+default. Decide, in this order:
+1. It is copy a person reads: add a key to `en.json` and `es.json` and render it with `t()`.
+2. It is not copy (a style value, a field name, an enum token): add the prop, word or callee
+ to `packages/shared/i18n-lint.cjs` with a comment saying why. Both apps read that file.
+ Do not add an `eslint-disable` comment.
+3. It cannot be fixed cleanly in this change: baseline that file with
+ `npx eslint <file> --suppress-rule i18next/no-literal-string`, which writes
+ `eslint-suppressions.json`. This is a last resort and the file only shrinks: when you
+ migrate in an app that has one, run `npx eslint . --prune-suppressions` there and commit
+ the smaller file.
**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.
diff --git a/mobile/app/(tabs)/nutrition/index.tsx b/mobile/app/(tabs)/nutrition/index.tsx
index 68cce05..127d56f 100644
--- a/mobile/app/(tabs)/nutrition/index.tsx
+++ b/mobile/app/(tabs)/nutrition/index.tsx
@@ -433,10 +433,10 @@ export default function Nutrition() {
<Label className="px-1">{t('food.trends.dailyAverage', { period: historyPeriod })}</Label>
<View className="flex-row gap-3">
{([
- [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]) => (
+ { label: t('food.macro.protein'), key: 'protein', color: MACRO_COLORS.protein },
+ { label: t('food.macro.carbs'), key: 'carbs', color: MACRO_COLORS.carbs },
+ { label: t('food.macro.fat'), key: 'fat', color: 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">
<View style={{ width: 8, height: 8, borderRadius: 2, backgroundColor: color }} />
diff --git a/mobile/eslint.config.js b/mobile/eslint.config.js
index d22b2bc..26d34c7 100644
--- a/mobile/eslint.config.js
+++ b/mobile/eslint.config.js
@@ -1,6 +1,8 @@
// Flat-config ESLint (v9) for the Expo app, extending Expo's shared config
// (eslint-config-expo, SDK-54-matched v57). The `lint` script blocks on errors.
const expoConfig = require('eslint-config-expo/flat')
+const i18next = require('eslint-plugin-i18next')
+const i18nLint = require('../packages/shared/i18n-lint.cjs')
module.exports = [
...expoConfig,
@@ -22,6 +24,17 @@ module.exports = [
'react-hooks/exhaustive-deps': 'warn',
},
},
+ {
+ // The i18n guard: new screen copy goes through t() (CLAUDE.md, "UI Strings"). The
+ // rule data lives in packages/shared/i18n-lint.cjs, shared with web.
+ files: ['app/**/*.{ts,tsx}', 'src/**/*.{ts,tsx}'],
+ ignores: ['**/*.test.{ts,tsx}', 'src/testing/**'],
+ plugins: { i18next },
+ rules: {
+ 'i18next/no-literal-string': ['error', i18nLint.noLiteralString],
+ 'no-restricted-syntax': ['error', ...i18nLint.restrictedSyntax],
+ },
+ },
{
ignores: ['dist/*', '.expo/*', 'node_modules/*', 'expo-env.d.ts'],
},
diff --git a/mobile/package.json b/mobile/package.json
index 54ce58d..b237dcd 100644
--- a/mobile/package.json
+++ b/mobile/package.json
@@ -64,6 +64,7 @@
"@types/react-test-renderer": "~19.1.0",
"eslint": "^9.39.4",
"eslint-config-expo": "^57.0.0",
+ "eslint-plugin-i18next": "^6.1.5",
"jest": "^29.7.0",
"jest-expo": "~54.0.17",
"react-test-renderer": "19.1.0",
diff --git a/package-lock.json b/package-lock.json
index 0302f63..d4780a4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -65,6 +65,7 @@
"@types/react-test-renderer": "~19.1.0",
"eslint": "^9.39.4",
"eslint-config-expo": "^57.0.0",
+ "eslint-plugin-i18next": "^6.1.5",
"jest": "^29.7.0",
"jest-expo": "~54.0.17",
"react-test-renderer": "19.1.0",
@@ -9766,6 +9767,18 @@
"eslint": ">=8.10"
}
},
+ "node_modules/eslint-plugin-i18next": {
+ "version": "6.1.5",
+ "resolved": "https://registry.npmjs.org/eslint-plugin-i18next/-/eslint-plugin-i18next-6.1.5.tgz",
+ "integrity": "sha512-xCTfstbK9ZpQ6UFT5S1s6zbZMhKn2o2jRSQYiU2UkV7wt8y1m3WjkUYGkGlipgRdFInYI9+LAqE+JQU/L73HmA==",
+ "dev": true,
+ "dependencies": {
+ "requireindex": "~1.1.0"
+ },
+ "engines": {
+ "node": ">=18.10.0"
+ }
+ },
"node_modules/eslint-plugin-import": {
"version": "2.32.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz",
@@ -17243,6 +17256,15 @@
"path-parse": "^1.0.5"
}
},
+ "node_modules/requireindex": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/requireindex/-/requireindex-1.1.0.tgz",
+ "integrity": "sha512-LBnkqsDE7BZKvqylbmn7lTIVdpx4K/QCduRATpO5R+wtPmky/a8pN1bO2D6wXppn1497AJF9mNjqAXr6bdl9jg==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.10.5"
+ }
+ },
"node_modules/requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
@@ -20192,6 +20214,7 @@
"autoprefixer": "^10.4.16",
"cross-env": "^10.1.0",
"eslint": "^9.39.5",
+ "eslint-plugin-i18next": "^6.1.5",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.9.0",
diff --git a/packages/shared/i18n-lint.cjs b/packages/shared/i18n-lint.cjs
new file mode 100644
index 0000000..617e737
--- /dev/null
+++ b/packages/shared/i18n-lint.cjs
@@ -0,0 +1,131 @@
+// The i18n guard's rule data, plain so web/eslint.config.mjs (ESM) and
+// mobile/eslint.config.js (CJS) import the one copy and cannot drift apart.
+//
+// eslint-plugin-i18next replaces a default list wholesale when an option is given,
+// so every list below restates the defaults it still wants.
+//
+// A hit means one of: the string is copy and belongs in the catalog (CLAUDE.md,
+// "UI Strings"); it is not copy and the prop / word / callee belongs in a list here,
+// with the reason; or, last resort, it is baselined with `eslint --suppress-rule`.
+
+const MESSAGE = 'UI copy goes through t() — CLAUDE.md, UI Strings'
+
+// Props whose value is never shown to a person. Anything not listed is checked, so a
+// newly invented copy prop (`emptyText`, `hint`) is caught by default.
+const NON_COPY_PROPS = [
+ // eslint-plugin-i18next defaults
+ 'className', 'styleName', 'style', 'type', 'key', 'id', 'width', 'height',
+ // test hooks and routing
+ 'testID', 'data-testid', 'path', 'to', 'href', 'src', 'source', 'target', 'rel',
+ 'htmlFor', 'name', 'accept', 'capture', 'pattern',
+ // values, not labels
+ 'value', 'defaultValue', 'min', 'max', 'step', 'tabIndex',
+ // enums and tokens the component switches on
+ 'variant', 'size', 'tone', 'icon', 'kind', 'mode', 'layout', 'edges', 'behavior',
+ 'haptic', 'descriptionTone', 'descriptionId', 'animationType', 'presentation',
+ 'resizeMode', 'contentFit', 'pointerEvents', 'role', 'accessibilityRole',
+ // keyboard, scrolling, camera and live-region behaviour
+ 'keyboardShouldPersistTaps', 'keyboardDismissMode', 'submitBehavior',
+ 'accessibilityLiveRegion', 'facing', 'barcodeScannerSettings', 'display',
+ 'themeVariant', 'align', 'side', 'tint',
+ 'keyboardType', 'autoCapitalize', 'autoComplete', 'autoCorrect', 'textContentType',
+ 'inputMode', 'enterKeyHint', 'returnKeyType',
+ // colours and geometry
+ 'color', 'colors', 'defaultFill', 'thumbColor', 'fill', 'fillOpacity', 'stroke',
+ 'strokeOpacity', 'strokeLinecap', 'strokeLinejoin', 'textAnchor', 'bg', 'border',
+ 'background', 'xmlns', 'viewBox', 'd',
+ // chart wiring
+ 'dataKey', 'stackId', 'domain', 'interval',
+ // the aria-* props that are state or ids, not text (aria-label, aria-description
+ // and aria-placeholder are copy and stay checked)
+ 'aria-live', 'aria-hidden', 'aria-expanded', 'aria-pressed', 'aria-checked',
+ 'aria-selected', 'aria-current', 'aria-modal', 'aria-haspopup', 'aria-busy',
+ 'aria-disabled', 'aria-invalid', 'aria-controls', 'aria-describedby',
+ 'aria-labelledby', 'aria-orientation', 'aria-atomic', 'aria-relevant',
+ 'aria-valuemin', 'aria-valuemax', 'aria-valuenow',
+]
+
+// Object keys inside JSX (`style={{ ... }}`, `tick={{ ... }}`, data rows) whose value is
+// styling or an identifier. `label`, `title` and friends are deliberately absent.
+const NON_COPY_OBJECT_KEYS = [
+ '[A-Z_-]+',
+ 'id', 'key', 'value', 'icon', 'color', 'bg', 'background', 'border', 'borderRadius',
+ 'fontSize', 'fill', 'stroke', 'strokeWidth', 'radius', 'r', 'cursor', 'letterSpacing',
+ 'plate', 'plateEdge', 'collar', 'kind', 'source',
+ 'alignItems', 'alignSelf', 'justifyContent', 'flexDirection', 'textAlign', 'position',
+ 'overflow',
+]
+
+// Strings that are never words. Each entry is anchored by the plugin (^...$).
+const NON_COPY_WORDS = [
+ // eslint-plugin-i18next defaults
+ '[0-9!-/:-@[-`{-~]+',
+ '[A-Z_-]+',
+ /^\p{Emoji}+$/u,
+ // digits and glyphs outside ASCII: a Unicode minus, arrows, a separator dot, (c)
+ '[0-9\\s·×—–…•%°−→←↑↓©!-/:-@[-`{-~]+',
+ // unit symbols, alone or after a number, and brands (CLAUDE.md, "Numbers & Locale");
+ // the wordmark is lowercase
+ '[0-9.,\\s]*(kg|lbs?|g|kcal)',
+ '(©\\s*)?(Lyftr|lyftr|SQLite|Open Food Facts)',
+ 'https?://\\S+',
+ // a catalog key held as data and translated at render: 'auth.hero.features.food'
+ '[a-z][a-zA-Z]*(\\.[a-zA-Z0-9_]+){2,}',
+ // a field name: 'actual_weight'
+ '[a-z]+(_[a-z0-9]+)+',
+ // CSS values: currentColor, transparent, #3b82f6, rgba(...), var(--x), calc(...)
+ 'currentColor|transparent|#[0-9a-fA-F]{3,8}|(rgba?|hsla?|var|calc)\\(.*\\)',
+ // direction and theme tokens passed to local helpers: pick('system'), tick('left', 28)
+ '(left|right|top|bottom|system|dark|light)',
+ // A Tailwind class list. Every token carries a hyphen, colon, slash or bracket, so a
+ // plain English phrase never matches.
+ '[a-z0-9:/.%#!*_()\\[\\]-]*[-:/\\[][a-z0-9:/.%#!*_()\\[\\]-]*(\\s+[a-z0-9:/.%#!*_()\\[\\]-]*[-:/\\[][a-z0-9:/.%#!*_()\\[\\]-]*)*',
+]
+
+const noLiteralString = {
+ framework: 'react',
+ mode: 'jsx-only',
+ message: MESSAGE,
+ 'jsx-components': { include: [], exclude: ['Trans'] },
+ 'jsx-attributes': { include: [], exclude: NON_COPY_PROPS },
+ 'object-properties': { include: [], exclude: NON_COPY_OBJECT_KEYS },
+ words: { exclude: NON_COPY_WORDS },
+ callees: {
+ include: [],
+ exclude: [
+ // eslint-plugin-i18next defaults
+ 'i18n(ext)?', 't', 'require', 'addEventListener', 'removeEventListener',
+ 'postMessage', 'getElementById', 'dispatch', 'commit', 'includes', 'indexOf',
+ 'endsWith', 'startsWith',
+ // translation and formatting entry points
+ 'i18n\\.t', 'translate', 'format', 'formatDay', 'formatDate', 'languageChoiceLabel',
+ // setters and updaters whose string argument names a state or a field
+ 'setPhase', 'setGymState', 'setTab', 'updateSet', 'onUpdateSet',
+ 'sanitizeNumericInput',
+ // navigation, class names and logging are not copy
+ 'router\\..*', 'navigate', 'cn', 'clsx', 'console\\..*',
+ ],
+ },
+}
+
+// Copy that never reaches JSX in the same expression, so the rule above cannot see it.
+const restrictedSyntax = [
+ {
+ selector:
+ 'CallExpression[callee.name=/^(apiErrorMessage|useAsyncAction|useServerList)$/] > :matches(Literal[value=/\\s/], TemplateLiteral)',
+ message: MESSAGE,
+ },
+ {
+ selector:
+ 'CallExpression[callee.name=/^set\\w*(Error|Msg|Message)$/] > :matches(Literal[value=/./], TemplateLiteral)',
+ message: MESSAGE,
+ },
+ {
+ // A default of '0.0' is a format hint, not copy, so only a value with a letter counts.
+ selector:
+ 'AssignmentPattern[left.name=/^(\\w*Label|label|placeholder|title|message|sublabel)$/] > Literal[value=/\\p{L}/u]',
+ message: MESSAGE,
+ },
+]
+
+module.exports = { MESSAGE, noLiteralString, restrictedSyntax }
diff --git a/packages/shared/src/i18n/catalog.test.ts b/packages/shared/src/i18n/catalog.test.ts
index 5e7eef6..caba25e 100644
--- a/packages/shared/src/i18n/catalog.test.ts
+++ b/packages/shared/src/i18n/catalog.test.ts
@@ -137,6 +137,14 @@ describe('key safety', () => {
// @ts-expect-error unknown key is a type error
i18n.t('settings.noSuchKey')
})
+
+ it('rejects a key that is only known to be a string', () => {
+ // A key built at run time cannot be checked against the catalog, so tsc refuses it:
+ // a template key has to be typed to a union of real keys (food.meal.${Meal}).
+ const dynamic: string = 'settings.title'
+ // @ts-expect-error a string-typed key is a type error
+ i18n.t(dynamic)
+ })
})
describe('language registry', () => {
diff --git a/packages/shared/src/i18n/locales/README.md b/packages/shared/src/i18n/locales/README.md
index 83bfad4..66fea3d 100644
--- a/packages/shared/src/i18n/locales/README.md
+++ b/packages/shared/src/i18n/locales/README.md
@@ -14,3 +14,34 @@ from `LANGUAGE_NAMES`.
How to add a language, and the key-naming rules: see the "Translations" section of
[CONTRIBUTING.md](../../../../../CONTRIBUTING.md).
+
+## Spanish: voice and glossary
+
+`es.json` is machine-translated from `en.json` and has not been reviewed by a native
+speaker. It is neutral Latin-American Spanish in the informal *tú* voice (`Registra tu
+primer peso`, never *usted*). Keep `{{placeholders}}` verbatim, and keep short labels short:
+they have to fit a 390px phone.
+
+Use the same word for the same thing everywhere, so the app reads as one voice:
+
+| English | Spanish |
+|---------|---------|
+| Settings | Ajustes |
+| Workout (the activity, a heading) | entrenamiento |
+| Workouts (the tab label only) | Entrenos |
+| set, sets | serie, series |
+| reps (a column or tile) | Reps |
+| reps (running text) | repeticiones |
+| Rest | descanso |
+| Rest day | día de descanso |
+| Gym Mode | Modo gimnasio |
+| countdown | cuenta atrás |
+| Program | programa |
+| Exercise | ejercicio |
+| Food, a meal | comida (a food item: alimento) |
+| log, to log | registro, registrar |
+| Body weight | peso corporal |
+| Volume | volumen |
+
+Never translated: the unit symbols `kg`, `lb`, `lbs`, `g`, `kcal`; the brands Lyftr, SQLite
+and Open Food Facts; exercise and food names; anything a user typed.
diff --git a/web/eslint.config.mjs b/web/eslint.config.mjs
index 6700871..fb327d2 100644
--- a/web/eslint.config.mjs
+++ b/web/eslint.config.mjs
@@ -19,6 +19,8 @@ import globals from 'globals'
import tseslint from 'typescript-eslint'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
+import i18next from 'eslint-plugin-i18next'
+import i18nLint from '../packages/shared/i18n-lint.cjs'
export default tseslint.config(
{
@@ -56,6 +58,17 @@ export default tseslint.config(
}],
},
},
+ {
+ // The i18n guard: new screen copy goes through t() (CLAUDE.md, "UI Strings"). The
+ // rule data lives in packages/shared/i18n-lint.cjs, shared with mobile.
+ files: ['src/**/*.{ts,tsx}'],
+ ignores: ['src/**/*.test.{ts,tsx}'],
+ plugins: { i18next },
+ rules: {
+ 'i18next/no-literal-string': ['error', i18nLint.noLiteralString],
+ 'no-restricted-syntax': ['error', ...i18nLint.restrictedSyntax],
+ },
+ },
{
// Playwright's fixture callback is named `use`, which trips the rules-of-hooks
// heuristic ("a function starting with `use` must be a hook"). It isn't React.
diff --git a/web/package.json b/web/package.json
index 23e1df0..98797da 100644
--- a/web/package.json
+++ b/web/package.json
@@ -46,6 +46,7 @@
"autoprefixer": "^10.4.16",
"cross-env": "^10.1.0",
"eslint": "^9.39.5",
+ "eslint-plugin-i18next": "^6.1.5",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.9.0",