Colota - Android GPS Location tracker
refactor(i18n): move the Connection screen into the catalog (#901)
Max Dietrich261ac8d070d8
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsxindex 00760312..b1a97d5b 100644--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx@@ -42,6 +42,7 @@ import {Toggle} from "../../index"import { showChoice } from "../../../services/modalService"+import { useTranslation } from "../../../i18n/useTranslation"interface ConnectionSettingsProps {settings: Settings@@ -69,12 +70,6 @@ const SERVER_ICONS: Record<ServerIcon, LucideIcon> = {check: CircleCheckBig}-const SCHEME_ERROR = "Starts with http:// or https:// and names a host."-const PUBLIC_HTTP_ERROR = "http is refused for a public host. Use https."-const PRIVATE_HTTP_WARNING = "Not encrypted: plain http on a private host."-const KEY_WARNING =- "This address carries a key. It is stored with settings, not encrypted, and included in setup links. Use a header where the server allows it."-export function ConnectionSettings({settings,onSettingsLocal,@@ -87,6 +82,7 @@ export function ConnectionSettings({navigation}: ConnectionSettingsProps) {const { colors } = useTheme()+ const { t } = useTranslation()const [draft, setDraft] = useState(settings.endpoint)const [validation, setValidation] = useState<Validation>({ warnings: [] })const [test, setTest] = useState<TestState | null>(null)@@ -95,14 +91,14 @@ export function ConnectionSettings({setDraft(settings.endpoint)}, [settings.endpoint])- const tone = (t: ServerTone) =>- t === "success"+ const tone = (value: ServerTone) =>+ value === "success"? colors.success- : t === "error"+ : value === "error"? colors.error- : t === "warning"+ : value === "warning"? colors.warning- : t === "light"+ : value === "light"? colors.textLight: colors.textSecondary@@ -118,13 +114,16 @@ export function ConnectionSettings({if (stats.queued > 0) {const hasEndpoint = !!settings.endpointconst buttons = [- ...(hasEndpoint ? [{ text: "Sync first", style: "primary" as const }] : []),- { text: "Keep in queue", style: "secondary" as const },- { text: "Cancel", style: "secondary" as const }+ ...(hasEndpoint ? [{ text: t("connection.offline.syncFirst"), style: "primary" as const }] : []),+ { text: t("connection.offline.keep"), style: "secondary" as const },+ { text: t("common.cancel"), style: "secondary" as const }]const choice = await showChoice({- title: "Unsent locations",- message: `You have ${stats.queued} locations waiting to sync. What would you like to do?`,+ title: t("connection.offline.unsent.title"),+ message: t("connection.offline.unsent.message", {+ count: stats.queued,+ n: stats.queued.toLocaleString()+ }),buttons})const action = hasEndpoint@@ -148,7 +147,7 @@ export function ConnectionSettings({}apply({ ...settings, isOfflineMode: enabled })},- [settings, onSettingsLocal, onSettingsChange]+ [settings, onSettingsLocal, onSettingsChange, t])const handleDraftChange = (text: string) => {@@ -171,28 +170,28 @@ export function ConnectionSettings({}if (text === "") return store([])if (!isEndpointAllowed(text)) {- setValidation({ error: SCHEME_ERROR, warnings: [] })+ setValidation({ error: t("connection.endpoint.scheme"), warnings: [] })return false}- const warnings = endpointCarriesKey(text) ? [KEY_WARNING] : []+ const warnings = endpointCarriesKey(text) ? [t("connection.endpoint.key")] : []if (text.startsWith("http://")) {const isPrivate = await NativeLocationService.isPrivateEndpoint(text)if (!isPrivate) {- setValidation({ error: PUBLIC_HTTP_ERROR, warnings: [] })+ setValidation({ error: t("connection.endpoint.publicHttp"), warnings: [] })return false}- return store([PRIVATE_HTTP_WARNING, ...warnings])+ return store([t("connection.endpoint.privateHttp"), ...warnings])}return store(warnings)- }, [draft, settings, onSettingsLocal, onSettingsChange])+ }, [draft, settings, onSettingsLocal, onSettingsChange, t])const draftPasses = draft.trim() !== "" && isEndpointAllowed(draft.trim()) && !validation.errorconst testBlocker = !draft.trim()- ? "Enter a server endpoint to test."+ ? t("connection.test.noEndpoint"): !draftPasses- ? "Fix the address above to test."+ ? t("connection.test.fixAddress"): !hasFix- ? "Needs one recorded location to send. Start tracking first."+ ? t("connection.test.needsFix"): nullconst handleTestEndpoint = useCallback(async () => {@@ -204,7 +203,7 @@ export function ConnectionSettings({try {const recentLocation = await NativeLocationService.getMostRecentLocation()if (!recentLocation) {- setTest({ kind: "done", ok: false, status: 0, at: Date.now(), message: "No recorded location to send." })+ setTest({ kind: "done", ok: false, status: 0, at: Date.now(), message: t("connection.test.noLocation") })return}@@ -236,7 +235,7 @@ export function ConnectionSettings({ok: false,status: 0,at: Date.now(),- message: "Local network permission required to reach this server"+ message: t("connection.test.localNetwork")})return}@@ -259,22 +258,30 @@ export function ConnectionSettings({ok: result.ok,status: result.status,at: Date.now(),- message: result.ok ? undefined : result.errorMessage || `Server returned ${result.status}`+ message: result.ok+ ? undefined+ : result.errorMessage || t("connection.test.serverReturned", { status: result.status })})} catch (err: any) {- const msg = err?.message || "Unknown error"+ const msg = err?.message || t("common.unknownError")logger.warn("[ConnectionSettings] Test failed:", err?.name, msg)- setTest({ kind: "done", ok: false, status: 0, at: Date.now(), message: `Connection failed: ${msg}` })+ setTest({+ kind: "done",+ ok: false,+ status: 0,+ at: Date.now(),+ message: t("connection.test.failed", { message: msg })+ })}- }, [testBlocker, commitDraft, draft, settings])+ }, [testBlocker, commitDraft, draft, settings, t])const example = endpointExample(settings.apiTemplate, settings.dawarichMode)- const helper = "https for public hosts, http only for private hosts."+ const helper = t("connection.endpoint.helper")const ServerGlyph = SERVER_ICONS[server.icon]return (<View>- <SectionTitle>Server</SectionTitle>+ <SectionTitle>{t("connection.section.server")}</SectionTitle><Card rows><StateLineicon={ServerGlyph}@@ -284,9 +291,9 @@ export function ConnectionSettings({testID="server-state"/><Divider tight />- <SettingRow label="Offline mode" hint="Locations stay on this device and nothing is sent.">+ <SettingRow label={t("connection.offline")} hint={t("connection.offline.hint")}><Toggle- accessibilityLabel="Offline mode"+ accessibilityLabel={t("connection.offline")}value={settings.isOfflineMode}onValueChange={handleOfflineModeChange}/>@@ -300,7 +307,7 @@ export function ConnectionSettings({<View style={styles.block}><View><TextField- label="Server endpoint"+ label={t("connection.endpoint")}testID="endpoint-input"monovalue={draft}@@ -325,7 +332,7 @@ export function ConnectionSettings({<View><Buttonicon={Radio}- title="Test connection"+ title={t("connection.test")}onPress={handleTestEndpoint}disabled={testBlocker !== null}loading={test?.kind === "testing"}@@ -338,8 +345,8 @@ export function ConnectionSettings({<StateLineicon={<ActivityIndicator size="small" color={colors.textLight} />}iconColor={colors.textLight}- label="Testing"- caption="Sending your latest location"+ label={t("connection.test.testing")}+ caption={t("connection.test.sending")}testID="test-result"/>)}@@ -348,8 +355,8 @@ export function ConnectionSettings({<StateLineicon={test.ok ? CircleCheckBig : CircleAlert}iconColor={test.ok ? colors.success : colors.error}- label={test.ok ? "Reachable" : "Not reachable"}- caption={`${test.status > 0 ? `HTTP ${test.status}` : "No response"} · ${formatTime(Math.floor(test.at / 1000))}`}+ label={test.ok ? t("connection.test.reachable") : t("connection.test.notReachable")}+ caption={`${test.status > 0 ? t("connection.test.http", { status: test.status }) : t("connection.test.noResponse")} · ${formatTime(Math.floor(test.at / 1000))}`}testID="test-result"/>{!test.ok && test.message ? <FieldMessage variant="error">{test.message}</FieldMessage> : null}@@ -362,12 +369,12 @@ export function ConnectionSettings({{!settings.isOfflineMode && (<>- <SectionTitle style={styles.groupTop}>Server details</SectionTitle>+ <SectionTitle style={styles.groupTop}>{t("connection.section.details")}</SectionTitle><Card rows><ListItemtestID="nav-request-format"icon={Braces}- label="Request format"+ label={t("screen.requestFormat")}sub={requestSummary}onPress={() => navigation.navigate("Request Format")}/>@@ -375,7 +382,7 @@ export function ConnectionSettings({<ListItemtestID="nav-auth-settings"icon={KeyRound}- label="Authentication"+ label={t("screen.authSettings")}sub={authSummary}onPress={() => navigation.navigate("Auth Settings")}/>@@ -383,7 +390,7 @@ export function ConnectionSettings({<ListItemtestID="nav-mtls-settings"icon={ShieldCheck}- label="Client certificate"+ label={t("screen.mtlsSettings")}sub={certificateSummary}onPress={() => navigation.navigate("mTLS Settings")}/>diff --git a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsxindex 2f311913..a2ba9ac4 100644--- a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx+++ b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx@@ -330,6 +330,20 @@ describe("ConnectionSettings", () => {expect(onSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))})+ it("counts a single unsent location in the singular", async () => {+ mockGetStats.mockResolvedValue({ queued: 1, sent: 50, total: 51, today: 5, databaseSizeMB: 1 })+ mockShowChoice.mockResolvedValue(2)+ const api = renderComponent()++ fireEvent(toggle(api), "valueChange", true)++ await waitFor(() =>+ expect(mockShowChoice).toHaveBeenCalledWith(+ expect.objectContaining({ message: "You have 1 location waiting to sync. What would you like to do?" })+ )+ )+ })+it("does not enable offline when Cancel is chosen", async () => {mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })mockShowChoice.mockResolvedValue(2)diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.jsonindex 2fa33605..71f585bc 100644--- a/apps/mobile/src/i18n/locales/en.json+++ b/apps/mobile/src/i18n/locales/en.json@@ -142,5 +142,68 @@"trackingSync.filter.on": "Drops fixes the chip rates worse than {{threshold}}. Stricter leaves gaps indoors.","trackingSync.filter.off": "Every fix is kept. When on, fixes worse than {{threshold}} are dropped.","trackingSync.threshold": "Accuracy threshold",- "trackingSync.threshold.hint": "At least 1 {{unit}}. The chip's own estimate, often optimistic; lower drops more fixes."+ "trackingSync.threshold.hint": "At least 1 {{unit}}. The chip's own estimate, often optimistic; lower drops more fixes.",+ "server.queued_one": "{{n}} queued",+ "server.queued_other": "{{n}} queued",+ "server.queuedOnDevice_one": "{{n}} queued on this device",+ "server.queuedOnDevice_other": "{{n}} queued on this device",+ "server.savedToday_one": "{{n}} saved today",+ "server.savedToday_other": "{{n}} saved today",+ "server.today_one": "{{n}} today",+ "server.today_other": "{{n}} today",+ "server.nothingSent": "nothing is sent",+ "server.savedLocally": "Offline - saved locally",+ "server.queueEmpty": "queue empty",+ "server.lastSync": "last sync {{when}}",+ "server.lastSyncNever": "last sync never",+ "server.lastSyncStart": "Last sync {{when}}",+ "server.lastSuccess": "last success {{when}}",+ "server.lastSuccessNever": "last success never",+ "server.noNetworkClause": "no network",+ "server.syncFailingClause": "sync failing",+ "server.noServerConfigured": "No server configured",+ "server.word.offline": "Offline mode",+ "server.word.noServer": "No server",+ "server.word.noNetwork": "No network",+ "server.word.failing": "Sync failing",+ "server.word.notSynced": "Not synced yet",+ "server.word.synced": "Synced",+ "server.cert.expiresIn_one": "client certificate expires in {{n}} day",+ "server.cert.expiresIn_other": "client certificate expires in {{n}} days",+ "server.cert.expired": "client certificate expired",+ "auth.none": "None",+ "auth.basic": "Basic auth",+ "auth.bearer": "Bearer token",+ "connection.headers_one": "{{n}} header",+ "connection.headers_other": "{{n}} headers",+ "connection.section.server": "Server",+ "connection.section.details": "Server details",+ "connection.offline": "Offline mode",+ "connection.offline.hint": "Locations stay on this device and nothing is sent.",+ "connection.offline.unsent.title": "Unsent locations",+ "connection.offline.unsent.message_one": "You have {{n}} location waiting to sync. What would you like to do?",+ "connection.offline.unsent.message_other": "You have {{n}} locations waiting to sync. What would you like to do?",+ "connection.offline.syncFirst": "Sync first",+ "connection.offline.keep": "Keep in queue",+ "connection.endpoint": "Server endpoint",+ "connection.endpoint.helper": "https for public hosts, http only for private hosts.",+ "connection.endpoint.scheme": "Starts with http:// or https:// and names a host.",+ "connection.endpoint.publicHttp": "http is refused for a public host. Use https.",+ "connection.endpoint.privateHttp": "Not encrypted: plain http on a private host.",+ "connection.endpoint.key": "This address carries a key. It is stored with settings, not encrypted, and included in setup links. Use a header where the server allows it.",+ "connection.test": "Test connection",+ "connection.test.noEndpoint": "Enter a server endpoint to test.",+ "connection.test.fixAddress": "Fix the address above to test.",+ "connection.test.needsFix": "Needs one recorded location to send. Start tracking first.",+ "connection.test.noLocation": "No recorded location to send.",+ "connection.test.localNetwork": "Local network permission required to reach this server",+ "connection.test.serverReturned": "Server returned {{status}}",+ "connection.test.failed": "Connection failed: {{message}}",+ "connection.test.testing": "Testing",+ "connection.test.sending": "Sending your latest location",+ "connection.test.reachable": "Reachable",+ "connection.test.notReachable": "Not reachable",+ "connection.test.http": "HTTP {{status}}",+ "connection.test.noResponse": "No response",+ "common.unknownError": "Unknown error"}diff --git a/apps/mobile/src/screens/ConnectionScreen.tsx b/apps/mobile/src/screens/ConnectionScreen.tsxindex af5a3c7b..177e3d51 100644--- a/apps/mobile/src/screens/ConnectionScreen.tsx+++ b/apps/mobile/src/screens/ConnectionScreen.tsx@@ -17,20 +17,23 @@ import { describeServer } from "../utils/serverState"import { describeCertificate } from "../utils/certificateState"import { logger } from "../utils/logger"import { space } from "../constants"+import { t } from "../i18n/t"+import { useTranslation } from "../i18n/useTranslation"-const AUTH_WORDS = { none: "None", basic: "Basic auth", bearer: "Bearer token" } as const+const AUTH_KEYS = { none: "auth.none", basic: "auth.basic", bearer: "auth.bearer" } as constexport function authSummary(auth: AuthConfig | null): string {if (!auth) return ""const headers = Object.keys(auth.customHeaders).length- return headers > 0- ? `${AUTH_WORDS[auth.authType]} · ${headers} ${headers === 1 ? "header" : "headers"}`- : AUTH_WORDS[auth.authType]+ const method = t(AUTH_KEYS[auth.authType])+ return headers > 0 ? `${method} · ${t("connection.headers", { count: headers, n: headers })}` : method}export function ConnectionScreen({ navigation }: ScreenProps) {const { settings, setSettings, updateSettingsLocal, restartTracking } = useTracking()const { saving, message: saveMessage, isError: saveIsError, immediateSaveAndRestart } = useAutoSave()+ // Subscribes to language changes; the strings below come from the non-hook t().+ useTranslation()const [stats, setStats] = useState<DatabaseStats | null>(null)const [deviceOnline, setDeviceOnline] = useState(true)@@ -92,7 +95,7 @@ export function ConnectionScreen({ navigation }: ScreenProps) {lastSyncError: stats?.lastSyncError ?? "",certificate})- const template = settings.apiTemplate === "custom" ? "Custom" : API_TEMPLATES[settings.apiTemplate].label+ const template = settings.apiTemplate === "custom" ? t("common.custom") : API_TEMPLATES[settings.apiTemplate].labelconst requestSummary = `${template} · ${settings.httpMethod ?? "POST"}`return (diff --git a/apps/mobile/src/utils/__tests__/serverState.test.ts b/apps/mobile/src/utils/__tests__/serverState.test.tsindex 93b098f6..3bc42a96 100644--- a/apps/mobile/src/utils/__tests__/serverState.test.ts+++ b/apps/mobile/src/utils/__tests__/serverState.test.ts@@ -49,6 +49,13 @@ describe("describeServer", () => {expect(s.rowSub).toBe("tracks.example.org · 3 queued · no network")})+ it("says never rather than a time when nothing has synced yet", () => {+ expect(describeServer({ ...base, deviceOnline: false, lastSyncTime: 0 }).caption).toBe("0 queued · last sync never")+ expect(describeServer({ ...base, lastSyncError: "HTTP 500", lastSyncTime: 0 }).caption).toBe(+ "HTTP 500 · 0 queued · last success never"+ )+ })+it("puts the server's own sentence first when sync is failing, then the queue and the last success", () => {const s = describeServer({ ...base, lastSyncError: "HTTP 401 Unauthorized", queued: 38 })expect(s.word).toBe("Sync failing")@@ -87,6 +94,13 @@ describe("describeServer", () => {})expect(expiring.caption).toMatch(/ · client certificate expires in 12 days$/)+ const lastDay = describeServer({+ ...base,+ certificate: { state: "expiring", days: 1, word: "Expires in 1 day", caption: "", rowSub: "" }+ })+ // The last day is the warning most worth reading right, so it takes the singular.+ expect(lastDay.caption).toMatch(/ · client certificate expires in 1 day$/)+const expired = describeServer({...base,lastSyncError: "TLS handshake failed",diff --git a/apps/mobile/src/utils/serverState.ts b/apps/mobile/src/utils/serverState.tsindex 10078f74..59db7218 100644--- a/apps/mobile/src/utils/serverState.ts+++ b/apps/mobile/src/utils/serverState.ts@@ -6,6 +6,7 @@import { formatWhen } from "./geo"import { formatCount } from "./format"import type { CertificateState } from "./certificateState"+import { t } from "../i18n/t"export type ServerIcon = "cloudOff" | "cloud" | "wifiOff" | "alert" | "dashed" | "check"export type ServerTone = "secondary" | "warning" | "error" | "light" | "success"@@ -32,8 +33,10 @@ export interface ServerState {rowSub: string}-function count(n: number, noun: string): string {- return `${formatCount(n)} ${noun}`+type CountKey = "server.queued" | "server.queuedOnDevice" | "server.savedToday" | "server.today"++function count(n: number, key: CountKey): string {+ return t(key, { count: n, n: formatCount(n) })}/** The host of an endpoint for a row label, or the text itself when it is not a URL yet. */@@ -45,72 +48,76 @@ export function endpointHost(endpoint: string): string {}}-function certificateClause(certificate: CertificateState | null | undefined): string {+function certificateClause(certificate: CertificateState | null | undefined): string | null {if (certificate?.state === "expiring")- return ` · client certificate expires in ${certificate.days} ${certificate.days === 1 ? "day" : "days"}`- if (certificate?.state === "expired") return " · client certificate expired"- return ""+ return t("server.cert.expiresIn", { count: certificate.days, n: certificate.days })+ if (certificate?.state === "expired") return t("server.cert.expired")+ return null}+const clauses = (...parts: (string | null | false)[]) => parts.filter(Boolean).join(" · ")+/** One derivation of the server relationship for the Connection card, the dock and the Settings row. First match wins. */export function describeServer(input: ServerStateInput): ServerState {const now = input.now ?? new Date()- const queued = count(input.queued, "queued")- const lastSync = input.lastSyncTime > 0 ? formatWhen(Math.floor(input.lastSyncTime / 1000), now) : "never"+ const queued = count(input.queued, "server.queued")+ const when = input.lastSyncTime > 0 ? formatWhen(Math.floor(input.lastSyncTime / 1000), now) : null+ const lastSync = when ? t("server.lastSync", { when }) : t("server.lastSyncNever")+ const lastSuccess = when ? t("server.lastSuccess", { when }) : t("server.lastSuccessNever")const cert = certificateClause(input.certificate)if (input.offline) {return {icon: "cloudOff",tone: "secondary",- word: "Offline mode",- caption: `${count(input.today, "saved today")} · nothing is sent`,- rowSub: `Offline - saved locally · ${count(input.today, "today")}`+ word: t("server.word.offline"),+ caption: clauses(count(input.today, "server.savedToday"), t("server.nothingSent")),+ rowSub: clauses(t("server.savedLocally"), count(input.today, "server.today"))}}if (!input.endpoint) {return {icon: "cloud",tone: "warning",- word: "No server",- caption: `${queued} on this device`,- rowSub: "No server configured"+ word: t("server.word.noServer"),+ caption: count(input.queued, "server.queuedOnDevice"),+ rowSub: t("server.noServerConfigured")}}const server = endpointHost(input.endpoint)- const rowQueue = input.queued > 0 ? ` · ${queued}` : ""+ const rowQueue = input.queued > 0 && queuedif (!input.deviceOnline) {return {icon: "wifiOff",tone: "secondary",- word: "No network",- caption: `${queued} · last sync ${lastSync}${cert}`,- rowSub: `${server}${rowQueue} · no network`+ word: t("server.word.noNetwork"),+ caption: clauses(queued, lastSync, cert),+ rowSub: clauses(server, rowQueue, t("server.noNetworkClause"))}}if (input.lastSyncError !== "") {return {icon: "alert",tone: "error",- word: "Sync failing",- caption: `${input.lastSyncError} · ${queued} · last success ${lastSync}${cert}`,- rowSub: `${server}${rowQueue} · sync failing`+ word: t("server.word.failing"),+ caption: clauses(input.lastSyncError, queued, lastSuccess, cert),+ rowSub: clauses(server, rowQueue, t("server.syncFailingClause"))}}- if (input.lastSyncTime === 0) {+ if (!when) {return {icon: "dashed",tone: "light",- word: "Not synced yet",- caption: `${queued}${cert}`,- rowSub: `${server}${rowQueue}`+ word: t("server.word.notSynced"),+ caption: clauses(queued, cert),+ rowSub: clauses(server, rowQueue)}}return {icon: "check",tone: "success",- word: "Synced",- caption: `Last sync ${lastSync} · ${input.queued > 0 ? queued : "queue empty"}${cert}`,- rowSub: `${server}${rowQueue} · last sync ${lastSync}`+ word: t("server.word.synced"),+ caption: clauses(t("server.lastSyncStart", { when }), input.queued > 0 ? queued : t("server.queueEmpty"), cert),+ rowSub: clauses(server, rowQueue, lastSync)}}