Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Language: an instance can set DEFAULT_LANG for the sign-in screen and for profiles that never picked a language, and a new visitor otherwise starts in their browser's language (#303)
Duarte Santos36cf6f9c25b0
diff --git a/.env.example b/.env.exampleindex 02a41f69c..6e7cf5569 100644--- a/.env.example+++ b/.env.example@@ -42,6 +42,15 @@ RP_NAME=openGym## ALLOW_GUEST=0+# ── Default language (optional) ────────────────────────────────────────────+# For an instance whose people share a language: the sign-in screen, and every+# profile that has never picked a language in Settings, start in this one+# instead of English (or the browser's language). Anyone's own choice in+# Settings still wins. Use a code from Settings → Language: en, de, de-CH, es,+# fr, it, pt, pt-BR, pl, tr, ru, uk, zh, ko, hi, th, hu, ar.+#+# DEFAULT_LANG=pt-BR+# ── Password sign-in (optional, off by default) ────────────────────────────# Lets people sign in with their profile name and a password next to passkeys:# for browsers that cannot make a passkey (plain http:// on a LAN address, somediff --git a/api/openapi.yaml b/api/openapi.yamlindex e364a32a2..81992bc64 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -76,6 +76,8 @@ info:log served by `GET /api/admin/audit`.- `PASSWORD_LOGIN=1` — adds the `password` routes and `password_login: true` in`GET /api/config`. Off by default.+ - `DEFAULT_LANG` (e.g. `pt-BR`; unset by default) — `default_lang` in `GET /api/config`,+ the language of the sign-in screen and of every profile that never picked one.- `TRUST_PROXY=1` — the throttle reads the client address from proxy headers (set bythe bundled `docker-compose.yml`, where only the web container can reach the API).- `MEDIA_UPLOADS` (default on; `0` removes the `media` routes and the `media` block of@@ -181,7 +183,8 @@ paths:description: |The flags the login screen needs before anyone is signed in. Both reflectenvironment variables on the server (`INVITE_ONLY`, `ALLOW_GUEST`), and so does- `password_login`, which is there only when `PASSWORD_LOGIN=1`.+ `password_login`, which is there only when `PASSWORD_LOGIN=1`, and `default_lang`,+ which is there only when `DEFAULT_LANG` is set.`media` is there unless the instance runs with `MEDIA_UPLOADS=0`, for everybody: thecaps are not a secret, and its absence is how the app knows this server does not@@ -239,6 +242,14 @@ paths:Present (and true) only when the instance runs withPASSWORD_LOGIN=1 — the client then offers name-and-passwordsign-in next to passkeys.+ default_lang:+ type: string+ example: pt-BR+ description: >-+ Present only when the instance runs with DEFAULT_LANG set: the+ language tag the sign-in screen, and every profile that has never+ picked a language in Settings, starts in. A profile's own choice+ always wins; a tag the app has no translation for is ignored.media:$ref: '#/components/schemas/MediaConfig'examples:diff --git a/api/server.js b/api/server.jsindex acd93f614..9aacfc8d0 100644--- a/api/server.js+++ b/api/server.js@@ -49,6 +49,17 @@ const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');// every account that opts in, so an instance has to ask for it. While it is off every password// route answers 404 and the app shows none of it; hashes already stored stay where they are.const PASSWORD_LOGIN = /^(1|true|yes|on)$/i.test(process.env.PASSWORD_LOGIN || '');+// The language the sign-in screen, and every profile that never picked one, starts in (#303) —+// for an instance whose people share a language. Only a tag's shape is checked here; the app+// matches it against the languages it has and ignores one it does not know. Unset, it is left+// out of /api/config and the app behaves as before.+const DEFAULT_LANG = (() => {+ const v = String(process.env.DEFAULT_LANG || '').trim();+ if (!v) return '';+ if (/^[A-Za-z]{2,3}([-_][A-Za-z0-9]{2,8})?$/.test(v)) return v;+ console.warn(`DEFAULT_LANG "${v.slice(0, 40)}" is not a language tag such as pt-BR or de — ignored`);+ return '';+})();// Whether the address a request came from may be read from the headers a proxy sets. Only the// sign-in throttle asks (limitAddress below); the bundled compose file sets it, because the API// is reachable there only through the web container, which overwrites those headers.@@ -1593,6 +1604,8 @@ const routes = {invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST,// Only when on, so an instance without passwords answers exactly as it did before (#118)....(PASSWORD_LOGIN ? { password_login: true } : {}),+ // Public: the sign-in screen is the first thing that reads it.+ ...(DEFAULT_LANG ? { default_lang: DEFAULT_LANG } : {}),// Public like the two flags above: the caps are not a secret, and the absence of the// block is how the app knows this server does not take photos and videos at all....(MEDIA_ON ? { media: mediaConfig(MEDIA_LIMITS) } : {}),diff --git a/api/test/server-config-session.test.js b/api/test/server-config-session.test.jsindex 5f0a4da65..983e7117b 100644--- a/api/test/server-config-session.test.js+++ b/api/test/server-config-session.test.js@@ -86,3 +86,15 @@ test('no Coach configured: no block for anyone, signed in or not', async t => {const signedIn = await fetch(`${h.api}/api/config`, { headers: { Cookie: `gymsid=${mint(UID)}` } }).then(r => r.json());assert.equal(signedIn.coach, null, 'the key says "asked with a session"; null says "no Coach here"');});++test('GET /api/config: DEFAULT_LANG is public when set, absent when unset or malformed (#303)', async t => {+ const set = await startServer(t, { DEFAULT_LANG: 'pt-BR' });+ const anon = await fetch(`${set.api}/api/config`).then(r => r.json());+ assert.deepEqual(anon, { invite_only: true, allow_guest: false, default_lang: 'pt-BR' }, 'the sign-in screen can read it');++ const bad = await startServer(t, { DEFAULT_LANG: '<script>' });+ assert.equal('default_lang' in await fetch(`${bad.api}/api/config`).then(r => r.json()), false);++ const unset = await startServer(t, { DEFAULT_LANG: '' });+ assert.equal('default_lang' in await fetch(`${unset.api}/api/config`).then(r => r.json()), false);+});diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 8e53a24ba..d5fe7c2e6 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -134,6 +134,22 @@ out and locked out everywhere until you re-enable it), and — with `INVITE_ONLYrevoking invite codes. Existing accounts keep working when you switch invite-only on. Admin accessis gated by your passkey and enforced server-side, so it needs no separate login.+### Default language++An instance whose people share a language can start everyone in it:++```bash+DEFAULT_LANG=pt-BR # any code from Settings → Language: de, es, fr, pt-BR, …+```++The sign-in and create-profile screens open in that language, and so does every profile that+has never picked one in **Settings → Language**. Anyone's own choice there always wins, and+profiles that existed before this setting keep the language they have — the app cannot tell an+old profile that chose English from one that never looked, so it leaves them alone. Without+`DEFAULT_LANG`, a new visitor starts in their browser's language when openGym has it, else+English. A code the app has no translation for is ignored. The phone app in local mode has no+server to ask and is unaffected.+### The activity logThe dashboard also keeps an **activity log**: sign-ins, sign-outs, failed attempts, refuseddiff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 2dc1362dd..d292125b1 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -95,6 +95,9 @@ function Shell() {mql.addEventListener('change', onChange)return () => mql.removeEventListener('change', onChange)}, [S.theme, S.accent])+ // A profile that never picked a language follows the instance default or the browser (#303).+ const config = useStore(s => s.config)+ useEffect(() => { useStore.getState().applyAutoLang() }, [config, S.langAuto, S.lang])useEffect(() => { setLang(S.lang || 'en', S.enParens?.[baseLang(S.lang || 'en')] ?? true, S.enOnly?.[baseLang(S.lang || 'en')] === true) }, [S.lang, S.enParens, S.enOnly])// Same shape as the language: a module-level display setting, pushed when it changes (#139).useEffect(() => { setWeightDecimals(S.wdec) }, [S.wdec])diff --git a/frontend/src/lib/default-lang.js b/frontend/src/lib/default-lang.jsnew file mode 100644index 000000000..96b8812de--- /dev/null+++ b/frontend/src/lib/default-lang.js@@ -0,0 +1,39 @@+// Which language a profile that never picked one should be in (#303).+//+// A profile's language is a setting like any other and is synced with it, so "never chose" has+// to be a fact in the state rather than a guess: `lang: 'en'` is also what everybody who picked+// English has. `langAuto: true` marks a copy that started fresh on this build and has not had a+// language picked in Settings since. Copies older than it carry no mark and are left exactly as+// they are — including every existing profile whose `lang` is the old default.+//+// For a marked copy, the instance's DEFAULT_LANG (GET /api/config `default_lang`) comes first,+// then the first of the browser's languages this app speaks, then English.+import { LANGS } from './i18n-core.js'++const KEYS = Object.keys(LANGS)++/** A language tag ('pt-BR', 'pt_br', 'de-AT', 'en-US') as one of LANGS' keys, or null. */+export function matchLocale(tag) {+ if (typeof tag !== 'string') return null+ const want = tag.trim().replace(/_/g, '-').toLowerCase()+ if (!want) return null+ const exact = KEYS.find(k => k.toLowerCase() === want)+ if (exact) return exact+ const base = want.split('-')[0]+ return KEYS.includes(base) ? base : null+}++/** The language a copy that never chose one should be in, or null for a copy that chose. */+export function autoLang(S, config, navLangs = []) {+ if (!S || S.langAuto !== true) return null+ return matchLocale(config?.default_lang)+ || (navLangs || []).map(matchLocale).find(Boolean)+ || 'en'+}++export function browserLangs() {+ try {+ const list = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language]+ return list.filter(Boolean)+ } catch { return [] }+}diff --git a/frontend/src/lib/default-lang.test.js b/frontend/src/lib/default-lang.test.jsnew file mode 100644index 000000000..0484ff33b--- /dev/null+++ b/frontend/src/lib/default-lang.test.js@@ -0,0 +1,34 @@+// #303: an instance-wide default language, and the browser's, apply only to a copy nobody has+// picked a language for — never to an existing profile, whose `lang: 'en'` may be a choice.+import { describe, expect, it } from 'vitest'+import { matchLocale, autoLang } from './default-lang.js'++describe('matchLocale', () => {+ it('matches the full tag first, in any case or separator', () => {+ expect(matchLocale('pt-BR')).toBe('pt-BR')+ expect(matchLocale('pt_br')).toBe('pt-BR')+ expect(matchLocale(' DE-ch ')).toBe('de-CH')+ })+ it('falls back to the base language, and to nothing for one the app does not have', () => {+ expect(matchLocale('de-AT')).toBe('de')+ expect(matchLocale('en-US')).toBe('en')+ expect(matchLocale('pt')).toBe('pt')+ expect(matchLocale('nl-NL')).toBe(null)+ expect(matchLocale('')).toBe(null)+ expect(matchLocale(undefined)).toBe(null)+ })+})++describe('autoLang', () => {+ const fresh = { lang: 'en', langAuto: true }+ it('leaves a copy alone that chose, or that predates the mark', () => {+ expect(autoLang({ lang: 'en' }, { default_lang: 'pt-BR' }, ['de-DE'])).toBe(null)+ expect(autoLang({ lang: 'en', langAuto: false }, { default_lang: 'pt-BR' }, ['de-DE'])).toBe(null)+ })+ it('puts DEFAULT_LANG before the browser, the browser before English', () => {+ expect(autoLang(fresh, { default_lang: 'pt-BR' }, ['de-DE'])).toBe('pt-BR')+ expect(autoLang(fresh, {}, ['nl-NL', 'de-DE'])).toBe('de')+ expect(autoLang(fresh, {}, ['nl-NL'])).toBe('en')+ expect(autoLang(fresh, { default_lang: 'xx' }, ['fr-FR'])).toBe('fr')+ })+})diff --git a/frontend/src/store/useStore.default-lang.test.jsx b/frontend/src/store/useStore.default-lang.test.jsxnew file mode 100644index 000000000..12246282f--- /dev/null+++ b/frontend/src/store/useStore.default-lang.test.jsx@@ -0,0 +1,58 @@+// @vitest-environment happy-dom+// #303: DEFAULT_LANG from /api/config sets the language of a fresh copy — the sign-in screen,+// and a profile created from it — and nothing else. A copy saved before the mark existed keeps+// its language even when that is the old default, 'en': it may well have been chosen.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn() }))++import { api } from '../lib/api.js'+import { useStore, freshState, DEF } from './useStore.js'++const nav = langs => Object.defineProperty(navigator, 'languages', { value: langs, configurable: true })++beforeEach(() => { api.mockReset(); nav(['en-US']); useStore.setState({ config: null }) })+afterEach(() => { useStore.setState({ config: null }) })++describe('instance default language', () => {+ it('a fresh copy is marked as not having picked a language; DEF is not', () => {+ expect(freshState().langAuto).toBe(true)+ expect(DEF.langAuto).toBeUndefined()+ })++ it('a fresh copy takes DEFAULT_LANG once the config is in', async () => {+ useStore.setState({ S: freshState() })+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('en') // nothing to go on before the config++ api.mockResolvedValueOnce({ invite_only: false, allow_guest: true, default_lang: 'pt-BR' })+ await useStore.getState().refreshConfig()+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('pt-BR')+ expect(useStore.getState().S.langAuto).toBe(true)+ })++ it('without DEFAULT_LANG a fresh copy follows the browser when the app speaks it', () => {+ nav(['de-DE', 'en'])+ useStore.setState({ S: freshState(), config: { invite_only: false, allow_guest: true } })+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('de')+ })++ it('an existing copy with lang "en" and no mark is left in English', () => {+ nav(['de-DE'])+ useStore.setState({ S: { ...JSON.parse(JSON.stringify(DEF)), lang: 'en' }, config: { default_lang: 'pt-BR' } })+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('en')+ })++ it('a language picked in Settings wins over DEFAULT_LANG from then on', () => {+ useStore.setState({ S: freshState(), config: { default_lang: 'pt-BR' } })+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('pt-BR')+ // What the Settings picker does.+ useStore.getState().update(s => { s.lang = 'en'; s.langAuto = false })+ useStore.getState().applyAutoLang()+ expect(useStore.getState().S.lang).toBe('en')+ })+})diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex eb2d12189..c7175e9f6 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -4,6 +4,7 @@ import { localTZ } from '../lib/format.js'import { t } from '../lib/i18n.js'import { registerCustom } from '../lib/exercises.js'import { DEMO, DEMO_SEEDED } from '../lib/demo.js'+import { autoLang, browserLangs } from '../lib/default-lang.js'import { guestAllowed } from '../lib/guest.js'import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonFile, syncReminder, writeAutoBackup, writeJsonFile } from '../lib/mobile.js'import { mergeStates, localExtras, stampRoutines, stampCustomEx } from '../lib/sync-merge.js'@@ -175,6 +176,17 @@ const detectedLang = () => {return 'en'}+// A copy started from nothing on this device. `langAuto` marks its language as one nobody has+// picked yet, so the instance's DEFAULT_LANG or the browser's language may set it+// (lib/default-lang.js, #303); picking one in Settings clears it. DEF does not carry the mark:+// merged under a saved copy it would claim that every existing profile never chose.+export function freshState() {+ const s = clone(DEF)+ s.lang = detectedLang()+ s.langAuto = true+ return s+}+function loadState() {try {const raw = localStorage.getItem(KEY)@@ -185,9 +197,7 @@ function loadState() {return s}} catch (e) { /* ignore */ }- const s = clone(DEF)- s.lang = detectedLang()- return s+ return freshState()}// Whether a copy holds anything of its own worth keeping over another: workouts, routines,@@ -531,7 +541,7 @@ export const useStore = create((set, get) => {if (!user || e.newValue === user.id) returnclearTimeout(pushTm)pushTm = null- const S = e.newValue ? loadState() : clone(DEF)+ const S = e.newValue ? loadState() : freshState()meta.set(S, e.newValue ? { base: readStoredSync(), owed: storedOwed() } : { base: null, owed: false })set({ user: null, S })})@@ -578,7 +588,8 @@ export const useStore = create((set, get) => {localStorage.removeItem('gym_guest')forgetSync()localStorage.removeItem(KEY)- persist(clone(DEF), false)+ // Signed out, this device is nobody's: the sign-in screen is in the instance's language.+ persist(freshState(), false)localStorage.removeItem('gym_owner_name')localStorage.removeItem('gym_owner')setSync({ offline: false, auth: false, lastError: null, pending: false, lastSynced: 0 })@@ -812,6 +823,17 @@ export const useStore = create((set, get) => {// while a paired phone sits on the setup screen — that screen wants today's answer.// Two callers that ask at once get one request: signing in re-asks (setUser) and the pairing// flow awaits a refresh of its own immediately after, and there is one answer to have.+ // A copy whose language nobody picked follows DEFAULT_LANG, else the browser (#303). Written+ // without a push: the value is derived, and a profile's next real change carries it — a+ // sync round per boot per device, possibly with differing browser languages, would be churn.+ // Only once the server's config is in hand, so a boot does not flip to the browser's+ // language and back while it is being fetched.+ applyAutoLang() {+ const { S, config } = get()+ if (!config) return+ const l = autoLang(S, config, browserLangs())+ if (l && l !== S.lang) get().update(s => { s.lang = l }, false)+ },async refreshConfig() {if (configFetch) return configFetchconfigFetch = (async () => {diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 7420141d4..69de60a6e 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -313,7 +313,7 @@ export default function Settings() {<Section title={t('General')} footer={t('Switching the unit offers to convert every stored weight.')}><SelectRowicon="globe" iconTint="var(--blue)" title={t('Language')}- value={S.lang || 'en'} onChange={v => update(s => { s.lang = v })}+ value={S.lang || 'en'} onChange={v => update(s => { s.lang = v; s.langAuto = false })}options={Object.entries(LANGS).map(([k, name]) => ({value: k, label: name,subtitle: INSTR_LANGS.includes(k) ? null : t("Exercise instructions aren't available in this language yet — they stay in English."),