Colota - Android GPS Location tracker
feat(i18n): add the i18next foundation and a pilot screen (#650)
Max Dietrich4ff2260eeda2
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 2a6eba80..02794fd9 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -12,6 +12,8 @@ import { fonts } from "./src/styles/typography"import { TrackingProvider } from "./src/contexts/TrackingProvider"import { ErrorBoundary } from "./src/components/ui/ErrorBoundary"import type { RootStackParamList, RootStackRoute } from "./src/types/navigation"++import "./src/i18n"import {ActivityLogScreen,DashboardScreen,diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.ktindex 4ae642a1..49f10c65 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BuildConfigModule.kt@@ -8,6 +8,7 @@import com.facebook.react.bridge.ReactApplicationContextimport com.Colota.BuildConfigimport com.facebook.react.bridge.ReactContextBaseJavaModule+import java.util.Localeclass BuildConfigModule(reactContext: ReactApplicationContext) :ReactContextBaseJavaModule(reactContext) {@@ -24,7 +25,8 @@ class BuildConfigModule(reactContext: ReactApplicationContext) :"NDK_VERSION" to BuildConfig.NDK_VERSION,"VERSION_NAME" to BuildConfig.VERSION_NAME,"VERSION_CODE" to BuildConfig.VERSION_CODE,- "FLAVOR" to BuildConfig.FLAVOR+ "FLAVOR" to BuildConfig.FLAVOR,+ "APP_LANGUAGE" to Locale.getDefault().toLanguageTag())}}\ No newline at end of filediff --git a/apps/mobile/jest.setup.js b/apps/mobile/jest.setup.jsindex afdc07bc..ec990c59 100644--- a/apps/mobile/jest.setup.js+++ b/apps/mobile/jest.setup.js@@ -54,3 +54,7 @@ jest.mock("react-native/Libraries/AppState/AppState", () => ({addEventListener: jest.fn(() => ({ remove: jest.fn() }))}}))++const i18next = require("i18next")+const { I18N_OPTIONS } = require("./src/i18n/options")+i18next.init({ ...I18N_OPTIONS, lng: "en" })diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex cf9c31ba..52a7a8a5 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -24,6 +24,7 @@"@maplibre/maplibre-react-native": "^11.3.0","@react-navigation/native": "^7.2.5","@react-navigation/native-stack": "^7.16.0",+ "i18next": "^26.4.2","lucide-react-native": "^1.17.0","react": "19.2.8","react-native": "0.87.0",diff --git a/apps/mobile/src/i18n/__tests__/i18n.test.ts b/apps/mobile/src/i18n/__tests__/i18n.test.tsnew file mode 100644index 00000000..e8c8118f--- /dev/null+++ b/apps/mobile/src/i18n/__tests__/i18n.test.ts@@ -0,0 +1,75 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getBuildConfig: jest.fn() }+}))++import i18next from "i18next"+import NativeLocationService from "../../services/NativeLocationService"+import { initI18n, SUPPORTED_LANGUAGES, t } from "../index"+import en from "../locales/en.json"++const mockGetBuildConfig = NativeLocationService.getBuildConfig as jest.Mock++describe("initI18n", () => {+ beforeEach(() => {+ mockGetBuildConfig.mockReset()+ })++ it("uses the device language when a catalog exists for it", () => {+ mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "en-GB" })++ // The device tag carries a region and the catalogs do not, so only the base tag can match.+ expect(initI18n()).toBe("en")+ })++ it("falls back to English for a language with no catalog", () => {+ mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "pl-PL" })++ expect(initI18n()).toBe("en")+ })++ it("falls back to English when the native module is unavailable", () => {+ // getBuildConfig returns null when the bridge module is missing, which must not throw during+ // module-scope init or the app fails to start rather than starting in English.+ mockGetBuildConfig.mockReturnValue(null)++ expect(initI18n()).toBe("en")+ })++ it("resolves keys synchronously, so a first paint never shows raw keys", () => {+ mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "en-US" })++ initI18n()++ expect(t("appearance.darkMode")).toBe("Dark Mode")+ })++ it("returns the key itself when it is missing, rather than empty text", () => {+ mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "en" })+ initI18n()++ expect(t("appearance.doesNotExist")).toBe("appearance.doesNotExist")+ })+})++describe("catalog", () => {+ it("every supported language is a real i18next resource after init", () => {+ mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "en" })+ initI18n()++ for (const lang of SUPPORTED_LANGUAGES) {+ expect(i18next.getResourceBundle(lang, "translation")).toBeTruthy()+ }+ })++ it("has no empty values, which would render as blank UI", () => {+ const empty = Object.entries(en).filter(([, value]) => String(value).trim() === "")++ expect(empty).toEqual([])+ })+})diff --git a/apps/mobile/src/i18n/index.ts b/apps/mobile/src/i18n/index.tsnew file mode 100644index 00000000..378ed23f--- /dev/null+++ b/apps/mobile/src/i18n/index.ts@@ -0,0 +1,60 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import i18next from "i18next"+import NativeLocationService from "../services/NativeLocationService"+import { logger } from "../utils/logger"+import { I18N_OPTIONS, FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, type SupportedLanguage } from "./options"++export { SUPPORTED_LANGUAGES }++/** Matches "de-DE" and "de" alike, since the device tag carries a region and the catalogs do not. */+function resolveLanguage(tag: string | undefined): SupportedLanguage {+ const base = (tag ?? "").split("-")[0].toLowerCase()+ return (SUPPORTED_LANGUAGES as readonly string[]).includes(base) ? (base as SupportedLanguage) : FALLBACK_LANGUAGE+}++/** Languages whose plurals need more than one/other, so they cannot ride the English fallback. */+const COMPLEX_PLURAL_LANGUAGES: readonly string[] = ["pl", "ru", "cs", "ar", "uk", "hr", "lt", "sk"]++/**+ * Hermes implements most of Intl but not PluralRules, and i18next then applies English one/other+ * rules without saying so. Correct while only en ships, wrong for Polish or Russian, so warn now+ * and fail only once a supported language depends on it: throwing outright would kill every Hermes+ * build at bundle evaluation, which no test can catch because Node has PluralRules.+ */+function checkPluralRules(): void {+ if (typeof Intl !== "undefined" && typeof Intl.PluralRules !== "undefined") return++ const affected = SUPPORTED_LANGUAGES.filter((l) => COMPLEX_PLURAL_LANGUAGES.includes(l))+ if (affected.length > 0) {+ throw new Error(+ `Intl.PluralRules is missing but ${affected.join(", ")} need it. i18next would silently use ` ++ "English plural rules. Add @formatjs/intl-pluralrules."+ )+ }+ logger.warn("[i18n] Intl.PluralRules is unavailable; add @formatjs/intl-pluralrules before a language needs it")+}++export function initI18n(): SupportedLanguage {+ const deviceTag = NativeLocationService.getBuildConfig()?.APP_LANGUAGE+ const language = resolveLanguage(deviceTag)++ i18next.init({ ...I18N_OPTIONS, lng: language })++ checkPluralRules()+ logger.debug(`[i18n] Initialised as '${language}' (device reported '${deviceTag ?? "unknown"}')`)+ return language+}++// Runs on first import, not from a call in App.tsx: ES imports hoist, so a call there would execute+// only after every screen module had evaluated. No screen resolves a key at module scope yet, so this+// starts mattering the day the screen-config and preset constants become keys.+initI18n()++/** The non-React entry point. Nothing calls it yet; modalService and setupConfig are the ones that will. */+export function t(key: string, options?: Record<string, unknown>): string {+ return i18next.t(key, options) as string+}diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.jsonnew file mode 100644index 00000000..2be07253--- /dev/null+++ b/apps/mobile/src/i18n/locales/en.json@@ -0,0 +1,14 @@+{+ "appearance.darkMode": "Dark Mode",+ "appearance.units": "Units",+ "appearance.units.metric": "Metric",+ "appearance.units.imperial": "Imperial",+ "appearance.timeFormat": "Time Format",+ "appearance.mapTileServer": "Map Tile Server",+ "appearance.mapStyle.placeholder": "Default",+ "appearance.mapStyle.emptyHint": "Leave empty to use the default",+ "appearance.mapStyle.reset": "Reset to default",+ "appearance.mapStyle.subtitle": "Override the default map tile source",+ "appearance.mapStyle.light": "Light style URL",+ "appearance.mapStyle.dark": "Dark style URL"+}diff --git a/apps/mobile/src/i18n/options.ts b/apps/mobile/src/i18n/options.tsnew file mode 100644index 00000000..d57d9d75--- /dev/null+++ b/apps/mobile/src/i18n/options.ts@@ -0,0 +1,26 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import en from "./locales/en.json"++export const SUPPORTED_LANGUAGES = ["en"] as const+export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number]++export const FALLBACK_LANGUAGE: SupportedLanguage = "en"++/**+ * Side-effect free so `jest.setup.js` can share it: importing the entry point would run device+ * detection against an unmocked bridge.+ *+ * `keySeparator: false` because the catalogs are flat, or i18next reads a dotted key as a nested+ * path first. Resources are inline because `init()` is synchronous only when they are.+ */+export const I18N_OPTIONS = {+ fallbackLng: FALLBACK_LANGUAGE,+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ returnNull: false,+ keySeparator: false as const+}diff --git a/apps/mobile/src/i18n/useTranslation.ts b/apps/mobile/src/i18n/useTranslation.tsnew file mode 100644index 00000000..d7f9936d--- /dev/null+++ b/apps/mobile/src/i18n/useTranslation.ts@@ -0,0 +1,25 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { useCallback, useSyncExternalStore } from "react"+import i18next from "i18next"++function subscribe(onChange: () => void): () => void {+ i18next.on("languageChanged", onChange)+ return () => i18next.off("languageChanged", onChange)+}++function getSnapshot(): string {+ return i18next.language+}++export function useTranslation(): { t: (key: string, options?: Record<string, unknown>) => string } {+ const language = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)+ const t = useCallback(+ (key: string, options?: Record<string, unknown>) => i18next.getFixedT(language)(key, options) as string,+ [language]+ )+ return { t }+}diff --git a/apps/mobile/src/screens/AppearanceScreen.tsx b/apps/mobile/src/screens/AppearanceScreen.tsxindex 2c10560d..b2aa0e8c 100644--- a/apps/mobile/src/screens/AppearanceScreen.tsx+++ b/apps/mobile/src/screens/AppearanceScreen.tsx@@ -7,6 +7,7 @@ import React, { useState, useCallback, useEffect } from "react"import { Text, StyleSheet, Switch, View, ScrollView, Pressable, TextInput } from "react-native"import { ScreenProps } from "../types/global"import { useTheme } from "../hooks/useTheme"+import { useTranslation } from "../i18n/useTranslation"import NativeLocationService from "../services/NativeLocationService"import { fonts } from "../styles/typography"import { Card, Container, Divider, SettingRow } from "../components"@@ -17,6 +18,7 @@ import type { UnitSystem, TimeFormat } from "../utils/geo"export function AppearanceScreen({}: ScreenProps) {const { mode, toggleTheme, colors } = useTheme()+ const { t } = useTranslation()const [unitSystem, setUnitSystem] = useState<UnitSystem>(getUnitSystem)const [timeFormat, setTimeFormat] = useState<TimeFormat>(getTimeFormat)@@ -90,7 +92,7 @@ export function AppearanceScreen({}: ScreenProps) {showsVerticalScrollIndicator={false}><Card>- <SettingRow label="Dark Mode">+ <SettingRow label={t("appearance.darkMode")}><SwitchtestID="dark-mode-switch"value={mode === "dark"}@@ -105,7 +107,7 @@ export function AppearanceScreen({}: ScreenProps) {<Divider />- <SettingRow label="Units">+ <SettingRow label={t("appearance.units")}><View style={styles.chipGroup}>{(["metric", "imperial"] as const).map((unit) => {const selected = unitSystem === unit@@ -123,7 +125,7 @@ export function AppearanceScreen({}: ScreenProps) {onPress={() => selectUnitSystem(unit)}><Text style={[styles.chipLabel, { color: selected ? colors.primary : colors.text }]}>- {unit === "metric" ? "Metric" : "Imperial"}+ {unit === "metric" ? t("appearance.units.metric") : t("appearance.units.imperial")}</Text></Pressable>)@@ -133,7 +135,7 @@ export function AppearanceScreen({}: ScreenProps) {<Divider />- <SettingRow label="Time Format">+ <SettingRow label={t("appearance.timeFormat")}><View style={styles.chipGroup}>{(["24h", "12h"] as const).map((fmt) => {const selected = timeFormat === fmt@@ -165,10 +167,8 @@ export function AppearanceScreen({}: ScreenProps) {onPress={() => setShowMapTileServer(!showMapTileServer)}><View style={styles.linkContent}>- <Text style={[styles.linkLabel, { color: colors.text }]}>Map Tile Server</Text>- <Text style={[styles.linkSub, { color: colors.textSecondary }]}>- Override the default map tile source- </Text>+ <Text style={[styles.linkLabel, { color: colors.text }]}>{t("appearance.mapTileServer")}</Text>+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>{t("appearance.mapStyle.subtitle")}</Text></View>{showMapTileServer ? (<ChevronUp size={20} color={colors.textLight} />@@ -180,7 +180,7 @@ export function AppearanceScreen({}: ScreenProps) {{showMapTileServer && (<View style={styles.mapTilePanel}><Text style={[styles.mapStyleSub, styles.mapStyleSubFirst, { color: colors.textSecondary }]}>- Light style URL+ {t("appearance.mapStyle.light")}</Text><TextInputtestID="map-style-url-light"@@ -191,14 +191,14 @@ export function AppearanceScreen({}: ScreenProps) {value={mapStyleUrlLight}onChangeText={setMapStyleUrlLight}onBlur={() => saveMapStyleUrl("mapStyleUrlLight", mapStyleUrlLight)}- placeholder="Default"+ placeholder={t("appearance.mapStyle.placeholder")}placeholderTextColor={colors.placeholder}autoCapitalize="none"autoCorrect={false}keyboardType="url"/><Text style={[styles.mapStyleSub, styles.mapStyleSubSecond, { color: colors.textSecondary }]}>- Dark style URL+ {t("appearance.mapStyle.dark")}</Text><TextInputtestID="map-style-url-dark"@@ -209,20 +209,24 @@ export function AppearanceScreen({}: ScreenProps) {value={mapStyleUrlDark}onChangeText={setMapStyleUrlDark}onBlur={() => saveMapStyleUrl("mapStyleUrlDark", mapStyleUrlDark)}- placeholder="Default"+ placeholder={t("appearance.mapStyle.placeholder")}placeholderTextColor={colors.placeholder}autoCapitalize="none"autoCorrect={false}keyboardType="url"/><View style={styles.mapStyleFooter}>- <Text style={[styles.mapStyleHint, { color: colors.textLight }]}>Leave empty to use the default</Text>+ <Text style={[styles.mapStyleHint, { color: colors.textLight }]}>+ {t("appearance.mapStyle.emptyHint")}+ </Text>{mapStyleUrlLight.trim() || mapStyleUrlDark.trim() ? (<PressableonPress={resetMapStyle}style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}>- <Text style={[styles.mapStyleHint, { color: colors.primary }]}>Reset to default</Text>+ <Text style={[styles.mapStyleHint, { color: colors.primary }]}>+ {t("appearance.mapStyle.reset")}+ </Text></Pressable>) : null}</View>diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex f3692db4..5287351a 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -722,6 +722,7 @@ class NativeLocationService {VERSION_NAME: stringVERSION_CODE: numberFLAVOR: string+ APP_LANGUAGE: string} | null {if (!BuildConfigModule) {logger.warn("[NativeLocationService] BuildConfigModule not available")diff --git a/package-lock.json b/package-lock.jsonindex 651d6885..6862eb96 100644--- a/package-lock.json+++ b/package-lock.json@@ -50,6 +50,7 @@"@maplibre/maplibre-react-native": "^11.3.0","@react-navigation/native": "^7.2.5","@react-navigation/native-stack": "^7.16.0",+ "i18next": "^26.4.2","lucide-react-native": "^1.17.0","react": "19.2.8","react-native": "0.87.0",@@ -17316,6 +17317,34 @@"node": ">=10.18"}},+ "node_modules/i18next": {+ "version": "26.4.2",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-26.4.2.tgz",+ "integrity": "sha512-RX+R0VLg13IbvRuJSxnqykUFS9vQZTl8wYpWPCIUDWVrSGjsQywB5Y+pjzrkboxGAuYfJZVH1InFTdgBdxq6ug==",+ "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"+ }+ ],+ "license": "MIT",+ "peerDependencies": {+ "typescript": "^5 || ^6 || ^7"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ }+ },"node_modules/iconv-lite": {"version": "0.7.3","resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",