Skip to content

Colota - Android GPS Location tracker

refactor(i18n): move units and number formatting into the catalog (#916)

Max Dietrichea2bf31f274b
diff --git a/apps/mobile/src/components/features/inspector/LocationTable.tsx b/apps/mobile/src/components/features/inspector/LocationTable.tsx
index 1e7e1854..65ce0e31 100644
--- a/apps/mobile/src/components/features/inspector/LocationTable.tsx
+++ b/apps/mobile/src/components/features/inspector/LocationTable.tsx
@@ -20,6 +20,7 @@ import { formatTime, getSpeedUnit, getTimeFormat } from "../../../utils/geo"
import { size, space, STATE_LAYER_ALPHA } from "../../../constants"
import { Divider } from "../../ui/Divider"
import { t } from "../../../i18n/t"
+import { formatDecimal } from "../../../utils/format"
interface Props {
locations: LocationCoords[]
@@ -58,10 +59,11 @@ function val(v?: number | null, decimals = 0): string {
}
function gap(seconds: number): string {
- if (seconds < 60) return `${seconds}s`
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`
- return `${Math.floor(seconds / 86400)}d ${Math.floor((seconds % 86400) / 3600)}h`
+ const [d, h, m, s] = [t("unit.compact.d"), t("unit.compact.h"), t("unit.compact.min"), t("unit.compact.s")]
+ if (seconds < 60) return `${seconds}${s}`
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}${m} ${seconds % 60}${s}`
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}${h} ${Math.floor((seconds % 3600) / 60)}${m}`
+ return `${Math.floor(seconds / 86400)}${d} ${Math.floor((seconds % 86400) / 3600)}${h}`
}
function timeOf(item: TableRow): string {
@@ -117,7 +119,7 @@ const DataRow = React.memo(
`${val(item.latitude, 5)}, ${val(item.longitude, 5)}`,
t("table.fact.accuracy", { value: val(item.accuracy) }),
item.speed != null
- ? t("table.fact.speed", { value: (item.speed * speedUnit.factor).toFixed(1), unit: speedUnit.unit })
+ ? t("table.fact.speed", { value: formatDecimal(item.speed * speedUnit.factor, 1), unit: speedUnit.unit })
: null,
item.altitude != null ? t("table.fact.altitude", { value: val(item.altitude) }) : null,
item.bearing != null ? t("table.fact.bearing", { value: val(item.bearing) }) : null,
@@ -154,7 +156,7 @@ const DataRow = React.memo(
{val(item.accuracy)}
</Text>
<Text style={[mono, { width: COLUMN_WIDTHS.speed }]} numberOfLines={1}>
- {item.speed != null ? (item.speed * speedUnit.factor).toFixed(1) : "-"}
+ {item.speed != null ? formatDecimal(item.speed * speedUnit.factor, 1) : "-"}
</Text>
<Text style={[mono, { width: COLUMN_WIDTHS.alt }]} numberOfLines={1}>
{val(item.altitude)}
diff --git a/apps/mobile/src/components/features/inspector/PointCard.tsx b/apps/mobile/src/components/features/inspector/PointCard.tsx
index 46921d89..67c4f7d3 100644
--- a/apps/mobile/src/components/features/inspector/PointCard.tsx
+++ b/apps/mobile/src/components/features/inspector/PointCard.tsx
@@ -10,7 +10,7 @@ import { useTheme } from "../../../hooks/useTheme"
import { showPrompt } from "../../../services/modalService"
import { fontSizes, fonts } from "../../../styles/typography"
import { size, space } from "../../../constants"
-import { formatSpeed, formatTime } from "../../../utils/geo"
+import { formatSpeed, formatTime, metersToInput, shortDistanceUnit } from "../../../utils/geo"
import type { LocationCoords } from "../../../types/global"
import { Divider } from "../../ui/Divider"
import { IconButton } from "../../ui/IconButton"
@@ -80,7 +80,7 @@ export function PointCard({ point, note, hasEndpoint, onSplit, onDelete, onClose
<StatRow
icon={Crosshair}
label={t("point.accuracy")}
- value={`±${Math.round(point.accuracy)} m`}
+ value={`±${Math.round(metersToInput(point.accuracy))} ${shortDistanceUnit()}`}
testID="point-accuracy"
/>
</>
@@ -91,7 +91,7 @@ export function PointCard({ point, note, hasEndpoint, onSplit, onDelete, onClose
<StatRow
icon={Mountain}
label={t("point.altitude")}
- value={`${Math.round(point.altitude)} m`}
+ value={`${Math.round(metersToInput(point.altitude))} ${shortDistanceUnit()}`}
testID="point-altitude"
/>
</>
diff --git a/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx
index 0347872e..c4989597 100644
--- a/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx
+++ b/apps/mobile/src/components/features/inspector/__tests__/InspectorDock.test.tsx
@@ -15,6 +15,8 @@ jest.mock("../../../../hooks/useTheme", () => ({
}))
jest.mock("../../../../utils/geo", () => ({
+ metersToInput: (m: number) => m,
+ shortDistanceUnit: () => "m",
formatDistance: (m: number) => `${(m / 1000).toFixed(1)} km`,
spokenDistance: (m: number) => `${(m / 1000).toFixed(1)} kilometres`,
formatDuration: (s: number) => `${Math.round(s / 60)}min`,
diff --git a/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx b/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx
index 9f2bdc45..f7acea93 100644
--- a/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx
+++ b/apps/mobile/src/components/features/inspector/__tests__/PointCard.test.tsx
@@ -15,7 +15,10 @@ jest.mock("../../../../hooks/useTheme", () => ({
useTheme: () => ({ colors: require("@colota/shared").lightColors })
}))
+let mockFeet = false
jest.mock("../../../../utils/geo", () => ({
+ metersToInput: (m: number) => (mockFeet ? m * 3.28084 : m),
+ shortDistanceUnit: () => (mockFeet ? "ft" : "m"),
formatSpeed: (mps: number) => `${(mps * 3.6).toFixed(1)} km/h`,
formatTime: (ts: number, seconds?: boolean) => {
const h = Math.floor(ts / 3600)
@@ -72,6 +75,18 @@ describe("PointCard", () => {
expect(getByLabelText("Close")).toBeTruthy()
})
+ // An imperial user reads feet everywhere else, so metres here would be a second unit on one screen.
+ it("prints accuracy and altitude in the unit the user chose", () => {
+ mockFeet = true
+ try {
+ const { getByLabelText } = renderCard()
+ expect(getByLabelText("Accuracy, ±28 ft")).toBeTruthy()
+ expect(getByLabelText("Altitude, 1353 ft")).toBeTruthy()
+ } finally {
+ mockFeet = false
+ }
+ })
+
it("lists speed, accuracy, altitude and sync with a seam before each, and the note row last", () => {
const { getByLabelText, UNSAFE_getAllByType } = renderCard()
diff --git a/apps/mobile/src/components/features/map/OfflinePackManager.ts b/apps/mobile/src/components/features/map/OfflinePackManager.ts
index 2f812f45..b53d5ef1 100644
--- a/apps/mobile/src/components/features/map/OfflinePackManager.ts
+++ b/apps/mobile/src/components/features/map/OfflinePackManager.ts
@@ -7,7 +7,8 @@ import { OfflineManager, type OfflinePack } from "@maplibre/maplibre-react-nativ
import { MAP_STYLE_URL_LIGHT as MAP_STYLE_URL } from "../../../constants"
import NativeLocationService from "../../../services/NativeLocationService"
import { logger } from "../../../utils/logger"
-import { formatBytes } from "../../../utils/format"
+import { formatBytes, formatDecimal } from "../../../utils/format"
+import { t } from "../../../i18n/t"
const MIN_ZOOM = 8
const MAX_ZOOM = 14 // mxd.codes / OpenFreeMap caps vector tiles at z14
@@ -113,9 +114,9 @@ export function estimateSizeBytes(ne: [number, number], sw: [number, number]): n
/** Returns a human-readable estimated download size string (e.g. "~45 MB"). */
export function estimateSizeLabel(ne: [number, number], sw: [number, number]): string {
const mb = estimateSizeBytes(ne, sw) / (1024 * 1024)
- if (mb < 1) return `~${(mb * 1024).toFixed(0)} KB`
- if (mb >= 1000) return `~${(mb / 1024).toFixed(1)} GB`
- return `~${mb.toFixed(0)} MB`
+ if (mb < 1) return `~${formatDecimal(mb * 1024, 0)} ${t("unit.KB")}`
+ if (mb >= 1000) return `~${formatDecimal(mb / 1024, 1)} ${t("unit.GB")}`
+ return `~${formatDecimal(mb, 0)} ${t("unit.MB")}`
}
/** Finds a pack by its stored metadata.name (packs are identified by UUID in v11). */
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index 07d208a8..6248f7f6 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -81,6 +81,25 @@
"unit.s": "s",
"unit.min": "min",
"unit.h": "h",
+ "unit.m": "m",
+ "unit.ft": "ft",
+ "unit.km": "km",
+ "unit.mi": "mi",
+ "unit.kmh": "km/h",
+ "unit.mph": "mph",
+ "unit.B": "B",
+ "unit.KB": "KB",
+ "unit.MB": "MB",
+ "unit.GB": "GB",
+ "unit.thousand": "K",
+ "unit.million": "M",
+ "unit.km.spoken": "{{n}} kilometres",
+ "unit.mi.spoken": "{{n}} miles",
+ "unit.compact.d": "d",
+ "unit.compact.h": "h",
+ "unit.compact.min": "m",
+ "unit.compact.s": "s",
+ "common.never": "Never",
"unit.points": "points",
"validation.wholeNumber": "A whole number",
"validation.atLeast": "At least {{min}} {{unit}}",
diff --git a/apps/mobile/src/screens/TripDetailScreen.tsx b/apps/mobile/src/screens/TripDetailScreen.tsx
index 332b3965..60a48d5a 100644
--- a/apps/mobile/src/screens/TripDetailScreen.tsx
+++ b/apps/mobile/src/screens/TripDetailScreen.tsx
@@ -24,7 +24,7 @@ import { ExportFormatDialog } from "../components/ui/ExportFormatDialog"
import { InspectorDock } from "../components/features/inspector/InspectorDock"
import { InteractiveLineChart } from "../components/features/inspector/InteractiveLineChart"
import { getTripColor, computeTripStats, buildBoundaryOverrideMap, splitBlockedReason } from "../utils/trips"
-import { formatDate, formatDistance, formatDuration, formatSpeed, formatTime } from "../utils/geo"
+import { formatDate, formatDistance, formatDuration, formatShortDistance, formatSpeed, formatTime } from "../utils/geo"
import { EXPORT_FORMATS, type ExportFormat } from "../utils/exportConverters"
import { size, space } from "../constants"
import { showAlert, showConfirm } from "../services/modalService"
@@ -359,7 +359,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
<StatRow
icon={TrendingUp}
label={t("tripDetail.elevGain")}
- value={`${Math.round(stats.elevationGain)}m`}
+ value={formatShortDistance(stats.elevationGain)}
/>
</>
)}
@@ -369,7 +369,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
<StatRow
icon={TrendingDown}
label={t("tripDetail.elevLoss")}
- value={`${Math.round(stats.elevationLoss)}m`}
+ value={formatShortDistance(stats.elevationLoss)}
/>
</>
)}
@@ -398,7 +398,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
color={colors.primary}
textColor={colors.text}
backgroundColor={colors.card}
- formatValue={(v) => formatSpeed(v).replace(/\.\d+/, "")}
+ formatValue={(v) => formatSpeed(v, 0)}
activeIndex={chartActiveIndex}
onActiveIndexChange={setChartActiveIndex}
/>
@@ -420,7 +420,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
<View style={styles.chartTitleRow}>
<SectionTitle>{t("tripDetail.elevation")}</SectionTitle>
<Text style={[styles.chartRange, { color: colors.textSecondary }]}>
- {Math.round(minElevation)}m - {Math.round(maxElevation)}m
+ {formatShortDistance(minElevation)} - {formatShortDistance(maxElevation)}
</Text>
</View>
<Card style={styles.chartCard}>
@@ -429,7 +429,7 @@ export function TripDetailScreen({ route, navigation }: RootScreenProps<"Trip De
color={colors.primary}
textColor={colors.text}
backgroundColor={colors.card}
- formatValue={(v) => `${Math.round(v)}m`}
+ formatValue={formatShortDistance}
activeIndex={chartActiveIndex}
onActiveIndexChange={setChartActiveIndex}
/>
diff --git a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
index 57f0633c..a15d4a3f 100644
--- a/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SetupImportScreen.test.tsx
@@ -17,6 +17,7 @@ const mockDeleteProfile = jest.fn().mockResolvedValue(true)
const mockNavigate = jest.fn()
const mockShowAlert = jest.fn()
let mockCurrentEndpoint = ""
+let mockUnitSystem = "metric"
jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
@@ -29,7 +30,8 @@ jest.mock("../../services/NativeLocationService", () => ({
deleteGeofence: (...args: any[]) => mockDeleteGeofence(...args),
createProfile: (...args: any[]) => mockCreateProfile(...args),
getProfiles: (...args: any[]) => mockGetProfiles(...args),
- deleteProfile: (...args: any[]) => mockDeleteProfile(...args)
+ deleteProfile: (...args: any[]) => mockDeleteProfile(...args),
+ getSetting: (key: string) => Promise.resolve(key === "unitSystem" ? mockUnitSystem : "")
}
}))
@@ -104,6 +106,7 @@ jest.mock("../../utils/logger", () => ({
}))
import { SetupImportScreen } from "../SetupImportScreen"
+import { loadDisplayPreferences } from "../../utils/geo"
// --- Helpers ---
@@ -122,9 +125,11 @@ function renderScreen(configParam?: string) {
// --- Tests ---
-beforeEach(() => {
+beforeEach(async () => {
jest.clearAllMocks()
mockCurrentEndpoint = ""
+ mockUnitSystem = "metric"
+ await loadDisplayPreferences()
})
describe("SetupImportScreen", () => {
@@ -159,20 +164,40 @@ describe("SetupImportScreen", () => {
it("parses tracking settings", () => {
const { getByText } = renderScreen(encode({ interval: 10, distance: 5, syncInterval: 0 }))
- expect(getByText("10s")).toBeTruthy()
+ expect(getByText("10 s")).toBeTruthy()
expect(getByText("5m")).toBeTruthy()
expect(getByText("Instant")).toBeTruthy()
})
+ // The user judges the link by these values, so they read as the settings screens print them, not as stored ids.
+ it("prints durations, the sync condition and the auth method the way the settings screens do", () => {
+ const { getByText } = renderScreen(
+ encode({ syncInterval: 300, syncCondition: "wifi_any", auth: { type: "basic", username: "u" } })
+ )
+ expect(getByText("5 min")).toBeTruthy()
+ expect(getByText("Wi-Fi or Ethernet")).toBeTruthy()
+ expect(getByText("Basic auth")).toBeTruthy()
+ })
+
+ it("prints distances in the unit the user chose", async () => {
+ mockUnitSystem = "imperial"
+ await loadDisplayPreferences()
+ const { getByText } = renderScreen(encode({ distance: 100 }))
+ expect(getByText("328 ft")).toBeTruthy()
+ })
+
it("parses API settings", () => {
const { getByText } = renderScreen(encode({ apiTemplate: "owntracks", httpMethod: "POST" }))
- expect(getByText("owntracks")).toBeTruthy()
+ expect(getByText("OwnTracks")).toBeTruthy()
expect(getByText("POST")).toBeTruthy()
})
it("parses auth settings with masked token", () => {
- const { getByText } = renderScreen(encode({ auth: { type: "bearer", bearerToken: "abcdefghijkl" } }))
- expect(getByText("bearer")).toBeTruthy()
+ const { getByText, getAllByText } = renderScreen(
+ encode({ auth: { type: "bearer", bearerToken: "abcdefghijkl" } })
+ )
+ // The method's value and the token row's label read the same.
+ expect(getAllByText("Bearer token")).toHaveLength(2)
// Token should be masked: first 4 + dots + last 4
expect(getByText(/abcd.*ijkl/)).toBeTruthy()
})
diff --git a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx
index 7e48436c..2f41e6a8 100644
--- a/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/TripDetailScreen.test.tsx
@@ -123,6 +123,7 @@ import NativeLocationService from "../../services/NativeLocationService"
import { showConfirm, showAlert, showPrompt } from "../../services/modalService"
import { BOUNDARY_ACTION_SPLIT } from "../../types/global"
import { space, size } from "../../constants"
+import { loadDisplayPreferences } from "../../utils/geo"
function makeTrip(pointCount: number): Trip {
const locations = Array.from({ length: pointCount }, (_, i) => ({
@@ -382,3 +383,25 @@ describe("TripDetailScreen - header and stepper", () => {
expect(bar.getByLabelText("Delete trip")).toBeTruthy()
})
})
+
+describe("TripDetailScreen - elevation", () => {
+ afterEach(async () => {
+ ;(NativeLocationService.getSetting as jest.Mock).mockResolvedValue("")
+ await loadDisplayPreferences()
+ })
+
+ // The speed and distance rows already follow the unit setting, so metres here would mix two units on one card.
+ it("prints the elevation range in the unit the user chose", async () => {
+ ;(NativeLocationService.getSetting as jest.Mock).mockImplementation((key: string) =>
+ Promise.resolve(key === "unitSystem" ? "imperial" : "")
+ )
+ await loadDisplayPreferences()
+ const trip = makeTrip(6)
+ trip.locations = trip.locations.map((l, i) => ({ ...l, altitude: 100 + i * 60 }))
+
+ const { getByText } = render(<TripDetailScreen {...makeProps(trip)} />)
+ await act(async () => {})
+
+ expect(getByText(/^\d+ ft - \d+ ft$/)).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/utils/__tests__/format.test.ts b/apps/mobile/src/utils/__tests__/format.test.ts
index 3068557d..e204220e 100644
--- a/apps/mobile/src/utils/__tests__/format.test.ts
+++ b/apps/mobile/src/utils/__tests__/format.test.ts
@@ -1,4 +1,4 @@
-import { formatBytes, formatCount } from "../format"
+import { formatBytes, formatCount, formatDecimal, formatExportDateTime } from "../format"
describe("formatCount", () => {
it("keeps counts that fit a stat column exact to the digit", () => {
@@ -60,3 +60,17 @@ describe("formatBytes", () => {
expect(formatBytes(524.288, { locale: "en-US" })).toBe("524 B")
})
})
+
+describe("formatDecimal", () => {
+ // Distances, speeds and sizes share it, so every number in the app takes the device's separator.
+ it("uses the locale's decimal separator and never groups thousands", () => {
+ expect(formatDecimal(1234.56, 1, "en-US")).toBe("1234.6")
+ expect(formatDecimal(1234.56, 1, "de-DE")).toBe("1234,6")
+ })
+})
+
+describe("formatExportDateTime", () => {
+ it("says Never for an export that has not run, rather than printing 1970", () => {
+ expect(formatExportDateTime(0)).toBe("Never")
+ })
+})
diff --git a/apps/mobile/src/utils/__tests__/geo.test.ts b/apps/mobile/src/utils/__tests__/geo.test.ts
index e6c255c3..494d54da 100644
--- a/apps/mobile/src/utils/__tests__/geo.test.ts
+++ b/apps/mobile/src/utils/__tests__/geo.test.ts
@@ -9,6 +9,7 @@ import {
inputToMeters,
metersToInput,
getSpeedUnit,
+ spokenDistance,
speedToInput,
inputToSpeed,
loadDisplayPreferences,
@@ -199,6 +200,25 @@ describe("getSpeedUnit", () => {
await setPreferences("imperial", "")
expect(getSpeedUnit()).toEqual({ factor: 2.23694, unit: "mph" })
})
+
+ // Callers list it in dependency arrays, so a new object per call would re-run their effects.
+ it("hands back the same object while the unit stays the same", async () => {
+ await setPreferences("metric", "")
+ expect(getSpeedUnit()).toBe(getSpeedUnit())
+ })
+})
+
+describe("spokenDistance", () => {
+ afterEach(async () => {
+ await setPreferences("", "")
+ })
+
+ it("spells the unit out, since a screen reader reads km as letters", async () => {
+ await setPreferences("metric", "")
+ expect(spokenDistance(12345)).toBe("12.3 kilometres")
+ await setPreferences("imperial", "")
+ expect(spokenDistance(12345)).toBe("7.7 miles")
+ })
})
describe("shortDistanceUnit", () => {
diff --git a/apps/mobile/src/utils/format.ts b/apps/mobile/src/utils/format.ts
index 8f1a687b..18fd412e 100644
--- a/apps/mobile/src/utils/format.ts
+++ b/apps/mobile/src/utils/format.ts
@@ -3,17 +3,22 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import { t } from "../i18n/t"
+
+/** A fixed number of decimals in the device locale's separator, ungrouped. */
+export const formatDecimal = (n: number, decimals: number, locale?: string): string =>
+ n.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals, useGrouping: false })
+
/** B, KB, MB or GB in the device locale's decimal separator, ungrouped, with one decimal unless `decimals` says otherwise. */
export const formatBytes = (
bytes: number,
{ decimals = 1, locale }: { decimals?: number; locale?: string } = {}
): string => {
- const scaled = (n: number) =>
- n.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals, useGrouping: false })
- if (bytes < 1024) return `${Math.round(bytes)} B`
- if (bytes < 1024 ** 2) return `${scaled(bytes / 1024)} KB`
- if (bytes < 1024 ** 3) return `${scaled(bytes / 1024 ** 2)} MB`
- return `${scaled(bytes / 1024 ** 3)} GB`
+ const scaled = (n: number) => formatDecimal(n, decimals, locale)
+ if (bytes < 1024) return `${Math.round(bytes)} ${t("unit.B")}`
+ if (bytes < 1024 ** 2) return `${scaled(bytes / 1024)} ${t("unit.KB")}`
+ if (bytes < 1024 ** 3) return `${scaled(bytes / 1024 ** 2)} ${t("unit.MB")}`
+ return `${scaled(bytes / 1024 ** 3)} ${t("unit.GB")}`
}
/**
@@ -22,13 +27,10 @@ export const formatBytes = (
*/
export const formatCount = (count: number): string => {
if (count < 100_000) return count.toLocaleString()
- if (count < 1_000_000) return `${Math.floor(count / 1_000)}K`
- return `${(count / 1_000_000).toFixed(1)}M`
+ if (count < 1_000_000) return `${Math.floor(count / 1_000)}${t("unit.thousand")}`
+ return `${formatDecimal(count / 1_000_000, 1)}${t("unit.million")}`
}
-/** "1 file", "12 files". The count carries thousands separators; the noun takes the s. */
-export const plural = (n: number, noun: string): string => `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`
-
/** Clamps `value` to the inclusive range [min, max]. */
export const clamp = (value: number, min: number, max: number): number => Math.max(min, Math.min(max, value))
@@ -37,7 +39,7 @@ export const pad2 = (n: number): string => n.toString().padStart(2, "0")
/** Locale-independent YYYY-MM-DD HH:mm (24h). Empty epoch -> "Never". */
export const formatExportDateTime = (epochSeconds: number): string => {
- if (epochSeconds === 0) return "Never"
+ if (epochSeconds === 0) return t("common.never")
const d = new Date(epochSeconds * 1000)
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
}
diff --git a/apps/mobile/src/utils/geo.ts b/apps/mobile/src/utils/geo.ts
index 19edc0c0..1a993aa0 100644
--- a/apps/mobile/src/utils/geo.ts
+++ b/apps/mobile/src/utils/geo.ts
@@ -4,6 +4,8 @@
*/
import NativeLocationService from "../services/NativeLocationService"
+import { formatDecimal } from "./format"
+import { t } from "../i18n/t"
const EARTH_RADIUS_METERS = 6_371_000
const FEET_PER_METER = 3.28084
@@ -93,19 +95,29 @@ function usesMiles(): boolean {
// -- Formatting functions --
/** Format m/s into a human-readable speed string. */
-export function formatSpeed(metersPerSecond: number): string {
+export function formatSpeed(metersPerSecond: number, decimals = 1): string {
if (usesMiles()) {
const mph = metersPerSecond * MPH_PER_MPS
- return `${mph.toFixed(1)} mph`
+ return `${formatDecimal(mph, decimals)} ${t("unit.mph")}`
}
const kmh = metersPerSecond * 3.6
- return `${kmh.toFixed(1)} km/h`
+ return `${formatDecimal(kmh, decimals)} ${t("unit.kmh")}`
}
/** Return the speed unit info (used by TrackMap). */
-// Module-level so the identity tracks the unit, and a caller can read it during render.
-const MPH = Object.freeze({ factor: MPH_PER_MPS, unit: "mph" })
-const KMH = Object.freeze({ factor: 3.6, unit: "km/h" })
+// Module-level so the identity tracks the unit; the getter resolves the label at read time.
+const MPH = Object.freeze({
+ factor: MPH_PER_MPS,
+ get unit() {
+ return t("unit.mph")
+ }
+})
+const KMH = Object.freeze({
+ factor: 3.6,
+ get unit() {
+ return t("unit.kmh")
+ }
+})
export function getSpeedUnit(): { factor: number; unit: string } {
return usesMiles() ? MPH : KMH
@@ -116,14 +128,15 @@ export function formatDuration(seconds: number): string {
const s = Math.max(0, seconds)
const hours = Math.floor(s / 3600)
const minutes = Math.floor((s % 3600) / 60)
- if (hours > 0) return `${hours}h ${minutes}min`
- return `${minutes}min`
+ if (hours > 0) return `${hours}${t("unit.h")} ${minutes}${t("unit.min")}`
+ return `${minutes}${t("unit.min")}`
}
/** Format a Unix-seconds timestamp as a localized time string. */
/** The unit spelled out, for a screen reader. */
export function spokenDistance(meters: number): string {
- return formatDistance(meters).replace(/ km$/, " kilometres").replace(/ mi$/, " miles")
+ if (usesMiles()) return t("unit.mi.spoken", { n: formatDecimal(meters / 1609.344, 1) })
+ return t("unit.km.spoken", { n: formatDecimal(meters / 1000, 1) })
}
/** The app's clock, with the format passed in, so a sample of a format cannot drift from it. */
@@ -152,19 +165,19 @@ export function formatDate(unixSeconds: number): string {
/** Format meters as a long distance string (e.g. "12.3 km" / "7.6 mi"). */
export function formatDistance(meters: number): string {
- if (usesMiles()) return `${(meters / 1609.344).toFixed(1)} mi`
- return `${(meters / 1000).toFixed(1)} km`
+ if (usesMiles()) return `${formatDecimal(meters / 1609.344, 1)} ${t("unit.mi")}`
+ return `${formatDecimal(meters / 1000, 1)} ${t("unit.km")}`
}
/** Format meters as a short distance string (e.g. "50m" / "164 ft"). */
export function formatShortDistance(meters: number): string {
- if (usesMiles()) return `${Math.round(meters * FEET_PER_METER)} ft`
- return `${Math.round(meters)}m`
+ if (usesMiles()) return `${Math.round(meters * FEET_PER_METER)} ${t("unit.ft")}`
+ return `${Math.round(meters)}${t("unit.m")}`
}
/** Returns the short distance unit label for input fields ("m" or "ft"). */
export function shortDistanceUnit(): string {
- return usesMiles() ? "ft" : "m"
+ return usesMiles() ? t("unit.ft") : t("unit.m")
}
/** A stored speed in m/s as the whole number the speed field shows, in the user's unit. */
diff --git a/apps/mobile/src/utils/offlineArea.ts b/apps/mobile/src/utils/offlineArea.ts
index 349c0a6c..41de0136 100644
--- a/apps/mobile/src/utils/offlineArea.ts
+++ b/apps/mobile/src/utils/offlineArea.ts
@@ -10,7 +10,7 @@ import type {
OfflineAreaInfo,
OfflinePackStatus
} from "../components/features/map/OfflinePackManager"
-import { formatBytes } from "./format"
+import { formatBytes, formatDecimal } from "./format"
import { formatDateWithYear } from "./geo"
import { t } from "../i18n/t"
@@ -128,7 +128,7 @@ export function deleteAreaConfirm(name: string, sizeBytes: number | null, isLast
}
export function storageMessage(estimate: Estimate, availableMB: number): string {
- const free = availableMB.toFixed(1)
+ const free = formatDecimal(availableMB, 1)
return estimate.large
? t("offline.storage.atLeast", { size: estimate.label, free })
: t("offline.storage", { size: estimate.label, free })
diff --git a/apps/mobile/src/utils/setupConfig.ts b/apps/mobile/src/utils/setupConfig.ts
index 84b71055..002a99b9 100644
--- a/apps/mobile/src/utils/setupConfig.ts
+++ b/apps/mobile/src/utils/setupConfig.ts
@@ -20,9 +20,20 @@ import {
type Geofence,
type TrackingProfile,
type ProfileConditionType,
- type AuthType
+ type AuthType,
+ type SyncCondition
} from "../types/global"
import { t } from "../i18n/t"
+import type { TranslationKey } from "../i18n/options"
+import { formatDuration, syncIntervalLabel } from "./dashboardState"
+import { formatShortDistance } from "./geo"
+
+const SYNC_CONDITION_KEYS: Record<SyncCondition, TranslationKey> = {
+ any: "trackingSync.condition.any",
+ wifi_any: "trackingSync.condition.wifiAny",
+ wifi_ssid: "trackingSync.condition.wifiSsid",
+ vpn: "trackingSync.condition.vpn"
+}
export type ImportGeofence = Omit<Geofence, "id" | "createdAt">
export type ImportProfile = Omit<TrackingProfile, "id" | "createdAt">
@@ -120,7 +131,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "interval",
label: t("setup.field.interval"),
- value: `${obj.interval}${t("unit.s")}`,
+ value: formatDuration(obj.interval),
category: "tracking"
})
}
@@ -130,7 +141,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "distanceThreshold",
label: t("setup.field.distanceThreshold"),
- value: `${obj.distance}m`,
+ value: formatShortDistance(obj.distance),
category: "tracking"
})
}
@@ -140,7 +151,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "syncInterval",
label: t("setup.field.syncInterval"),
- value: obj.syncInterval === 0 ? t("syncInterval.instant") : `${obj.syncInterval}${t("unit.s")}`,
+ value: syncIntervalLabel(obj.syncInterval),
category: "tracking"
})
}
@@ -150,7 +161,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "retryInterval",
label: t("setup.field.retryInterval"),
- value: `${obj.retryInterval}${t("unit.s")}`,
+ value: formatDuration(obj.retryInterval),
category: "tracking"
})
}
@@ -160,7 +171,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "accuracyThreshold",
label: t("setup.field.accuracyThreshold"),
- value: `${obj.accuracyThreshold}m`,
+ value: formatShortDistance(obj.accuracyThreshold),
category: "tracking"
})
}
@@ -190,7 +201,9 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "syncCondition",
label: t("setup.field.syncCondition"),
- value: obj.syncCondition,
+ value: Object.prototype.hasOwnProperty.call(SYNC_CONDITION_KEYS, obj.syncCondition)
+ ? t(SYNC_CONDITION_KEYS[obj.syncCondition as SyncCondition])
+ : obj.syncCondition,
category: "tracking"
})
}
@@ -208,7 +221,15 @@ export function validateConfig(raw: unknown): ValidationResult {
VALID_API_TEMPLATES.includes(obj.apiTemplate as ApiTemplateName)
) {
settings.apiTemplate = obj.apiTemplate as ApiTemplateName
- entries.push({ field: "apiTemplate", label: t("setup.field.apiTemplate"), value: obj.apiTemplate, category: "api" })
+ entries.push({
+ field: "apiTemplate",
+ label: t("setup.field.apiTemplate"),
+ value:
+ obj.apiTemplate === "custom"
+ ? t("common.custom")
+ : API_TEMPLATES[obj.apiTemplate as Exclude<ApiTemplateName, "custom">].label,
+ category: "api"
+ })
}
if (
@@ -229,7 +250,7 @@ export function validateConfig(raw: unknown): ValidationResult {
entries.push({
field: "dawarichMode",
label: t("setup.field.dawarichMode"),
- value: obj.dawarichMode,
+ value: t(`requestFormat.dawarich.${obj.dawarichMode as DawarichMode}`),
category: "api"
})
}
@@ -293,7 +314,12 @@ export function validateConfig(raw: unknown): ValidationResult {
if ("type" in authObj && typeof authObj.type === "string" && VALID_AUTH_TYPES.includes(authObj.type as AuthType)) {
auth.authType = authObj.type as AuthType
- entries.push({ field: "authType", label: t("setup.field.authType"), value: authObj.type, category: "auth" })
+ entries.push({
+ field: "authType",
+ label: t("setup.field.authType"),
+ value: t(`auth.${authObj.type as AuthType}`),
+ category: "auth"
+ })
}
if ("username" in authObj && typeof authObj.username === "string" && authObj.username.length > 0) {
@@ -369,7 +395,7 @@ export function validateConfig(raw: unknown): ValidationResult {
heartbeatEnabled: typeof g.heartbeatEnabled === "boolean" ? g.heartbeatEnabled : false,
heartbeatIntervalMinutes: typeof g.heartbeatIntervalMinutes === "number" ? g.heartbeatIntervalMinutes : 15
})
- entries.push({ field: "geofence", label: g.name, value: `${g.radius}m`, category: "geofence" })
+ entries.push({ field: "geofence", label: g.name, value: formatShortDistance(g.radius), category: "geofence" })
}
}
@@ -420,7 +446,7 @@ export function validateConfig(raw: unknown): ValidationResult {
enabled: typeof p.enabled === "boolean" ? p.enabled : true,
condition
})
- entries.push({ field: "profile", label: p.name, value: `${p.interval}${t("unit.s")}`, category: "profile" })
+ entries.push({ field: "profile", label: p.name, value: formatDuration(p.interval), category: "profile" })
}
}
diff --git a/fastlane/metadata/android/en-US/changelogs/51.txt b/fastlane/metadata/android/en-US/changelogs/51.txt
index 882ff5d1..42b587f6 100644
--- a/fastlane/metadata/android/en-US/changelogs/51.txt
+++ b/fastlane/metadata/android/en-US/changelogs/51.txt
@@ -3,3 +3,4 @@
- Placing a geofence shows where you are and the locate button puts the zone there
- A tracking profile's sync interval takes effect as soon as the profile switches
- Tracking that cannot restart after a reboot because location services are off shows a tap-to-resume notification and resumes by itself within about 10 minutes of turning them on
+- Elevation and a point's accuracy and altitude follow the Units setting, and distances and speeds use your device's decimal separator