Colota - Android GPS Location tracker
refactor(settings): five groups, and every row carries its value (#859)
Max Dietrichbd269738d0d6
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 52e543dc..e0f6a632 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -16,7 +16,8 @@ import type { RootStackParamList, RootStackRoute } from "./src/types/navigation"import "./src/i18n"import {- ActivityLogScreen,+ LoggingScreen,+ LogPreviewScreen,DashboardScreen,SettingsScreen,ApiSettingsScreen,@@ -164,9 +165,14 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [},{name: "Logging",- component: ActivityLogScreen,+ component: LoggingScreen,title: "Logging"},+ {+ name: "Log Preview",+ component: LogPreviewScreen,+ title: "Log preview"+ },{name: "Backup & Restore",component: BackupRestoreScreen,diff --git a/apps/mobile/src/components/features/log/FileLoggingPanel.tsx b/apps/mobile/src/components/features/log/FileLoggingPanel.tsxdeleted file mode 100644index 089b1ba4..00000000--- a/apps/mobile/src/components/features/log/FileLoggingPanel.tsx+++ /dev/null@@ -1,214 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React, { useCallback, useEffect, useState } from "react"-import { View, Text, Switch, StyleSheet, ScrollView, ActivityIndicator } from "react-native"-import { Card, Divider, SectionTitle } from "../../index"-import { Button } from "../../ui/Button"-import { useTheme } from "../../../hooks/useTheme"-import { fonts, fontSizes } from "../../../styles/typography"-import NativeLocationService from "../../../services/NativeLocationService"-import { logger } from "../../../utils/logger"-import { showAlert, showChoice } from "../../../services/modalService"-import { formatBytes } from "../../../utils/format"--export function FileLoggingPanel() {- const { colors } = useTheme()- const [enabled, setEnabled] = useState(false)- const [sizeBytes, setSizeBytes] = useState(0)- const [busy, setBusy] = useState(false)- const [loading, setLoading] = useState(true)-- const refreshSize = useCallback(async () => {- try {- const size = await NativeLocationService.getFileLogSize()- setSizeBytes(size)- } catch (err) {- logger.error("[FileLoggingPanel] getFileLogSize failed:", err)- }- }, [])-- useEffect(() => {- let cancelled = false- ;(async () => {- try {- const enabledStr = await NativeLocationService.getSetting("debugFileLoggingEnabled", "false")- if (cancelled) return- setEnabled(enabledStr === "true")- await refreshSize()- } catch (err) {- logger.error("[FileLoggingPanel] initial load failed:", err)- } finally {- if (!cancelled) setLoading(false)- }- })()- return () => {- cancelled = true- }- }, [refreshSize])-- // Size grows in the background while logging is on - poll while panel is visible.- useEffect(() => {- if (!enabled) return- const id = setInterval(refreshSize, 3000)- return () => clearInterval(id)- }, [enabled, refreshSize])-- const handleToggle = useCallback(async (value: boolean) => {- setEnabled(value)- try {- await NativeLocationService.setFileLoggingEnabled(value)- } catch (err) {- logger.error("[FileLoggingPanel] setFileLoggingEnabled failed:", err)- setEnabled(!value)- }- }, [])-- const handleExport = useCallback(async () => {- setBusy(true)- try {- const treeUri = await NativeLocationService.pickExportDirectory()- if (!treeUri) return- const docUri = await NativeLocationService.exportFileLogToUri(treeUri)- if (docUri) {- showAlert("Log exported", "Saved to the selected directory.", "success")- } else {- showAlert("Nothing to export", "There are no log entries yet.", "info")- }- } catch (err) {- logger.error("[FileLoggingPanel] export failed:", err)- showAlert("Export failed", err instanceof Error ? err.message : "Could not save log file.", "error")- } finally {- setBusy(false)- }- }, [])-- const handleClear = useCallback(async () => {- const choice = await showChoice({- title: "Clear log files?",- message: "All persisted log entries will be deleted. This cannot be undone.",- variant: "warning",- buttons: [- { text: "Cancel", style: "secondary" },- { text: "Clear", style: "destructive" }- ]- })- if (choice !== 1) return-- setBusy(true)- try {- await NativeLocationService.clearFileLog()- await refreshSize()- } catch (err) {- logger.error("[FileLoggingPanel] clearFileLog failed:", err)- showAlert("Clear failed", "Could not delete log files.", "error")- } finally {- setBusy(false)- }- }, [refreshSize])-- if (loading) {- return (- <View style={styles.centered}>- <ActivityIndicator size="large" color={colors.primary} />- </View>- )- }-- return (- <ScrollView contentContainerStyle={styles.scroll}>- <SectionTitle>File Logging</SectionTitle>-- <Card style={styles.card}>- <Text style={[styles.intro, { color: colors.textSecondary }]}>- Save app logs to a file on this device. Useful when a bug takes hours or days to reproduce - the file keeps a- record even if the app is restarted in between. Files may contain your location coordinates, so only share- with people you trust.- </Text>-- <View style={styles.toggleRow}>- <View style={styles.toggleLabel}>- <Text style={[styles.label, { color: colors.text }]}>Persistent file logging</Text>- </View>- <Switch- value={enabled}- onValueChange={handleToggle}- trackColor={{ false: colors.border, true: colors.primary + "80" }}- thumbColor={enabled ? colors.primary : colors.border}- />- </View>-- <Divider />-- <View style={styles.section}>- <View style={styles.sizeRow}>- <Text style={[styles.label, { color: colors.text }]}>Current size</Text>- <Text style={[styles.sizeValue, { color: colors.text }]}>{formatBytes(sizeBytes)}</Text>- </View>- <Text style={[styles.hint, { color: colors.textSecondary }]}>- The log file grows as long as logging is on. Use "Clear log files" to reset it.- </Text>- </View>- </Card>-- <Button title="Export log file…" onPress={handleExport} loading={busy} />- <Button title="Clear log files" variant="danger" onPress={handleClear} disabled={busy || sizeBytes === 0} />- </ScrollView>- )-}--const styles = StyleSheet.create({- scroll: {- padding: 16,- paddingBottom: 40- },- card: {- marginBottom: 12- },- centered: {- flex: 1,- justifyContent: "center",- alignItems: "center"- },- intro: {- marginBottom: 12,- fontSize: 14,- lineHeight: 20- },- toggleRow: {- flexDirection: "row",- alignItems: "center",- paddingVertical: 4- },- toggleLabel: {- flex: 1,- paddingRight: 12- },- section: {- paddingVertical: 4- },- label: {- fontSize: fontSizes.label,- ...fonts.semiBold,- marginBottom: 4- },- hint: {- fontSize: 13,- ...fonts.regular,- lineHeight: 18,- marginBottom: 12- },- sizeRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- marginBottom: 4- },- sizeValue: {- fontSize: 15,- ...fonts.medium,- fontFamily: "monospace"- }-})diff --git a/apps/mobile/src/components/features/settings/StatsCard.tsx b/apps/mobile/src/components/features/settings/StatsCard.tsxdeleted file mode 100644index 8c70c4c3..00000000--- a/apps/mobile/src/components/features/settings/StatsCard.tsx+++ /dev/null@@ -1,253 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */-import React from "react"-import { View, Text, StyleSheet, Pressable } from "react-native"-import { AlertTriangle, ChevronRight } from "lucide-react-native"-import { useTracking } from "../../../contexts/TrackingProvider"-import { useTheme } from "../../../hooks/useTheme"-import { getQueueColor } from "../../../utils/queueStatus"-import { formatCount } from "../../../utils/format"-import { fonts } from "../../../styles/typography"-import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../../../constants"--interface StatsCardProps {- queueCount: number- sentCount: number- todayCount?: number- interval: string- onManageClick?: () => void-}--type WarningLevel = "normal" | "warning" | "critical"--/**- * StatsCard Component - Improved Design- *- * Enhanced visual hierarchy with:- * - Cleaner stat presentation- * - Better color coding- * - Improved warning states- * - More prominent CTA when needed- */-export function StatsCard({ queueCount, sentCount, todayCount, interval, onManageClick }: StatsCardProps) {- const { settings } = useTracking()- const { colors } = useTheme()- const isOfflineMode = settings.isOfflineMode- const getWarningLevel = (): WarningLevel => {- if (queueCount > CRITICAL_QUEUE_THRESHOLD) return "critical"- if (queueCount > HIGH_QUEUE_THRESHOLD) return "warning"- return "normal"- }-- const queuedColor = getQueueColor(queueCount, colors)- const warningLevel = getWarningLevel()- const showWarning = queueCount > HIGH_QUEUE_THRESHOLD-- const getBorderColor = () => {- switch (warningLevel) {- case "critical":- return colors.error- case "warning":- return colors.warning- default:- return colors.border- }- }-- const getBackgroundGradient = () => {- switch (warningLevel) {- case "critical":- return colors.error + "12"- case "warning":- return colors.warning + "12"- default:- return "transparent"- }- }-- return (- <View- style={[- styles.container,- {- backgroundColor: colors.card,- borderColor: getBorderColor()- }- ]}- >- {/* Gradient overlay for warning states */}- {warningLevel !== "normal" && (- <View style={[styles.gradientOverlay, { backgroundColor: getBackgroundGradient() }]} />- )}-- {/* Stats Grid */}- <View style={styles.statsGrid}>- {isOfflineMode ? (- <>- {/* Today */}- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Today</Text>- <Text numberOfLines={1} style={[styles.statValue, { color: colors.info }]}>- {formatCount(todayCount ?? 0)}- </Text>- </View>-- <View style={[styles.divider, { backgroundColor: colors.border }]} />- </>- ) : (- <>- {/* Queued */}- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Queued</Text>- <Text numberOfLines={1} style={[styles.statValue, { color: queuedColor }]}>- {formatCount(queueCount)}- </Text>- </View>-- <View style={[styles.divider, { backgroundColor: colors.border }]} />-- {/* Sent */}- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Sent</Text>- <Text numberOfLines={1} style={[styles.statValue, { color: colors.success }]}>- {formatCount(sentCount)}- </Text>- </View>-- <View style={[styles.divider, { backgroundColor: colors.border }]} />- </>- )}-- {/* Interval */}- <View style={styles.statItem}>- <Text style={[styles.statLabel, { color: colors.textSecondary }]}>Interval</Text>- <Text numberOfLines={1} style={[styles.statValue, { color: colors.info }]}>- {interval}- <Text style={[styles.unit, { color: colors.textSecondary }]}>s</Text>- </Text>- </View>- </View>-- {/* Warning Banner */}- {!isOfflineMode && showWarning && onManageClick && (- <View style={styles.warningWrapper}>- <Pressable- style={({ pressed }) => {- const accent = warningLevel === "critical" ? colors.error : colors.warning- return [- styles.warningButton,- {- backgroundColor: accent + "15",- borderColor: accent + "40"- },- pressed && { opacity: colors.pressedOpacity }- ]- }}- onPress={onManageClick}- >- <View style={styles.warningContent}>- <AlertTriangle size={20} color={warningLevel === "critical" ? colors.error : colors.warning} />- <View style={styles.warningText}>- <Text- style={[- styles.warningTitle,- {- color: warningLevel === "critical" ? colors.error : colors.warning- }- ]}- >- {warningLevel === "critical" ? "Critical Queue Size" : "High Queue Size"}- </Text>- <Text style={[styles.warningHint, { color: colors.textSecondary }]}>Tap to manage data</Text>- </View>- </View>- <ChevronRight size={20} color={warningLevel === "critical" ? colors.error : colors.warning} />- </Pressable>- </View>- )}- </View>- )-}--const styles = StyleSheet.create({- container: {- borderRadius: 16,- borderWidth: 2,- marginBottom: 24,- overflow: "hidden"- },- gradientOverlay: {- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0- },- statsGrid: {- flexDirection: "row",- padding: 20- },- statItem: {- flex: 1,- alignItems: "center"- },- statLabel: {- fontSize: 12,- ...fonts.semiBold,- textTransform: "uppercase",- letterSpacing: 0.8,- marginBottom: 8- },- statValue: {- fontSize: 24,- ...fonts.bold,- letterSpacing: -0.5- },- unit: {- fontSize: 16,- ...fonts.medium- },- disabledHint: {- fontSize: 11,- marginTop: 2,- fontStyle: "italic"- },- divider: {- width: 1,- marginHorizontal: 12,- opacity: 0.3- },- warningWrapper: {- paddingHorizontal: 12,- paddingBottom: 12- },- warningButton: {- flexDirection: "row",- alignItems: "center",- justifyContent: "space-between",- paddingHorizontal: 16,- paddingVertical: 12,- borderRadius: 12,- borderWidth: 1.5- },- warningContent: {- flexDirection: "row",- alignItems: "center",- flex: 1- },- warningText: {- flex: 1,- marginLeft: 12- },- warningTitle: {- fontSize: 14,- ...fonts.semiBold,- marginBottom: 2- },- warningHint: {- fontSize: 12,- ...fonts.regular- }-})diff --git a/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsx b/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsxdeleted file mode 100644index 15f3c581..00000000--- a/apps/mobile/src/components/features/settings/__tests__/StatsCard.test.tsx+++ /dev/null@@ -1,132 +0,0 @@-import React from "react"-import { render, fireEvent } from "@testing-library/react-native"--let mockSettings = { isOfflineMode: false }--jest.mock("../../../../contexts/TrackingProvider", () => ({- useTracking: () => ({- settings: mockSettings- })-}))--jest.mock("../../../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- text: "#000",- textSecondary: "#6b7280",- success: "#22c55e",- warning: "#f59e0b",- error: "#ef4444",- info: "#3b82f6",- card: "#fff",- border: "#e5e7eb"- }- })-}))--jest.mock("../../../../utils/queueStatus", () => ({- getQueueColor: () => "#000"-}))--jest.mock("lucide-react-native", () => {- const R = require("react")- const { View } = require("react-native")- return {- AlertTriangle: () => R.createElement(View, null),- ChevronRight: () => R.createElement(View, null)- }-})--import { StatsCard } from "../StatsCard"--const baseProps = {- queueCount: 5,- sentCount: 100,- todayCount: 8,- interval: "30"-}--describe("StatsCard", () => {- beforeEach(() => {- mockSettings = { isOfflineMode: false }- })-- describe("online mode", () => {- it("shows Queued, Sent, and Interval stats", () => {- const { getByText } = render(<StatsCard {...baseProps} />)-- expect(getByText("Queued")).toBeTruthy()- expect(getByText("5")).toBeTruthy()- expect(getByText("Sent")).toBeTruthy()- expect(getByText("100")).toBeTruthy()- expect(getByText("Interval")).toBeTruthy()- })-- it("abbreviates a multi-million sent count so the fixed-width column stays one line", () => {- const { getByText, queryByText } = render(<StatsCard {...baseProps} sentCount={2_000_000} />)-- expect(getByText("2.0M")).toBeTruthy()- expect(queryByText("2,000,000")).toBeNull()- })-- it("does not show Today stat", () => {- const { queryByText } = render(<StatsCard {...baseProps} />)-- expect(queryByText("Today")).toBeNull()- })-- it("shows warning banner when queue is high", () => {- const onManage = jest.fn()- const { getByText } = render(<StatsCard {...baseProps} queueCount={75} onManageClick={onManage} />)-- expect(getByText("High Queue Size")).toBeTruthy()- expect(getByText("Tap to manage data")).toBeTruthy()- })-- it("shows critical warning when queue is very high", () => {- const onManage = jest.fn()- const { getByText } = render(<StatsCard {...baseProps} queueCount={200} onManageClick={onManage} />)-- expect(getByText("Critical Queue Size")).toBeTruthy()- })-- it("calls onManageClick when warning banner is pressed", () => {- const onManage = jest.fn()- const { getByText } = render(<StatsCard {...baseProps} queueCount={75} onManageClick={onManage} />)-- fireEvent.press(getByText("Tap to manage data"))-- expect(onManage).toHaveBeenCalledTimes(1)- })- })-- describe("offline mode", () => {- beforeEach(() => {- mockSettings = { isOfflineMode: true }- })-- it("shows Today and Interval instead of Queued/Sent", () => {- const { getByText } = render(<StatsCard {...baseProps} />)-- expect(getByText("Today")).toBeTruthy()- expect(getByText("8")).toBeTruthy()- expect(getByText("Interval")).toBeTruthy()- })-- it("hides Queued and Sent stats", () => {- const { queryByText } = render(<StatsCard {...baseProps} />)-- expect(queryByText("Queued")).toBeNull()- expect(queryByText("Sent")).toBeNull()- })-- it("hides warning banner even with high queue count", () => {- const onManage = jest.fn()- const { queryByText } = render(<StatsCard {...baseProps} queueCount={200} onManageClick={onManage} />)-- expect(queryByText("High Queue Size")).toBeNull()- expect(queryByText("Critical Queue Size")).toBeNull()- })- })-})diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.tsindex 5846bc46..b11fe159 100644--- a/apps/mobile/src/components/index.ts+++ b/apps/mobile/src/components/index.ts@@ -68,7 +68,6 @@ export { TrackMap } from "./features/inspector/TrackMap"export { ConnectionSettings } from "./features/settings/ConnectionSettings"export { SyncStrategySettings } from "./features/settings/SyncStrategySettings"export { StatRow } from "./ui/StatRow"-export { Footer } from "./ui/Footer"export { DashboardBanner } from "./features/dashboard/DashboardBanner"export { DashboardDock } from "./features/dashboard/DashboardDock"export { DayHeader } from "./features/inspector/DayHeader"@@ -76,4 +75,3 @@ export { DayPickerModal } from "./features/inspector/DayPickerModal"export { TripRow } from "./features/inspector/TripRow"export { InspectorDock } from "./features/inspector/InspectorDock"export { PointCard } from "./features/inspector/PointCard"-export { StatsCard } from "./features/settings/StatsCard"diff --git a/apps/mobile/src/components/ui/Footer.tsx b/apps/mobile/src/components/ui/Footer.tsxdeleted file mode 100644index 5c223f85..00000000--- a/apps/mobile/src/components/ui/Footer.tsx+++ /dev/null@@ -1,31 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React from "react"-import { View, Text, StyleSheet } from "react-native"-import { useTheme } from "../../hooks/useTheme"-import { fonts } from "../../styles/typography"--export function Footer() {- const { colors } = useTheme()-- return (- <View style={styles.footer}>- <Text style={[styles.copyright, { color: colors.textLight }]}>© 2026 Max Dietrich</Text>- </View>- )-}--const styles = StyleSheet.create({- footer: {- marginTop: 32,- marginBottom: 16,- alignItems: "center"- },- copyright: {- fontSize: 12,- ...fonts.regular- }-})diff --git a/apps/mobile/src/screens/AboutScreen.tsx b/apps/mobile/src/screens/AboutScreen.tsxindex c7f7afeb..07c471fc 100644--- a/apps/mobile/src/screens/AboutScreen.tsx+++ b/apps/mobile/src/screens/AboutScreen.tsx@@ -3,386 +3,83 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useEffect, useCallback, useMemo } from "react"-import { Text, StyleSheet, View, ScrollView, Linking, Pressable, Image } from "react-native"-import { ScreenProps, ThemeColors } from "../types/global"+import React, { useCallback } from "react"+import { Image, Linking, ScrollView, StyleSheet, Text, View } from "react-native"+import { Code, ExternalLink, FileText, ScrollText } from "lucide-react-native"+import { radius } from "@colota/shared"+import { Card, Container, Divider, ListItem, SectionTitle } from "../components"import { useTheme } from "../hooks/useTheme"-import { ExternalLink, Bug, FileText, Code, ScrollText, MessageCircle, Copy, Check } from "lucide-react-native"-import { fonts } from "../styles/typography"-import { Card, Container, Divider, SectionTitle, Footer } from "../components"-import { useTimeout } from "../hooks/useTimeout"import NativeLocationService from "../services/NativeLocationService"-import icon from "../assets/icons/icon.png"-import { REPO_URL, ISSUES_URL, PRIVACY_POLICY_URL, TILE_SERVER_DOCS_URL } from "../constants"+import { showAlert } from "../services/modalService"import { logger } from "../utils/logger"--// Helper function to map SDK to Android version-function getAndroidVersion(sdkVersion: number): string {- const versions: Record<number, string> = {- 24: "7.0",- 25: "7.1",- 26: "8.0",- 27: "8.1",- 28: "9",- 29: "10",- 30: "11",- 31: "12",- 32: "12L",- 33: "13",- 34: "14",- 35: "15",- 36: "16",- 37: "17"- }- return versions[sdkVersion] || "Unknown"-}--function getVariantLabel(flavor: string): string {- switch (flavor) {- case "foss":- return "FOSS"- case "gms":- return "Google Play"- default:- return flavor || "Unknown"- }-}--const LinkRow = ({- icon: Icon,- title,- subtitle,- url,- colors,- onOpenURL-}: {- icon: React.ComponentType<{ size: number; color: string }>- title: string- subtitle: string- url: string- colors: ThemeColors- onOpenURL: (url: string) => void-}) => (- <Pressable- style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}- onPress={() => onOpenURL(url)}- >- <Icon size={20} color={colors.textLight} />- <View style={styles.linkTextContainer}>- <Text style={[styles.linkTitle, { color: colors.text }]}>{title}</Text>- <Text style={[styles.linkSubtitle, { color: colors.textLight }]}>{subtitle}</Text>- </View>- <ExternalLink size={18} color={colors.textLight} />- </Pressable>-)--const DEBUG_MODE_SETTING_KEY = "debug_mode_enabled"--function InfoCard({ rows }: { rows: { label: string; value: string }[] }) {- const { colors } = useTheme()- return (- <Card>- {rows.map((row, i) => (- <React.Fragment key={row.label}>- <View style={styles.techRow}>- <Text style={[styles.techLabel, { color: colors.textSecondary }]}>{row.label}</Text>- <Text style={[styles.techValue, { color: colors.text }]}>{row.value}</Text>- </View>- {i < rows.length - 1 && <Divider />}- </React.Fragment>- ))}- </Card>- )-}+import { buildLine } from "../utils/settingsRow"+import { fonts, fontSizes, lineHeights, type } from "../styles/typography"+import { PRIVACY_POLICY_URL, REPO_URL, space } from "../constants"+import icon from "../assets/icons/icon.png"+import type { ScreenProps } from "../types/global"export function AboutScreen({}: ScreenProps) {const { colors } = useTheme()- const [showDebugInfo, setShowDebugInfo] = useState(false)- const [tapCount, setTapCount] = useState(0)- const [copied, setCopied] = useState(false)- const copiedTimeout = useTimeout()- const [deviceInfo, setDeviceInfo] = useState<{- model: string- brand: string- deviceId: string- systemVersion: string- apiLevel: string- } | null>(null)+ const build = NativeLocationService.getBuildConfig()- const buildConfig = useMemo(() => NativeLocationService.getBuildConfig(), [])-- // Load persisted debug mode- useEffect(() => {- NativeLocationService.getSetting(DEBUG_MODE_SETTING_KEY, "false").then((value) => {- if (value === "true") {- setShowDebugInfo(true)- }+ const openURL = useCallback((url: string) => {+ Linking.openURL(url).catch((err) => {+ logger.error("[AboutScreen] Failed to open URL:", err)+ showAlert("Error", "Could not open the link.", "error")})}, [])- // Persist debug mode changes- const toggleDebugMode = useCallback((enabled: boolean) => {- setShowDebugInfo(enabled)- NativeLocationService.saveSetting(DEBUG_MODE_SETTING_KEY, String(enabled))- }, [])-- // Load device info lazily when debug mode is enabled- useEffect(() => {- if (!showDebugInfo || deviceInfo) return-- NativeLocationService.getDeviceInfo()- .then((info) => {- setDeviceInfo({- model: info.model,- brand: info.brand,- deviceId: info.deviceId,- systemVersion: info.systemVersion,- apiLevel: info.apiLevel.toString()- })- })- .catch((err) => logger.error("Failed to load device info:", err))- }, [showDebugInfo, deviceInfo])-- // Reset tap count after 2 seconds- useEffect(() => {- if (tapCount > 0) {- const timer = setTimeout(() => setTapCount(0), 2000)- return () => clearTimeout(timer)- }- }, [tapCount])-- const handleVersionTap = useCallback(() => {- const newCount = tapCount + 1- setTapCount(newCount)-- if (newCount >= 7) {- toggleDebugMode(true)- setTapCount(0)- }- }, [tapCount, toggleDebugMode])-- const handleOpenURL = useCallback((url: string) => {- Linking.openURL(url).catch((err) => logger.error("Failed to open URL:", err))- }, [])-- const handleCopyDebugInfo = useCallback(async () => {- if (!buildConfig) return-- const lines = [- `Colota v${buildConfig.VERSION_NAME} (${buildConfig.VERSION_CODE})`,- `Variant: ${getVariantLabel(buildConfig.FLAVOR)}`,- `Target SDK: ${buildConfig.TARGET_SDK_VERSION} (Android ${getAndroidVersion(buildConfig.TARGET_SDK_VERSION)})`,- `Min SDK: ${buildConfig.MIN_SDK_VERSION} (Android ${getAndroidVersion(buildConfig.MIN_SDK_VERSION)})`,- `Compile SDK: ${buildConfig.COMPILE_SDK_VERSION}`,- `Build Tools: ${buildConfig.BUILD_TOOLS_VERSION}`,- `Kotlin: ${buildConfig.KOTLIN_VERSION}`,- `NDK: ${buildConfig.NDK_VERSION}`- ]-- if (deviceInfo) {- lines.push(- "",- `OS: Android ${deviceInfo.systemVersion} (API ${deviceInfo.apiLevel})`,- `Device: ${deviceInfo.brand} ${deviceInfo.model}`,- `Device ID: ${deviceInfo.deviceId}`- )- }-- try {- await NativeLocationService.copyToClipboard(lines.join("\n"), "Debug Info")- setCopied(true)- copiedTimeout.set(() => setCopied(false), 2000)- } catch (err) {- logger.error("Failed to copy debug info:", err)- }- }, [buildConfig, deviceInfo, copiedTimeout])-- // Fallback if buildConfig is not available- if (!buildConfig) {- return (- <Container>- <ScrollView contentContainerStyle={styles.scrollContent}>- <View style={styles.header}>- <Text style={[styles.title, { color: colors.text }]}>Colota</Text>- </View>- </ScrollView>- </Container>- )- }-- const debugRows = [- { label: "Variant", value: getVariantLabel(buildConfig.FLAVOR) },- {- label: "Target SDK",- value: `${buildConfig.TARGET_SDK_VERSION} (Android ${getAndroidVersion(buildConfig.TARGET_SDK_VERSION)})`- },- {- label: "Min SDK",- value: `${buildConfig.MIN_SDK_VERSION} (Android ${getAndroidVersion(buildConfig.MIN_SDK_VERSION)})`- },- { label: "Compile SDK", value: buildConfig.COMPILE_SDK_VERSION.toString() },- { label: "Build Tools", value: buildConfig.BUILD_TOOLS_VERSION },- { label: "Kotlin", value: buildConfig.KOTLIN_VERSION },- { label: "NDK", value: buildConfig.NDK_VERSION }- ]-- const deviceRows = deviceInfo- ? [- { label: "OS", value: `Android ${deviceInfo.systemVersion}` },- { label: "API Level", value: deviceInfo.apiLevel },- { label: "Model", value: deviceInfo.model },- { label: "Brand", value: deviceInfo.brand },- { label: "Device ID", value: deviceInfo.deviceId }- ]- : []-return (<Container><ScrollView contentContainerStyle={styles.scrollContent}>- {/* Header */}- <View style={styles.header}>- <Pressable- style={({ pressed }) => [styles.appIconContainer, pressed && { opacity: 0.8 }]}- onPress={handleVersionTap}- >+ <View style={styles.identity}>+ <View style={styles.appIconContainer}><Image source={icon} style={styles.appIcon} resizeMode="contain" />- </Pressable>- <Text style={[styles.title, { color: colors.text }]}>Colota</Text>- <Pressable onPress={handleVersionTap} style={({ pressed }) => pressed && { opacity: 0.8 }}>- <Text style={[styles.version, { color: colors.textSecondary }]}>Version {buildConfig.VERSION_NAME}</Text>- </Pressable>-- {/* Tap counter hint */}- {tapCount > 0 && tapCount < 7 && (- <Text style={[styles.debugHint, { color: colors.textLight }]}>- {7 - tapCount} more taps to enable debug mode- </Text>- )}-- {showDebugInfo && (- <Pressable- onPress={() => toggleDebugMode(false)}- style={({ pressed }) => [- styles.debugBadge,- { backgroundColor: colors.warning + "20" },- pressed && { opacity: colors.pressedOpacity }- ]}- >- <Bug size={14} color={colors.warning} />- <Text style={[styles.debugText, { color: colors.warning }]}>Debug Mode (tap to hide)</Text>- </Pressable>- )}+ </View>+ <Text style={[styles.name, { color: colors.text }]}>Colota</Text>+ <Text style={[styles.version, { color: colors.textSecondary }]} testID="about-version">+ Version {buildLine(build)}+ </Text></View>- {/* Links */}- <Card>- <LinkRow- icon={FileText}- title="Privacy Policy"- subtitle={PRIVACY_POLICY_URL}- url={PRIVACY_POLICY_URL}- colors={colors}- onOpenURL={handleOpenURL}- />- <Divider />- <LinkRow- icon={Code}- title="Source Code"- subtitle="github.com/dietrichmax/colota"- url={REPO_URL}- colors={colors}- onOpenURL={handleOpenURL}- />- <Divider />- <LinkRow- icon={ScrollText}- title="License"- subtitle="GNU AGPLv3"- url={`${REPO_URL}/blob/main/LICENSE`}- colors={colors}- onOpenURL={handleOpenURL}- />- <Divider />- <LinkRow- icon={MessageCircle}- title="Report a Bug"- subtitle="github.com/dietrichmax/colota/issues"- url={ISSUES_URL}- colors={colors}- onOpenURL={handleOpenURL}- />- </Card>-- {/* Map Data Attribution */}<View style={styles.section}>- <SectionTitle>Map Data</SectionTitle>- <Card>- <Pressable- style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}- onPress={() => handleOpenURL(TILE_SERVER_DOCS_URL)}- >- <View style={styles.linkTextContainer}>- <Text style={[styles.linkTitle, { color: colors.text }]}>Colota Tiles</Text>- <Text style={[styles.linkSubtitle, { color: colors.textLight }]}>- Self-hosted map tile server - configure your own- </Text>- </View>- <ExternalLink size={18} color={colors.textLight} />- </Pressable>- <Divider />- <Pressable- style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}- onPress={() => handleOpenURL("https://www.openstreetmap.org/copyright")}- >- <View style={styles.linkTextContainer}>- <Text style={[styles.linkTitle, { color: colors.text }]}>OpenStreetMap</Text>- <Text style={[styles.linkSubtitle, { color: colors.textLight }]}>- Map data by OpenStreetMap contributors- </Text>- </View>- <ExternalLink size={18} color={colors.textLight} />- </Pressable>+ <SectionTitle>Legal</SectionTitle>+ <Card rows>+ <ListItem+ testID="nav-privacy-policy"+ icon={FileText}+ label="Privacy policy"+ sub="colota.app/privacy-policy"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ onPress={() => openURL(PRIVACY_POLICY_URL)}+ />+ <Divider tight inset />+ <ListItem+ testID="nav-license"+ icon={ScrollText}+ label="License"+ sub="GNU AGPLv3"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ onPress={() => openURL(`${REPO_URL}/blob/main/LICENSE`)}+ />+ <Divider tight inset />+ <ListItem+ testID="nav-source-code"+ icon={Code}+ label="Source code"+ sub="github.com/dietrichmax/colota"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ onPress={() => openURL(REPO_URL)}+ /></Card>+ <Text style={[styles.copyright, { color: colors.textLight }]}>+ Copyright © 2026 Max Dietrich and contributors. Colota is free software, with no warranty; the License+ row above has the terms.+ </Text></View>-- {/* Debug Info - Only shown when enabled */}- {showDebugInfo && (- <>- <View style={styles.section}>- <SectionTitle>BUILD</SectionTitle>- <InfoCard rows={debugRows} />- </View>-- {deviceRows.length > 0 && (- <View style={styles.section}>- <SectionTitle>DEVICE</SectionTitle>- <InfoCard rows={deviceRows} />- </View>- )}-- <View style={styles.debugActions}>- <Pressable- style={({ pressed }) => [- styles.copyButton,- { borderColor: colors.border },- pressed && { opacity: colors.pressedOpacity }- ]}- onPress={handleCopyDebugInfo}- >- {copied ? <Check size={16} color={colors.success} /> : <Copy size={16} color={colors.primaryDark} />}- <Text style={[styles.copyButtonText, { color: copied ? colors.success : colors.primaryDark }]}>- {copied ? "Copied!" : "Copy Debug Info"}- </Text>- </Pressable>-- <Text style={[styles.logHint, { color: colors.textLight }]}>- View and export logs from Settings > Logging.- </Text>- </View>- </>- )}-- <Footer /></ScrollView></Container>)@@ -390,110 +87,43 @@ export function AboutScreen({}: ScreenProps) {const styles = StyleSheet.create({scrollContent: {- paddingHorizontal: 16,- paddingBottom: 40,- paddingTop: 8+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},- header: {- marginTop: 20,- marginBottom: 24,- alignItems: "center"+ identity: {+ alignItems: "center",+ marginTop: space.lg,+ marginBottom: space.xl},appIconContainer: {width: 80,height: 80,- borderRadius: 20,+ borderRadius: radius.lg,alignItems: "center",justifyContent: "center",- marginBottom: 16,+ marginBottom: space.lg,overflow: "hidden"},appIcon: {width: 80,height: 80},- title: {- fontSize: 28,- ...fonts.bold,- marginBottom: 4+ name: {+ ...type.display,+ marginBottom: space.xs},version: {- fontSize: 13,+ fontSize: fontSizes.description,...fonts.regular},- linkRow: {- flexDirection: "row",- alignItems: "center",- paddingVertical: 14,- gap: 12- },- linkTextContainer: {- flex: 1- },- linkTitle: {- fontSize: 15,- ...fonts.semiBold- },- linkSubtitle: {- fontSize: 12,- marginTop: 1- },- techRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 8- },- techLabel: {- fontSize: 14,- ...fonts.medium- },- techValue: {- fontSize: 14,- ...fonts.semiBold- },section: {- marginTop: 24- },- debugHint: {- fontSize: 11,- marginTop: 8,- fontStyle: "italic"- },- debugBadge: {- marginTop: 12,- paddingHorizontal: 12,- paddingVertical: 6,- borderRadius: 8,- flexDirection: "row",- alignItems: "center",- gap: 6- },- debugText: {- fontSize: 12,- ...fonts.semiBold- },- debugActions: {- gap: 10,- marginTop: 16- },- copyButton: {- flexDirection: "row",- alignItems: "center",- justifyContent: "center",- gap: 8,- paddingVertical: 12,- borderRadius: 12,- borderWidth: 1- },- copyButtonText: {- fontSize: 14,- ...fonts.semiBold+ marginBottom: space.xl},- logHint: {- fontSize: 12,- textAlign: "center",- fontStyle: "italic",- lineHeight: 16+ copyright: {+ fontSize: fontSizes.caption,+ ...fonts.regular,+ lineHeight: lineHeights.caption,+ marginTop: space.lg}})diff --git a/apps/mobile/src/screens/ActivityLogScreen.tsx b/apps/mobile/src/screens/ActivityLogScreen.tsxdeleted file mode 100644index 4cf7a252..00000000--- a/apps/mobile/src/screens/ActivityLogScreen.tsx+++ /dev/null@@ -1,418 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import React, { useState, useCallback, useMemo, useLayoutEffect, useRef } from "react"-import {- Text,- StyleSheet,- View,- ScrollView,- TextInput,- Pressable,- ActivityIndicator,- type ScrollViewInstance-} from "react-native"-import { useFocusEffect } from "@react-navigation/native"-import { useSafeAreaInsets } from "react-native-safe-area-context"-import { Share2, Search, X, ArrowDown } from "lucide-react-native"-import { fonts } from "../styles/typography"-import { Container, SectionTitle } from "../components"-import { Tab } from "../components/ui/Tab"-import { FileLoggingPanel } from "../components/features/log/FileLoggingPanel"-import { useTheme } from "../hooks/useTheme"-import { logger, LOG_LEVELS, type LogLevel } from "../utils/logger"-import { getMergedLogs, exportLogs, MergedLogEntry } from "../utils/logExport"-import NativeLocationService from "../services/NativeLocationService"-import { ScreenProps } from "../types/global"--type FilterLevel = LogLevel--type LogTab = "live" | "file"--export function ActivityLogScreen({ navigation }: ScreenProps) {- const { colors } = useTheme()- const insets = useSafeAreaInsets()- const [tab, setTab] = useState<LogTab>("live")- const [logs, setLogs] = useState<MergedLogEntry[]>([])- const [loading, setLoading] = useState(true)- const [exporting, setExporting] = useState(false)- const [searchQuery, setSearchQuery] = useState("")- const [activeLevels, setActiveLevels] = useState<Set<FilterLevel>>(new Set(LOG_LEVELS))- const [showScrollEnd, setShowScrollEnd] = useState(false)- const isNearEnd = useRef(true)- const scrollRef = useRef<ScrollViewInstance>(null)-- const loadLogs = useCallback(async () => {- try {- const merged = await getMergedLogs()- setLogs(merged)- } catch (err) {- logger.error("[ActivityLogScreen] Failed to load logs:", err)- } finally {- setLoading(false)- }- }, [])-- const handleContentSizeChange = useCallback(() => {- if (isNearEnd.current) {- scrollRef.current?.scrollToEnd({ animated: false })- }- }, [])-- useFocusEffect(- useCallback(() => {- if (tab !== "live") return- loadLogs()- const interval = setInterval(loadLogs, 3000)- return () => clearInterval(interval)- }, [loadLogs, tab])- )-- const handleExport = useCallback(async () => {- setExporting(true)- try {- const buildConfig = NativeLocationService.getBuildConfig()- let deviceInfo = null- try {- const info = await NativeLocationService.getDeviceInfo()- deviceInfo = { ...info, apiLevel: String(info.apiLevel) }- } catch {}- await exportLogs(buildConfig, deviceInfo)- } catch (err) {- logger.error("[ActivityLogScreen] Export failed:", err)- } finally {- setExporting(false)- }- }, [])-- const handleScroll = useCallback(({ nativeEvent }: any) => {- const { contentOffset, contentSize, layoutMeasurement } = nativeEvent- const distanceFromEnd = contentSize.height - contentOffset.y - layoutMeasurement.height- isNearEnd.current = distanceFromEnd < 100- setShowScrollEnd(distanceFromEnd > 200)- }, [])-- const scrollToEnd = useCallback(() => {- scrollRef.current?.scrollToEnd({ animated: true })- isNearEnd.current = true- setShowScrollEnd(false)- }, [])-- const headerRight = useCallback(- () => (- <View style={styles.headerButtons}>- <Pressable- onPress={handleExport}- disabled={exporting}- style={({ pressed }) => [styles.headerButton, pressed && { opacity: colors.pressedOpacity }]}- >- {exporting ? (- <ActivityIndicator size={18} color={colors.primary} />- ) : (- <Share2 size={20} color={colors.primary} />- )}- </Pressable>- </View>- ),- [handleExport, exporting, colors]- )-- useLayoutEffect(() => {- navigation.setOptions({ headerRight })- }, [navigation, headerRight])-- const toggleLevel = useCallback((level: FilterLevel) => {- setActiveLevels((prev) => {- const next = new Set(prev)- if (next.has(level)) {- next.delete(level)- } else {- next.add(level)- }- return next- })- }, [])-- const levelCounts = useMemo(() => {- const counts: Record<string, number> = {}- for (const level of LOG_LEVELS) counts[level] = 0- for (const entry of logs) {- if (entry.level in counts) counts[entry.level]++- }- return counts- }, [logs])-- const filteredLogs = useMemo(() => {- const query = searchQuery.toLowerCase()- return logs.filter((entry) => {- const levelMatch = entry.level === "NATIVE" || activeLevels.has(entry.level as FilterLevel)- if (!levelMatch) return false- if (query && !entry.message.toLowerCase().includes(query)) return false- return true- })- }, [logs, searchQuery, activeLevels])-- const levelColor = useCallback(- (level: MergedLogEntry["level"]) => {- switch (level) {- case "DEBUG":- return colors.textLight- case "INFO":- return colors.info- case "WARN":- return colors.warning- case "ERROR":- return colors.error- default:- return colors.textSecondary- }- },- [colors]- )-- const tabBar = (- <View style={styles.tabBar}>- <Tab label="Live" active={tab === "live"} onPress={() => setTab("live")} colors={colors} />- <Tab label="File" active={tab === "file"} onPress={() => setTab("file")} colors={colors} />- </View>- )-- if (loading && tab === "live") {- return (- <Container>- {tabBar}- <View style={styles.centered}>- <ActivityIndicator size="large" color={colors.primary} />- </View>- </Container>- )- }-- if (tab === "file") {- return (- <Container>- {tabBar}- <FileLoggingPanel />- </Container>- )- }-- return (- <Container>- {tabBar}- <View style={styles.filterBar}>- <View style={[styles.searchContainer, { backgroundColor: colors.card, borderColor: colors.border }]}>- <Search size={16} color={colors.textLight} />- <TextInput- style={[styles.searchInput, { color: colors.text }]}- placeholder="Filter logs..."- placeholderTextColor={colors.placeholder}- value={searchQuery}- onChangeText={setSearchQuery}- autoCapitalize="none"- autoCorrect={false}- />- {searchQuery.length > 0 && (- <Pressable onPress={() => setSearchQuery("")}>- <X size={16} color={colors.textLight} />- </Pressable>- )}- </View>-- <View style={styles.levelChips}>- {LOG_LEVELS.map((level) => {- const active = activeLevels.has(level)- const color = levelColor(level)- const count = levelCounts[level] || 0- return (- <Pressable- key={level}- onPress={() => toggleLevel(level)}- style={[- styles.chip,- {- backgroundColor: active ? color : colors.surface- }- ]}- >- <Text style={[styles.chipText, { color: active ? colors.textOnPrimary : colors.textLight }]}>- {level}- {count > 0 ? ` ${count}` : ""}- </Text>- </Pressable>- )- })}- </View>- </View>-- <View style={[styles.separator, { backgroundColor: colors.border }]} />-- <ScrollView- ref={scrollRef}- contentContainerStyle={styles.list}- showsVerticalScrollIndicator={false}- onScroll={handleScroll}- scrollEventThrottle={100}- onContentSizeChange={handleContentSizeChange}- >- {filteredLogs.length > 0 ? (- <>- <SectionTitle>Entries ({filteredLogs.length})</SectionTitle>- <Text style={[styles.logText, { color: colors.text }]} selectable>- {filteredLogs- .map((item) => {- const level = item.level === "NATIVE" ? "NATIVE" : item.level- const time =- item.time > 0- ? new Date(item.time).toLocaleTimeString([], {- hour: "2-digit",- minute: "2-digit",- second: "2-digit"- })- : " "- return `[${time}] [${level}] ${item.message}`- })- .join("\n")}- </Text>- </>- ) : (- <View style={styles.empty}>- <Text style={[styles.emptyText, { color: colors.textSecondary }]}>- {logs.length === 0 ? "No log entries yet" : "No logs match your filter"}- </Text>- <Text style={[styles.emptyHint, { color: colors.textLight }]}>- {logs.length === 0- ? "Logs are collected automatically as the app runs"- : "Try adjusting your search or level filters"}- </Text>- </View>- )}- </ScrollView>-- {showScrollEnd ? (- <Pressable- onPress={scrollToEnd}- style={[styles.scrollEndButton, { backgroundColor: colors.primary, bottom: insets.bottom + 24 }]}- >- <ArrowDown size={20} color={colors.textOnPrimary} />- </Pressable>- ) : filteredLogs.length > 0 ? (- <View style={[styles.followingBadge, { backgroundColor: colors.primary + "20", bottom: insets.bottom + 24 }]}>- <Text style={[styles.followingText, { color: colors.primary }]}>Following</Text>- </View>- ) : null}- </Container>- )-}--const styles = StyleSheet.create({- tabBar: {- flexDirection: "row",- marginBottom: 12- },- list: {- padding: 16,- paddingBottom: 40- },- headerButtons: {- flexDirection: "row",- gap: 8- },- headerButton: {- padding: 8- },- filterBar: {- paddingHorizontal: 16,- paddingTop: 8,- paddingBottom: 8,- gap: 8- },- searchContainer: {- flexDirection: "row",- alignItems: "center",- borderWidth: 1,- borderRadius: 8,- paddingHorizontal: 10,- height: 40,- gap: 8- },- searchInput: {- flex: 1,- ...fonts.regular,- fontSize: 14,- padding: 0- },- levelChips: {- flexDirection: "row",- gap: 6- },- chip: {- paddingHorizontal: 12,- paddingVertical: 5,- borderRadius: 12- },- separator: {- height: 1,- marginHorizontal: 16,- marginTop: 4- },- chipText: {- ...fonts.semiBold,- fontSize: 11- },- logText: {- ...fonts.regular,- fontSize: 12,- fontFamily: "monospace",- lineHeight: 18- },- centered: {- flex: 1,- justifyContent: "center",- alignItems: "center"- },- empty: {- alignItems: "center",- paddingTop: 40- },- emptyText: {- fontSize: 15,- ...fonts.medium,- marginBottom: 6- },- emptyHint: {- fontSize: 13,- ...fonts.regular,- textAlign: "center",- lineHeight: 18- },- scrollEndButton: {- position: "absolute",- bottom: 24,- right: 24,- width: 44,- height: 44,- borderRadius: 22,- alignItems: "center",- justifyContent: "center",- elevation: 4,- shadowColor: "#000",- shadowOffset: { width: 0, height: 2 },- shadowOpacity: 0.25,- shadowRadius: 4- },- followingBadge: {- position: "absolute",- bottom: 24,- right: 24,- paddingHorizontal: 12,- paddingVertical: 6,- borderRadius: 16- },- followingText: {- ...fonts.medium,- fontSize: 11- }-})diff --git a/apps/mobile/src/screens/AppearanceScreen.tsx b/apps/mobile/src/screens/AppearanceScreen.tsxindex b2aa0e8c..d84e75e2 100644--- a/apps/mobile/src/screens/AppearanceScreen.tsx+++ b/apps/mobile/src/screens/AppearanceScreen.tsx@@ -3,28 +3,55 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-import React, { useState, useCallback, useEffect } from "react"-import { Text, StyleSheet, Switch, View, ScrollView, Pressable, TextInput } from "react-native"+import React, { useState, useCallback, useEffect, useRef } from "react"+import { StyleSheet, View, ScrollView } from "react-native"import { ScreenProps } from "../types/global"-import { useTheme } from "../hooks/useTheme"+import { useTheme, type ThemePreference } from "../hooks/useTheme"import { useTranslation } from "../i18n/useTranslation"import NativeLocationService from "../services/NativeLocationService"-import { fonts } from "../styles/typography"-import { Card, Container, Divider, SettingRow } from "../components"+import {+ Button,+ Card,+ ChipGroup,+ Container,+ Divider,+ FieldMessage,+ SettingRow,+ TextField,+ ListItem,+ Toggle+} from "../components"import { ChevronDown, ChevronUp } from "lucide-react-native"import { logger } from "../utils/logger"import { loadDisplayPreferences, getUnitSystem, getTimeFormat } from "../utils/geo"import type { UnitSystem, TimeFormat } from "../utils/geo"+import { clockSample, isStyleUrlValid, tileRowSub, unitNotation } from "../utils/appearance"+import { space } from "../constants"++type StyleKey = "mapStyleUrlLight" | "mapStyleUrlDark"export function AppearanceScreen({}: ScreenProps) {- const { mode, toggleTheme, colors } = useTheme()+ const {+ preference,+ setPreference,+ colors,+ wallpaperColors,+ setWallpaperColors,+ wallpaperColorsAvailable,+ wallpaperPaletteReady+ } = useTheme()const { t } = useTranslation()const [unitSystem, setUnitSystem] = useState<UnitSystem>(getUnitSystem)const [timeFormat, setTimeFormat] = useState<TimeFormat>(getTimeFormat)- const [mapStyleUrlLight, setMapStyleUrlLight] = useState("")- const [mapStyleUrlDark, setMapStyleUrlDark] = useState("")+ // The row sub reads the saved pair, not the drafts, so the host moves on a save and not per keystroke.+ const [draftLight, setDraftLight] = useState("")+ const [draftDark, setDraftDark] = useState("")+ const [savedLight, setSavedLight] = useState("")+ const [savedDark, setSavedDark] = useState("")+ const [lightError, setLightError] = useState<string | undefined>()+ const [darkError, setDarkError] = useState<string | undefined>()const [showMapTileServer, setShowMapTileServer] = useState(false)const selectUnitSystem = useCallback(@@ -55,35 +82,62 @@ export function AppearanceScreen({}: ScreenProps) {[timeFormat])+ // The initial read must not undo a save that beat it.+ const edited = useRef(false)+useEffect(() => {Promise.all([NativeLocationService.getSetting("mapStyleUrlLight"),NativeLocationService.getSetting("mapStyleUrlDark")]).then(([light, dark]) => {- setMapStyleUrlLight(light ?? "")- setMapStyleUrlDark(dark ?? "")+ if (edited.current) return+ setDraftLight(light ?? "")+ setDraftDark(dark ?? "")+ setSavedLight(light ?? "")+ setSavedDark(dark ?? "")}).catch(() => {})}, [])- const saveMapStyleUrl = useCallback(async (key: "mapStyleUrlLight" | "mapStyleUrlDark", value: string) => {- try {- await NativeLocationService.saveSetting(key, value.trim())- } catch (err) {- logger.error("[AppearanceScreen] Failed to save map style URL:", err)- }- }, [])+ /** Refused rather than stored: a URL the map cannot load blanks every map, and only the reset undoes it. */+ const commitStyleUrl = useCallback(+ async (key: StyleKey, text: string) => {+ const setError = key === "mapStyleUrlLight" ? setLightError : setDarkError+ const setSaved = key === "mapStyleUrlLight" ? setSavedLight : setSavedDark+ const trimmed = text.trim()+ if (!isStyleUrlValid(trimmed)) {+ setError(t("appearance.mapStyle.error"))+ return+ }+ setError(undefined)+ edited.current = true+ try {+ await NativeLocationService.saveSetting(key, trimmed)+ setSaved(trimmed)+ } catch (err) {+ logger.error("[AppearanceScreen] Failed to save map style URL:", err)+ }+ },+ [t]+ )const resetMapStyle = useCallback(() => {- setMapStyleUrlLight("")- setMapStyleUrlDark("")+ edited.current = true+ setDraftLight("")+ setDraftDark("")+ setSavedLight("")+ setSavedDark("")+ setLightError(undefined)+ setDarkError(undefined)Promise.all([NativeLocationService.saveSetting("mapStyleUrlLight", ""),NativeLocationService.saveSetting("mapStyleUrlDark", "")]).catch((err) => logger.error("[AppearanceScreen] Failed to reset map style URLs:", err))}, [])+ const hasCustom = savedLight.trim() !== "" || savedDark.trim() !== ""+return (<Container><ScrollView@@ -91,145 +145,119 @@ export function AppearanceScreen({}: ScreenProps) {keyboardShouldPersistTaps="handled"showsVerticalScrollIndicator={false}>- <Card>- <SettingRow label={t("appearance.darkMode")}>- <Switch- testID="dark-mode-switch"- value={mode === "dark"}- onValueChange={toggleTheme}- trackColor={{- false: colors.border,- true: colors.primary + "80"- }}- thumbColor={mode === "dark" ? colors.primary : colors.border}+ <Card rows style={showMapTileServer ? (hasCustom ? styles.cardTailButton : styles.cardTail) : undefined}>+ <SettingRow label={t("appearance.theme")}>+ <ChipGroup+ options={[+ { value: "system", label: t("appearance.theme.system"), testID: "theme-system" },+ { value: "light", label: t("appearance.theme.light"), testID: "theme-light" },+ { value: "dark", label: t("appearance.theme.dark"), testID: "theme-dark" }+ ]}+ selected={preference}+ onSelect={(value) => setPreference(value as ThemePreference)}/></SettingRow>- <Divider />+ {wallpaperColorsAvailable && (+ <>+ <Divider tight />+ {/* Present whenever the platform offers it, so a failed read cannot hide the way to turn it off. */}+ <SettingRow+ label={t("appearance.wallpaperColors")}+ hint={t("appearance.wallpaperColors.hint")}+ disabled={!wallpaperPaletteReady}+ >+ <Toggle+ testID="wallpaper-colors-toggle"+ value={wallpaperColors}+ onValueChange={setWallpaperColors}+ disabled={!wallpaperPaletteReady}+ accessibilityLabel={t("appearance.wallpaperColors")}+ />+ </SettingRow>+ </>+ )}- <SettingRow label={t("appearance.units")}>- <View style={styles.chipGroup}>- {(["metric", "imperial"] as const).map((unit) => {- const selected = unitSystem === unit- return (- <Pressable- key={unit}- testID={`unit-${unit}`}- style={[- styles.chip,- {- backgroundColor: selected ? colors.primary + "15" : colors.background,- borderColor: selected ? colors.primary : colors.border- }- ]}- onPress={() => selectUnitSystem(unit)}- >- <Text style={[styles.chipLabel, { color: selected ? colors.primary : colors.text }]}>- {unit === "metric" ? t("appearance.units.metric") : t("appearance.units.imperial")}- </Text>- </Pressable>- )- })}- </View>+ <Divider tight />++ <SettingRow label={t("appearance.units")} hint={unitNotation(unitSystem)}>+ <ChipGroup+ options={[+ { value: "metric", label: t("appearance.units.metric"), testID: "unit-metric" },+ { value: "imperial", label: t("appearance.units.imperial"), testID: "unit-imperial" }+ ]}+ selected={unitSystem}+ onSelect={selectUnitSystem}+ /></SettingRow>- <Divider />+ <Divider tight />- <SettingRow label={t("appearance.timeFormat")}>- <View style={styles.chipGroup}>- {(["24h", "12h"] as const).map((fmt) => {- const selected = timeFormat === fmt- return (- <Pressable- key={fmt}- testID={`time-format-${fmt}`}- style={[- styles.chip,- {- backgroundColor: selected ? colors.primary + "15" : colors.background,- borderColor: selected ? colors.primary : colors.border- }- ]}- onPress={() => selectTimeFormat(fmt)}- >- <Text style={[styles.chipLabel, { color: selected ? colors.primary : colors.text }]}>{fmt}</Text>- </Pressable>- )- })}- </View>+ <SettingRow label={t("appearance.timeFormat")} hint={clockSample(timeFormat)}>+ <ChipGroup+ options={[+ { value: "24h", label: t("appearance.timeFormat.24h"), testID: "time-format-24h" },+ { value: "12h", label: t("appearance.timeFormat.12h"), testID: "time-format-12h" }+ ]}+ selected={timeFormat}+ onSelect={selectTimeFormat}+ /></SettingRow>- <Divider />+ <Divider tight />- <Pressable+ <ListItemtestID="map-tile-server-toggle"- style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}+ label={t("appearance.mapTileServer")}+ sub={tileRowSub(savedLight, savedDark)}+ subLines={2}+ trailingIcon={showMapTileServer ? ChevronUp : ChevronDown}+ expanded={showMapTileServer}onPress={() => setShowMapTileServer(!showMapTileServer)}- >- <View style={styles.linkContent}>- <Text style={[styles.linkLabel, { color: colors.text }]}>{t("appearance.mapTileServer")}</Text>- <Text style={[styles.linkSub, { color: colors.textSecondary }]}>{t("appearance.mapStyle.subtitle")}</Text>- </View>- {showMapTileServer ? (- <ChevronUp size={20} color={colors.textLight} />- ) : (- <ChevronDown size={20} color={colors.textLight} />- )}- </Pressable>+ />{showMapTileServer && (- <View style={styles.mapTilePanel}>- <Text style={[styles.mapStyleSub, styles.mapStyleSubFirst, { color: colors.textSecondary }]}>- {t("appearance.mapStyle.light")}- </Text>- <TextInput- testID="map-style-url-light"- style={[- styles.mapStyleInput,- { borderColor: colors.border, color: colors.text, backgroundColor: colors.background }- ]}- value={mapStyleUrlLight}- onChangeText={setMapStyleUrlLight}- onBlur={() => saveMapStyleUrl("mapStyleUrlLight", mapStyleUrlLight)}- placeholder={t("appearance.mapStyle.placeholder")}- placeholderTextColor={colors.placeholder}- autoCapitalize="none"- autoCorrect={false}- keyboardType="url"- />- <Text style={[styles.mapStyleSub, styles.mapStyleSubSecond, { color: colors.textSecondary }]}>- {t("appearance.mapStyle.dark")}- </Text>- <TextInput- testID="map-style-url-dark"- style={[- styles.mapStyleInput,- { borderColor: colors.border, color: colors.text, backgroundColor: colors.background }- ]}- value={mapStyleUrlDark}- onChangeText={setMapStyleUrlDark}- onBlur={() => saveMapStyleUrl("mapStyleUrlDark", mapStyleUrlDark)}- placeholder={t("appearance.mapStyle.placeholder")}- placeholderTextColor={colors.placeholder}- autoCapitalize="none"- autoCorrect={false}- keyboardType="url"- />- <View style={styles.mapStyleFooter}>- <Text style={[styles.mapStyleHint, { color: colors.textLight }]}>- {t("appearance.mapStyle.emptyHint")}- </Text>- {mapStyleUrlLight.trim() || mapStyleUrlDark.trim() ? (- <Pressable- onPress={resetMapStyle}- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}- >- <Text style={[styles.mapStyleHint, { color: colors.primary }]}>- {t("appearance.mapStyle.reset")}- </Text>- </Pressable>- ) : null}+ <View style={styles.panel}>+ <View style={styles.fields}>+ <TextField+ testID="map-style-url-light"+ label={t("appearance.mapStyle.light")}+ mono+ value={draftLight}+ onChangeText={setDraftLight}+ onBlur={() => commitStyleUrl("mapStyleUrlLight", draftLight)}+ error={lightError}+ placeholder={t("appearance.mapStyle.placeholder")}+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ keyboardType="url"+ />+ <TextField+ testID="map-style-url-dark"+ label={t("appearance.mapStyle.dark")}+ mono+ value={draftDark}+ onChangeText={setDraftDark}+ onBlur={() => commitStyleUrl("mapStyleUrlDark", draftDark)}+ error={darkError}+ placeholder={t("appearance.mapStyle.placeholder")}+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ keyboardType="url"+ /></View>+ <FieldMessage>{t("appearance.mapStyle.emptyHint")}</FieldMessage>+ {hasCustom && (+ <Button+ variant="ghost"+ shape="rounded"+ testID="map-style-reset-btn"+ title={t("appearance.mapStyle.reset")}+ onPress={resetMapStyle}+ />+ )}</View>)}</Card>@@ -239,69 +267,17 @@ export function AppearanceScreen({}: ScreenProps) {}const styles = StyleSheet.create({+ // `rows` drops the card's vertical padding, and the panel's last child is not a row, so it comes back.+ cardTail: { paddingBottom: space.lg },+ cardTailButton: { paddingBottom: space.sm },scrollContent: {- paddingHorizontal: 16,- paddingTop: 16,- paddingBottom: 16- },- linkRow: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- paddingVertical: 12- },- linkContent: {- flex: 1- },- linkLabel: {- fontSize: 16,- ...fonts.semiBold,- marginBottom: 2- },- linkSub: {- fontSize: 13,- ...fonts.regular- },- chipGroup: {- flexDirection: "row",- gap: 8- },- chip: {- paddingHorizontal: 14,- paddingVertical: 8,- borderRadius: 10,- borderWidth: 1.5- },- chipLabel: {- fontSize: 13,- ...fonts.semiBold- },- mapTilePanel: {- marginTop: 4,- paddingBottom: 4- },- mapStyleSub: {- fontSize: 12,- ...fonts.medium,- marginBottom: 6- },- mapStyleSubFirst: { marginTop: 12 },- mapStyleSubSecond: { marginTop: 10 },- mapStyleInput: {- borderWidth: 1.5,- padding: 12,- borderRadius: 12,- fontSize: 13,- ...fonts.regular- },- mapStyleFooter: {- flexDirection: "row",- justifyContent: "space-between",- alignItems: "center",- marginTop: 8+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},- mapStyleHint: {- fontSize: 11,- ...fonts.regular+ // Pulled up against the owning row's bottom padding, so it groups with that row and not the next.+ panel: { marginTop: -space.xs },+ fields: {+ gap: space.lg}})diff --git a/apps/mobile/src/screens/LogPreviewScreen.tsx b/apps/mobile/src/screens/LogPreviewScreen.tsxnew file mode 100644index 00000000..e4dbe24e--- /dev/null+++ b/apps/mobile/src/screens/LogPreviewScreen.tsx@@ -0,0 +1,266 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"+import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, TextInput, View } from "react-native"+import { useFocusEffect } from "@react-navigation/native"+import { FileSearch, RefreshCw, Search, X } from "lucide-react-native"+import { ChipGroup, Container, Divider, EmptyState, HeaderAction } from "../components"+import { useTheme } from "../hooks/useTheme"+import { useTimeout } from "../hooks/useTimeout"+import NativeLocationService from "../services/NativeLocationService"+import { logger } from "../utils/logger"+import { getMergedLogs, type MergedLogEntry } from "../utils/logExport"+import {+ countByFloor,+ DEFAULT_LOG_FLOOR,+ floorOptions,+ levelLetter,+ logTime,+ passesFloor,+ resultLine,+ rowLabel,+ type LogFloor+} from "../utils/logCapture"+import type { ThemeColors } from "../types/global"+import type { LogLevel } from "../utils/logger"+import { fonts, fontSizes, lineHeights, type } from "../styles/typography"+import { HIT_SLOP_MD, LOG_FILTER_DEBOUNCE_MS, size, space, STATE_LAYER_ALPHA } from "../constants"+import { radius } from "@colota/shared"+import type { ScreenProps } from "../types/global"++function levelColor(level: LogLevel, colors: ThemeColors): string {+ switch (level) {+ case "ERROR":+ return colors.error+ case "WARN":+ return colors.warning+ case "INFO":+ return colors.info+ default:+ return colors.textLight+ }+}++/** Module level, or the list sees a new component type on every render. */+function LogLine({ entry }: { entry: MergedLogEntry }) {+ const { colors } = useTheme()+ const stamp = logTime(entry.time)+ return (+ <View style={styles.line} accessibilityRole="text" accessibilityLabel={rowLabel(entry, stamp)}>+ <Text style={[styles.mono, { color: levelColor(entry.level, colors) }]}>{levelLetter(entry.level)}</Text>+ <Text style={[styles.mono, { color: colors.textSecondary }]}>{stamp}</Text>+ <Text style={[styles.mono, styles.body, { color: colors.text }]} selectable>+ {entry.message}+ </Text>+ </View>+ )+}++export function LogPreviewScreen({ navigation }: ScreenProps) {+ const { colors } = useTheme()+ const debounce = useTimeout()++ const [entries, setEntries] = useState<MergedLogEntry[]>([])+ const [fromFile, setFromFile] = useState(false)+ const [loading, setLoading] = useState(true)+ const [text, setText] = useState("")+ const [query, setQuery] = useState("")+ const [floor, setFloor] = useState<LogFloor>(DEFAULT_LOG_FLOOR)++ const loadRef = useRef(false)++ const load = useCallback(async () => {+ if (loadRef.current) return+ loadRef.current = true+ try {+ const [merged, enabled] = await Promise.all([+ getMergedLogs(),+ NativeLocationService.getSetting("debugFileLoggingEnabled", "false")+ ])+ // Newest first: what the reporter just reproduced is what they came to read.+ setEntries(merged.slice().reverse())+ setFromFile(enabled === "true")+ } catch (err) {+ logger.error("[LogPreviewScreen] Failed to load logs:", err)+ } finally {+ loadRef.current = false+ setLoading(false)+ }+ }, [])++ useFocusEffect(+ useCallback(() => {+ load()+ }, [load])+ )++ const headerRight = useCallback(+ () => (+ <HeaderAction+ icon={RefreshCw}+ label="Refresh"+ hint="Reads the log again"+ onPress={load}+ testID="refresh-log-btn"+ />+ ),+ [load]+ )++ useLayoutEffect(() => {+ navigation.setOptions({ headerRight })+ }, [navigation, headerRight])++ const handleType = useCallback(+ (next: string) => {+ setText(next)+ debounce.set(() => setQuery(next), LOG_FILTER_DEBOUNCE_MS)+ },+ [debounce]+ )++ const clear = useCallback(() => {+ debounce.clear()+ setText("")+ setQuery("")+ }, [debounce])++ // Counted over the search-matched set, so a chip's number and the result line's agree.+ const matched = useMemo(() => {+ if (!query) return entries+ const needle = query.toLowerCase()+ return entries.filter((entry) => entry.message.toLowerCase().includes(needle))+ }, [entries, query])++ const counts = useMemo(() => countByFloor(matched), [matched])+ const shown = useMemo(() => matched.filter((entry) => passesFloor(entry.level, floor)), [matched, floor])+ const options = useMemo(() => floorOptions(counts), [counts])++ if (loading) {+ return (+ <Container>+ <View style={styles.centered}>+ <ActivityIndicator size="large" color={colors.primary} />+ </View>+ </Container>+ )+ }++ // A search box and four chips reading zero can do nothing, so the empty state owns the screen.+ if (entries.length === 0) {+ return (+ <Container>+ <EmptyState icon={FileSearch} title="Nothing logged yet" hint="Lines appear as the app records and syncs." />+ </Container>+ )+ }++ return (+ <Container>+ <View style={styles.head}>+ <View style={[styles.searchBox, { backgroundColor: colors.well }]}>+ <Search size={size.icon.sm} color={colors.textLight} />+ <TextInput+ style={[styles.searchInput, { color: colors.text }]}+ accessibilityLabel="Search the log"+ placeholder="Search the log"+ placeholderTextColor={colors.textLight}+ value={text}+ onChangeText={handleType}+ autoCapitalize="none"+ autoCorrect={false}+ testID="log-search-input"+ />+ {text.length > 0 ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Clear search"+ hitSlop={HIT_SLOP_MD}+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA, borderless: true, radius: size.icon.md }}+ onPress={clear}+ testID="clear-search-btn"+ >+ <X size={size.icon.md} color={colors.textLight} />+ </Pressable>+ ) : null}+ </View>++ <ChipGroup accessibilityLabel="Lowest level shown" options={options} selected={floor} onSelect={setFloor} />++ <Text style={[styles.result, { color: colors.textSecondary }]} numberOfLines={1} testID="log-result-line">+ {resultLine(shown.length, entries.length, fromFile)}+ </Text>+ </View>+ <Divider tight />++ <FlatList+ data={shown}+ keyExtractor={(entry) => entry.id}+ renderItem={({ item }) => <LogLine entry={item} />}+ contentContainerStyle={styles.list}+ initialNumToRender={30}+ maxToRenderPerBatch={20}+ windowSize={11}+ showsVerticalScrollIndicator+ ListEmptyComponent={+ <EmptyState icon={FileSearch} title="No lines match" hint="Try a different word, or lower the level." />+ }+ />+ </Container>+ )+}++const styles = StyleSheet.create({+ centered: {+ flex: 1,+ alignItems: "center",+ justifyContent: "center"+ },+ head: {+ paddingHorizontal: space.lg,+ paddingTop: space.sm,+ gap: space.sm+ },+ searchBox: {+ flexDirection: "row",+ alignItems: "center",+ borderRadius: radius.sm,+ paddingHorizontal: space.md,+ minHeight: size.touch,+ gap: space.sm+ },+ searchInput: {+ flex: 1,+ ...fonts.regular,+ fontSize: fontSizes.body,+ padding: 0+ },+ result: {+ fontSize: fontSizes.caption,+ lineHeight: lineHeights.caption,+ ...fonts.regular,+ fontVariant: ["tabular-nums"],+ paddingVertical: space.sm+ },+ list: {+ paddingVertical: space.sm,+ paddingBottom: space.xxl,+ flexGrow: 1+ },+ line: {+ flexDirection: "row",+ alignItems: "flex-start",+ gap: space.sm,+ paddingHorizontal: space.lg,+ paddingVertical: space.xxs+ },+ mono: {+ ...type.mono+ },+ body: {+ flex: 1+ }+})diff --git a/apps/mobile/src/screens/LoggingScreen.tsx b/apps/mobile/src/screens/LoggingScreen.tsxnew file mode 100644index 00000000..317ec468--- /dev/null+++ b/apps/mobile/src/screens/LoggingScreen.tsx@@ -0,0 +1,246 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useCallback, useRef, useState } from "react"+import { ScrollView, StyleSheet, Text, View } from "react-native"+import { useFocusEffect } from "@react-navigation/native"+import { FileSearch, Save, Trash2 } from "lucide-react-native"+import {+ Button,+ Card,+ Container,+ Divider,+ FieldMessage,+ ListItem,+ SectionTitle,+ SettingRow,+ StateLine,+ Toggle+} from "../components"+import { useTheme } from "../hooks/useTheme"+import { useTimeout } from "../hooks/useTimeout"+import NativeLocationService from "../services/NativeLocationService"+import { showAlert, showConfirm } from "../services/modalService"+import { logger } from "../utils/logger"+import { buildAppLog, buildExportHeader } from "../utils/logExport"+import {+ CAPTURE_HINT,+ deleteConfirmMessage,+ deleteSub,+ describeCapture,+ LOG_CONTENTS_LINE,+ nextStepLine,+ previewRowSub+} from "../utils/logCapture"+import { fonts, fontSizes, lineHeights } from "../styles/typography"+import { LOG_SIZE_SETTLE_MS, space } from "../constants"+import type { ScreenProps } from "../types/global"++type Busy = "save" | "delete" | null++const INTRO = "Start recording, reproduce the problem, then save the log file and attach it to your report."++export function LoggingScreen({ navigation }: ScreenProps) {+ const { colors } = useTheme()+ const settle = useTimeout()++ const [enabled, setEnabled] = useState(false)+ const [bytes, setBytes] = useState(0)+ const [startedAt, setStartedAt] = useState(0)+ const [loaded, setLoaded] = useState(false)+ const [busy, setBusy] = useState<Busy>(null)++ // A ref, not the state, because two presses inside one render both read the same state value.+ const busyRef = useRef(false)++ const read = useCallback(async () => {+ const [enabledResult, sizeResult, startedResult] = await Promise.allSettled([+ NativeLocationService.getSetting("debugFileLoggingEnabled", "false"),+ NativeLocationService.getFileLogSize(),+ NativeLocationService.getSetting("debugFileLoggingStartedAt", "")+ ])+ if (enabledResult.status === "fulfilled") setEnabled(enabledResult.value === "true")+ if (sizeResult.status === "fulfilled") setBytes(sizeResult.value)+ if (startedResult.status === "fulfilled") setStartedAt(Number(startedResult.value ?? 0) || 0)+ setLoaded(true)+ }, [])++ useFocusEffect(+ useCallback(() => {+ read()+ }, [read])+ )++ const handleToggle = useCallback(+ async (value: boolean) => {+ setEnabled(value)+ try {+ await NativeLocationService.setFileLoggingEnabled(value)+ } catch (err) {+ logger.error("[LoggingScreen] setFileLoggingEnabled failed:", err)+ setEnabled(!value)+ showAlert("Could not change logging", "The setting was not saved. Try again.", "error")+ return+ }+ // Native stamps the start and the first lines land off-thread, so read once it settles.+ settle.set(() => {+ read()+ }, LOG_SIZE_SETTLE_MS)+ },+ [read, settle]+ )++ const handleSave = useCallback(async () => {+ if (busyRef.current) return+ if (!(await showConfirm({ title: "Save the log file?", message: LOG_CONTENTS_LINE, confirmText: "Choose folder" })))+ return++ const treeUri = await NativeLocationService.pickExportDirectory()+ if (!treeUri) return++ busyRef.current = true+ setBusy("save")+ try {+ const buildConfig = NativeLocationService.getBuildConfig()+ let deviceInfo = null+ try {+ const info = await NativeLocationService.getDeviceInfo()+ deviceInfo = { ...info, apiLevel: String(info.apiLevel) }+ } catch {+ // The header names what it can; a missing device block must not fail the save.+ }+ const header = buildExportHeader(buildConfig, deviceInfo, startedAt, Date.now())+ const written = await NativeLocationService.exportFileLogToUri(treeUri, header, buildAppLog())+ if (written) {+ showAlert("Log saved", "The file is in the folder you chose. Attach it to your report.", "success")+ } else {+ showAlert("Nothing to save", "There are no recorded log entries yet.", "info")+ }+ } catch (err) {+ logger.error("[LoggingScreen] save failed:", err)+ showAlert("Could not save the log", err instanceof Error ? err.message : "Pick a different folder.", "error")+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [startedAt])++ const handleDelete = useCallback(async () => {+ if (busyRef.current) return+ if (+ !(await showConfirm({+ title: "Delete the log file?",+ message: deleteConfirmMessage(bytes),+ confirmText: "Delete",+ destructive: true+ }))+ ) {+ return+ }+ busyRef.current = true+ setBusy("delete")+ try {+ await NativeLocationService.clearFileLog()+ await read()+ } catch (err) {+ logger.error("[LoggingScreen] clearFileLog failed:", err)+ showAlert("Could not delete the log", "The file is still there. Try again.", "error")+ } finally {+ busyRef.current = false+ setBusy(null)+ }+ }, [bytes, read])++ const state = describeCapture(enabled, bytes, startedAt)++ return (+ <Container>+ <ScrollView contentContainerStyle={styles.scrollContent}>+ <Text style={[styles.intro, { color: colors.textSecondary }]}>{INTRO}</Text>++ {!loaded ? null : (+ <>+ <View style={styles.section}>+ <Card rows>+ <StateLine+ icon={state.icon}+ iconColor={state.tone === "recording" ? colors.primary : colors.textSecondary}+ label={state.label}+ caption={state.caption}+ testID="capture-state"+ />+ <Divider tight />+ <SettingRow label="Record a log file" hint={CAPTURE_HINT}>+ <Toggle+ accessibilityLabel="Record a log file"+ value={enabled}+ onValueChange={handleToggle}+ testID="file-logging-toggle"+ />+ </SettingRow>+ <Divider tight />+ <ListItem+ icon={FileSearch}+ label="Read the log"+ sub={previewRowSub(enabled)}+ subLines={2}+ onPress={() => navigation.navigate("Log Preview")}+ testID="nav-log-preview"+ />+ </Card>+ {bytes === 0 ? <FieldMessage>{nextStepLine(enabled)}</FieldMessage> : null}+ </View>++ {bytes > 0 ? (+ <View style={styles.section}>+ <SectionTitle>The log file</SectionTitle>+ <View>+ <Button+ icon={Save}+ title="Save log file…"+ testID="save-log-btn"+ loading={busy === "save"}+ disabled={busy !== null}+ onPress={handleSave}+ />+ <FieldMessage variant="warning">{LOG_CONTENTS_LINE}</FieldMessage>+ </View>+ <View>+ <Button+ icon={Trash2}+ variant="danger"+ title="Delete the log file"+ testID="delete-log-btn"+ loading={busy === "delete"}+ disabled={busy !== null}+ onPress={handleDelete}+ />+ <FieldMessage>{deleteSub(bytes, enabled)}</FieldMessage>+ </View>+ </View>+ ) : null}+ </>+ )}+ </ScrollView>+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: {+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl+ },+ intro: {+ fontSize: fontSizes.body,+ ...fonts.regular,+ lineHeight: lineHeights.body,+ marginBottom: space.lg+ },+ section: {+ marginBottom: space.xl+ }+})diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex a0304649..24bd7588 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -6,148 +6,207 @@import React, { useState, useCallback, useMemo, useEffect } from "react"import { useFocusEffect } from "@react-navigation/native"import { StyleSheet, View, ScrollView, Linking, DeviceEventEmitter } from "react-native"-import { TRACKING_PRESETS, API_TEMPLATES } from "../types/global"import type { RootScreenProps } from "../types/navigation"import NativeLocationService from "../services/NativeLocationService"import { useTracking } from "../contexts/TrackingProvider"-import { SectionTitle, Card, Container, Divider, StatsCard, ListItem } from "../components"+import { useTheme } from "../hooks/useTheme"+import { showAlert } from "../services/modalService"+import { SectionTitle, Card, Container, Divider, ListItem } from "../components"import {- ExternalLink,+ Archive,+ ArrowUpDown,Cloud,- Navigation,- Braces,- UserRoundPen,- Palette,Database,- Download,- Upload,+ ExternalLink,+ Heart,+ Info,Map,+ MessageCircle,+ Navigation,+ Palette,ScrollText,- ShieldCheck,- Info,- Heart,- Clock,- Share2+ Sparkles,+ Share2,+ Star,+ UserRoundPen} from "lucide-react-native"+import { getTimeFormat, getUnitSystem } from "../utils/geo"+import { trackingSummary } from "../utils/dashboardState"+import { describeServer } from "../utils/serverState"+import { profileStateLabel } from "../utils/profileRow"+import { dataRowSub, loggingRowSub, offlineMapsRowSub, versionLine } from "../utils/settingsRow"+import { ProfileService } from "../services/ProfileService"+import { loadOfflineAreas, type OfflineAreaInfo } from "../components/features/map/OfflinePackManager"+import { appearanceRowSub } from "../utils/appearance"+import { backupRowSub } from "../utils/backupState"+import { transferRowSub } from "../utils/locationTransfer"import { logger } from "../utils/logger"+import { space, RELEASES_URL, ISSUES_URL, SUPPORT_URL, PLAY_STORE_MARKET_URL, PLAY_STORE_WEB_URL } from "../constants"type Props = RootScreenProps<"Settings">+type AutoExportStatus = Awaited<ReturnType<typeof NativeLocationService.getAutoExportStatus>>+export function SettingsScreen({ navigation }: Props) {- const { settings } = useTracking()+ const { settings, activeProfileName, tracking } = useTracking()+ const { colors, preference } = useTheme()+ const [totalCount, setTotalCount] = useState(0)+ const [databaseSizeMB, setDatabaseSizeMB] = useState(0)const [queueCount, setQueueCount] = useState(0)- const [sentCount, setSentCount] = useState(0)const [todayCount, setTodayCount] = useState(0)+ const [lastSyncTime, setLastSyncTime] = useState(0)+ const [lastSyncError, setLastSyncError] = useState("")+ const [deviceOnline, setDeviceOnline] = useState(true)+ const [lastBackupAt, setLastBackupAt] = useState<number | null>(null)+ const [profileCount, setProfileCount] = useState(0)+ const [autoExport, setAutoExport] = useState<AutoExportStatus | null>(null)+ const [fileLogging, setFileLogging] = useState({ enabled: false, bytes: 0 })+ const [offlineAreas, setOfflineAreas] = useState<OfflineAreaInfo[]>([])+ const [, setFocusTick] = useState(0)- const updateStats = useCallback(async () => {+ /** The two cheap reads behind the Connection sub; every sync event re-runs these alone. */+ const readSyncState = useCallback(async () => {+ const [stats, online] = await Promise.allSettled([+ NativeLocationService.getStats(),+ NativeLocationService.isNetworkAvailable()+ ])+ if (stats.status === "fulfilled") {+ setTotalCount(stats.value.total)+ setDatabaseSizeMB(stats.value.databaseSizeMB)+ setQueueCount(stats.value.queued)+ setTodayCount(stats.value.today)+ setLastSyncTime(stats.value.lastSyncTime ?? 0)+ setLastSyncError(stats.value.lastSyncError ?? "")+ } else {+ logger.error("[SettingsScreen] Failed to get stats:", stats.reason)+ }+ if (online.status === "fulfilled") setDeviceOnline(online.value)+ }, [])++ const readAutoExport = useCallback(async () => {try {- const stats = await NativeLocationService.getStats()- setQueueCount(stats.queued)- setSentCount(stats.sent)- setTodayCount(stats.today)+ setAutoExport(await NativeLocationService.getAutoExportStatus())} catch (err) {- logger.error("[SettingsScreen] Failed to get stats:", err)+ logger.error("[SettingsScreen] Failed to read the auto-export status:", err)}}, [])+ /** Every sub keeps its last value when its own read rejects, so one slow pack walk never blanks the card. */+ 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([+ readSyncState(),+ ProfileService.getProfiles(),+ NativeLocationService.getAutoExportStatus(),+ NativeLocationService.getSetting("debugFileLoggingEnabled", "false"),+ NativeLocationService.getFileLogSize(),+ loadOfflineAreas(),+ NativeLocationService.getSetting("last_backup_at", "0")+ ])+ if (profiles.status === "fulfilled") setProfileCount(profiles.value.length)+ if (exportStatus.status === "fulfilled") setAutoExport(exportStatus.value)+ setFileLogging((prev) => ({+ enabled: logEnabled.status === "fulfilled" ? logEnabled.value === "true" : prev.enabled,+ bytes: logBytes.status === "fulfilled" ? logBytes.value : prev.bytes+ }))+ 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.+ setFocusTick((tick) => tick + 1)+ }, [readSyncState])+useFocusEffect(useCallback(() => {- updateStats()+ readAll()const subs = [- DeviceEventEmitter.addListener("onLocationUpdate", updateStats),- DeviceEventEmitter.addListener("onSyncProgress", updateStats),- DeviceEventEmitter.addListener("onSyncError", updateStats)+ DeviceEventEmitter.addListener("onLocationUpdate", readSyncState),+ DeviceEventEmitter.addListener("onSyncProgress", readSyncState),+ DeviceEventEmitter.addListener("onSyncError", readSyncState),+ DeviceEventEmitter.addListener("onAutoExportComplete", readAutoExport)]return () => subs.forEach((s) => s.remove())- }, [updateStats])+ }, [readAll, readSyncState, readAutoExport]))useEffect(() => {- updateStats()- }, [settings.isOfflineMode, settings.endpoint, updateStats])+ readSyncState()+ }, [settings.isOfflineMode, settings.endpoint, readSyncState])- const connectionSummary = useMemo(() => {- if (settings.isOfflineMode) return "Offline - saved locally"- if (!settings.endpoint) return "No server configured"- try {- return new URL(settings.endpoint).host- } catch {- return settings.endpoint- }- }, [settings.isOfflineMode, settings.endpoint])+ const server = useMemo(+ () =>+ describeServer({+ offline: settings.isOfflineMode,+ endpoint: settings.endpoint,+ deviceOnline,+ queued: queueCount,+ today: todayCount,+ lastSyncTime,+ lastSyncError+ }),+ [settings.isOfflineMode, settings.endpoint, deviceOnline, queueCount, todayCount, lastSyncTime, lastSyncError]+ )- const syncSummary = useMemo(() => {- const preset = settings.syncPreset- if (preset !== "custom" && TRACKING_PRESETS[preset]) {- return `${TRACKING_PRESETS[preset].label} · every ${settings.interval}s`- }- return `Custom · every ${settings.interval}s`- }, [settings.syncPreset, settings.interval])+ const syncSummary = useMemo(+ () => trackingSummary(settings.interval, settings.distance, settings.syncInterval, settings.isOfflineMode),+ [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.+ const appearanceSummary = appearanceRowSub(preference, getUnitSystem(), getTimeFormat())++ const profileSummary = profileCount === 0 ? "No profiles yet" : profileStateLabel(activeProfileName, tracking)+ const inForce = profileCount > 0 && tracking && !!activeProfileName+ const serverTint = server.tone === "error" ? colors.error : server.tone === "warning" ? colors.warning : undefined- const apiSummary = useMemo(() => {- const template = settings.apiTemplate- if (template === "custom") {- const fieldCount = Object.values(settings.fieldMap).filter(Boolean).length + settings.customFields.length- return `Custom (${fieldCount} field${fieldCount === 1 ? "" : "s"})`+ 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("Error", "Could not open the link.", "error")}- return API_TEMPLATES[template]?.label ?? "Custom"- }, [settings.apiTemplate, settings.fieldMap, settings.customFields])+ }, [])- const handleNavigateDataManagement = useCallback(() => {- navigation.navigate("Data Management")- }, [navigation])+ const isPlayBuild = NativeLocationService.getBuildConfig()?.FLAVOR === "gms"return (<Container>- <ScrollView- contentContainerStyle={styles.scrollContent}- keyboardShouldPersistTaps="handled"- showsVerticalScrollIndicator={false}- >- <StatsCard- queueCount={queueCount}- sentCount={sentCount}- todayCount={todayCount}- interval={settings.interval.toString()}- onManageClick={handleNavigateDataManagement}- />-+ <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}><View style={styles.section}>- <Card>+ <SectionTitle>Tracking</SectionTitle>+ <Card rows><ListItemtestID="nav-connection"icon={Cloud}+ iconColor={serverTint}label="Connection"- sub={connectionSummary}+ sub={server.rowSub}+ subLines={2}onPress={() => navigation.navigate("Connection")}/>- <Divider />+ <Divider tight inset /><ListItemtestID="nav-tracking-sync"icon={Navigation}- label="Tracking & Sync"+ label="Tracking & sync"sub={syncSummary}onPress={() => navigation.navigate("Tracking & Sync")}/>- {!settings.isOfflineMode && (- <>- <Divider />- <ListItem- testID="nav-api-config"- icon={Braces}- label="API Field Mapping"- sub={apiSummary}- onPress={() => navigation.navigate("Request Format")}- />- </>- )}- <Divider />+ <Divider tight inset /><ListItemtestID="nav-tracking-profiles"icon={UserRoundPen}- label="Tracking Profiles"- sub="Auto-switch GPS settings based on conditions"+ iconColor={inForce ? colors.success : undefined}+ label="Tracking profiles"+ sub={profileSummary}onPress={() => navigation.navigate("Tracking Profiles")}/></Card>@@ -155,105 +214,130 @@ export function SettingsScreen({ navigation }: Props) {<View style={styles.section}><SectionTitle>Display</SectionTitle>- <Card>+ <Card rows><ListItemtestID="nav-appearance"icon={Palette}label="Appearance"- sub="Theme, units, time format and map tiles"+ sub={appearanceSummary}onPress={() => navigation.navigate("Appearance")}/>+ <Divider tight inset />+ <ListItem+ testID="nav-offline-maps"+ icon={Map}+ label="Offline maps"+ sub={offlineMapsRowSub(offlineAreas)}+ onPress={() => navigation.navigate("Offline Maps")}+ /></Card></View><View style={styles.section}><SectionTitle>Data</SectionTitle>- <Card>+ <Card rows><ListItemtestID="nav-data-management"icon={Database}- label="Data Management"- sub="View queue and clear data"+ label="Data management"+ sub={dataRowSub(totalCount, databaseSizeMB)}onPress={() => navigation.navigate("Data Management")}/>- <Divider />+ <Divider tight inset /><ListItem- testID="nav-import-locations"- icon={Download}- label="Export & Import"- sub="Merge locations from a GeoJSON or Google Timeline file"+ testID="nav-export-import"+ icon={ArrowUpDown}+ label="Export & import"+ sub={transferRowSub(autoExport)}+ subLines={2}onPress={() => navigation.navigate("Export & Import")}/>- <Divider />- <ListItem- testID="nav-export-locations"- icon={Upload}- label="Export & Import"- sub="Export locations as CSV, GeoJSON, GPX or KML"- onPress={() => navigation.navigate("Export & Import")}- />- <Divider />- <ListItem- testID="nav-auto-export"- icon={Clock}- label="Auto-Export"- sub="Schedule daily, weekly or monthly exports"- onPress={() => navigation.navigate("Auto-Export")}- />- <Divider />+ <Divider tight inset /><ListItemtestID="nav-backup-restore"- icon={ShieldCheck}- label="Backup & Restore"- sub="Encrypted backup of all your data"+ icon={Archive}+ label="Backup & restore"+ sub={backupRowSub(lastBackupAt)}onPress={() => navigation.navigate("Backup & Restore")}/>- <Divider />+ <Divider tight inset /><ListItemtestID="nav-share-setup"icon={Share2}- label="Share Setup"- sub="Share your settings, geofences and profiles as a link"+ label="Share setup"+ sub="Settings, geofences and profiles as a link"onPress={() => navigation.navigate("Share Setup")}/>- <Divider />- <ListItem- testID="nav-offline-maps"- icon={Map}- label="Offline Maps"- sub="Download map tiles for use without internet"- onPress={() => navigation.navigate("Offline Maps")}- />- <Divider />+ </Card>+ </View>++ <View style={styles.section}>+ <SectionTitle>Help</SectionTitle>+ <Card rows><ListItemtestID="nav-logging"icon={ScrollText}label="Logging"- sub="View activity log and configure file logging"+ sub={loggingRowSub(fileLogging.enabled, fileLogging.bytes)}onPress={() => navigation.navigate("Logging")}/>+ <Divider tight inset />+ <ListItem+ testID="nav-feedback"+ icon={MessageCircle}+ label="Feedback & help"+ sub="github.com/dietrichmax/colota/issues"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ onPress={() => openLink(ISSUES_URL)}+ />+ <Divider tight inset />+ <ListItem+ testID="nav-whats-new"+ icon={Sparkles}+ label="What's new"+ sub="colota.app/releases"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ onPress={() => openLink(RELEASES_URL)}+ /></Card></View><View style={styles.section}>- <Card>- <ListItem- testID="nav-about"- icon={Info}- label="About Colota"- sub="Version, licenses and links"- onPress={() => navigation.navigate("About Colota")}- />- <Divider />+ <SectionTitle>About</SectionTitle>+ <Card rows>+ {isPlayBuild && (+ <>+ <ListItem+ testID="nav-rate"+ icon={Star}+ label="Rate the app"+ sub="Google Play"+ trailingIcon={ExternalLink}+ accessibilityRole="link"+ accessibilityHint="Opens Colota in Google Play"+ onPress={() => openLink(PLAY_STORE_MARKET_URL, PLAY_STORE_WEB_URL)}+ />+ <Divider tight inset />+ </>+ )}<ListItemtestID="nav-support"icon={Heart}- label="Support"- sub="Support development of the app"+ label="Say thanks"+ sub="mxd.codes/support"trailingIcon={ExternalLink}accessibilityRole="link"- accessibilityHint="Opens external support page"- onPress={() => Linking.openURL("https://mxd.codes/support")}+ onPress={() => openLink(SUPPORT_URL)}+ />+ <Divider tight inset />+ <ListItem+ testID="nav-about"+ icon={Info}+ label="About"+ sub={`Version ${versionLine(NativeLocationService.getBuildConfig())}`}+ onPress={() => navigation.navigate("About Colota")}/></Card></View>@@ -264,11 +348,11 @@ export function SettingsScreen({ navigation }: Props) {const styles = StyleSheet.create({scrollContent: {- paddingHorizontal: 16,- paddingTop: 16,- paddingBottom: 16+ paddingHorizontal: space.lg,+ paddingTop: space.lg,+ paddingBottom: space.xxl},section: {- marginBottom: 24+ marginBottom: space.xl}})diff --git a/apps/mobile/src/screens/__tests__/AboutScreen.test.tsx b/apps/mobile/src/screens/__tests__/AboutScreen.test.tsxindex 85f68539..fe61de58 100644--- a/apps/mobile/src/screens/__tests__/AboutScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AboutScreen.test.tsx@@ -2,231 +2,134 @@ import React from "react"import { render, fireEvent, waitFor } from "@testing-library/react-native"import { Linking } from "react-native"-// --- Mocks -----jest.mock("@react-navigation/native", () => ({- useFocusEffect: jest.fn()-}))-jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- colors: {- primary: "#0d9488",- text: "#000",- textSecondary: "#6b7280",- card: "#fff",- warning: "#f59e0b",- border: "#e5e7eb",- textLight: "#9ca3af",- success: "#22c55e",- primaryDark: "#0d9488",- textOnPrimary: "#fff",- background: "#fff"- },- mode: "light"- })-}))--jest.mock("../../hooks/useTimeout", () => ({- useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })+ useTheme: () => ({ colors: require("@colota/shared").lightColors })}))-const mockGetBuildConfig = jest.fn().mockReturnValue({- VERSION_NAME: "1.3.0",- VERSION_CODE: 10,- FLAVOR: "foss",- TARGET_SDK_VERSION: 35,- MIN_SDK_VERSION: 26,- COMPILE_SDK_VERSION: 35,- BUILD_TOOLS_VERSION: "35.0.0",- KOTLIN_VERSION: "2.0.0",- NDK_VERSION: "27.0.0"-})-const mockGetSetting = jest.fn().mockResolvedValue("false")-const mockSaveSetting = jest.fn().mockResolvedValue(undefined)-const mockGetDeviceInfo = jest.fn().mockResolvedValue({- model: "Pixel 8",- brand: "Google",- deviceId: "abc123",- systemVersion: "15",- apiLevel: 35-})-const mockCopyToClipboard = jest.fn().mockResolvedValue(undefined)-const mockGetNativeLogs = jest.fn().mockResolvedValue([])-const mockWriteFile = jest.fn().mockResolvedValue("/tmp/logs.txt")-const mockShareFile = jest.fn().mockResolvedValue(undefined)-+// getBuildConfig only. Any device read from this screen must fail this suite: the phone belongs to+// Android's own About phone and to the log header, not here.+let mockBuildConfig: { VERSION_NAME: string; VERSION_CODE: number; FLAVOR: string } | nulljest.mock("../../services/NativeLocationService", () => ({__esModule: true,- default: {- getBuildConfig: (...args: any[]) => mockGetBuildConfig(...args),- getSetting: (...args: any[]) => mockGetSetting(...args),- saveSetting: (...args: any[]) => mockSaveSetting(...args),- getDeviceInfo: (...args: any[]) => mockGetDeviceInfo(...args),- copyToClipboard: (...args: any[]) => mockCopyToClipboard(...args),- getNativeLogs: (...args: any[]) => mockGetNativeLogs(...args),- writeFile: (...args: any[]) => mockWriteFile(...args),- shareFile: (...args: any[]) => mockShareFile(...args)- }+ default: { getBuildConfig: () => mockBuildConfig }}))-jest.mock("../../utils/logger", () => ({- logger: { error: jest.fn() }+const mockShowAlert = jest.fn()+jest.mock("../../services/modalService", () => ({+ showAlert: (...a: unknown[]) => mockShowAlert(...a)}))-jest.mock("../../utils/logExport", () => ({- exportLogs: jest.fn().mockResolvedValue(undefined)-}))+jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))jest.mock("../../assets/icons/icon.png", () => "mock-icon")jest.mock("../../components", () => {const R = require("react")- const { View, Text } = require("react-native")+ const { View, Text, Pressable } = require("react-native")return {Container: ({ children }: any) => R.createElement(View, null, children),Card: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => null,SectionTitle: ({ children }: any) => R.createElement(Text, null, children),- Footer: () => R.createElement(View, null),- Divider: () => R.createElement(View, null)- }-})--jest.mock("lucide-react-native", () => {- const R = require("react")- const { Text } = require("react-native")- const stub = (name: string) => (_props: any) => R.createElement(Text, null, name)- return {- ExternalLink: stub("ExternalLink"),- Bug: stub("Bug"),- FileText: stub("FileText"),- Code: stub("Code"),- ScrollText: stub("ScrollText"),- MessageCircle: stub("MessageCircle"),- Copy: stub("Copy"),- Check: stub("Check")+ // The rows must carry the link role that ListItem turns into "Opens {label} in the browser",+ // so the role has to reach the assertion.+ ListItem: ({ label, sub, onPress, testID, accessibilityRole }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress, accessibilityRole },+ R.createElement(Text, null, label),+ sub ? R.createElement(Text, null, sub) : null+ )}})import { AboutScreen } from "../AboutScreen"-describe("AboutScreen", () => {- beforeEach(() => {- jest.clearAllMocks()- mockGetSetting.mockResolvedValue("false")- jest.spyOn(Linking, "openURL").mockResolvedValue(true as any)- })-- function renderScreen() {- return render(<AboutScreen navigation={{} as any} />)- }-- it("renders app title and version", () => {- const { getByText } = renderScreen()-- expect(getByText("Colota")).toBeTruthy()- expect(getByText("Version 1.3.0")).toBeTruthy()- })-- it("shows tap hint after first taps", () => {- const { getByText } = renderScreen()-- const versionText = getByText("Version 1.3.0")- fireEvent.press(versionText)-- expect(getByText("6 more taps to enable debug mode")).toBeTruthy()- })+const COPYRIGHT = /Copyright © 2026 Max Dietrich and contributors\. Colota is free software, with no warranty/- it("enables debug mode after 7 taps", async () => {- const { getByText } = renderScreen()+const renderScreen = () => render(<AboutScreen navigation={{} as any} />)- const versionText = getByText("Version 1.3.0")- for (let i = 0; i < 7; i++) {- fireEvent.press(versionText)- }+beforeEach(() => {+ jest.clearAllMocks()+ mockBuildConfig = { VERSION_NAME: "1.3.0", VERSION_CODE: 10, FLAVOR: "foss" }+ jest.spyOn(Linking, "openURL").mockResolvedValue(true as any)+})- await waitFor(() => {- expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()- })+describe("AboutScreen", () => {+ // The changelog files, Play's crash reports and F-Droid are keyed by the code, and one+ // versionName has shipped under two of them.+ it("prints the app's name and the version line with the build code the changelog files are keyed by", () => {+ const api = renderScreen()- expect(mockSaveSetting).toHaveBeenCalledWith("debug_mode_enabled", "true")+ expect(api.getByText("Colota")).toBeTruthy()+ expect(api.getByText("Version 1.3.0 (10) · FOSS")).toBeTruthy()})- it("shows debug badge when debug mode is enabled", async () => {- const { getByText } = renderScreen()-- const versionText = getByText("Version 1.3.0")- for (let i = 0; i < 7; i++) {- fireEvent.press(versionText)- }+ // Play requires the privacy policy link inside the app, so it cannot depend on a bridge module.+ it("says Unknown when the build module did not link, and still renders every legal row", () => {+ mockBuildConfig = null+ const api = renderScreen()- await waitFor(() => {- expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()- })+ expect(api.getByText("Version Unknown")).toBeTruthy()+ expect(api.getByTestId("nav-privacy-policy")).toBeTruthy()+ expect(api.getByTestId("nav-license")).toBeTruthy()+ expect(api.getByTestId("nav-source-code")).toBeTruthy()+ expect(api.getByText(COPYRIGHT)).toBeTruthy()})- it("shows BUILD section with SDK info when debug enabled", async () => {- const { getByText } = renderScreen()-- const versionText = getByText("Version 1.3.0")- for (let i = 0; i < 7; i++) {- fireEvent.press(versionText)- }-- await waitFor(() => {- expect(getByText("BUILD")).toBeTruthy()- })-- expect(getByText("FOSS")).toBeTruthy()- expect(getByText("35 (Android 15)")).toBeTruthy()- expect(getByText("26 (Android 8.0)")).toBeTruthy()- expect(getByText("35.0.0")).toBeTruthy()- expect(getByText("2.0.0")).toBeTruthy()- expect(getByText("27.0.0")).toBeTruthy()+ it("links the privacy policy, the licence and the source, each a link row naming its host", async () => {+ const api = renderScreen()++ fireEvent.press(api.getByTestId("nav-privacy-policy"))+ expect(Linking.openURL).toHaveBeenLastCalledWith("https://colota.app/privacy-policy")+ fireEvent.press(api.getByTestId("nav-license"))+ expect(Linking.openURL).toHaveBeenLastCalledWith("https://github.com/dietrichmax/colota/blob/main/LICENSE")+ fireEvent.press(api.getByTestId("nav-source-code"))+ expect(Linking.openURL).toHaveBeenLastCalledWith("https://github.com/dietrichmax/colota")++ expect(api.getByText("colota.app/privacy-policy")).toBeTruthy()+ expect(api.getByText("GNU AGPLv3")).toBeTruthy()+ expect(api.getByText("github.com/dietrichmax/colota")).toBeTruthy()+ expect(await api.findAllByRole("link")).toHaveLength(3)+ expect(api.queryAllByRole("button")).toHaveLength(0)})- it("disables debug mode when debug badge is tapped", async () => {- const { getByText, queryByText } = renderScreen()-- const versionText = getByText("Version 1.3.0")- for (let i = 0; i < 7; i++) {- fireEvent.press(versionText)- }-- await waitFor(() => {- expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()- })-- mockSaveSetting.mockClear()-- fireEvent.press(getByText("Debug Mode (tap to hide)"))+ it("reports a link the device refused, because the user pressed it", async () => {+ jest.spyOn(Linking, "openURL").mockRejectedValue(new Error("no handler"))+ const api = renderScreen()- await waitFor(() => {- expect(queryByText("Debug Mode (tap to hide)")).toBeNull()- })+ fireEvent.press(api.getByTestId("nav-source-code"))- expect(mockSaveSetting).toHaveBeenCalledWith("debug_mode_enabled", "false")+ await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Could not open the link.", "error"))})- it("loads persisted debug mode on mount", async () => {- mockGetSetting.mockResolvedValue("true")+ // AGPL section 0 asks for the notice once; the app carried it twice, two screens apart.+ it("carries the copyright and no-warranty notice once, under the License row it points at", () => {+ const api = renderScreen()- const { getByText } = renderScreen()-- await waitFor(() => {- expect(getByText("Debug Mode (tap to hide)")).toBeTruthy()- })-- expect(mockGetSetting).toHaveBeenCalledWith("debug_mode_enabled", "false")+ expect(api.getAllByText(COPYRIGHT)).toHaveLength(1)})- it("opens Privacy Policy URL when link pressed", async () => {- const { getByText } = renderScreen()-- fireEvent.press(getByText("Privacy Policy"))-- await waitFor(() => {- expect(Linking.openURL).toHaveBeenCalledWith("https://colota.app/privacy-policy")- })+ // The phone is on Android's About phone and in the log header; the toolchain is in build.gradle+ // at the tag; the map credits are on the map's own dialog, live from the style.+ it("shows nothing about the phone, the toolchain or the map, which the log file and the map's own dialog carry", () => {+ const api = renderScreen()++ for (const gone of [+ "Build",+ "Device",+ "Variant",+ "Target SDK",+ "Kotlin",+ "NDK",+ "Model",+ "Device ID",+ "Copy debug info",+ "Map data",+ "OpenStreetMap",+ "Colota tiles"+ ]) {+ expect(api.queryByText(gone)).toBeNull()+ }})})diff --git a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsxindex f1692266..e4a2353a 100644--- a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx@@ -3,34 +3,32 @@ import { render, fireEvent, waitFor } from "@testing-library/react-native"// --- Mocks ----const mockToggleTheme = jest.fn()+const mockSetPreference = jest.fn()+const mockSetWallpaperColors = jest.fn()+const theme = { wallpaperColors: false, wallpaperColorsAvailable: true, wallpaperPaletteReady: true }jest.mock("../../hooks/useTheme", () => ({useTheme: () => ({mode: "light",- toggleTheme: mockToggleTheme,- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- card: "#fff",- backgroundElevated: "#f9fafb",- placeholder: "#9ca3af"- }+ preference: "system",+ setPreference: mockSetPreference,+ wallpaperColors: theme.wallpaperColors,+ setWallpaperColors: mockSetWallpaperColors,+ wallpaperColorsAvailable: theme.wallpaperColorsAvailable,+ wallpaperPaletteReady: theme.wallpaperPaletteReady,+ colors: require("@colota/shared").lightColors})}))const mockSaveSetting = jest.fn().mockResolvedValue(undefined)+const mockGetSetting = jest.fn().mockResolvedValue(null)jest.mock("../../services/NativeLocationService", () => ({__esModule: true,default: {saveSetting: (key: string, value: string) => mockSaveSetting(key, value),- getSetting: jest.fn().mockResolvedValue(null)+ getSetting: (key: string) => mockGetSetting(key),+ getBuildConfig: () => ({ APP_LANGUAGE: "en-GB" })}}))@@ -45,10 +43,51 @@ jest.mock("../../components", () => {const R = require("react")const { View, Text } = require("react-native")return {+ ListItem: require("../../testing/componentStubs").ListItemStub,+ TextField: require("../../testing/componentStubs").TextFieldStub,+ ChipGroup: function (props: any) {+ const RN = require("react-native")+ return R.createElement(+ View,+ null,+ props.options.map(function (o: any) {+ return R.createElement(+ RN.Pressable,+ { key: o.value, testID: o.testID, onPress: () => props.onSelect(o.value) },+ R.createElement(Text, null, o.label)+ )+ })+ )+ },+ Button: function (props: any) {+ return require("react").createElement(+ require("react-native").Pressable,+ { testID: props.testID, onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },+ require("react").createElement(require("react-native").Text, null, props.title)+ )+ },+ Toggle: function (props: any) {+ return require("react").createElement(require("react-native").Pressable, {+ testID: props.testID,+ accessibilityLabel: props.accessibilityLabel,+ disabled: props.disabled,+ accessibilityState: { disabled: !!props.disabled },+ onPress: () => props.onValueChange(!props.value)+ })+ },+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),Container: ({ children }: any) => R.createElement(View, null, children),Card: ({ children }: any) => R.createElement(View, null, children),Divider: () => R.createElement(View, null),- SettingRow: ({ label, children }: any) => R.createElement(View, null, R.createElement(Text, null, label), children)+ SettingRow: ({ label, hint, children }: any) =>+ R.createElement(+ View,+ null,+ R.createElement(Text, null, label),+ hint ? R.createElement(Text, null, hint) : null,+ children+ )}})@@ -59,15 +98,19 @@ const mockNavigation = { navigate: jest.fn() } as anydescribe("AppearanceScreen", () => {beforeEach(() => {jest.clearAllMocks()+ theme.wallpaperColors = false+ theme.wallpaperColorsAvailable = true+ theme.wallpaperPaletteReady = true+ mockGetSetting.mockResolvedValue(null)})- it("renders dark mode, units and time format rows", () => {+ it("renders theme, units and time format rows", () => {const { getByText, getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)- expect(getByText("Dark Mode")).toBeTruthy()+ expect(getByText("Theme")).toBeTruthy()expect(getByText("Units")).toBeTruthy()expect(getByText("Time format")).toBeTruthy()- expect(getByTestId("dark-mode-switch")).toBeTruthy()+ expect(getByTestId("theme-system")).toBeTruthy()})it("shows unit system chips with Metric and Imperial", () => {@@ -104,12 +147,90 @@ describe("AppearanceScreen", () => {})})- it("toggles theme when dark mode switch is pressed", () => {+ it("offers system alongside light and dark, which a toggle could not", () => {const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)- fireEvent(getByTestId("dark-mode-switch"), "valueChange", true)+ expect(getByTestId("theme-system")).toBeTruthy()+ expect(getByTestId("theme-light")).toBeTruthy()+ expect(getByTestId("theme-dark")).toBeTruthy()+ })++ it("records the picked mode rather than flipping the current one", () => {+ const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)++ fireEvent.press(getByTestId("theme-dark"))++ expect(mockSetPreference).toHaveBeenCalledWith("dark")+ })++ it("keeps the wallpaper palette out of the mode chips, which answer a different question", () => {+ const { getByTestId, queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)++ expect(getByTestId("wallpaper-colors-toggle")).toBeTruthy()+ expect(queryByTestId("theme-wallpaper")).toBeNull()+ })++ it("hides the wallpaper row where the platform has no palette, rather than disabling it", () => {+ theme.wallpaperColorsAvailable = false++ const { queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)++ expect(queryByTestId("wallpaper-colors-toggle")).toBeNull()+ })++ // A failed read must not hide the only control that turns the setting off.+ it("keeps the wallpaper row when the palette read has not landed, and disables it", () => {+ theme.wallpaperPaletteReady = false++ const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)- expect(mockToggleTheme).toHaveBeenCalled()+ expect(getByTestId("wallpaper-colors-toggle").props.accessibilityState.disabled).toBe(true)+ })++ it("hands the wallpaper choice to the theme, which owns the palette", () => {+ const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)++ fireEvent.press(getByTestId("wallpaper-colors-toggle"))++ expect(mockSetWallpaperColors).toHaveBeenCalledWith(true)+ })++ it("puts the units the choice produces under the label", async () => {+ const { getByText, queryByText } = render(<AppearanceScreen navigation={mockNavigation} />)++ expect(getByText("km · km/h · m")).toBeTruthy()++ fireEvent.press(getByText("Imperial"))++ await waitFor(() => expect(getByText("mi · mph · ft")).toBeTruthy())+ expect(queryByText("km · km/h · m")).toBeNull()+ })++ it("puts a clock in the chosen format under the time format label", async () => {+ const { getByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ const { clockSample } = require("../../utils/appearance")++ expect(getByText(clockSample("24h"))).toBeTruthy()++ fireEvent.press(getByText("12h"))++ await waitFor(() => expect(getByText(clockSample("12h"))).toBeTruthy())+ })++ it("names the host serving tiles rather than describing the setting", async () => {+ const { findByText } = render(<AppearanceScreen navigation={mockNavigation} />)++ expect(await findByText("maps.mxd.codes")).toBeTruthy()+ })++ it("names both hosts when the two styles come from different servers", async () => {+ mockGetSetting.mockImplementation((key: string) =>+ Promise.resolve(key === "mapStyleUrlLight" ? "https://a.example.org/l.json" : "https://b.example.org/d.json")+ )++ const { findByText } = render(<AppearanceScreen navigation={mockNavigation} />)++ expect(await findByText("a.example.org · b.example.org")).toBeTruthy()})it("toggles the map tile server panel when pressed", () => {@@ -122,4 +243,53 @@ describe("AppearanceScreen", () => {expect(queryByTestId("map-style-url-light")).toBeTruthy()expect(queryByTestId("map-style-url-dark")).toBeTruthy()})++ // A stored typo blanks every map, and only the reset undoes it.+ it("refuses a URL that is not one, and saves nothing", async () => {+ const { getByTestId, findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ fireEvent.press(getByTestId("map-tile-server-toggle"))++ fireEvent.changeText(getByTestId("map-style-url-light"), "htps://tiles.example.org")+ fireEvent(getByTestId("map-style-url-light"), "blur")++ expect(await findByText("Starts with http:// or https:// and names a host.")).toBeTruthy()+ expect(mockSaveSetting).not.toHaveBeenCalledWith("mapStyleUrlLight", expect.anything())+ })++ it("saves a good URL and moves the host on the row", async () => {+ const { getByTestId, findByText } = render(<AppearanceScreen navigation={mockNavigation} />)+ fireEvent.press(getByTestId("map-tile-server-toggle"))++ fireEvent.changeText(getByTestId("map-style-url-light"), "https://tiles.example.org/light.json")+ fireEvent(getByTestId("map-style-url-light"), "blur")++ await waitFor(() =>+ expect(mockSaveSetting).toHaveBeenCalledWith("mapStyleUrlLight", "https://tiles.example.org/light.json")+ )+ expect(await findByText(/tiles\.example\.org/)).toBeTruthy()+ })++ it("accepts an emptied field as a return to the default", async () => {+ mockGetSetting.mockResolvedValue("https://tiles.example.org/light.json")+ const { getByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ fireEvent.press(getByTestId("map-tile-server-toggle"))++ fireEvent.changeText(getByTestId("map-style-url-light"), "")+ fireEvent(getByTestId("map-style-url-light"), "blur")++ await waitFor(() => expect(mockSaveSetting).toHaveBeenCalledWith("mapStyleUrlLight", ""))+ })++ it("offers the reset only once something custom is stored", async () => {+ const { getByTestId, queryByTestId } = render(<AppearanceScreen navigation={mockNavigation} />)+ fireEvent.press(getByTestId("map-tile-server-toggle"))++ expect(queryByTestId("map-style-reset-btn")).toBeNull()++ mockGetSetting.mockResolvedValue("https://tiles.example.org/light.json")+ const custom = render(<AppearanceScreen navigation={mockNavigation} />)+ fireEvent.press(custom.getByTestId("map-tile-server-toggle"))++ await waitFor(() => expect(custom.getByTestId("map-style-reset-btn")).toBeTruthy())+ })})diff --git a/apps/mobile/src/screens/__tests__/LogPreviewScreen.test.tsx b/apps/mobile/src/screens/__tests__/LogPreviewScreen.test.tsxnew file mode 100644index 00000000..6db7942f--- /dev/null+++ b/apps/mobile/src/screens/__tests__/LogPreviewScreen.test.tsx@@ -0,0 +1,251 @@+import React from "react"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ const cleanup = cb()+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])+ }+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++const mockGetSetting = jest.fn()+jest.mock("../../services/NativeLocationService", () => {+ const service: Record<string, unknown> = {}+ Object.assign(service, {+ getSetting: function (this: unknown, ...a: unknown[]) {+ if (this !== service) throw new TypeError("undefined is not a function")+ return mockGetSetting(...a)+ }+ })+ return { __esModule: true, default: service }+})++const mockGetMergedLogs = jest.fn()+jest.mock("../../utils/logExport", () => ({+ getMergedLogs: (...a: unknown[]) => mockGetMergedLogs(...a)+}))++jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn() } }))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => R.createElement(View, null),+ EmptyState: ({ title, hint }: any) =>+ R.createElement(View, null, R.createElement(Text, null, title), R.createElement(Text, null, hint)),+ HeaderAction: ({ label, onPress, testID, disabled }: any) =>+ R.createElement(Pressable, { testID, onPress, disabled, accessibilityLabel: label }),+ ChipGroup: ({ options, selected, onSelect }: any) =>+ R.createElement(+ View,+ null,+ options.map((o: any) =>+ R.createElement(+ Pressable,+ {+ key: o.value,+ testID: o.testID,+ accessibilityState: { checked: selected === o.value },+ onPress: () => onSelect(o.value)+ },+ R.createElement(Text, null, o.label)+ )+ )+ )+ }+})++import { LogPreviewScreen } from "../LogPreviewScreen"++const AT = Date.parse("2026-09-09T09:46:58.000Z")++const entry = (level: string, message: string, offsetSeconds = 0) => ({+ id: `${level}-${message}`,+ time: AT + offsetSeconds * 1000,+ level,+ source: "NATIVE",+ message,+ raw: message+})++const mockNavigation = { navigate: jest.fn(), setOptions: jest.fn(), goBack: jest.fn() }+const renderScreen = () => render(<LogPreviewScreen navigation={mockNavigation as any} />)++const SAMPLE = [+ entry("DEBUG", "SyncManager: periodic sync stopped", 0),+ entry("INFO", "SyncManager: instant send", 1),+ entry("WARN", "SyncManager: no unmetered network", 2),+ entry("ERROR", "NetworkManager: connect timeout", 3)+]++beforeEach(() => {+ jest.clearAllMocks()+ jest.useFakeTimers()+ mockGetMergedLogs.mockResolvedValue(SAMPLE)+ mockGetSetting.mockResolvedValue("true")+})++afterEach(() => {+ jest.useRealTimers()+})++describe("what the preview shows", () => {+ // What the reporter just reproduced is what they came to read, and descending order needs no+ // auto-stick, no scroll-to-end control and no measurement of variable-height rows.+ it("puts the most recent line first", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-result-line")).toBeTruthy())++ const messages = api.getAllByText(/SyncManager|NetworkManager/).map((n) => n.props.children)+ expect(messages[0]).toBe("NetworkManager: connect timeout")+ expect(messages[messages.length - 1]).toBe("SyncManager: periodic sync stopped")+ })++ // This previews what is being sent, so a default that hides most of the file misrepresents the+ // one thing under review.+ it("opens on every level", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-result-line")).toBeTruthy())++ expect(api.getByTestId("log-result-line").props.children).toBe("4 lines from the log file")+ expect(api.getByTestId("floor-all").props.accessibilityState.checked).toBe(true)+ })++ it("names the source it is reading, which the toggle silently decides", async () => {+ mockGetSetting.mockResolvedValue("false")+ const api = renderScreen()++ await waitFor(() => expect(api.getByTestId("log-result-line").props.children).toBe("4 lines from the system log"))+ })++ it("has an empty state for a log with nothing in it", async () => {+ mockGetMergedLogs.mockResolvedValue([])+ const api = renderScreen()++ await waitFor(() => expect(api.getByText("Nothing logged yet")).toBeTruthy())+ })+})++describe("the level floor", () => {+ it("shows every level at or above the one chosen", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("floor-warn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("floor-warn"))+ })++ expect(api.getByTestId("log-result-line").props.children).toBe("2 of 4 lines from the log file")+ expect(api.queryByText("SyncManager: instant send")).toBeNull()+ expect(api.getByText("NetworkManager: connect timeout")).toBeTruthy()+ })++ // The count rides on the chip, or learning there is one error means selecting Errors to find out,+ // which is changing state to read a fact.+ it("carries the count on each chip without needing a selection", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("floor-all")).toBeTruthy())++ expect(api.getByText("All 4")).toBeTruthy()+ expect(api.getByText("Warnings 2")).toBeTruthy()+ expect(api.getByText("Errors 1")).toBeTruthy()+ })++ it("has an empty state that tells the filter apart from an empty log", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("floor-error")).toBeTruthy())++ await act(async () => {+ fireEvent.changeText(api.getByTestId("log-search-input"), "nothing matches this")+ jest.advanceTimersByTime(200)+ })++ expect(api.getByText("No lines match")).toBeTruthy()+ })+})++describe("search", () => {+ it("filters on the message, after the typing settles", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-search-input")).toBeTruthy())++ await act(async () => {+ fireEvent.changeText(api.getByTestId("log-search-input"), "timeout")+ })+ expect(api.getByTestId("log-result-line").props.children).toBe("4 lines from the log file")++ await act(async () => {+ jest.advanceTimersByTime(200)+ })+ expect(api.getByTestId("log-result-line").props.children).toBe("1 of 4 lines from the log file")+ })++ // Counted over the search-matched set, so the active chip's number and the result line's first+ // number are the same number.+ it("counts the chips over what the search matched", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-search-input")).toBeTruthy())++ await act(async () => {+ fireEvent.changeText(api.getByTestId("log-search-input"), "SyncManager")+ jest.advanceTimersByTime(200)+ })++ expect(api.getByText("All 3")).toBeTruthy()+ expect(api.getByText("Errors 0")).toBeTruthy()+ })++ it("clears without waiting for the debounce", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-search-input")).toBeTruthy())++ await act(async () => {+ fireEvent.changeText(api.getByTestId("log-search-input"), "timeout")+ jest.advanceTimersByTime(200)+ })+ expect(api.getByTestId("log-result-line").props.children).toBe("1 of 4 lines from the log file")++ await act(async () => {+ fireEvent.press(api.getByTestId("clear-search-btn"))+ })+ expect(api.getByTestId("log-result-line").props.children).toBe("4 lines from the log file")+ })+})++describe("reading again", () => {+ // A preview that moves under the reader destroys a text selection before it can be used.+ it("does not poll", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("log-result-line")).toBeTruthy())+ const reads = mockGetMergedLogs.mock.calls.length++ await act(async () => {+ jest.advanceTimersByTime(30000)+ })++ expect(mockGetMergedLogs.mock.calls.length).toBe(reads)+ })++ it("reads again when Refresh is pressed", async () => {+ renderScreen()+ await waitFor(() => expect(mockNavigation.setOptions).toHaveBeenCalled())+ const reads = mockGetMergedLogs.mock.calls.length++ const headerRight = mockNavigation.setOptions.mock.calls.at(-1)![0].headerRight+ const action = render(headerRight())+ await act(async () => {+ fireEvent.press(action.getByTestId("refresh-log-btn"))+ })++ expect(mockGetMergedLogs.mock.calls.length).toBe(reads + 1)+ })+})diff --git a/apps/mobile/src/screens/__tests__/LoggingScreen.test.tsx b/apps/mobile/src/screens/__tests__/LoggingScreen.test.tsxnew file mode 100644index 00000000..c3b87c8d--- /dev/null+++ b/apps/mobile/src/screens/__tests__/LoggingScreen.test.tsx@@ -0,0 +1,321 @@+import React from "react"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"++jest.mock("@react-navigation/native", () => ({+ useFocusEffect: (cb: () => (() => void) | void) => {+ const R = require("react")+ R.useEffect(() => {+ const cleanup = cb()+ return typeof cleanup === "function" ? cleanup : undefined+ }, [cb])+ }+}))++jest.mock("../../hooks/useTheme", () => ({+ useTheme: () => ({ colors: require("@colota/shared").lightColors })+}))++const mockGetSetting = jest.fn()+const mockGetFileLogSize = jest.fn()+const mockSetFileLoggingEnabled = jest.fn()+const mockClearFileLog = jest.fn()+const mockPickExportDirectory = jest.fn()+const mockExportFileLogToUri = jest.fn()+const mockGetBuildConfig = jest.fn()+const mockGetDeviceInfo = jest.fn()++// Every real method is a static opening with ensureModule(), so a bare reference throws.+jest.mock("../../services/NativeLocationService", () => {+ const service: Record<string, unknown> = {}+ const onReceiver = (impl: (...a: unknown[]) => unknown) =>+ function (this: unknown, ...a: unknown[]) {+ if (this !== service) throw new TypeError("undefined is not a function")+ return impl(...a)+ }+ Object.assign(service, {+ getSetting: onReceiver((...a) => mockGetSetting(...a)),+ getFileLogSize: onReceiver((...a) => mockGetFileLogSize(...a)),+ setFileLoggingEnabled: onReceiver((...a) => mockSetFileLoggingEnabled(...a)),+ clearFileLog: onReceiver((...a) => mockClearFileLog(...a)),+ pickExportDirectory: onReceiver((...a) => mockPickExportDirectory(...a)),+ exportFileLogToUri: onReceiver((...a) => mockExportFileLogToUri(...a)),+ getBuildConfig: onReceiver((...a) => mockGetBuildConfig(...a)),+ getDeviceInfo: onReceiver((...a) => mockGetDeviceInfo(...a))+ })+ return { __esModule: true, default: service }+})++const mockShowConfirm = jest.fn()+const mockShowAlert = jest.fn()+jest.mock("../../services/modalService", () => ({+ showConfirm: (...a: unknown[]) => mockShowConfirm(...a),+ showAlert: (...a: unknown[]) => mockShowAlert(...a)+}))++jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn() } }))++jest.mock("../../utils/logExport", () => ({+ buildExportHeader: jest.fn(() => "HEADER\n"),+ buildAppLog: jest.fn(() => "APPLOG\n")+}))++jest.mock("../../components", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ Container: ({ children }: any) => R.createElement(View, null, children),+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => R.createElement(View, null),+ StateLine: ({ label, caption, testID }: any) =>+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),+ FieldMessage: ({ children, variant }: any) =>+ R.createElement(Text, { accessibilityValue: { text: variant ?? "info" } }, children),+ SettingRow: ({ label, hint, children }: any) =>+ R.createElement(View, null, R.createElement(Text, null, label), R.createElement(Text, null, hint), children),+ ListItem: ({ label, sub, onPress, testID }: any) =>+ R.createElement(+ Pressable,+ { testID, onPress },+ R.createElement(Text, null, label),+ R.createElement(Text, null, sub)+ ),+ Toggle: ({ value, onValueChange, testID, accessibilityLabel }: any) =>+ R.createElement(Pressable, { testID, accessibilityLabel, onPress: () => onValueChange(!value) }),+ Button: ({ title, onPress, disabled, testID, loading, variant }: any) =>+ R.createElement(+ Pressable,+ {+ testID,+ onPress,+ disabled,+ accessibilityState: { disabled: !!disabled, busy: !!loading },+ accessibilityValue: { text: variant ?? "primary" }+ },+ R.createElement(Text, null, title)+ )+ }+})++import { LoggingScreen } from "../LoggingScreen"++const mockNavigation = { navigate: jest.fn(), setOptions: jest.fn(), goBack: jest.fn() }+const renderScreen = () => render(<LoggingScreen navigation={mockNavigation as any} />)++const settings = (enabled: string, startedAt: string) => {+ mockGetSetting.mockImplementation((key: string) => {+ if (key === "debugFileLoggingEnabled") return Promise.resolve(enabled)+ if (key === "debugFileLoggingStartedAt") return Promise.resolve(startedAt)+ return Promise.resolve("")+ })+}++beforeEach(() => {+ jest.clearAllMocks()+ jest.useFakeTimers()+ settings("true", "1757400000000")+ mockGetFileLogSize.mockResolvedValue(2_516_582)+ mockSetFileLoggingEnabled.mockResolvedValue(undefined)+ mockClearFileLog.mockResolvedValue(undefined)+ mockPickExportDirectory.mockResolvedValue("content://tree/logs")+ mockExportFileLogToUri.mockResolvedValue("content://tree/logs/colota-log.txt")+ mockGetBuildConfig.mockReturnValue({ VERSION_NAME: "1.16.0", VERSION_CODE: 48, FLAVOR: "gms" })+ mockGetDeviceInfo.mockResolvedValue({ systemVersion: "15", apiLevel: 35, brand: "Google", model: "Pixel 8" })+ mockShowConfirm.mockResolvedValue(true)+})++afterEach(() => {+ jest.useRealTimers()+})++describe("what the screen says on arrival", () => {+ it("opens on the three steps, in the order a reporter does them", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("capture-state")).toBeTruthy())++ expect(api.getByText(/Start recording, reproduce the problem, then save the log file/)).toBeTruthy()+ })++ it("reports the capture and what it has written", async () => {+ const api = renderScreen()++ await waitFor(() => expect(api.getByText("Recording")).toBeTruthy())+ expect(api.getByText(/^2\.4 MB since /)).toBeTruthy()+ })++ // Printing "No log file on this device" over 8 MB would be false, and the subtree only mounts to+ // be torn down.+ it("renders nothing about the capture until the first read lands", () => {+ settings("true", "0")+ mockGetFileLogSize.mockReturnValue(new Promise(() => {}))+ const api = renderScreen()++ expect(api.queryByTestId("capture-state")).toBeNull()+ expect(api.queryByTestId("save-log-btn")).toBeNull()+ })+})++describe("the actions", () => {+ // With no file there is nothing to save, so the section is absent rather than disabled: a saved+ // log that was never recorded is the useless report the whole screen exists to prevent.+ it("offers no save or delete while the file is empty", async () => {+ mockGetFileLogSize.mockResolvedValue(0)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("capture-state")).toBeTruthy())++ expect(api.queryByTestId("save-log-btn")).toBeNull()+ expect(api.queryByTestId("delete-log-btn")).toBeNull()+ expect(api.getByText(/Leave this on while you reproduce the problem/)).toBeTruthy()+ })++ it("names what leaves the device before the folder picker opens", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("save-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("save-log-btn"))+ })++ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ message: expect.stringContaining("geofences") })+ )+ expect(mockShowConfirm.mock.invocationCallOrder[0]).toBeLessThan(+ mockPickExportDirectory.mock.invocationCallOrder[0]+ )+ })++ // Native has no access to the JS ring buffer or the build config, so without these two arguments+ // the attached file carries no version, no flavor, no device and no JS line at all.+ it("hands native the header and the app log to merge in", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("save-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("save-log-btn"))+ })++ expect(mockExportFileLogToUri).toHaveBeenCalledWith("content://tree/logs", "HEADER\n", "APPLOG\n")+ expect(mockShowAlert).toHaveBeenCalledWith("Log saved", expect.any(String), "success")+ })++ it("does not report a save when the picker was dismissed", async () => {+ mockPickExportDirectory.mockResolvedValue(null)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("save-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("save-log-btn"))+ })++ expect(mockExportFileLogToUri).not.toHaveBeenCalled()+ expect(mockShowAlert).not.toHaveBeenCalled()+ })++ it("says so when there was nothing recorded to write", async () => {+ mockExportFileLogToUri.mockResolvedValue(null)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("save-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("save-log-btn"))+ })++ expect(mockShowAlert).toHaveBeenCalledWith("Nothing to save", expect.any(String), "info")+ })++ // A user-pressed failure that only logs leaves the reporter believing the file was written.+ it("alerts when the save fails", async () => {+ mockExportFileLogToUri.mockRejectedValue(new Error("Could not create document"))+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("save-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("save-log-btn"))+ })++ expect(mockShowAlert).toHaveBeenCalledWith("Could not save the log", "Could not create document", "error")+ })++ it("names the size it is about to delete, and asks first", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("delete-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("delete-log-btn"))+ })++ expect(mockShowConfirm).toHaveBeenCalledWith(+ expect.objectContaining({ message: expect.stringContaining("2.4 MB"), destructive: true })+ )+ expect(mockClearFileLog).toHaveBeenCalled()+ })++ it("deletes nothing when the confirmation is dismissed", async () => {+ mockShowConfirm.mockResolvedValue(false)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("delete-log-btn")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("delete-log-btn"))+ })++ expect(mockClearFileLog).not.toHaveBeenCalled()+ })+})++describe("the toggle", () => {+ // Native stamps the start and the first lines land off-thread, so the size is read once after the+ // write settles. A poll would rebuild the view continuously for a number that rarely moves.+ it("reads back once after the write settles, rather than polling", async () => {+ settings("false", "")+ mockGetFileLogSize.mockResolvedValue(0)+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("file-logging-toggle")).toBeTruthy())+ const readsAfterMount = mockGetFileLogSize.mock.calls.length++ await act(async () => {+ fireEvent.press(api.getByTestId("file-logging-toggle"))+ })+ expect(mockSetFileLoggingEnabled).toHaveBeenCalledWith(true)+ expect(mockGetFileLogSize.mock.calls.length).toBe(readsAfterMount)++ await act(async () => {+ jest.advanceTimersByTime(2000)+ })+ expect(mockGetFileLogSize.mock.calls.length).toBe(readsAfterMount + 1)+ })++ // A toggle that snaps back with no explanation reads as the app ignoring the press.+ it("puts the switch back and says so when the write fails", async () => {+ settings("false", "")+ mockSetFileLoggingEnabled.mockRejectedValue(new Error("db locked"))+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("file-logging-toggle")).toBeTruthy())++ await act(async () => {+ fireEvent.press(api.getByTestId("file-logging-toggle"))+ })++ expect(mockShowAlert).toHaveBeenCalledWith("Could not change logging", expect.any(String), "error")+ expect(api.getByText("Not recording")).toBeTruthy()+ })+})++describe("the reader", () => {+ it("says which source it will show, and opens it", async () => {+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("nav-log-preview")).toBeTruthy())++ expect(api.getByText("The log file's most recent lines, newest first")).toBeTruthy()+ fireEvent.press(api.getByTestId("nav-log-preview"))+ expect(mockNavigation.navigate).toHaveBeenCalledWith("Log Preview")+ })++ it("says the other source while the capture is off", async () => {+ settings("false", "")+ const api = renderScreen()+ await waitFor(() => expect(api.getByTestId("nav-log-preview")).toBeTruthy())++ expect(api.getByText("The system log's last few minutes, newest first")).toBeTruthy()+ })+})diff --git a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsxindex a0e1d5be..b375b4cf 100644--- a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx@@ -1,64 +1,72 @@import React from "react"-import { render, fireEvent } from "@testing-library/react-native"+import { render, fireEvent, waitFor, act } from "@testing-library/react-native"+import { DeviceEventEmitter, Linking } from "react-native"+import { lightColors } from "@colota/shared"import { DEFAULT_SETTINGS, Settings } from "../../types/global"-// --- Mocks ----jest.mock("@react-navigation/native", () => ({useFocusEffect: (cb: () => (() => void) | void) => require("react").useEffect(() => cb(), [])}))let mockSettings: Settings = { ...DEFAULT_SETTINGS }let mockTracking = false+let mockActiveProfileName: string | null = nulljest.mock("../../contexts/TrackingProvider", () => ({useTracking: () => ({settings: mockSettings,- setSettings: jest.fn(),- updateSettingsLocal: jest.fn(),- restartTracking: jest.fn(),- tracking: mockTracking+ tracking: mockTracking,+ activeProfileName: mockActiveProfileName})}))+// The real getters fall back to the host locale, which decides the assertion otherwise.+jest.mock("../../utils/geo", () => ({+ ...jest.requireActual("../../utils/geo"),+ getUnitSystem: () => "metric",+ getTimeFormat: () => "24h"+}))+jest.mock("../../hooks/useTheme", () => ({- useTheme: () => ({- mode: "light",- toggleTheme: jest.fn(),- colors: {- primary: "#0d9488",- primaryDark: "#115E59",- border: "#e5e7eb",- text: "#000",- textSecondary: "#6b7280",- textLight: "#9ca3af",- background: "#fff",- info: "#3b82f6",- success: "#22c55e",- error: "#ef4444",- card: "#fff",- backgroundElevated: "#f9fafb",- placeholder: "#9ca3af",- textOnPrimary: "#fff"- }- })+ useTheme: () => ({ mode: "light", preference: "dark", colors: require("@colota/shared").lightColors })+}))++const mockGetStats = jest.fn()+const mockGetProfiles = jest.fn()+const mockIsNetworkAvailable = jest.fn()+const mockGetAutoExportStatus = jest.fn()+const mockGetSetting = jest.fn()+const mockGetFileLogSize = jest.fn()+const mockLoadOfflineAreas = jest.fn()+let mockFlavor = "gms"++jest.mock("../../services/ProfileService", () => ({+ ProfileService: { getProfiles: (...args: unknown[]) => mockGetProfiles(...args) }}))jest.mock("../../services/NativeLocationService", () => ({__esModule: true,default: {- getStats: jest.fn().mockResolvedValue({- queued: 5,- sent: 42,- total: 100,- today: 10,- databaseSizeMB: 1.2- }),- saveSetting: jest.fn().mockResolvedValue(undefined),- getSetting: jest.fn().mockResolvedValue(null)+ getStats: (...args: unknown[]) => mockGetStats(...args),+ isNetworkAvailable: (...args: unknown[]) => mockIsNetworkAvailable(...args),+ getAutoExportStatus: (...args: unknown[]) => mockGetAutoExportStatus(...args),+ getSetting: (...args: unknown[]) => mockGetSetting(...args),+ getFileLogSize: (...args: unknown[]) => mockGetFileLogSize(...args),+ getBuildConfig: () => ({ FLAVOR: mockFlavor, VERSION_NAME: "1.16.0" })}}))+jest.mock("../../components/features/map/OfflinePackManager", () => ({+ loadOfflineAreas: (...args: unknown[]) => mockLoadOfflineAreas(...args)+}))++const mockShowAlert = jest.fn()+jest.mock("../../services/modalService", () => ({ showAlert: (...args: unknown[]) => mockShowAlert(...args) }))++jest.mock("../../utils/logger", () => ({+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }+}))+jest.mock("../../components", () => {const R = require("react")const { View, Text, Pressable } = require("react-native")@@ -67,19 +75,33 @@ jest.mock("../../components", () => {SectionTitle: ({ children }: any) => R.createElement(Text, null, children),Card: ({ children }: any) => R.createElement(View, null, children),Divider: () => R.createElement(View, null),- StatsCard: ({ queueCount, sentCount }: any) =>- R.createElement(- View,- { testID: "StatsCard" },- R.createElement(Text, null, `${queueCount}`),- R.createElement(Text, null, `${sentCount}`)- ),- ListItem: ({ testID, label, sub, onPress }: any) =>+ ListItem: ({+ testID,+ label,+ sub,+ onPress,+ icon,+ iconColor,+ subLines,+ trailingIcon,+ accessibilityRole,+ accessibilityHint+ }: any) =>R.createElement(Pressable,- { testID, onPress },+ {+ testID,+ onPress,+ accessibilityRole: accessibilityRole ?? "button",+ accessibilityHint:+ accessibilityHint ?? (accessibilityRole === "link" ? `Opens ${label} in the browser` : `Opens ${label}`),+ accessibilityValue: {+ text: `${iconColor ?? "default"}|${subLines ?? 1}|${trailingIcon ? "link" : "chevron"}`+ }+ },R.createElement(Text, null, label),- sub ? R.createElement(Text, null, sub) : null+ sub ? R.createElement(Text, null, sub) : null,+ R.createElement(Text, { testID: `${testID}-glyph` }, icon?.displayName ?? "icon"))}})@@ -88,136 +110,370 @@ import { SettingsScreen } from "../SettingsScreen"const mockNavigate = jest.fn()const mockProps = { navigation: { navigate: mockNavigate }, route: { key: "Settings", name: "Settings" } } as any+const renderScreen = () => render(<SettingsScreen {...mockProps} />)+const meta = (api: ReturnType<typeof render>, testID: string) =>+ api.getByTestId(testID).props.accessibilityValue.text.split("|")describe("SettingsScreen", () => {beforeEach(() => {jest.clearAllMocks()+ mockGetStats.mockResolvedValue({+ queued: 5,+ sent: 42,+ total: 12480,+ today: 10,+ databaseSizeMB: 3.4213,+ lastSyncTime: 0,+ lastSyncError: ""+ })+ mockGetProfiles.mockResolvedValue([])+ mockIsNetworkAvailable.mockResolvedValue(true)+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: false,+ interval: "weekly",+ format: "geojson",+ lastError: null+ })+ mockGetSetting.mockResolvedValue("false")+ mockGetFileLogSize.mockResolvedValue(0)+ mockLoadOfflineAreas.mockResolvedValue([])mockSettings = { ...DEFAULT_SETTINGS }mockTracking = false+ mockActiveProfileName = null+ mockFlavor = "gms"})- it("renders grouped section headers", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("Display")).toBeTruthy()- expect(getByText("Data")).toBeTruthy()- })-- it("renders StatsCard with stats", () => {- const { getByTestId } = render(<SettingsScreen {...mockProps} />)-- expect(getByTestId("StatsCard")).toBeTruthy()- })-- // --- Summary rows ----- it("shows the endpoint host as the Connection summary", () => {- mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://api.example.com/track" }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("api.example.com")).toBeTruthy()+ describe("the shape", () => {+ it("is five groups, Help then About, with no banner and nothing above the list", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ expect(api.getByText("Tracking")).toBeTruthy()+ expect(api.getByText("Display")).toBeTruthy()+ expect(api.getByText("Data")).toBeTruthy()+ expect(api.getByText("Help")).toBeTruthy()+ // The group and its terminal row are both "About", which is the Android convention.+ expect(api.getAllByText("About")).toHaveLength(2)+ expect(api.queryByText("Colota")).toBeNull()+ expect(api.queryByTestId("queue-warning")).toBeNull()+ })++ it("carries no Request format row, so no row appears or disappears with a setting", async () => {+ const online = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())+ expect(online.queryByTestId("nav-api-config")).toBeNull()++ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }+ const offline = renderScreen()+ await waitFor(() => expect(offline.queryByTestId("nav-api-config")).toBeNull())+ expect(offline.getByTestId("nav-connection")).toBeTruthy()+ })++ it("keeps each group's rows in the order the hub was designed around", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ const ids: string[] = []+ const walk = (node: any) => {+ if (!node || typeof node !== "object") return+ if (Array.isArray(node)) return node.forEach(walk)+ const id = node.props?.testID+ if (typeof id === "string" && id.startsWith("nav-") && !id.endsWith("-glyph")) ids.push(id)+ ;(node.children ?? []).forEach(walk)+ }+ walk(api.toJSON())++ expect(ids).toEqual([+ "nav-connection",+ "nav-tracking-sync",+ "nav-tracking-profiles",+ "nav-appearance",+ "nav-offline-maps",+ "nav-data-management",+ "nav-export-import",+ "nav-backup-restore",+ "nav-share-setup",+ "nav-logging",+ "nav-feedback",+ "nav-whats-new",+ "nav-rate",+ "nav-support",+ "nav-about"+ ])+ })++ it("opens the destinations it names", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ const routes: [string, string][] = [+ ["nav-connection", "Connection"],+ ["nav-tracking-sync", "Tracking & Sync"],+ ["nav-tracking-profiles", "Tracking Profiles"],+ ["nav-appearance", "Appearance"],+ ["nav-offline-maps", "Offline Maps"],+ ["nav-data-management", "Data Management"],+ ["nav-export-import", "Export & Import"],+ ["nav-backup-restore", "Backup & Restore"],+ ["nav-share-setup", "Share Setup"],+ ["nav-logging", "Logging"],+ ["nav-about", "About Colota"]+ ]+ for (const [testID, route] of routes) {+ fireEvent.press(api.getByTestId(testID))+ expect(mockNavigate).toHaveBeenCalledWith(route)+ }+ })})- it("shows 'No server configured' when endpoint is empty and not offline", () => {- mockSettings = { ...DEFAULT_SETTINGS, endpoint: "", isOfflineMode: false }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("No server configured")).toBeTruthy()+ describe("the two state rows", () => {+ it("prints the server relationship and tints the glyph when it is wrong", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://api.example.com/track" }+ mockGetStats.mockResolvedValue({+ queued: 1240,+ sent: 0,+ total: 12480,+ today: 10,+ databaseSizeMB: 3.4,+ lastSyncTime: 0,+ lastSyncError: "HTTP 401 Unauthorized"+ })+ const api = renderScreen()++ expect(await api.findByText("api.example.com · 1,240 queued · sync failing")).toBeTruthy()+ expect(meta(api, "nav-connection")[0]).toBe(lightColors.error)+ })++ it("can say no network, which the hardcoded flag made unreachable", async () => {+ mockSettings = { ...DEFAULT_SETTINGS, endpoint: "https://api.example.com/track" }+ mockIsNetworkAvailable.mockResolvedValue(false)+ const api = renderScreen()++ expect(await api.findByText(/no network$/)).toBeTruthy()+ })++ it("warns on a missing server and leaves an offline tracker untinted", async () => {+ const api = renderScreen()+ expect(await api.findByText("No server configured")).toBeTruthy()+ expect(meta(api, "nav-connection")[0]).toBe(lightColors.warning)++ mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }+ const offline = renderScreen()+ expect(await offline.findByText("Offline - saved locally · 10 today")).toBeTruthy()+ expect(meta(offline, "nav-connection")[0]).toBe("default")+ })++ it("names the rule in force and tints only then, in the Profiles screen's own words", async () => {+ mockGetProfiles.mockResolvedValue([{ id: 1 }])+ mockTracking = true+ mockActiveProfileName = "Charging"+ const api = renderScreen()++ expect(await api.findByText("Charging is active")).toBeTruthy()+ expect(meta(api, "nav-tracking-profiles")[0]).toBe(lightColors.success)+ })++ it("says no profile active while tracking runs without one, and no profiles yet at zero", async () => {+ mockGetProfiles.mockResolvedValue([{ id: 1 }])+ mockTracking = true+ const active = renderScreen()+ expect(await active.findByText("No profile active")).toBeTruthy()+ expect(meta(active, "nav-tracking-profiles")[0]).toBe("default")++ mockGetProfiles.mockResolvedValue([])+ const empty = renderScreen()+ expect(await empty.findByText("No profiles yet")).toBeTruthy()+ })++ it("gives Connection the room to wrap, since a self-hosted host is unbounded", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ expect(meta(api, "nav-connection")[1]).toBe("2")+ expect(meta(api, "nav-tracking-sync")[1]).toBe("1")+ })})- it("shows 'Offline' as the Connection summary in offline mode", () => {- mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("Offline - saved locally")).toBeTruthy()+ describe("the value subs", () => {+ it("prints the cadence, the appearance and the ledger's own numbers", async () => {+ const api = renderScreen()++ expect(await api.findByText("12,480 locations · 3.42 MB")).toBeTruthy()+ expect(api.getByText("Every 5 s, any movement · syncs each fix")).toBeTruthy()+ expect(api.getByText("Dark · Metric · 24h")).toBeTruthy()+ })++ it("prints the formats from the shared table, not a sentence about the screen", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ expect(api.getByText("GeoJSON, GPX, KML, Google Timeline, CSV in, and out")).toBeTruthy()+ expect(api.queryByText(/Merge locations from/)).toBeNull()+ expect(api.queryByText("Encrypted backup of all your data")).toBeNull()+ })++ it("reads auto-export, logging and the offline packs on focus", async () => {+ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ interval: "weekly",+ format: "geojson",+ lastError: "Folder not writable"+ })+ mockGetSetting.mockResolvedValue("true")+ mockGetFileLogSize.mockResolvedValue(2516582)+ mockLoadOfflineAreas.mockResolvedValue([+ { name: "Munich", sizeBytes: 44040192, isComplete: true, isActive: false, bounds: null }+ ])+ const api = renderScreen()++ expect(await api.findByText("Auto-export weekly · GeoJSON · last export failed")).toBeTruthy()+ expect(api.getByText("File logging on · 2.4 MB")).toBeTruthy()+ expect(api.getByText("1 area · 42.0 MB")).toBeTruthy()+ })++ it("keeps every other sub when one read rejects, rather than blanking the card", async () => {+ // A resolved read whose value differs from the default, so a swallowed rejection would show.+ mockGetSetting.mockResolvedValue("true")+ mockGetFileLogSize.mockResolvedValue(2516582)+ mockLoadOfflineAreas.mockRejectedValue(new Error("MapLibre"))+ mockGetAutoExportStatus.mockRejectedValue(new Error("bridge"))+ const api = renderScreen()++ expect(await api.findByText("12,480 locations · 3.42 MB")).toBeTruthy()+ expect(api.getByText("File logging on · 2.4 MB")).toBeTruthy()+ expect(api.getByText("No saved areas")).toBeTruthy()+ // The export status never landed, so the row falls back to the nouns inside the screen.+ expect(api.getByText(/in, and out$/)).toBeTruthy()+ })++ it("issues every focus read at once, so a slow pack walk does not hold the others back", async () => {+ let releaseStats: (v: unknown) => void = () => {}+ mockGetStats.mockImplementationOnce(() => new Promise((r) => (releaseStats = r)))+ renderScreen()++ // The five slower reads must already be in flight while getStats is still pending.+ await waitFor(() => expect(mockLoadOfflineAreas).toHaveBeenCalled())+ expect(mockGetAutoExportStatus).toHaveBeenCalled()+ releaseStats({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0, lastSyncTime: 0, lastSyncError: "" })+ })++ it("re-reads only the two cheap values on a sync event, not the pack walk", async () => {+ const api = renderScreen()+ await api.findByText("12,480 locations · 3.42 MB")+ const packWalks = mockLoadOfflineAreas.mock.calls.length++ mockGetStats.mockResolvedValue({+ queued: 7,+ sent: 42,+ total: 12481,+ today: 11,+ databaseSizeMB: 3.4213,+ lastSyncTime: 0,+ lastSyncError: ""+ })+ act(() => {+ DeviceEventEmitter.emit("onLocationUpdate", {})+ })++ expect(await api.findByText("12,481 locations · 3.42 MB")).toBeTruthy()+ expect(mockLoadOfflineAreas.mock.calls.length).toBe(packWalks)+ })++ it("re-reads the export status when a scheduled run completes, so the row is not stale", async () => {+ const api = renderScreen()+ await api.findByText(/in, and out$/)++ mockGetAutoExportStatus.mockResolvedValue({+ enabled: true,+ interval: "daily",+ format: "gpx",+ uri: "content://tree",+ lastError: null,+ retentionCount: 0+ })+ act(() => {+ DeviceEventEmitter.emit("onAutoExportComplete", {})+ })++ expect(await api.findByText("Auto-export daily · GPX")).toBeTruthy()+ })++ it("words the zero states rather than printing a zero", async () => {+ mockGetStats.mockResolvedValue({+ queued: 0,+ sent: 0,+ total: 0,+ today: 0,+ databaseSizeMB: 0.02,+ lastSyncTime: 0,+ lastSyncError: ""+ })+ const api = renderScreen()++ expect(await api.findByText("No locations recorded")).toBeTruthy()+ expect(api.getByText("No saved areas")).toBeTruthy()+ expect(api.getByText("File logging off")).toBeTruthy()+ })})- it("shows the preset label as the Sync Strategy summary", () => {- mockSettings = { ...DEFAULT_SETTINGS, syncPreset: "balanced" }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText(/Balanced/)).toBeTruthy()- })-- it("shows a custom summary when syncPreset is custom", () => {- mockSettings = { ...DEFAULT_SETTINGS, syncPreset: "custom", interval: 45 }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("Custom · every 45s")).toBeTruthy()- })-- // --- Navigation ----- it("navigates to Appearance", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("Appearance"))-- expect(mockNavigate).toHaveBeenCalledWith("Appearance")- })-- it("navigates to Connection", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("Connection"))-- expect(mockNavigate).toHaveBeenCalledWith("Connection")- })-- it("navigates to Tracking & Sync", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("Tracking & Sync"))-- expect(mockNavigate).toHaveBeenCalledWith("Tracking & Sync")- })-- it("navigates to Tracking Profiles", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("Tracking Profiles"))-- expect(mockNavigate).toHaveBeenCalledWith("Tracking Profiles")- })-- it("navigates to Data Management", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("Data Management"))-- expect(mockNavigate).toHaveBeenCalledWith("Data Management")- })-- it("navigates to API Config", () => {- const { getByText } = render(<SettingsScreen {...mockProps} />)-- fireEvent.press(getByText("API Field Mapping"))-- expect(mockNavigate).toHaveBeenCalledWith("Request Format")- })-- // --- Offline mode ----- it("hides API Field Mapping link when offline mode is enabled", () => {- mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }-- const { queryByText } = render(<SettingsScreen {...mockProps} />)-- expect(queryByText("API Field Mapping")).toBeNull()- })-- it("still shows Connection, Tracking Profiles and Data Management in offline mode", () => {- mockSettings = { ...DEFAULT_SETTINGS, isOfflineMode: true }-- const { getByText } = render(<SettingsScreen {...mockProps} />)-- expect(getByText("Connection")).toBeTruthy()- expect(getByText("Tracking Profiles")).toBeTruthy()- expect(getByText("Data Management")).toBeTruthy()+ describe("the rows that leave the app", () => {+ it("names the destination, marks itself a link and says so to a screen reader", async () => {+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ expect(api.getByText("github.com/dietrichmax/colota/issues")).toBeTruthy()+ expect(api.getByText("colota.app/releases")).toBeTruthy()+ expect(api.getByText("mxd.codes/support")).toBeTruthy()+ expect(meta(api, "nav-feedback")[2]).toBe("link")+ expect(api.getByTestId("nav-feedback").props.accessibilityHint).toBe("Opens Feedback & help in the browser")+ expect(api.getByTestId("nav-rate").props.accessibilityHint).toBe("Opens Colota in Google Play")+ expect(meta(api, "nav-about")[2]).toBe("chevron")+ })++ it("opens the destination each link row names", async () => {+ const spy = jest.spyOn(Linking, "openURL").mockResolvedValue(undefined)+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ fireEvent.press(api.getByTestId("nav-feedback"))+ expect(spy).toHaveBeenLastCalledWith("https://github.com/dietrichmax/colota/issues")+ fireEvent.press(api.getByTestId("nav-whats-new"))+ expect(spy).toHaveBeenLastCalledWith("https://colota.app/releases")+ fireEvent.press(api.getByTestId("nav-support"))+ expect(spy).toHaveBeenLastCalledWith("https://mxd.codes/support")+ spy.mockRestore()+ })++ it("falls back to the Play website when the store app is not there, and reports a dead link", async () => {+ const spy = jest+ .spyOn(Linking, "openURL")+ .mockRejectedValueOnce(new Error("no activity"))+ .mockResolvedValue(undefined)+ const api = renderScreen()+ await waitFor(() => expect(mockGetStats).toHaveBeenCalled())++ fireEvent.press(api.getByTestId("nav-rate"))+ await waitFor(() => expect(spy).toHaveBeenCalledWith("https://play.google.com/store/apps/details?id=com.Colota"))++ spy.mockRejectedValue(new Error("no browser"))+ fireEvent.press(api.getByTestId("nav-support"))+ await waitFor(() => expect(mockShowAlert).toHaveBeenCalledWith("Error", "Could not open the link.", "error"))+ spy.mockRestore()+ })++ it("hides Rate the app on the FOSS build, where a Play listing is a dead end", async () => {+ mockFlavor = "foss"+ const api = renderScreen()++ expect(await api.findByText("Version 1.16.0 · FOSS")).toBeTruthy()+ expect(api.queryByTestId("nav-rate")).toBeNull()+ expect(api.getByTestId("nav-support")).toBeTruthy()+ })++ it("prints the build on the About row in the words the About screen uses", async () => {+ const api = renderScreen()++ expect(await api.findByText("Version 1.16.0 · Google Play")).toBeTruthy()+ })})})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 7f54a9ca..b5b8e334 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -3,7 +3,6 @@* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.*/-export { ActivityLogScreen } from "./ActivityLogScreen"export { ApiSettingsScreen } from "./ApiSettingsScreen"export { AutoExportScreen } from "./AutoExportScreen"export { AuthSettingsScreen } from "./AuthSettingsScreen"@@ -29,3 +28,5 @@ export { BackupRestoreScreen } from "./BackupRestoreScreen"export { BackendTemplateScreen } from "./BackendTemplateScreen"export { PlaceZoneScreen } from "./PlaceZoneScreen"export { ExportImportScreen } from "./ExportImportScreen"+export { LoggingScreen } from "./LoggingScreen"+export { LogPreviewScreen } from "./LogPreviewScreen"diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.tsindex 93508c21..894629c4 100644--- a/apps/mobile/src/types/navigation.ts+++ b/apps/mobile/src/types/navigation.ts@@ -35,6 +35,7 @@ export type RootStackParamList = {"Trip Detail": { trip: Trip; trips: Trip[] }"Offline Maps": undefinedLogging: undefined+ "Log Preview": undefined"Backup & Restore": undefined}diff --git a/apps/mobile/src/utils/__tests__/appearance.test.ts b/apps/mobile/src/utils/__tests__/appearance.test.tsnew file mode 100644index 00000000..74e7c21a--- /dev/null+++ b/apps/mobile/src/utils/__tests__/appearance.test.ts@@ -0,0 +1,86 @@+jest.mock("../../services/NativeLocationService", () => ({+ __esModule: true,+ default: { getBuildConfig: () => ({ APP_LANGUAGE: "en-GB" }) }+}))++import { MAP_STYLE_URL_LIGHT } from "../../constants"+import { formatTimeIn } from "../geo"+import { appearanceRowSub, clockSample, isStyleUrlValid, tileRowSub, unitNotation } from "../appearance"++describe("unitNotation", () => {+ it("names distance, speed and elevation, in the order the app prints them", () => {+ expect(unitNotation("metric")).toBe("km · km/h · m")+ expect(unitNotation("imperial")).toBe("mi · mph · ft")+ })+})++describe("clockSample", () => {+ const noon = new Date("2026-09-09T14:05:00Z")++ it("shows the current time in the format being offered", () => {+ expect(clockSample("24h", noon)).toBe(formatTimeIn(Math.floor(noon.getTime() / 1000), "24h"))+ expect(clockSample("12h", noon)).toBe(formatTimeIn(Math.floor(noon.getTime() / 1000), "12h"))+ })++ it("differs between the two formats", () => {+ expect(clockSample("24h", noon)).not.toBe(clockSample("12h", noon))+ })+})++describe("tileRowSub", () => {+ it("names the default host when nothing is stored", () => {+ expect(tileRowSub("", "")).toBe("maps.mxd.codes")+ expect(MAP_STYLE_URL_LIGHT).toContain("maps.mxd.codes")+ })++ it("names one host when both styles come from it", () => {+ expect(tileRowSub("https://tiles.example.org/l.json", "https://tiles.example.org/d.json")).toBe("tiles.example.org")+ })++ it("names both when they differ, since one name would hide half the answer", () => {+ expect(tileRowSub("https://a.example.org/l.json", "https://b.example.org/d.json")).toBe(+ "a.example.org · b.example.org"+ )+ })++ it("falls back per field, so filling one leaves the other on the default", () => {+ expect(tileRowSub("https://a.example.org/l.json", "")).toBe("a.example.org · maps.mxd.codes")+ })+})++describe("isStyleUrlValid", () => {+ it("accepts an empty value as a return to the default", () => {+ expect(isStyleUrlValid("")).toBe(true)+ expect(isStyleUrlValid(" ")).toBe(true)+ })++ it("accepts either scheme, because a tile server on a LAN is a real case", () => {+ expect(isStyleUrlValid("https://tiles.example.org/style.json")).toBe(true)+ expect(isStyleUrlValid("http://192.168.1.20:8080/style.json")).toBe(true)+ })++ it("refuses what MapLibre could never load", () => {+ expect(isStyleUrlValid("htps://tiles.example.org")).toBe(false)+ expect(isStyleUrlValid("tiles.example.org")).toBe(false)+ expect(isStyleUrlValid("asset://style.json")).toBe(false)+ })+})++describe("appearanceRowSub", () => {+ it("reads back how the app looks and reads", () => {+ expect(appearanceRowSub("dark", "metric", "24h")).toBe("Dark · Metric · 24h")+ expect(appearanceRowSub("system", "imperial", "12h")).toBe("System · Imperial · 12h")+ })++ it("takes every word from the catalog, including the clock", () => {+ expect(appearanceRowSub("light", "metric", "12h")).not.toContain("timeFormat")+ expect(appearanceRowSub("light", "metric", "12h")).toContain("12h")+ })++ it("adds the tile host only once a custom style is stored", () => {+ expect(appearanceRowSub("dark", "metric", "24h", "", "")).toBe("Dark · Metric · 24h")+ expect(appearanceRowSub("dark", "metric", "24h", "https://a.example.org/l.json", "")).toBe(+ "Dark · Metric · 24h · a.example.org · maps.mxd.codes"+ )+ })+})diff --git a/apps/mobile/src/utils/__tests__/logCapture.test.ts b/apps/mobile/src/utils/__tests__/logCapture.test.tsnew file mode 100644index 00000000..91d72374--- /dev/null+++ b/apps/mobile/src/utils/__tests__/logCapture.test.ts@@ -0,0 +1,164 @@+import type { MergedLogEntry } from "../logExport"+import {+ CAPTURE_HINT,+ countByFloor,+ DEFAULT_LOG_FLOOR,+ deleteSub,+ describeCapture,+ floorOptions,+ levelLetter,+ levelWord,+ LOG_CONTENTS_LINE,+ logTime,+ nextStepLine,+ passesFloor,+ previewRowSub,+ resultLine,+ rowLabel+} from "../logCapture"++const entry = (level: MergedLogEntry["level"], message = "x", time = 1_757_400_000_000): MergedLogEntry => ({+ id: `${level}-${time}`,+ time,+ level,+ source: "NATIVE",+ message,+ raw: message+})++describe("describeCapture", () => {+ it("separates a device with a capture running from one with an old file lying around", () => {+ expect(describeCapture(true, 2_500_000, 1_757_400_000_000).label).toBe("Recording")+ expect(describeCapture(false, 2_500_000, 0).caption).toBe("2.4 MB kept from an earlier capture")+ expect(describeCapture(false, 0, 0).caption).toBe("No log file on this device")+ })++ // A reporter who has just armed it needs to see that it took, before anything is written.+ it("says recording before the first byte lands", () => {+ const state = describeCapture(true, 0, 1_757_400_000_000)+ expect(state.label).toBe("Recording")+ expect(state.caption).toBe("Nothing written yet")+ })++ /**+ * A user who had logging on before the start time was ever recorded has no window to report, and+ * printing "since 01:00" from a zero would date the capture to 1970.+ */+ it("drops the since clause rather than inventing a start", () => {+ expect(describeCapture(true, 2_500_000, 0).caption).toBe("2.4 MB written")+ expect(describeCapture(true, 2_500_000, 1_757_400_000_000).caption).toMatch(/^2\.4 MB since \d{2}:\d{2}$/)+ })+})++describe("the wording a reporter acts on", () => {+ // The step missing from every bug report: leave it on while you reproduce the problem.+ it("names the next step, and which step it is", () => {+ expect(nextStepLine(false)).toContain("Switch on Record a log file")+ expect(nextStepLine(true)).toContain("Leave this on while you reproduce")+ })++ // The bridge swaps the reader's source on the toggle and nothing has ever said so on screen.+ it("says which source the reader is showing", () => {+ expect(previewRowSub(true)).toContain("log file")+ expect(previewRowSub(false)).toContain("system log")+ })++ it("says logging survives a restart, which is the fact reporters get wrong", () => {+ expect(CAPTURE_HINT).toContain("restarts included")+ })++ /**+ * Naming the contents is the disclosure. A vague warning gives a reporter nothing to decide with,+ * and an absolute promise of no coordinates would be false exactly when it mattered: no log call+ * writes a latitude, but NetworkManager logs a rejected upload's response body, so a server that+ * echoes the payload it refused puts them in the file anyway.+ */+ it("names what leaves the device, and stops short of promising an absence", () => {+ expect(LOG_CONTENTS_LINE).toContain("geofences")+ expect(LOG_CONTENTS_LINE).toContain("tracking profiles")+ expect(LOG_CONTENTS_LINE).toContain("server host")+ expect(LOG_CONTENTS_LINE).toContain("Colota writes no coordinates")+ expect(LOG_CONTENTS_LINE).toMatch(/rejected upload can carry your server/)+ })++ it("says the capture continues after a delete, only when it does", () => {+ expect(deleteSub(2_500_000, true)).toContain("carries on")+ expect(deleteSub(2_500_000, false)).not.toContain("carries on")+ })+})++describe("the level floor", () => {+ /**+ * A floor rather than a set of levels. The counts are nested subsets, so the number on the chip+ * and the number in the result line cannot disagree, which four independent multi-select chips+ * could never guarantee.+ */+ it("admits every level at or above itself", () => {+ expect(passesFloor("DEBUG", "all")).toBe(true)+ expect(passesFloor("DEBUG", "info")).toBe(false)+ expect(passesFloor("WARN", "info")).toBe(true)+ expect(passesFloor("ERROR", "error")).toBe(true)+ expect(passesFloor("WARN", "error")).toBe(false)+ })++ it("counts nested subsets, so no two chips can contradict each other", () => {+ const counts = countByFloor([entry("DEBUG"), entry("INFO"), entry("WARN"), entry("ERROR"), entry("ERROR")])+ expect(counts).toEqual({ all: 5, info: 4, warn: 3, error: 2 })+ expect(counts.all).toBeGreaterThanOrEqual(counts.info)+ expect(counts.info).toBeGreaterThanOrEqual(counts.warn)+ expect(counts.warn).toBeGreaterThanOrEqual(counts.error)+ })++ /**+ * The preview exists to show what is being sent. Opening on WARN would show four lines of a+ * 1,204-line file and misrepresent the one thing under review.+ */+ it("opens on everything, because this previews what leaves the device", () => {+ expect(DEFAULT_LOG_FLOOR).toBe("all")+ })++ // Without the count a reporter selects Errors to learn there are four: changing state to read a fact.+ it("carries each count on its own chip", () => {+ const options = floorOptions({ all: 1204, info: 312, warn: 47, error: 4 })+ expect(options.map((o) => o.label)).toEqual(["All 1,204", "Info 312", "Warnings 47", "Errors 4"])+ })+})++describe("resultLine", () => {+ it("names the source, and says so only once", () => {+ expect(resultLine(1204, 1204, true)).toBe("1,204 lines from the log file")+ expect(resultLine(1204, 1204, false)).toBe("1,204 lines from the system log")+ })++ it("shows both numbers only while something is filtered out", () => {+ expect(resultLine(86, 1204, true)).toBe("86 of 1,204 lines from the log file")+ expect(resultLine(0, 1204, true)).toBe("0 of 1,204 lines from the log file")+ })++ it("does not print a plural for a single line", () => {+ expect(resultLine(1, 1, true)).toBe("1 line from the log file")+ })+})++describe("the log row", () => {+ /**+ * Forced to 24 hours whatever Appearance says: the file this previews is written 24-hour, and a+ * mono column whose width changes by locale defeats the face it is set in.+ */+ it("keeps the column square, including for a line with no usable time", () => {+ expect(logTime(0)).toBe("--:--:--")+ expect(logTime(1_757_400_000_000)).toMatch(/^\d{2}:\d{2}:\d{2}$/)+ })++ it("gives one letter and one spoken word per level", () => {+ expect(levelLetter("ERROR")).toBe("E")+ expect(levelLetter("WARN")).toBe("W")+ expect(levelWord("ERROR")).toBe("Error")+ expect(levelWord("DEBUG")).toBe("Debug")+ })++ // One node per line, rather than one node holding three thousand lines.+ it("reads as a sentence to a screen reader", () => {+ expect(rowLabel(entry("ERROR", "sync failed"), "09:46:58")).toBe("Error, 09:46:58, sync failed")+ })+})diff --git a/apps/mobile/src/utils/__tests__/logExport.test.ts b/apps/mobile/src/utils/__tests__/logExport.test.tsindex 81227a92..b03bd1bd 100644--- a/apps/mobile/src/utils/__tests__/logExport.test.ts+++ b/apps/mobile/src/utils/__tests__/logExport.test.ts@@ -1,4 +1,4 @@-import { getMergedLogs, exportLogs } from "../logExport"+import { APP_LOG_COVERAGE, buildAppLog, buildExportHeader, getMergedLogs } from "../logExport"const mockGetLogEntries = jest.fn()const mockGetNativeLogs = jest.fn()@@ -7,6 +7,7 @@ const mockShareFile = jest.fn()jest.mock("../logger", () => ({getLogEntries: (...args: any[]) => mockGetLogEntries(...args),+ MAX_BUFFER_SIZE: 2000,logger: { error: jest.fn() }}))@@ -105,6 +106,8 @@ describe("getMergedLogs", () => {expect(result[0].message).toContain("native first")expect(result[1].message).toBe("js middle")expect(result[2].message).toContain("native last")+ // The stamp, pid, tid and level are stripped, so a search matches a JS line the same way.+ expect(result[0].message).toBe("Colota.Service: native first")})it("handles native log fetch failure gracefully", async () => {@@ -119,13 +122,33 @@ describe("getMergedLogs", () => {expect(result[0].message).toBe("still works")})- it("assigns NATIVE level for unrecognized logcat format", async () => {- mockGetNativeLogs.mockResolvedValue(["some unstructured log line"])+ // An unparsed line is a continuation, typically a stack frame, not a category of its own. A level+ // of its own puts it outside every filter, and a time of zero pins it above everything.+ it("gives a continuation the time and level of the line it belongs to", async () => {+ mockGetNativeLogs.mockResolvedValue([+ "2026-03-31 10:00:03.000 ERROR/Sync: Network error",+ "\tat com.Colota.sync.NetworkManager.run(NetworkManager.kt:88)",+ "\tat com.Colota.sync.SyncManager.flush(SyncManager.kt:214)"+ ])const result = await getMergedLogs()- expect(result).toHaveLength(1)- expect(result[0].level).toBe("NATIVE")+ expect(result).toHaveLength(3)+ expect(result.map((e) => e.level)).toEqual(["ERROR", "ERROR", "ERROR"])+ expect(result[1].time).toBe(result[0].time)+ expect(result[2].time).toBe(result[0].time)+ })++ it("keeps a leading orphan out of the way rather than pinning it above everything", async () => {+ mockGetNativeLogs.mockResolvedValue([+ "some unstructured log line",+ "2026-03-31 10:00:03.000 ERROR/Sync: Network error"+ ])++ const result = await getMergedLogs()++ expect(result).toHaveLength(2)+ expect(result[0].level).toBe("DEBUG")expect(result[0].time).toBe(0)})@@ -146,41 +169,63 @@ describe("getMergedLogs", () => {})})-describe("exportLogs", () => {- it("writes file and opens share sheet", async () => {- await exportLogs(- { VERSION_NAME: "1.5.1", VERSION_CODE: 31 },- { systemVersion: "14", apiLevel: "34", brand: "Google", model: "Pixel 7" }+describe("buildExportHeader", () => {+ // gms against foss is fused location against LocationManager, which changes what half the log+ // below can even mean.+ it("names the build, the flavor and the device", () => {+ const header = buildExportHeader(+ { VERSION_NAME: "1.16.0", VERSION_CODE: 48, FLAVOR: "gms" },+ { systemVersion: "15", apiLevel: "35", brand: "Google", model: "Pixel 8" },+ 0,+ Date.parse("2026-09-09T14:22:07.000Z"))- expect(mockWriteFile).toHaveBeenCalledTimes(1)- const [fileName, content] = mockWriteFile.mock.calls[0]- expect(fileName).toMatch(/^colota_logs_\d+\.txt$/)- expect(content).toContain("=== Colota Debug Log Export ===")- expect(content).toContain("Version: 1.5.1 (31)")- expect(content).toContain("OS: Android 14 (API 34)")- expect(content).toContain("Device: Google Pixel 7")+ expect(header).toContain("=== Colota log export ===")+ expect(header).toContain("App: 1.16.0 (48) gms")+ expect(header).toContain("Android: 15 (API 35)")+ expect(header).toContain("Device: Google Pixel 8")+ })++ it("names the capture window only when one was recorded", () => {+ const withStart = buildExportHeader(null, null, Date.parse("2026-09-09T09:41:12.000Z"), Date.now())+ expect(withStart).toContain("Recording started:")+ expect(buildExportHeader(null, null, 0, Date.now())).not.toContain("Recording started:")+ })- expect(mockShareFile).toHaveBeenCalledWith("/tmp/logs.txt", "text/plain", "Colota Debug Logs")+ it("still writes a header when neither block could be read", () => {+ expect(buildExportHeader(null, null, 0, Date.now())).toContain("=== Colota log export ===")})+})- it("works without build config and device info", async () => {- await exportLogs(null, null)+describe("buildAppLog", () => {+ // Native places these by timestamp, so they must be in AppFileLogger's exact shape or the merge+ // cannot read them and they all sink to the tail.+ it("writes the buffer in the file logger's own line shape", () => {+ mockGetLogEntries.mockReturnValue([{ timestamp: "2026-03-31T10:00:00.000Z", level: "WARN", message: "check this" }])++ const lines = buildAppLog().trimEnd().split("\n")- expect(mockWriteFile).toHaveBeenCalledTimes(1)- const content = mockWriteFile.mock.calls[0][1]- expect(content).toContain("=== Colota Debug Log Export ===")- expect(content).not.toContain("App Info")- expect(content).not.toContain("Device Info")+ expect(lines).toHaveLength(2)+ expect(lines[1]).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} WARN\/JS: check this$/)})- it("includes merged log entries in export", async () => {- mockGetLogEntries.mockReturnValue([{ timestamp: "2026-03-31T10:00:00.000Z", level: "INFO", message: "hello" }])+ // The buffer is process-lifetime while the recorded file spans restarts, so a merged stream+ // implies the app was quiet before this launch unless something says where its coverage starts.+ it("marks where its coverage starts, once", () => {+ mockGetLogEntries.mockReturnValue([+ { timestamp: "2026-03-31T10:00:00.000Z", level: "INFO", message: "one" },+ { timestamp: "2026-03-31T10:00:01.000Z", level: "INFO", message: "two" }+ ])++ const out = buildAppLog()- await exportLogs(null, null)+ expect(out.split(APP_LOG_COVERAGE)).toHaveLength(2)+ expect(out.indexOf(APP_LOG_COVERAGE)).toBeLessThan(out.indexOf("one"))+ expect(APP_LOG_COVERAGE).toContain("this session only")+ })- const content = mockWriteFile.mock.calls[0][1]- expect(content).toContain("--- Log Entries (1) ---")- expect(content).toContain("[2026-03-31T10:00:00.000Z] [JS] INFO hello")+ it("writes nothing at all rather than a marker over an empty buffer", () => {+ mockGetLogEntries.mockReturnValue([])+ expect(buildAppLog()).toBe("")})})diff --git a/apps/mobile/src/utils/__tests__/logger.test.ts b/apps/mobile/src/utils/__tests__/logger.test.tsindex 9313d08a..ab0ddf87 100644--- a/apps/mobile/src/utils/__tests__/logger.test.ts+++ b/apps/mobile/src/utils/__tests__/logger.test.ts@@ -148,3 +148,20 @@ describe("logger", () => {})})})++describe("what the buffer captures", () => {+ /**+ * The preview opens on every level now, so nothing here decides a default. What still matters is+ * that the buffer keeps DEBUG: the filter is a view and the exported file is not, so dropping a+ * level at the source would empty the one diagnostic this project runs on.+ */+ it("keeps every level, because the filter is a view and the export is not", () => {+ const mod = require("../logger")+ mod.logger.debug("zone lookup")+ mod.logger.info("sync tick")++ const levels = mod.getLogEntries().map((e: { level: string }) => e.level)+ expect(levels).toContain("DEBUG")+ expect(levels).toContain("INFO")+ })+})diff --git a/apps/mobile/src/utils/__tests__/queueStatus.test.ts b/apps/mobile/src/utils/__tests__/queueStatus.test.tsdeleted file mode 100644index 280b06cf..00000000--- a/apps/mobile/src/utils/__tests__/queueStatus.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { getQueueColor } from "../queueStatus"-import { ThemeColors } from "../../types/global"--const mockColors = {- text: "#202124",- warning: "#FF9800",- error: "#D32F2F"-} as ThemeColors--describe("getQueueColor", () => {- it("returns text color for zero items", () => {- expect(getQueueColor(0, mockColors)).toBe(mockColors.text)- })-- it("returns text color for count at threshold boundary (50)", () => {- expect(getQueueColor(50, mockColors)).toBe(mockColors.text)- })-- it("returns warning color when count exceeds 50", () => {- expect(getQueueColor(51, mockColors)).toBe(mockColors.warning)- })-- it("returns warning color at critical boundary (100)", () => {- expect(getQueueColor(100, mockColors)).toBe(mockColors.warning)- })-- it("returns error color when count exceeds 100", () => {- expect(getQueueColor(101, mockColors)).toBe(mockColors.error)- })-- it("returns error color for very large counts", () => {- expect(getQueueColor(10000, mockColors)).toBe(mockColors.error)- })-- it("returns text color for negative numbers", () => {- expect(getQueueColor(-1, mockColors)).toBe(mockColors.text)- })-})diff --git a/apps/mobile/src/utils/__tests__/settingsRow.test.ts b/apps/mobile/src/utils/__tests__/settingsRow.test.tsnew file mode 100644index 00000000..297ef681--- /dev/null+++ b/apps/mobile/src/utils/__tests__/settingsRow.test.ts@@ -0,0 +1,90 @@+import { buildLine, dataRowSub, getVariantLabel, loggingRowSub, offlineMapsRowSub, versionLine } from "../settingsRow"++const area = (name: string, sizeBytes: number | null) => ({+ name,+ sizeBytes,+ isComplete: true,+ isActive: false,+ bounds: null+})++describe("offlineMapsRowSub", () => {+ it("counts the areas and sums what they take on disk", () => {+ expect(offlineMapsRowSub([area("Munich", 42 * 1024 * 1024), area("Alps", 76 * 1024 * 1024)])).toBe(+ "2 areas · 118.0 MB"+ )+ expect(offlineMapsRowSub([area("Munich", 42 * 1024 * 1024)])).toBe("1 area · 42.0 MB")+ })++ it("falls back to the count when no pack reports a size, since sizeBytes is nullable", () => {+ expect(offlineMapsRowSub([area("Munich", null), area("Alps", null)])).toBe("2 areas")+ })++ it("says none rather than a zero", () => {+ expect(offlineMapsRowSub([])).toBe("No saved areas")+ })+})++describe("loggingRowSub", () => {+ it("names the size while the log is being written", () => {+ expect(loggingRowSub(true, 2516582)).toBe("File logging on · 2.4 MB")+ })++ /**+ * Switching the toggle off stops writing and deletes nothing. A bare "File logging off" over+ * megabytes of named-zone and profile history reads as though the file went with the switch.+ */+ it("still says what is on disk after the switch goes off", () => {+ expect(loggingRowSub(false, 2516582)).toBe("File logging off · 2.4 MB kept")+ expect(loggingRowSub(false, 0)).toBe("File logging off")+ })+})++describe("dataRowSub", () => {+ it("formats exactly as the ledger it opens, two decimals and a grouped count", () => {+ expect(dataRowSub(12480, 3.4213)).toBe("12,480 locations · 3.42 MB")+ })++ it("words the zero rather than printing 0 locations · 0.00 MB", () => {+ expect(dataRowSub(0, 0.02)).toBe("No locations recorded")+ })+})++describe("getVariantLabel", () => {+ it("names each flavor as the About row and the About screen print it after the version", () => {+ expect(getVariantLabel("gms")).toBe("Google Play")+ expect(getVariantLabel("foss")).toBe("FOSS")+ expect(getVariantLabel("")).toBe("Unknown")+ })+})++const gms = { VERSION_NAME: "1.16.0", VERSION_CODE: 48, FLAVOR: "gms" }+const foss = { VERSION_NAME: "1.16.0", VERSION_CODE: 48, FLAVOR: "foss" }++describe("versionLine", () => {+ it("is the hub's About row, version and flavor", () => {+ expect(versionLine(gms)).toBe("1.16.0 · Google Play")+ expect(versionLine(foss)).toBe("1.16.0 · FOSS")+ })++ // A missing bridge module used to print "Version · Unknown" on the hub.+ it("says Unknown for a build module that did not link", () => {+ expect(versionLine(null)).toBe("Unknown")+ })+})++describe("buildLine", () => {+ // Play's crash reports, F-Droid and changelogs/<code>.txt are keyed by the code, and 1.8.0+ // shipped under both 36 and 37.+ it("is the About screen's line, with the version code the release artefacts are keyed by", () => {+ expect(buildLine(gms)).toBe("1.16.0 (48) · Google Play")+ expect(buildLine(foss)).toBe("1.16.0 (48) · FOSS")+ expect(buildLine(null)).toBe("Unknown")+ })++ it("is the row's line with the code inserted, so the two cannot disagree", () => {+ for (const config of [gms, foss]) {+ expect(buildLine(config).replace(" (48)", "")).toBe(versionLine(config))+ }+ })+})diff --git a/apps/mobile/src/utils/appearance.ts b/apps/mobile/src/utils/appearance.tsnew file mode 100644index 00000000..25f9a26f--- /dev/null+++ b/apps/mobile/src/utils/appearance.ts@@ -0,0 +1,56 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { MAP_STYLE_URL_LIGHT, MAP_STYLE_URL_DARK } from "../constants"+import { t } from "../i18n"+import type { ThemePreference } from "../hooks/useTheme"+import { formatTimeIn, type TimeFormat, type UnitSystem } from "./geo"+import { endpointHost } from "./serverState"+import { isEndpointAllowed } from "./settingsValidation"++/**+ * What each Appearance choice produces, as the words the rows print. Computed rather than+ * translated: this is the app's only translated screen, so a value costs a translator nothing.+ */++/** The units the choice puts on screen, in the order distance, speed then elevation. */+export function unitNotation(unit: UnitSystem): string {+ return unit === "imperial" ? "mi · mph · ft" : "km · km/h · m"+}++/** The current time in the chosen format, through the app's own formatter so it cannot drift. */+export function clockSample(format: TimeFormat, now: Date = new Date()): string {+ return formatTimeIn(Math.floor(now.getTime() / 1000), format)+}++/** The host actually serving tiles. One name when both styles agree, both when they do not. */+export function tileRowSub(light: string, dark: string): string {+ const lightHost = endpointHost(light.trim() || MAP_STYLE_URL_LIGHT)+ const darkHost = endpointHost(dark.trim() || MAP_STYLE_URL_DARK)+ return lightHost === darkHost ? lightHost : `${lightHost} · ${darkHost}`+}++/** Empty means the default, so only a non-empty value has to be a URL this app can load. */+export function isStyleUrlValid(text: string): boolean {+ const trimmed = text.trim()+ return trimmed === "" || isEndpointAllowed(trimmed)+}++/** The Settings hub row: what the app looks and reads like, and the tile host once one is stored. */+export function appearanceRowSub(+ preference: ThemePreference,+ unit: UnitSystem,+ format: TimeFormat,+ light = "",+ dark = ""+): string {+ const parts = [+ t(`appearance.theme.${preference}`),+ t(`appearance.units.${unit}`),+ t(`appearance.timeFormat.${format}`)+ ]+ if (light.trim() || dark.trim()) parts.push(tileRowSub(light, dark))+ return parts.join(" · ")+}diff --git a/apps/mobile/src/utils/logCapture.ts b/apps/mobile/src/utils/logCapture.tsnew file mode 100644index 00000000..5bd36ea1--- /dev/null+++ b/apps/mobile/src/utils/logCapture.ts@@ -0,0 +1,156 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import type { LucideIcon } from "lucide-react-native"+import { FileClock, FileText, FileX } from "lucide-react-native"+import type { LogLevel } from "./logger"+import type { MergedLogEntry } from "./logExport"+import { formatBytes } from "./format"+import { formatTimeIn } from "./geo"++/**+ * What a log capture is worth handing over, in the words the screen prints.+ *+ * The screen has one product, a file a maintainer can read, so every line here is worded against+ * that: what is being recorded, what leaves the device with it, and what a preview of it can and+ * cannot show. Nothing here reads the bridge or the theme, so the strings are testable without+ * rendering, which is the `dataScope.ts` and `backupState.ts` contract.+ */++export type LogFloor = "all" | "info" | "warn" | "error"++export const DEFAULT_LOG_FLOOR: LogFloor = "all"++/**+ * Names the contents rather than promising an absence. No log call in either tree writes a+ * latitude or longitude, but `NetworkManager` logs a rejected upload's response body, so a server+ * that echoes the payload it refused puts coordinates in the file through the back door. An+ * absolute "holds no coordinates" would be false exactly when it mattered.+ */+export const LOG_CONTENTS_LINE =+ "The file names your geofences, your tracking profiles and your server host. Colota writes no coordinates into it, but a rejected upload can carry your server's reply. Read it before you attach it."++export const CAPTURE_HINT = "Keeps writing until you switch it off, restarts included."++export interface CaptureState {+ icon: LucideIcon+ tone: "recording" | "idle"+ label: string+ caption: string+}++/**+ * Five states, because "off" over 8 MB of named-zone history is a different situation from "off"+ * over nothing, and a reporter who has just armed it needs to see that it took.+ */+export function describeCapture(enabled: boolean, bytes: number, startedAtMs: number): CaptureState {+ if (enabled) {+ if (bytes === 0) {+ return { icon: FileClock, tone: "recording", label: "Recording", caption: "Nothing written yet" }+ }+ const since = startedAtMs > 0 ? ` since ${formatTimeIn(Math.floor(startedAtMs / 1000), "24h", false)}` : " written"+ return { icon: FileClock, tone: "recording", label: "Recording", caption: `${formatBytes(bytes)}${since}` }+ }+ if (bytes > 0) {+ return {+ icon: FileText,+ tone: "idle",+ label: "Not recording",+ caption: `${formatBytes(bytes)} kept from an earlier capture`+ }+ }+ return { icon: FileX, tone: "idle", label: "Not recording", caption: "No log file on this device" }+}++/**+ * The reader shows the log file while recording is on and the system log otherwise, which the+ * bridge decides and nothing has ever said out loud.+ */+export function previewRowSub(enabled: boolean): string {+ return enabled ? "The log file's most recent lines, newest first" : "The system log's last few minutes, newest first"+}++/** The step that is missing from every bug report: leave it on while you reproduce the problem. */+export function nextStepLine(enabled: boolean): string {+ return enabled+ ? "Nothing written yet. Leave this on while you reproduce the problem, then come back and save the file."+ : "Switch on Record a log file, reproduce the problem, then come back and save the file."+}++export function deleteSub(bytes: number, enabled: boolean): string {+ const carries = enabled ? " Recording carries on into a new file." : ""+ return `Removes ${formatBytes(bytes)}.${carries}`+}++export function deleteConfirmMessage(bytes: number): string {+ return `Deletes ${formatBytes(bytes)} of recorded log. Anything you have not saved is gone for good.`+}++/**+ * One count, one place, outside the scroller, arithmetically true against the chip beside it.+ * Never called with no lines at all: the empty state owns that screen, head and count included.+ */+export function resultLine(shown: number, total: number, fromFile: boolean): string {+ const source = fromFile ? "log file" : "system log"+ const noun = total === 1 ? "line" : "lines"+ if (shown === total) return `${total.toLocaleString()} ${noun} from the ${source}`+ return `${shown.toLocaleString()} of ${total.toLocaleString()} ${noun} from the ${source}`+}++const FLOOR_RANK: Record<LogFloor, number> = { all: 0, info: 1, warn: 2, error: 3 }+const LEVEL_RANK: Record<LogLevel, number> = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 }++/** A floor, not a set: the counts are nested subsets, so they cannot disagree with each other. */+export function passesFloor(level: LogLevel, floor: LogFloor): boolean {+ return LEVEL_RANK[level] >= FLOOR_RANK[floor]+}++export function countByFloor(entries: readonly MergedLogEntry[]): Record<LogFloor, number> {+ const counts: Record<LogFloor, number> = { all: 0, info: 0, warn: 0, error: 0 }+ for (const entry of entries) {+ counts.all+++ if (passesFloor(entry.level, "info")) counts.info+++ if (passesFloor(entry.level, "warn")) counts.warn+++ if (passesFloor(entry.level, "error")) counts.error+++ }+ return counts+}++/**+ * The count rides on the chip so a reporter learns there are four errors without selecting Errors+ * to find out, which is changing state to read a fact.+ */+export function floorOptions(+ counts: Record<LogFloor, number>+): readonly { value: LogFloor; label: string; testID: string }[] {+ return [+ { value: "all", label: `All ${counts.all.toLocaleString()}`, testID: "floor-all" },+ { value: "info", label: `Info ${counts.info.toLocaleString()}`, testID: "floor-info" },+ { value: "warn", label: `Warnings ${counts.warn.toLocaleString()}`, testID: "floor-warn" },+ { value: "error", label: `Errors ${counts.error.toLocaleString()}`, testID: "floor-error" }+ ]+}++/**+ * Forced to 24 hours whatever the Appearance clock says: the file this previews is written+ * 24-hour, and a mono column whose width changes by locale defeats the face it is set in.+ */+export function logTime(ms: number): string {+ if (!(ms > 0)) return "--:--:--"+ return formatTimeIn(Math.floor(ms / 1000), "24h", true)+}++export function levelLetter(level: LogLevel): string {+ return level.charAt(0)+}++export function levelWord(level: LogLevel): string {+ return level.charAt(0) + level.slice(1).toLowerCase()+}++/** One node per line for TalkBack, rather than one node holding three thousand lines. */+export function rowLabel(entry: MergedLogEntry, stamp: string): string {+ return `${levelWord(entry.level)}, ${stamp}, ${entry.message}`+}diff --git a/apps/mobile/src/utils/logExport.ts b/apps/mobile/src/utils/logExport.tsindex a6fbb3e6..14c98913 100644--- a/apps/mobile/src/utils/logExport.ts+++ b/apps/mobile/src/utils/logExport.ts@@ -4,53 +4,67 @@*/import NativeLocationService from "../services/NativeLocationService"-import { getLogEntries, type LogLevel } from "./logger"+import { getLogEntries, MAX_BUFFER_SIZE, type LogLevel } from "./logger"export interface MergedLogEntry {id: stringtime: number- level: LogLevel | "NATIVE"+ level: LogLevelsource: "JS" | "NATIVE"message: stringraw: string}-type ParsedLevel = MergedLogEntry["level"]+/** `AppFileLogger`'s own line shape, which the exported file is written in end to end. */+const FILE_LINE = /^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})\s+(DEBUG|INFO|WARN|ERROR)\/(.*)$/+/** logcat threadtime, the source the reader falls back to while file logging is off. */+const LOGCAT_LINE = /^(\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})\s+\d+\s+\d+\s+([VDIWEF])\s+(.*)$/++const LOGCAT_LEVEL: Record<string, LogLevel> = {+ V: "DEBUG",+ D: "DEBUG",+ I: "INFO",+ W: "WARN",+ E: "ERROR",+ F: "ERROR"+}++export interface ParsedNativeLine {+ time: number+ level: LogLevel+ message: string+}/**- * Recognises both logcat threadtime (`MM-DD HH:MM:SS.mmm PID TID L TAG: msg`)- * and AppFileLogger output (`yyyy-MM-dd HH:mm:ss.SSS LEVEL/TAG: msg`).+ * Returns null for a line that is neither shape, which is a continuation of the one before it+ * rather than a category of its own. A stack trace is the case that matters: its frames carry no+ * stamp and no level, and giving them a level of their own is what put them outside every filter.*/-function parseNativeLogLine(raw: string): { time: number; level: ParsedLevel } {- const fileMatch = raw.match(/^(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})\s+(DEBUG|INFO|WARN|ERROR)\//)+export function parseNativeLogLine(raw: string): ParsedNativeLine | null {+ const fileMatch = raw.match(FILE_LINE)if (fileMatch) {return {time: new Date(`${fileMatch[1]}T${fileMatch[2]}`).getTime(),- level: fileMatch[3] as ParsedLevel+ level: fileMatch[3] as LogLevel,+ message: fileMatch[4]}}- const logcatMatch = raw.match(/^(\d{2}-\d{2})\s+(\d{2}:\d{2}:\d{2}\.\d{3})/)- const time = logcatMatch ? new Date(`${new Date().getFullYear()}-${logcatMatch[1]}T${logcatMatch[2]}`).getTime() : 0-- const levelMatch = raw.match(/\d+\s+\d+\s+([VDIWEF])\s/)- const nativeLevel = levelMatch ? levelMatch[1] : ""- const level: ParsedLevel =- nativeLevel === "E"- ? "ERROR"- : nativeLevel === "W"- ? "WARN"- : nativeLevel === "I"- ? "INFO"- : nativeLevel === "D"- ? "DEBUG"- : "NATIVE"-- return { time, level }+ const logcatMatch = raw.match(LOGCAT_LINE)+ if (logcatMatch) {+ return {+ time: new Date(`${new Date().getFullYear()}-${logcatMatch[1]}T${logcatMatch[2]}`).getTime(),+ level: LOGCAT_LEVEL[logcatMatch[3]] ?? "DEBUG",+ message: logcatMatch[4]+ }+ }++ return null}/**- * Merges JS and native log entries chronologically.+ * Merges the JS ring buffer with whatever the bridge answers, ascending. The screen reverses for+ * display; the ascending order is what the export and `logExport.test.ts` depend on.*/export async function getMergedLogs(): Promise<MergedLogEntry[]> {const merged: MergedLogEntry[] = []@@ -70,15 +84,23 @@ export async function getMergedLogs(): Promise<MergedLogEntry[]> {try {const nativeLogs = await NativeLocationService.getNativeLogs()+ // A continuation inherits the line above it, so a stack trace sorts and filters with its throw+ // instead of sinking to epoch zero above every real entry.+ let lastTime = 0+ let lastLevel: LogLevel = "DEBUG"for (let i = 0; i < nativeLogs.length; i++) {const raw = nativeLogs[i]- const { time, level } = parseNativeLogLine(raw)+ const parsed = parseNativeLogLine(raw)+ if (parsed) {+ lastTime = parsed.time+ lastLevel = parsed.level+ }merged.push({id: `native-${i}`,- time,- level,+ time: parsed ? parsed.time : lastTime,+ level: parsed ? parsed.level : lastLevel,source: "NATIVE",- message: raw,+ message: parsed ? parsed.message : raw,raw: `[NATIVE] ${raw}`})}@@ -90,35 +112,59 @@ export async function getMergedLogs(): Promise<MergedLogEntry[]> {return merged}+const pad = (n: number, width = 2): string => String(n).padStart(width, "0")++/** Device local, matching `AppFileLogger`, so the two halves of the exported file compare. */+function localStamp(ms: number): string {+ const d = new Date(ms)+ const date = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`+ const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`+ return `${date} ${time}`+}+/**- * Exports merged logs to a text file and opens the share sheet.+ * The block a maintainer reads first. `FLAVOR` is in it because gms against foss is fused location+ * against `LocationManager`, which changes what half the log below can even mean.*/-export async function exportLogs(- buildConfig: { VERSION_NAME: string; VERSION_CODE: number } | null,- deviceInfo: { systemVersion: string; apiLevel: string | number; brand: string; model: string } | null-): Promise<void> {- const lines: string[] = ["=== Colota Debug Log Export ===", `Exported: ${new Date().toISOString()}`, ""]-+export function buildExportHeader(+ buildConfig: { VERSION_NAME: string; VERSION_CODE: number; FLAVOR?: string } | null,+ deviceInfo: { systemVersion: string; apiLevel: string | number; brand: string; model: string } | null,+ startedAtMs: number,+ nowMs: number+): string {+ const lines = ["=== Colota log export ===", `Exported: ${localStamp(nowMs)}`]if (buildConfig) {- lines.push("--- App Info ---", `Version: ${buildConfig.VERSION_NAME} (${buildConfig.VERSION_CODE})`, "")+ const flavor = buildConfig.FLAVOR ? ` ${buildConfig.FLAVOR}` : ""+ lines.push(`App: ${buildConfig.VERSION_NAME} (${buildConfig.VERSION_CODE})${flavor}`)}-if (deviceInfo) {- lines.push(- "--- Device Info ---",- `OS: Android ${deviceInfo.systemVersion} (API ${deviceInfo.apiLevel})`,- `Device: ${deviceInfo.brand} ${deviceInfo.model}`,- ""- )+ lines.push(`Android: ${deviceInfo.systemVersion} (API ${deviceInfo.apiLevel})`)+ lines.push(`Device: ${deviceInfo.brand} ${deviceInfo.model}`)}+ if (startedAtMs > 0) lines.push(`Recording started: ${localStamp(startedAtMs)}`)+ return `${lines.join("\n")}\n`+}- const merged = await getMergedLogs()- lines.push(`--- Log Entries (${merged.length}) ---`, "")- for (const entry of merged) {- lines.push(entry.raw)- }+export const APP_LOG_COVERAGE = `App log coverage starts here (this session only, last ${MAX_BUFFER_SIZE} lines)`- const fileName = `colota_logs_${Date.now()}.txt`- const filePath = await NativeLocationService.writeFile(fileName, lines.join("\n"))- await NativeLocationService.shareFile(filePath, "text/plain", "Colota Debug Logs")+/**+ * The JS ring buffer in `AppFileLogger`'s exact line shape, so native can interleave it into the+ * recorded file by timestamp rather than bolting it on as a second timeline.+ *+ * The buffer lives for one process while the file spans restarts, so the merge would silently+ * imply the app was quiet before this launch. `APP_LOG_COVERAGE` is emitted at the first JS line+ * to say where the second source starts, which is the one thing a merged stream cannot show by+ * itself.+ */+export function buildAppLog(): string {+ const entries = getLogEntries()+ if (entries.length === 0) return ""+ const lines: string[] = []+ for (let i = 0; i < entries.length; i++) {+ const entry = entries[i]+ const stamp = localStamp(new Date(entry.timestamp).getTime())+ if (i === 0) lines.push(`${stamp} INFO/${APP_LOG_COVERAGE}`)+ lines.push(`${stamp} ${entry.level}/JS: ${entry.message}`)+ }+ return `${lines.join("\n")}\n`}diff --git a/apps/mobile/src/utils/logger.ts b/apps/mobile/src/utils/logger.tsindex 09865cf3..f29a2303 100644--- a/apps/mobile/src/utils/logger.ts+++ b/apps/mobile/src/utils/logger.ts@@ -5,8 +5,8 @@* - debug/info: Only logged in development console* - warn/error: Always logged to console*- * All levels are always captured in a ring buffer for export- * via the Activity Log screen.+ * All levels are always captured in a ring buffer, which the Logging screen previews and the+ * exported log file carries alongside the recorded native lines.*/export type LogLevel = "DEBUG" | "INFO" | "WARN" | "ERROR"@@ -19,7 +19,8 @@ export interface LogEntry {message: string}-const MAX_BUFFER_SIZE = 2000+/** The buffer is process-lifetime, which the exported file has to state where the JS half begins. */+export const MAX_BUFFER_SIZE = 2000const logBuffer: LogEntry[] = []function formatArgs(args: unknown[]): string {diff --git a/apps/mobile/src/utils/queueStatus.ts b/apps/mobile/src/utils/queueStatus.tsdeleted file mode 100644index f7f2eba5..00000000--- a/apps/mobile/src/utils/queueStatus.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Copyright (C) 2026 Max Dietrich- * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.- */--import { ThemeColors } from "../types/global"-import { HIGH_QUEUE_THRESHOLD, CRITICAL_QUEUE_THRESHOLD } from "../constants"--/**- * Returns the appropriate color for the queue count based on severity- */-export const getQueueColor = (count: number, colors: ThemeColors) => {- if (count > CRITICAL_QUEUE_THRESHOLD) return colors.error- if (count > HIGH_QUEUE_THRESHOLD) return colors.warning- return colors.text-}diff --git a/apps/mobile/src/utils/settingsRow.ts b/apps/mobile/src/utils/settingsRow.tsnew file mode 100644index 00000000..680d85dd--- /dev/null+++ b/apps/mobile/src/utils/settingsRow.ts@@ -0,0 +1,62 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { formatBytes, plural } from "./format"+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"+ const bytes = areas.reduce((sum, area) => sum + (area.sizeBytes ?? 0), 0)+ const count = plural(areas.length, "area")+ return bytes > 0 ? `${count} · ${formatBytes(bytes)}` : count+}++/** "File logging on · 2.4 MB". The size only means something while the log is being written. */+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"+}++/** 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 · ${databaseSizeMB.toFixed(2)} MB`+}++/** The build a user is running, as `versionLine` and `buildLine` name it after the version. */+export function getVariantLabel(flavor: string): string {+ switch (flavor) {+ case "foss":+ return "FOSS"+ case "gms":+ return "Google Play"+ default:+ return flavor || "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"+ 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.+ */+export function buildLine(config: { VERSION_NAME: string; VERSION_CODE: number; FLAVOR: string } | null): string {+ if (!config) return "Unknown"+ return `${config.VERSION_NAME} (${config.VERSION_CODE}) · ${getVariantLabel(config.FLAVOR)}`+}