Skip to content

Colota - Android GPS Location tracker

refactor(i18n): move header titles, tab labels and dialog defaults into the catalog (#897)

Max Dietrichc6b8f61cc22c
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index e0f6a632..39b489ff 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -15,6 +15,8 @@ import { ErrorBoundary } from "./src/components/ui/ErrorBoundary"
import type { RootStackParamList, RootStackRoute } from "./src/types/navigation"
import "./src/i18n"
+import { useTranslation } from "./src/i18n/useTranslation"
+import type { TranslationKey } from "./src/i18n/options"
import {
LoggingScreen,
LogPreviewScreen,
@@ -55,148 +57,149 @@ registerTileServerUserAgent()
const Stack = createNativeStackNavigator<RootStackParamList>()
-type ScreenConfig = { name: RootStackRoute; component: React.ComponentType<any>; title: string }
+type ScreenConfig = { name: RootStackRoute; component: React.ComponentType<any>; titleKey: TranslationKey }
const SCREEN_CONFIG: readonly ScreenConfig[] = [
{
name: "Dashboard",
component: DashboardScreen,
- title: "Dashboard"
+ titleKey: "screen.dashboard"
},
{
name: "Settings",
component: SettingsScreen,
- title: "Settings"
+ titleKey: "screen.settings"
},
{
name: "Request Format",
component: ApiSettingsScreen,
- title: "Request format"
+ titleKey: "screen.requestFormat"
},
{
name: "Backend Template",
component: BackendTemplateScreen,
- title: "Backend template"
+ titleKey: "screen.backendTemplate"
},
{
name: "Auth Settings",
component: AuthSettingsScreen,
- title: "Authentication"
+ titleKey: "screen.authSettings"
},
{
name: "mTLS Settings",
component: MtlsSettingsScreen,
- title: "Client certificate"
+ titleKey: "screen.mtlsSettings"
},
{
name: "Geofences",
component: GeofenceScreen,
- title: "Geofences"
+ titleKey: "screen.geofences"
},
{
name: "Geofence Editor",
component: GeofenceEditorScreen,
- title: "Geofence editor"
+ titleKey: "screen.geofenceEditor"
},
{
name: "Place Zone",
component: PlaceZoneScreen,
- title: "Place zone"
+ titleKey: "screen.placeZone"
},
{
name: "Location History",
component: LocationHistoryScreen,
- title: "Location history"
+ titleKey: "screen.locationHistory"
},
{
name: "Location Summary",
component: LocationSummaryScreen,
- title: "Summary"
+ titleKey: "screen.locationSummary"
},
{
name: "Export & Import",
component: ExportImportScreen,
- title: "Export & import"
+ titleKey: "screen.exportImport"
},
{
name: "Auto-Export",
component: AutoExportScreen,
- title: "Auto-export"
+ titleKey: "screen.autoExport"
},
{
name: "Data Management",
component: DataManagementScreen,
- title: "Data management"
+ titleKey: "screen.dataManagement"
},
{
name: "Tracking Profiles",
component: TrackingProfilesScreen,
- title: "Tracking profiles"
+ titleKey: "screen.trackingProfiles"
},
{
name: "Profile Editor",
component: ProfileEditorScreen,
- title: "Profile editor"
+ titleKey: "screen.profileEditor"
},
{
name: "About Colota",
component: AboutScreen,
- title: "About"
+ titleKey: "screen.aboutColota"
},
{
name: "Setup Import",
component: SetupImportScreen,
- title: "Import configuration"
+ titleKey: "screen.setupImport"
},
{
name: "Share Setup",
component: ShareSetupScreen,
- title: "Share setup"
+ titleKey: "screen.shareSetup"
},
{
name: "Trip Detail",
component: TripDetailScreen,
- title: "Trip detail"
+ titleKey: "screen.tripDetail"
},
{
name: "Offline Maps",
component: OfflineMapsScreen,
- title: "Offline maps"
+ titleKey: "screen.offlineMaps"
},
{
name: "Logging",
component: LoggingScreen,
- title: "Logging"
+ titleKey: "screen.logging"
},
{
name: "Log Preview",
component: LogPreviewScreen,
- title: "Log preview"
+ titleKey: "screen.logPreview"
},
{
name: "Backup & Restore",
component: BackupRestoreScreen,
- title: "Backup & restore"
+ titleKey: "screen.backupRestore"
},
{
name: "Appearance",
component: AppearanceScreen,
- title: "Appearance"
+ titleKey: "screen.appearance"
},
{
name: "Connection",
component: ConnectionScreen,
- title: "Connection"
+ titleKey: "screen.connection"
},
{
name: "Tracking & Sync",
component: TrackingSyncScreen,
- title: "Tracking & sync"
+ titleKey: "screen.trackingSync"
}
]
function AppNavigator() {
const { colors, isDark } = useTheme()
+ const { t } = useTranslation()
const [currentRoute, setCurrentRoute] = useState<string | undefined>("Dashboard")
const screenOptions = useMemo(
() => ({
@@ -289,7 +292,7 @@ function AppNavigator() {
name={screen.name}
component={screen.component}
options={{
- headerTitle: screen.title,
+ headerTitle: t(screen.titleKey),
...(TAB_ROUTES.has(screen.name) && { headerBackVisible: false })
}}
/>
diff --git a/apps/mobile/src/components/ui/BottomTabBar.tsx b/apps/mobile/src/components/ui/BottomTabBar.tsx
index d8564020..5e0f322d 100644
--- a/apps/mobile/src/components/ui/BottomTabBar.tsx
+++ b/apps/mobile/src/components/ui/BottomTabBar.tsx
@@ -11,21 +11,23 @@ import { useTheme } from "../../hooks/useTheme"
import { fontSizes, fonts } from "../../styles/typography"
import { size, space, STATE_LAYER_ALPHA, elevation } from "../../constants"
import type { RootStackRoute } from "../../types/navigation"
+import { useTranslation } from "../../i18n/useTranslation"
+import type { TranslationKey } from "../../i18n/options"
type TabIcon = React.ComponentType<{ size?: number; color?: string; strokeWidth?: number }>
interface Tab {
name: string
- label: string
+ labelKey: TranslationKey
icon: TabIcon
route: RootStackRoute
}
const TABS: Tab[] = [
- { name: "dashboard", label: "Dashboard", icon: House, route: "Dashboard" },
- { name: "history", label: "History", icon: TrackMark, route: "Location History" },
- { name: "geofences", label: "Geofences", icon: CircleDot, route: "Geofences" },
- { name: "settings", label: "Settings", icon: Settings, route: "Settings" }
+ { name: "dashboard", labelKey: "tab.dashboard", icon: House, route: "Dashboard" },
+ { name: "history", labelKey: "tab.history", icon: TrackMark, route: "Location History" },
+ { name: "geofences", labelKey: "tab.geofences", icon: CircleDot, route: "Geofences" },
+ { name: "settings", labelKey: "tab.settings", icon: Settings, route: "Settings" }
]
/** Routes where the tab bar is visible. The one list; App.tsx reads it rather than repeating it. */
@@ -43,6 +45,7 @@ interface BottomTabBarProps {
export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
const { colors } = useTheme()
const insets = useSafeAreaInsets()
+ const { t } = useTranslation()
if (!currentRoute || !TAB_ROUTES.has(currentRoute)) return null
@@ -64,7 +67,7 @@ export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
key={tab.name}
accessibilityRole="tab"
accessibilityState={{ selected: active }}
- accessibilityLabel={tab.label}
+ accessibilityLabel={t(tab.labelKey)}
android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
style={styles.tab}
onPress={() => onNavigate(tab.route)}
@@ -72,7 +75,7 @@ export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
{/* The set has no filled variants, so weight is what marks the active glyph. */}
<tab.icon size={size.icon.lg} color={color} strokeWidth={active ? ACTIVE_STROKE : undefined} />
<Text numberOfLines={2} style={[styles.label, active && fonts.semiBold, { color }]}>
- {tab.label}
+ {t(tab.labelKey)}
</Text>
</Pressable>
)
diff --git a/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx b/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx
index 646bc240..9962f4bf 100644
--- a/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx
+++ b/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx
@@ -1,5 +1,6 @@
import React from "react"
-import { render } from "@testing-library/react-native"
+import { act, render } from "@testing-library/react-native"
+import i18next from "i18next"
jest.mock("react-native-safe-area-context", () => ({
useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
@@ -67,4 +68,22 @@ describe("BottomTabBar", () => {
expect(getByLabelText("History").findByType(TrackMark)).toBeTruthy()
})
+
+ it("relabels the tabs when the language changes, because the list holds keys and not English", () => {
+ i18next.addResourceBundle("xx", "translation", { "tab.history": "Verlauf" })
+ const { getByText, getByLabelText } = renderBar("Dashboard")
+
+ act(() => {
+ i18next.changeLanguage("xx")
+ })
+ try {
+ expect(getByText("Verlauf")).toBeTruthy()
+ expect(getByLabelText("Verlauf")).toBeTruthy()
+ } finally {
+ act(() => {
+ i18next.changeLanguage("en")
+ })
+ i18next.removeResourceBundle("xx", "translation")
+ }
+ })
})
diff --git a/apps/mobile/src/i18n/__tests__/i18n.test.ts b/apps/mobile/src/i18n/__tests__/i18n.test.ts
index 8f7cb03a..1f077f8e 100644
--- a/apps/mobile/src/i18n/__tests__/i18n.test.ts
+++ b/apps/mobile/src/i18n/__tests__/i18n.test.ts
@@ -12,6 +12,7 @@ import i18next from "i18next"
import NativeLocationService from "../../services/NativeLocationService"
import { initI18n, SUPPORTED_LANGUAGES, t } from "../index"
import en from "../locales/en.json"
+import type { TranslationKey } from "../options"
const mockGetBuildConfig = NativeLocationService.getBuildConfig as jest.Mock
@@ -53,7 +54,7 @@ describe("initI18n", () => {
mockGetBuildConfig.mockReturnValue({ APP_LANGUAGE: "en" })
initI18n()
- expect(t("appearance.doesNotExist")).toBe("appearance.doesNotExist")
+ expect(t("appearance.doesNotExist" as TranslationKey)).toBe("appearance.doesNotExist")
})
})
diff --git a/apps/mobile/src/i18n/index.ts b/apps/mobile/src/i18n/index.ts
index a96282e6..82e44602 100644
--- a/apps/mobile/src/i18n/index.ts
+++ b/apps/mobile/src/i18n/index.ts
@@ -9,22 +9,18 @@ import { logger } from "../utils/logger"
import { I18N_OPTIONS, FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, type SupportedLanguage } from "./options"
export { SUPPORTED_LANGUAGES }
+export { t } from "./t"
-/** Matches "de-DE" and "de" alike, since the device tag carries a region and the catalogs do not. */
+/** The device tag carries a region, 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. */
+/** Plurals beyond one/other, which the English fallback gets wrong. */
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.
- */
+// Hermes has no PluralRules; an unconditional throw would kill every build at bundle evaluation.
function checkPluralRules(): void {
if (typeof Intl !== "undefined" && typeof Intl.PluralRules !== "undefined") return
@@ -49,12 +45,5 @@ export function initI18n(): SupportedLanguage {
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.
+// On import, because a call in App.tsx would run after every screen module has evaluated.
initI18n()
-
-/** The non-React entry point, for a caller with no hook available. `utils/appearance` uses it. */
-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.json
index 12d7a3f5..a652c24a 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -17,5 +17,39 @@
"appearance.mapStyle.reset": "Reset to default",
"appearance.mapStyle.light": "Light style URL",
"appearance.mapStyle.dark": "Dark style URL",
- "appearance.mapStyle.error": "Starts with http:// or https:// and names a host."
+ "appearance.mapStyle.error": "Starts with http:// or https:// and names a host.",
+ "screen.dashboard": "Dashboard",
+ "screen.settings": "Settings",
+ "screen.requestFormat": "Request format",
+ "screen.backendTemplate": "Backend template",
+ "screen.authSettings": "Authentication",
+ "screen.mtlsSettings": "Client certificate",
+ "screen.geofences": "Geofences",
+ "screen.geofenceEditor": "Geofence editor",
+ "screen.placeZone": "Place zone",
+ "screen.locationHistory": "Location history",
+ "screen.locationSummary": "Summary",
+ "screen.exportImport": "Export & import",
+ "screen.autoExport": "Auto-export",
+ "screen.dataManagement": "Data management",
+ "screen.trackingProfiles": "Tracking profiles",
+ "screen.profileEditor": "Profile editor",
+ "screen.aboutColota": "About",
+ "screen.setupImport": "Import configuration",
+ "screen.shareSetup": "Share setup",
+ "screen.tripDetail": "Trip detail",
+ "screen.offlineMaps": "Offline maps",
+ "screen.logging": "Logging",
+ "screen.logPreview": "Log preview",
+ "screen.backupRestore": "Backup & restore",
+ "screen.appearance": "Appearance",
+ "screen.connection": "Connection",
+ "screen.trackingSync": "Tracking & sync",
+ "tab.dashboard": "Dashboard",
+ "tab.history": "History",
+ "tab.geofences": "Geofences",
+ "tab.settings": "Settings",
+ "common.ok": "OK",
+ "common.cancel": "Cancel",
+ "common.save": "Save"
}
diff --git a/apps/mobile/src/i18n/options.ts b/apps/mobile/src/i18n/options.ts
index d57d9d75..9e45bc81 100644
--- a/apps/mobile/src/i18n/options.ts
+++ b/apps/mobile/src/i18n/options.ts
@@ -8,15 +8,12 @@ import en from "./locales/en.json"
export const SUPPORTED_LANGUAGES = ["en"] as const
export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number]
+/** A key missing from the English catalog fails tsc. */
+export type TranslationKey = keyof typeof en
+
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.
- */
+/** Side-effect free so `jest.setup.js` can share it. Inline resources keep `init()` synchronous. */
export const I18N_OPTIONS = {
fallbackLng: FALLBACK_LANGUAGE,
resources: { en: { translation: en } },
diff --git a/apps/mobile/src/i18n/t.ts b/apps/mobile/src/i18n/t.ts
new file mode 100644
index 00000000..17225eac
--- /dev/null
+++ b/apps/mobile/src/i18n/t.ts
@@ -0,0 +1,12 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import i18next from "i18next"
+import type { TranslationKey } from "./options"
+
+/** For non-React callers. Side-effect free, unlike `index.ts`, so importing it runs no device detection. */
+export function t(key: TranslationKey, options?: Record<string, unknown>): string {
+ return i18next.t(key, options) as string
+}
diff --git a/apps/mobile/src/i18n/useTranslation.ts b/apps/mobile/src/i18n/useTranslation.ts
index d7f9936d..06ccc864 100644
--- a/apps/mobile/src/i18n/useTranslation.ts
+++ b/apps/mobile/src/i18n/useTranslation.ts
@@ -5,6 +5,7 @@
import { useCallback, useSyncExternalStore } from "react"
import i18next from "i18next"
+import type { TranslationKey } from "./options"
function subscribe(onChange: () => void): () => void {
i18next.on("languageChanged", onChange)
@@ -15,10 +16,10 @@ function getSnapshot(): string {
return i18next.language
}
-export function useTranslation(): { t: (key: string, options?: Record<string, unknown>) => string } {
+export function useTranslation(): { t: (key: TranslationKey, 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,
+ (key: TranslationKey, options?: Record<string, unknown>) => i18next.getFixedT(language)(key, options) as string,
[language]
)
return { t }
diff --git a/apps/mobile/src/services/__tests__/modalService.test.ts b/apps/mobile/src/services/__tests__/modalService.test.ts
index d168374f..1bfceb84 100644
--- a/apps/mobile/src/services/__tests__/modalService.test.ts
+++ b/apps/mobile/src/services/__tests__/modalService.test.ts
@@ -1,4 +1,5 @@
-import { registerModalHandler, showPrompt, type ModalRequest } from "../modalService"
+import i18next from "i18next"
+import { registerModalHandler, showAlert, showConfirm, showPrompt, type ModalRequest } from "../modalService"
describe("showPrompt", () => {
let last: ModalRequest | null = null
@@ -29,3 +30,41 @@ describe("showPrompt", () => {
await expect(cleared).resolves.toBe("")
})
})
+
+describe("default button labels", () => {
+ let last: ModalRequest | null = null
+
+ beforeEach(() => {
+ last = null
+ registerModalHandler((request) => {
+ last = request
+ })
+ })
+
+ afterEach(async () => {
+ await i18next.changeLanguage("en")
+ i18next.removeResourceBundle("xx", "translation")
+ })
+
+ it("reads the catalog on each call, so a dialog opened after a language change is not left in English", async () => {
+ i18next.addResourceBundle("xx", "translation", {
+ "common.ok": "Gut",
+ "common.cancel": "Zurück",
+ "common.save": "Sichern"
+ })
+ await i18next.changeLanguage("xx")
+
+ showAlert("Title", "Message")
+ expect(last!.buttons.map((b) => b.text)).toEqual(["Gut"])
+ showConfirm({ title: "Title", message: "Message" })
+ expect(last!.buttons.map((b) => b.text)).toEqual(["Zurück", "Gut"])
+ showPrompt({ title: "Title" })
+ expect(last!.buttons.map((b) => b.text)).toEqual(["Zurück", "Sichern"])
+ })
+
+ it("keeps a caller's own labels over the defaults", () => {
+ showConfirm({ title: "Title", message: "Message", confirmText: "Delete", cancelText: "Keep" })
+
+ expect(last!.buttons.map((b) => b.text)).toEqual(["Keep", "Delete"])
+ })
+})
diff --git a/apps/mobile/src/services/modalService.ts b/apps/mobile/src/services/modalService.ts
index 24098b87..f0044679 100644
--- a/apps/mobile/src/services/modalService.ts
+++ b/apps/mobile/src/services/modalService.ts
@@ -4,6 +4,7 @@
*/
import { Alert } from "react-native"
+import { t } from "../i18n/t"
export type AlertVariant = "info" | "error" | "warning" | "success"
@@ -43,7 +44,7 @@ export function showAlert(title: string, message: string, variant: AlertVariant
title,
message,
variant,
- buttons: [{ text: "OK", style: "primary" }],
+ buttons: [{ text: t("common.ok"), style: "primary" }],
resolve: () => {}
})
}
@@ -94,7 +95,7 @@ export function showConfirm(options: {
cancelText?: string
destructive?: boolean
}): Promise<boolean> {
- const { title, message, confirmText = "OK", cancelText = "Cancel", destructive = false } = options
+ const { title, message, confirmText = t("common.ok"), cancelText = t("common.cancel"), destructive = false } = options
return new Promise((resolve) => {
if (!_handler) {
@@ -138,8 +139,8 @@ export function showPrompt(options: {
placeholder,
initialValue,
multiline,
- confirmText = "Save",
- cancelText = "Cancel"
+ confirmText = t("common.save"),
+ cancelText = t("common.cancel")
} = options
return new Promise((resolve) => {
diff --git a/apps/mobile/src/utils/appearance.ts b/apps/mobile/src/utils/appearance.ts
index 25f9a26f..d3207f3b 100644
--- a/apps/mobile/src/utils/appearance.ts
+++ b/apps/mobile/src/utils/appearance.ts
@@ -4,7 +4,7 @@
*/
import { MAP_STYLE_URL_LIGHT, MAP_STYLE_URL_DARK } from "../constants"
-import { t } from "../i18n"
+import { t } from "../i18n/t"
import type { ThemePreference } from "../hooks/useTheme"
import { formatTimeIn, type TimeFormat, type UnitSystem } from "./geo"
import { endpointHost } from "./serverState"