Skip to content

Colota - Android GPS Location tracker

Feat/i18n settings (#898)

Max Dietrich67f3b51a026c
diff --git a/.github/labeler.yml b/.github/labeler.yml
index 0d8d8100..2c892ad7 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -47,6 +47,15 @@ docs:
- 'apps/docs/**'
- '**/*.md'
+# ============================
+# Translations (catalogs and native strings)
+# ============================
+i18n:
+ - changed-files:
+ - any-glob-to-any-file:
+ - 'apps/mobile/src/i18n/**'
+ - 'apps/mobile/android/app/src/main/res/values*/strings.xml'
+
# ============================
# Shared package (types, theme)
# ============================
diff --git a/apps/mobile/src/i18n/__tests__/i18n.test.ts b/apps/mobile/src/i18n/__tests__/i18n.test.ts
index 1f077f8e..9f9969e1 100644
--- a/apps/mobile/src/i18n/__tests__/i18n.test.ts
+++ b/apps/mobile/src/i18n/__tests__/i18n.test.ts
@@ -74,3 +74,20 @@ describe("catalog", () => {
expect(empty).toEqual([])
})
})
+
+describe("plurals without Intl.PluralRules", () => {
+ const original = Intl.PluralRules
+
+ afterEach(() => {
+ Object.defineProperty(Intl, "PluralRules", { value: original, configurable: true, writable: true })
+ })
+
+ it("still picks the English one and other forms, because Hermes ships no PluralRules and Node does", async () => {
+ Object.defineProperty(Intl, "PluralRules", { value: undefined, configurable: true, writable: true })
+ const hermesLike = i18next.createInstance()
+ await hermesLike.init({ lng: "en", resources: { en: { translation: en } }, keySeparator: false })
+
+ expect(hermesLike.t("settings.offlineMaps.areas", { count: 1, n: "1" })).toBe("1 area")
+ expect(hermesLike.t("settings.offlineMaps.areas", { count: 2, n: "2" })).toBe("2 areas")
+ })
+})
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index a652c24a..2b21f215 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -51,5 +51,30 @@
"tab.settings": "Settings",
"common.ok": "OK",
"common.cancel": "Cancel",
- "common.save": "Save"
+ "common.save": "Save",
+ "common.error": "Error",
+ "common.unknown": "Unknown",
+ "settings.section.tracking": "Tracking",
+ "settings.section.display": "Display",
+ "settings.section.data": "Data",
+ "settings.section.help": "Help",
+ "settings.section.about": "About",
+ "settings.profiles.none": "No profiles yet",
+ "settings.shareSetup.sub": "Settings, geofences and profiles as a link",
+ "settings.feedback": "Feedback & help",
+ "settings.whatsNew": "What's new",
+ "settings.rate": "Rate the app",
+ "settings.rate.hint": "Opens Colota in Google Play",
+ "settings.thanks": "Say thanks",
+ "settings.version": "Version {{version}}",
+ "settings.linkError": "Could not open the link.",
+ "settings.offlineMaps.none": "No saved areas",
+ "settings.offlineMaps.areas_one": "{{n}} area",
+ "settings.offlineMaps.areas_other": "{{n}} areas",
+ "settings.logging.on": "File logging on · {{size}}",
+ "settings.logging.offKept": "File logging off · {{size}} kept",
+ "settings.logging.off": "File logging off",
+ "settings.data.none": "No locations recorded",
+ "settings.data.locations_one": "{{n}} location · {{size}}",
+ "settings.data.locations_other": "{{n}} locations · {{size}}"
}
diff --git a/apps/mobile/src/i18n/options.ts b/apps/mobile/src/i18n/options.ts
index 9e45bc81..33ff1e8b 100644
--- a/apps/mobile/src/i18n/options.ts
+++ b/apps/mobile/src/i18n/options.ts
@@ -8,8 +8,11 @@ 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
+type CatalogKey = keyof typeof en
+type PluralBase<K> = K extends `${infer Base}_${"zero" | "one" | "two" | "few" | "many" | "other"}` ? Base : never
+
+/** A key missing from the English catalog fails tsc. A plural is called by its base with `count`. */
+export type TranslationKey = CatalogKey | PluralBase<CatalogKey>
export const FALLBACK_LANGUAGE: SupportedLanguage = "en"
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 24bd7588..675dff65 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -41,6 +41,7 @@ import { appearanceRowSub } from "../utils/appearance"
import { backupRowSub } from "../utils/backupState"
import { transferRowSub } from "../utils/locationTransfer"
import { logger } from "../utils/logger"
+import { useTranslation } from "../i18n/useTranslation"
import { space, RELEASES_URL, ISSUES_URL, SUPPORT_URL, PLAY_STORE_MARKET_URL, PLAY_STORE_WEB_URL } from "../constants"
type Props = RootScreenProps<"Settings">
@@ -50,6 +51,7 @@ type AutoExportStatus = Awaited<ReturnType<typeof NativeLocationService.getAutoE
export function SettingsScreen({ navigation }: Props) {
const { settings, activeProfileName, tracking } = useTracking()
const { colors, preference } = useTheme()
+ const { t } = useTranslation()
const [totalCount, setTotalCount] = useState(0)
const [databaseSizeMB, setDatabaseSizeMB] = useState(0)
@@ -92,7 +94,7 @@ export function SettingsScreen({ navigation }: Props) {
}
}, [])
- /** Every sub keeps its last value when its own read rejects, so one slow pack walk never blanks the card. */
+ /** A sub keeps its last value when its own read rejects. */
const readAll = useCallback(async () => {
// One batch: the MapLibre pack walk must not wait behind the two sync reads on every focus.
const [, profiles, exportStatus, logEnabled, logBytes, areas, lastBackup] = await Promise.allSettled([
@@ -112,8 +114,7 @@ export function SettingsScreen({ navigation }: Props) {
}))
if (areas.status === "fulfilled") setOfflineAreas(areas.value)
if (lastBackup.status === "fulfilled") setLastBackupAt(Number(lastBackup.value ?? 0) || null)
- // A focus read may change nothing the state above holds, and the Appearance sub reads a module
- // cache rather than state, so it needs a render to pick a change up.
+ // The Appearance sub reads a module cache, not state, so a focus needs a render of its own.
setFocusTick((tick) => tick + 1)
}, [readSyncState])
@@ -153,27 +154,29 @@ export function SettingsScreen({ navigation }: Props) {
[settings.interval, settings.distance, settings.syncInterval, settings.isOfflineMode]
)
- // Both getters read a module cache the Appearance screen refreshes on save, so this costs no
- // bridge call and is not worth a memo: memoising on `preference` alone would keep the units and
- // the time format from the render before the change for the rest of the session.
+ // No memo: the getters read a module cache, and keying on `preference` alone would freeze units and clock.
const appearanceSummary = appearanceRowSub(preference, getUnitSystem(), getTimeFormat())
- const profileSummary = profileCount === 0 ? "No profiles yet" : profileStateLabel(activeProfileName, tracking)
+ const profileSummary =
+ profileCount === 0 ? t("settings.profiles.none") : profileStateLabel(activeProfileName, tracking)
const inForce = profileCount > 0 && tracking && !!activeProfileName
const serverTint = server.tone === "error" ? colors.error : server.tone === "warning" ? colors.warning : undefined
- const openLink = useCallback(async (url: string, fallback?: string) => {
- try {
- await Linking.openURL(url)
- } catch (err) {
- if (fallback) {
- openLink(fallback)
- return
+ const openLink = useCallback(
+ async (url: string, fallback?: string) => {
+ try {
+ await Linking.openURL(url)
+ } catch (err) {
+ if (fallback) {
+ openLink(fallback)
+ return
+ }
+ logger.error("[SettingsScreen] Failed to open a link:", err)
+ showAlert(t("common.error"), t("settings.linkError"), "error")
}
- logger.error("[SettingsScreen] Failed to open a link:", err)
- showAlert("Error", "Could not open the link.", "error")
- }
- }, [])
+ },
+ [t]
+ )
const isPlayBuild = NativeLocationService.getBuildConfig()?.FLAVOR === "gms"
@@ -181,13 +184,13 @@ export function SettingsScreen({ navigation }: Props) {
<Container>
<ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
<View style={styles.section}>
- <SectionTitle>Tracking</SectionTitle>
+ <SectionTitle>{t("settings.section.tracking")}</SectionTitle>
<Card rows>
<ListItem
testID="nav-connection"
icon={Cloud}
iconColor={serverTint}
- label="Connection"
+ label={t("screen.connection")}
sub={server.rowSub}
subLines={2}
onPress={() => navigation.navigate("Connection")}
@@ -196,7 +199,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-tracking-sync"
icon={Navigation}
- label="Tracking & sync"
+ label={t("screen.trackingSync")}
sub={syncSummary}
onPress={() => navigation.navigate("Tracking & Sync")}
/>
@@ -205,7 +208,7 @@ export function SettingsScreen({ navigation }: Props) {
testID="nav-tracking-profiles"
icon={UserRoundPen}
iconColor={inForce ? colors.success : undefined}
- label="Tracking profiles"
+ label={t("screen.trackingProfiles")}
sub={profileSummary}
onPress={() => navigation.navigate("Tracking Profiles")}
/>
@@ -213,12 +216,12 @@ export function SettingsScreen({ navigation }: Props) {
</View>
<View style={styles.section}>
- <SectionTitle>Display</SectionTitle>
+ <SectionTitle>{t("settings.section.display")}</SectionTitle>
<Card rows>
<ListItem
testID="nav-appearance"
icon={Palette}
- label="Appearance"
+ label={t("screen.appearance")}
sub={appearanceSummary}
onPress={() => navigation.navigate("Appearance")}
/>
@@ -226,7 +229,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-offline-maps"
icon={Map}
- label="Offline maps"
+ label={t("screen.offlineMaps")}
sub={offlineMapsRowSub(offlineAreas)}
onPress={() => navigation.navigate("Offline Maps")}
/>
@@ -234,12 +237,12 @@ export function SettingsScreen({ navigation }: Props) {
</View>
<View style={styles.section}>
- <SectionTitle>Data</SectionTitle>
+ <SectionTitle>{t("settings.section.data")}</SectionTitle>
<Card rows>
<ListItem
testID="nav-data-management"
icon={Database}
- label="Data management"
+ label={t("screen.dataManagement")}
sub={dataRowSub(totalCount, databaseSizeMB)}
onPress={() => navigation.navigate("Data Management")}
/>
@@ -247,7 +250,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-export-import"
icon={ArrowUpDown}
- label="Export & import"
+ label={t("screen.exportImport")}
sub={transferRowSub(autoExport)}
subLines={2}
onPress={() => navigation.navigate("Export & Import")}
@@ -256,7 +259,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-backup-restore"
icon={Archive}
- label="Backup & restore"
+ label={t("screen.backupRestore")}
sub={backupRowSub(lastBackupAt)}
onPress={() => navigation.navigate("Backup & Restore")}
/>
@@ -264,20 +267,20 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-share-setup"
icon={Share2}
- label="Share setup"
- sub="Settings, geofences and profiles as a link"
+ label={t("screen.shareSetup")}
+ sub={t("settings.shareSetup.sub")}
onPress={() => navigation.navigate("Share Setup")}
/>
</Card>
</View>
<View style={styles.section}>
- <SectionTitle>Help</SectionTitle>
+ <SectionTitle>{t("settings.section.help")}</SectionTitle>
<Card rows>
<ListItem
testID="nav-logging"
icon={ScrollText}
- label="Logging"
+ label={t("screen.logging")}
sub={loggingRowSub(fileLogging.enabled, fileLogging.bytes)}
onPress={() => navigation.navigate("Logging")}
/>
@@ -285,7 +288,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-feedback"
icon={MessageCircle}
- label="Feedback & help"
+ label={t("settings.feedback")}
sub="github.com/dietrichmax/colota/issues"
trailingIcon={ExternalLink}
accessibilityRole="link"
@@ -295,7 +298,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-whats-new"
icon={Sparkles}
- label="What's new"
+ label={t("settings.whatsNew")}
sub="colota.app/releases"
trailingIcon={ExternalLink}
accessibilityRole="link"
@@ -305,18 +308,18 @@ export function SettingsScreen({ navigation }: Props) {
</View>
<View style={styles.section}>
- <SectionTitle>About</SectionTitle>
+ <SectionTitle>{t("settings.section.about")}</SectionTitle>
<Card rows>
{isPlayBuild && (
<>
<ListItem
testID="nav-rate"
icon={Star}
- label="Rate the app"
+ label={t("settings.rate")}
sub="Google Play"
trailingIcon={ExternalLink}
accessibilityRole="link"
- accessibilityHint="Opens Colota in Google Play"
+ accessibilityHint={t("settings.rate.hint")}
onPress={() => openLink(PLAY_STORE_MARKET_URL, PLAY_STORE_WEB_URL)}
/>
<Divider tight inset />
@@ -325,7 +328,7 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-support"
icon={Heart}
- label="Say thanks"
+ label={t("settings.thanks")}
sub="mxd.codes/support"
trailingIcon={ExternalLink}
accessibilityRole="link"
@@ -335,8 +338,8 @@ export function SettingsScreen({ navigation }: Props) {
<ListItem
testID="nav-about"
icon={Info}
- label="About"
- sub={`Version ${versionLine(NativeLocationService.getBuildConfig())}`}
+ label={t("screen.aboutColota")}
+ sub={t("settings.version", { version: versionLine(NativeLocationService.getBuildConfig()) })}
onPress={() => navigation.navigate("About Colota")}
/>
</Card>
diff --git a/apps/mobile/src/utils/__tests__/settingsRow.test.ts b/apps/mobile/src/utils/__tests__/settingsRow.test.ts
index c4d50062..3656583f 100644
--- a/apps/mobile/src/utils/__tests__/settingsRow.test.ts
+++ b/apps/mobile/src/utils/__tests__/settingsRow.test.ts
@@ -45,6 +45,10 @@ describe("dataRowSub", () => {
expect(dataRowSub(12480, 3.4213)).toBe("12,480 locations · 3 MB")
})
+ it("words a single location in the singular", () => {
+ expect(dataRowSub(1, 3.4213)).toBe("1 location · 3 MB")
+ })
+
it("words the zero count even when the database has a size", () => {
expect(dataRowSub(0, 0.02)).toBe("No locations recorded")
})
diff --git a/apps/mobile/src/utils/settingsRow.ts b/apps/mobile/src/utils/settingsRow.ts
index efbe3538..a74e3c12 100644
--- a/apps/mobile/src/utils/settingsRow.ts
+++ b/apps/mobile/src/utils/settingsRow.ts
@@ -3,38 +3,36 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import { formatBytes, plural } from "./format"
+import { formatBytes } from "./format"
+import { t } from "../i18n/t"
import type { OfflineAreaInfo } from "../components/features/map/OfflinePackManager"
-/**
- * The subs the Settings hub computes, as pure strings. Every one is a stored value, an on-disk
- * fact or the nouns inside the screen it opens, so a unit test pins the wording without rendering
- * the hub and a new file format cannot drift the row that lists them.
- */
-
/** "3 areas · 118.4 MB", or the count alone when no pack reports a readable size. */
export function offlineMapsRowSub(areas: OfflineAreaInfo[]): string {
- if (areas.length === 0) return "No saved areas"
+ if (areas.length === 0) return t("settings.offlineMaps.none")
const bytes = areas.reduce((sum, area) => sum + (area.sizeBytes ?? 0), 0)
- const count = plural(areas.length, "area")
+ const count = t("settings.offlineMaps.areas", { count: areas.length, n: areas.length.toLocaleString() })
return bytes > 0 ? `${count} · ${formatBytes(bytes)}` : count
}
-/** "File logging on · 2.4 MB". The size only means something while the log is being written. */
+/** "File logging on · 2.4 MB". */
export function loggingRowSub(enabled: boolean, bytes: number): string {
- if (enabled) return `File logging on · ${formatBytes(bytes)}`
- // Switching off stops writing and deletes nothing, so a bare "off" over megabytes of named-zone
- // history implies the data has gone.
- return bytes > 0 ? `File logging off · ${formatBytes(bytes)} kept` : "File logging off"
+ if (enabled) return t("settings.logging.on", { size: formatBytes(bytes) })
+ // Switching off deletes nothing, so a bare "off" would imply the file went with it.
+ return bytes > 0 ? t("settings.logging.offKept", { size: formatBytes(bytes) }) : t("settings.logging.off")
}
/** Formatted exactly as the ledger it opens, so the row and the screen cannot disagree. */
export function dataRowSub(total: number, databaseSizeMB: number): string {
- if (total === 0) return "No locations recorded"
- return `${total.toLocaleString()} locations · ${formatBytes(databaseSizeMB * 1024 * 1024, { decimals: 0 })}`
+ if (total === 0) return t("settings.data.none")
+ return t("settings.data.locations", {
+ count: total,
+ n: total.toLocaleString(),
+ size: formatBytes(databaseSizeMB * 1024 * 1024, { decimals: 0 })
+ })
}
-/** The build a user is running, as `versionLine` and `buildLine` name it after the version. */
+/** The flavor as `versionLine` and `buildLine` print it. */
export function getVariantLabel(flavor: string): string {
switch (flavor) {
case "foss":
@@ -42,21 +40,18 @@ export function getVariantLabel(flavor: string): string {
case "gms":
return "Google Play"
default:
- return flavor || "Unknown"
+ return flavor || t("common.unknown")
}
}
/** "1.16.0 · Google Play": the hub's About row, under the word Version. */
export function versionLine(config: { VERSION_NAME: string; FLAVOR: string } | null): string {
- if (!config) return "Unknown"
+ if (!config) return t("common.unknown")
return `${config.VERSION_NAME} · ${getVariantLabel(config.FLAVOR)}`
}
-/**
- * "1.16.0 (48) · Google Play": the About screen's line, the row's with the version code, which the
- * changelog files, Play's crash reports and F-Droid are keyed by; a versionName has shipped under two codes.
- */
+/** "1.16.0 (48) · Google Play": a versionName has shipped under two codes, so About prints the code. */
export function buildLine(config: { VERSION_NAME: string; VERSION_CODE: number; FLAVOR: string } | null): string {
- if (!config) return "Unknown"
+ if (!config) return t("common.unknown")
return `${config.VERSION_NAME} (${config.VERSION_CODE}) · ${getVariantLabel(config.FLAVOR)}`
}