Skip to content

Colota - Android GPS Location tracker

feat(ui): the primitives, map layer and type scale the screens build on (#849)

Max Dietrichc77184cf3c6a
diff --git a/apps/docs/src/components/DeepLinkGenerator.module.css b/apps/docs/src/components/DeepLinkGenerator.module.css
index 01e17115..a418b8f9 100644
--- a/apps/docs/src/components/DeepLinkGenerator.module.css
+++ b/apps/docs/src/components/DeepLinkGenerator.module.css
@@ -184,7 +184,7 @@
}
.output {
- background: var(--colota-card-elevated-bg);
+ background: var(--colota-card-bg);
border: 1px solid var(--colota-border);
border-radius: 8px;
padding: 0.75rem;
diff --git a/apps/docs/src/theme/Root.tsx b/apps/docs/src/theme/Root.tsx
index aa9900b8..306b05de 100644
--- a/apps/docs/src/theme/Root.tsx
+++ b/apps/docs/src/theme/Root.tsx
@@ -14,16 +14,12 @@ function colorVars(colors: ThemeColors) {
--ifm-color-primary-dark: ${colors.primaryDark};
--ifm-color-primary-darker: ${colors.primaryDark};
--ifm-color-primary-darkest: ${colors.primaryDark};
- --ifm-color-primary-light: ${colors.primaryLight};
- --ifm-color-primary-lighter: ${colors.primaryLight};
- --ifm-color-primary-lightest: ${colors.primaryLight};
--ifm-background-color: ${colors.background};
--ifm-font-color-base: ${colors.text};
--ifm-font-color-secondary: ${colors.textSecondary};
--ifm-link-color: ${colors.link};
--ifm-font-family-base: '${fontFamily}', system-ui, -apple-system, sans-serif;
--colota-card-bg: ${colors.card};
- --colota-card-elevated-bg: ${colors.cardElevated};
--colota-border: ${colors.border};
--colota-card-radius: 12px;
--colota-card-padding: 16px;
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 02794fd9..97fabbe2 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -3,7 +3,8 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
import React, { useMemo, useState, useCallback } from "react"
-import { NavigationContainer, NavigationContainerRef } from "@react-navigation/native"
+import { NavigationContainer, NavigationContainerRef, DefaultTheme, DarkTheme } from "@react-navigation/native"
+import { LucideProvider } from "lucide-react-native"
import { createNativeStackNavigator } from "@react-navigation/native-stack"
import { SafeAreaProvider } from "react-native-safe-area-context"
import { View, StatusBar, Platform, StyleSheet } from "react-native"
@@ -41,7 +42,7 @@ import {
TrackingSyncScreen,
BackupRestoreScreen
} from "./src/screens/"
-import { BottomTabBar } from "./src/components"
+import { BottomTabBar, TAB_ROUTES } from "./src/components"
import { loadDisplayPreferences } from "./src/utils/geo"
import { registerTileServerUserAgent } from "./src/utils/tileHeaders"
@@ -88,12 +89,12 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
{
name: "Geofence Editor",
component: GeofenceEditorScreen,
- title: "Geofence Editor"
+ title: "Geofence editor"
},
{
name: "Location History",
component: LocationHistoryScreen,
- title: "Location History"
+ title: "Location history"
},
{
name: "Location Summary",
@@ -103,57 +104,57 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
{
name: "Export Locations",
component: ExportLocationsScreen,
- title: "Export Locations"
+ title: "Export locations"
},
{
name: "Import Locations",
component: ImportLocationsScreen,
- title: "Import Locations"
+ title: "Import locations"
},
{
name: "Auto-Export",
component: AutoExportScreen,
- title: "Auto-Export"
+ title: "Auto-export"
},
{
name: "Data Management",
component: DataManagementScreen,
- title: "Data Management"
+ title: "Data management"
},
{
name: "Tracking Profiles",
component: TrackingProfilesScreen,
- title: "Tracking Profiles"
+ title: "Tracking profiles"
},
{
name: "Profile Editor",
component: ProfileEditorScreen,
- title: "Profile Editor"
+ title: "Profile editor"
},
{
name: "About Colota",
component: AboutScreen,
- title: "About Colota"
+ title: "About"
},
{
name: "Setup Import",
component: SetupImportScreen,
- title: "Import Configuration"
+ title: "Import configuration"
},
{
name: "Share Setup",
component: ShareSetupScreen,
- title: "Share Setup"
+ title: "Share setup"
},
{
name: "Trip Detail",
component: TripDetailScreen,
- title: "Trip Detail"
+ title: "Trip detail"
},
{
name: "Offline Maps",
component: OfflineMapsScreen,
- title: "Offline Maps"
+ title: "Offline maps"
},
{
name: "Logging",
@@ -163,7 +164,7 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
{
name: "Backup & Restore",
component: BackupRestoreScreen,
- title: "Backup & Restore"
+ title: "Backup & restore"
},
{
name: "Appearance",
@@ -178,12 +179,10 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
{
name: "Tracking & Sync",
component: TrackingSyncScreen,
- title: "Tracking & Sync"
+ title: "Tracking & sync"
}
]
-const TAB_SCREEN_NAMES = new Set(["Dashboard", "Location History", "Geofences", "Settings"])
-
function AppNavigator() {
const { colors, isDark } = useTheme()
const [currentRoute, setCurrentRoute] = useState<string | undefined>("Dashboard")
@@ -201,6 +200,7 @@ function AppNavigator() {
color: colors.text
},
headerTitleAlign: "left" as const,
+ contentStyle: { backgroundColor: colors.background },
headerBackTitleVisible: false,
...(Platform.OS === "android" && {
animation: "slide_from_right" as const
@@ -208,6 +208,20 @@ function AppNavigator() {
}),
[colors]
)
+ const navigationTheme = useMemo(() => {
+ const base = isDark ? DarkTheme : DefaultTheme
+ return {
+ ...base,
+ colors: {
+ ...base.colors,
+ background: colors.background,
+ card: colors.background,
+ text: colors.text,
+ border: colors.border,
+ primary: colors.primary
+ }
+ }
+ }, [colors, isDark])
const statusBarConfig = useMemo(
() => ({
barStyle: isDark ? ("light-content" as const) : ("dark-content" as const),
@@ -246,25 +260,33 @@ function AppNavigator() {
return (
<SafeAreaProvider>
- <StatusBar {...statusBarConfig} />
- <NavigationContainer linking={linking} ref={navigationRef} onStateChange={handleStateChange}>
- <View style={styles.flex}>
- <Stack.Navigator initialRouteName="Dashboard" screenOptions={screenOptions}>
- {SCREEN_CONFIG.map((screen) => (
- <Stack.Screen
- key={screen.name}
- name={screen.name}
- component={screen.component}
- options={{
- headerTitle: screen.title,
- ...(TAB_SCREEN_NAMES.has(screen.name) && { headerBackVisible: false })
- }}
- />
- ))}
- </Stack.Navigator>
- <BottomTabBar currentRoute={currentRoute} onNavigate={handleTabNavigate} />
- </View>
- </NavigationContainer>
+ {/* One provider so a 16 badge and a 24 tab glyph carry the same painted weight. */}
+ <LucideProvider strokeWidth={1.5} absoluteStrokeWidth>
+ <StatusBar {...statusBarConfig} />
+ <NavigationContainer
+ theme={navigationTheme}
+ linking={linking}
+ ref={navigationRef}
+ onStateChange={handleStateChange}
+ >
+ <View style={styles.flex}>
+ <Stack.Navigator initialRouteName="Dashboard" screenOptions={screenOptions}>
+ {SCREEN_CONFIG.map((screen) => (
+ <Stack.Screen
+ key={screen.name}
+ name={screen.name}
+ component={screen.component}
+ options={{
+ headerTitle: screen.title,
+ ...(TAB_ROUTES.has(screen.name) && { headerBackVisible: false })
+ }}
+ />
+ ))}
+ </Stack.Navigator>
+ <BottomTabBar currentRoute={currentRoute} onNavigate={handleTabNavigate} />
+ </View>
+ </NavigationContainer>
+ </LucideProvider>
</SafeAreaProvider>
)
}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 52a7a8a5..1db6f66d 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -25,7 +25,7 @@
"@react-navigation/native": "^7.2.5",
"@react-navigation/native-stack": "^7.16.0",
"i18next": "^26.4.2",
- "lucide-react-native": "^1.17.0",
+ "lucide-react-native": "^1.31.0",
"react": "19.2.8",
"react-native": "0.87.0",
"react-native-safe-area-context": "^5.8.0",
diff --git a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
index 7450b000..67f67e50 100644
--- a/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
+++ b/apps/mobile/src/components/features/dashboard/DatabaseStatistics.tsx
@@ -77,6 +77,7 @@ const styles = StyleSheet.create({
marginTop: 12
},
statCard: {
+ flex: 1,
alignItems: "center"
},
statUnit: {
diff --git a/apps/mobile/src/components/features/map/ColotaMapView.tsx b/apps/mobile/src/components/features/map/ColotaMapView.tsx
index 74ef2757..c20bee21 100644
--- a/apps/mobile/src/components/features/map/ColotaMapView.tsx
+++ b/apps/mobile/src/components/features/map/ColotaMapView.tsx
@@ -4,17 +4,34 @@
*/
import React, { useRef, useImperativeHandle, forwardRef, useState, useEffect, useCallback } from "react"
-import { StyleProp, ViewStyle, View, Text, StyleSheet, Linking, Pressable, Modal } from "react-native"
+import { StyleProp, ViewStyle, View, StyleSheet, Linking } from "react-native"
import { Map, Camera } from "@maplibre/maplibre-react-native"
-import type { MapRef, CameraRef, ViewStateChangeEvent, LngLatBounds } from "@maplibre/maplibre-react-native"
+import type {
+ MapRef,
+ CameraRef,
+ ViewStateChangeEvent,
+ LngLatBounds,
+ ViewPadding
+} from "@maplibre/maplibre-react-native"
import type { NativeSyntheticEvent } from "react-native"
-import { Compass, Info, X } from "lucide-react-native"
+import { Compass, ExternalLink, Info } from "lucide-react-native"
import { useIsFocused } from "@react-navigation/native"
import { useTheme } from "../../../hooks/useTheme"
-import { DEFAULT_MAP_ZOOM, MAP_STYLE_URL_LIGHT, MAP_STYLE_URL_DARK } from "../../../constants"
-import { fonts } from "../../../styles/typography"
+import {
+ DEFAULT_MAP_ZOOM,
+ MAP_STYLE_URL_DARK,
+ MAP_STYLE_URL_LIGHT,
+ MAX_MAP_ZOOM,
+ size,
+ space
+} from "../../../constants"
import NativeLocationService from "../../../services/NativeLocationService"
import { MapActionButton, mapActionStyles } from "./MapActionButton"
+import { DialogShell } from "../../ui/DialogShell"
+import { Divider } from "../../ui/Divider"
+import { ListItem } from "../../ui/ListItem"
+import { Button } from "../../ui/Button"
+import { logger } from "../../../utils/logger"
interface AttributionLink {
url: string
@@ -26,10 +43,35 @@ interface AttributionLink {
// OpenMapTiles CC-BY) so attribution is never silently hidden.
const FALLBACK_ATTRIBUTION_LINKS: AttributionLink[] = [
{ url: "https://www.openstreetmap.org/copyright", label: "© OpenStreetMap contributors" },
- { url: "https://maps.mxd.codes", label: "© maps.mxd.codes" },
- { url: "https://openmaptiles.org", label: "© OpenMapTiles" }
+ { url: "https://openmaptiles.org", label: "© OpenMapTiles" },
+ { url: "https://openfreemap.org", label: "OpenFreeMap" },
+ { url: "https://maps.mxd.codes", label: "maps.mxd.codes" }
]
+/** What each known source contributes; a custom tile server's own credits show without a role. */
+const ATTRIBUTION_ROLES: Record<string, string> = {
+ "openstreetmap.org": "Map data",
+ "openmaptiles.org": "Tile schema and base styles",
+ "openfreemap.org": "Planet tiles, rebuilt weekly",
+ "maps.mxd.codes": "Tile hosting and the Colota styles"
+}
+
+/** The credits come from the style JSON, so key on the host itself and not on a link that names one. */
+function attributionHost(url: string): string {
+ return url
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, "")
+ .split(/[/?#]/)[0]
+ .replace(/^[^@]*@/, "")
+ .split(":")[0]
+ .toLowerCase()
+}
+
+export function attributionRole(url: string): string | undefined {
+ const host = attributionHost(url)
+ const known = Object.keys(ATTRIBUTION_ROLES).find((name) => host === name || host.endsWith(`.${name}`))
+ return known ? ATTRIBUTION_ROLES[known] : undefined
+}
+
function parseStyleAttribution(sources: unknown): AttributionLink[] {
if (!sources || typeof sources !== "object") return []
const seen = new Set<string>()
@@ -66,12 +108,26 @@ interface Props {
onPress?: (coords: { latitude: number; longitude: number }) => void
onRegionDidChange?: (payload: RegionChangePayload) => void
onMapReady?: () => void
+ cameraPadding?: ViewPadding
+ controlsBottom?: number
+ controlsEnd?: number
style?: StyleProp<ViewStyle>
children?: React.ReactNode
}
-export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapView(
- { initialCenter, initialZoom = DEFAULT_MAP_ZOOM, onPress, onRegionDidChange, onMapReady, style, children },
+export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapViewInner(
+ {
+ initialCenter,
+ initialZoom = DEFAULT_MAP_ZOOM,
+ onPress,
+ onRegionDidChange,
+ onMapReady,
+ cameraPadding,
+ controlsBottom,
+ controlsEnd,
+ style,
+ children
+ },
ref
) {
const cameraRef = useRef<CameraRef>(null)
@@ -123,8 +179,8 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
const controller = new AbortController()
fetch(mapStyle, { signal: controller.signal })
.then((r) => r.json())
- .then((style: { sources?: unknown }) => {
- const parsed = parseStyleAttribution(style?.sources)
+ .then((loadedStyle: { sources?: unknown }) => {
+ const parsed = parseStyleAttribution(loadedStyle?.sources)
setAttributionLinks(parsed.length > 0 ? parsed : FALLBACK_ATTRIBUTION_LINKS)
})
.catch((err) => {
@@ -134,6 +190,13 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
return () => controller.abort()
}, [mapStyle])
+ const hasPadding = cameraPadding !== undefined
+ const { top, right, bottom, left } = cameraPadding ?? {}
+ useEffect(() => {
+ if (!hasPadding) return
+ cameraRef.current?.setStop({ padding: { top, right, bottom, left }, duration: 0 })
+ }, [hasPadding, top, right, bottom, left])
+
const handleRegionDidChange = useCallback(
(event: NativeSyntheticEvent<ViewStateChangeEvent>) => {
const { bearing, userInteraction, bounds } = event.nativeEvent
@@ -166,6 +229,19 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
)
const showCompass = Math.abs(heading) > 3
+ const columnEnd = controlsEnd !== undefined && { right: controlsEnd }
+ const attributionStyle = [
+ mapActionStyles.right,
+ controlsBottom !== undefined && { bottom: controlsBottom },
+ columnEnd
+ ]
+ const compassStyle = [
+ mapActionStyles.right,
+ controlsBottom === undefined
+ ? styles.compassPosition
+ : { bottom: controlsBottom + 2 * (size.iconColumn + space.lg) },
+ columnEnd
+ ]
return (
<View style={[styles.container, style]}>
@@ -178,14 +254,17 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
logo={false}
compass={false}
onDidFinishLoadingMap={onMapReady}
+ onDidFailLoadingMap={() => logger.error("[ColotaMapView] Map style failed to load")}
onPress={onPress ? handlePress : undefined}
onRegionDidChange={handleRegionDidChange}
>
<Camera
ref={cameraRef}
+ maxZoom={MAX_MAP_ZOOM}
initialViewState={{
center: initialCenter,
- zoom: initialZoom
+ zoom: initialZoom,
+ ...(cameraPadding && { padding: cameraPadding })
}}
/>
@@ -194,9 +273,14 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
{/* Custom compass button */}
{showCompass && (
- <MapActionButton onPress={handleCompassPress} style={[mapActionStyles.right, styles.compassPosition]}>
+ <MapActionButton
+ onPress={handleCompassPress}
+ style={compassStyle}
+ accessibilityRole="button"
+ accessibilityLabel="Reset map to north"
+ >
<View style={{ transform: [{ rotate: `${-heading}deg` }] }}>
- <Compass size={20} color={colors.textLight} />
+ <Compass size={size.icon.md} color={colors.textLight} />
</View>
</MapActionButton>
)}
@@ -205,49 +289,34 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
<>
<MapActionButton
onPress={() => setAttributionOpen(true)}
- style={mapActionStyles.right}
- hitSlop={8}
+ style={attributionStyle}
accessibilityRole="button"
accessibilityLabel="Show map attribution"
>
- <Info size={20} color={colors.textLight} />
+ <Info size={size.icon.md} color={colors.textLight} />
</MapActionButton>
- <Modal
- transparent
- statusBarTranslucent
+ <DialogShell
visible={attributionOpen}
- animationType="fade"
+ title="Map credits"
onRequestClose={() => setAttributionOpen(false)}
+ footer={<Button title="Close" variant="ghost" onPress={() => setAttributionOpen(false)} />}
>
- <Pressable style={styles.attributionBackdrop} onPress={() => setAttributionOpen(false)}>
- <Pressable
- onPress={() => {}}
- style={[styles.attributionPopup, { backgroundColor: colors.card, borderColor: colors.border }]}
- >
- <Pressable
- onPress={() => setAttributionOpen(false)}
- hitSlop={8}
- accessibilityRole="button"
- accessibilityLabel="Close"
- style={({ pressed }) => [styles.attributionClose, pressed && { opacity: colors.pressedOpacity }]}
- >
- <X size={20} color={colors.textLight} />
- </Pressable>
- {attributionLinks.map((link) => (
- <Pressable
- key={link.url}
+ <View style={styles.attributionRows}>
+ {attributionLinks.map((link, i) => (
+ <React.Fragment key={link.url}>
+ {i > 0 && <Divider tight />}
+ <ListItem
+ label={link.label}
+ sub={attributionRole(link.url)}
+ trailingIcon={ExternalLink}
+ accessibilityRole="link"
onPress={() => Linking.openURL(link.url)}
- style={({ pressed }) => pressed && { opacity: colors.pressedOpacity }}
- >
- <Text style={[styles.attributionPopupText, { color: colors.link }, fonts.regular]}>
- {link.label}
- </Text>
- </Pressable>
- ))}
- </Pressable>
- </Pressable>
- </Modal>
+ />
+ </React.Fragment>
+ ))}
+ </View>
+ </DialogShell>
</>
)}
</View>
@@ -257,36 +326,9 @@ export const ColotaMapView = forwardRef<ColotaMapRef, Props>(function ColotaMapV
const styles = StyleSheet.create({
container: { flex: 1 },
map: { flex: 1 },
- compassPosition: { bottom: 126 },
- attributionBackdrop: {
- flex: 1,
- backgroundColor: "rgba(0, 0, 0, 0.4)",
- alignItems: "center",
- justifyContent: "center",
- paddingHorizontal: 32
- },
- attributionPopup: {
- maxWidth: 320,
- width: "100%",
- paddingLeft: 16,
- paddingRight: 36,
- paddingVertical: 14,
- borderRadius: 10,
- borderWidth: 1,
- gap: 8,
- elevation: 8,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 2 },
- shadowOpacity: 0.25,
- shadowRadius: 6
- },
- attributionPopupText: {
- fontSize: 13
- },
- attributionClose: {
- position: "absolute",
- top: 6,
- right: 6,
- padding: 4
+ compassPosition: { bottom: space.xxl + 2 * (size.iconColumn + space.lg) },
+ // A row cancels a card's lg inset; the dialog pads xl, so the rows step out the remaining sm to reach its edge.
+ attributionRows: {
+ marginHorizontal: -space.sm
}
})
diff --git a/apps/mobile/src/components/features/map/GeofenceLayers.tsx b/apps/mobile/src/components/features/map/GeofenceLayers.tsx
index 8c885a57..f124d9dc 100644
--- a/apps/mobile/src/components/features/map/GeofenceLayers.tsx
+++ b/apps/mobile/src/components/features/map/GeofenceLayers.tsx
@@ -3,8 +3,10 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useMemo } from "react"
-import { GeoJSONSource, Layer } from "@maplibre/maplibre-react-native"
+import React, { useCallback, useMemo } from "react"
+import type { NativeSyntheticEvent } from "react-native"
+import { GeoJSONSource, Layer, type PressEventWithFeatures } from "@maplibre/maplibre-react-native"
+import { pickSmallestZone, ZONE_HITBOX } from "./mapUtils"
const geofenceFillStyle: any = {
fillColor: ["get", "fillColor"],
@@ -21,9 +23,19 @@ interface Props {
fills: GeoJSON.FeatureCollection
labels: GeoJSON.FeatureCollection
haloColor: string
+ /** Makes the circles tappable; absent, the layers stay a drawing. */
+ onPressZone?: (id: number) => void
}
-export function GeofenceLayers({ fills, labels, haloColor }: Props) {
+export function GeofenceLayers({ fills, labels, haloColor, onPressZone }: Props) {
+ const handlePress = useCallback(
+ (event: NativeSyntheticEvent<PressEventWithFeatures>) => {
+ const id = pickSmallestZone(event.nativeEvent.features)
+ if (id !== null) onPressZone?.(id)
+ },
+ [onPressZone]
+ )
+
const labelStyle = useMemo<any>(
() => ({
textField: ["get", "name"],
@@ -40,7 +52,12 @@ export function GeofenceLayers({ fills, labels, haloColor }: Props) {
return (
<>
{fills.features.length > 0 && (
- <GeoJSONSource id="geofence-fills" data={fills}>
+ <GeoJSONSource
+ id="geofence-fills"
+ data={fills}
+ onPress={onPressZone ? handlePress : undefined}
+ hitbox={onPressZone ? ZONE_HITBOX : undefined}
+ >
<Layer id="geofence-fill" type="fill" style={geofenceFillStyle} />
<Layer id="geofence-stroke" type="line" style={geofenceStrokeStyle} />
</GeoJSONSource>
diff --git a/apps/mobile/src/components/features/map/MapActionButton.tsx b/apps/mobile/src/components/features/map/MapActionButton.tsx
index 2c7156f2..f5564fb7 100644
--- a/apps/mobile/src/components/features/map/MapActionButton.tsx
+++ b/apps/mobile/src/components/features/map/MapActionButton.tsx
@@ -3,9 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import { elevation, HIT_SLOP_SM, size, space, STATE_LAYER_ALPHA } from "../../../constants"
import React from "react"
-import { Pressable, StyleSheet, ViewStyle, StyleProp, PressableProps } from "react-native"
+import { Pressable, StyleSheet, View, ViewStyle, StyleProp, PressableProps } from "react-native"
import { useTheme } from "../../../hooks/useTheme"
+import { radius } from "@colota/shared"
interface Props {
onPress: () => void
@@ -14,47 +16,64 @@ interface Props {
hitSlop?: PressableProps["hitSlop"]
accessibilityLabel?: string
accessibilityRole?: PressableProps["accessibilityRole"]
+ accessibilityState?: PressableProps["accessibilityState"]
+ anchored?: boolean
+ testID?: string
}
-export function MapActionButton({ onPress, style, children, hitSlop, accessibilityLabel, accessibilityRole }: Props) {
+export function MapActionButton({
+ onPress,
+ style,
+ children,
+ hitSlop = HIT_SLOP_SM,
+ accessibilityLabel,
+ accessibilityRole,
+ accessibilityState,
+ anchored = true,
+ testID
+}: Props) {
const { colors } = useTheme()
return (
- <Pressable
- style={({ pressed }) => [
- styles.button,
- { backgroundColor: colors.card },
- style,
- pressed && { opacity: colors.pressedOpacity }
- ]}
- onPress={onPress}
+ // The wrapper paints, clips and carries the slop: a touch never extends past the parent's bounds.
+ <View
hitSlop={hitSlop}
- accessibilityLabel={accessibilityLabel}
- accessibilityRole={accessibilityRole}
+ style={[styles.disc, anchored && styles.anchored, { backgroundColor: colors.surfaceRaised }, style]}
>
- {children}
- </Pressable>
+ <Pressable
+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
+ style={styles.button}
+ onPress={onPress}
+ hitSlop={hitSlop}
+ accessibilityLabel={accessibilityLabel}
+ accessibilityRole={accessibilityRole}
+ accessibilityState={accessibilityState}
+ testID={testID}
+ >
+ {children}
+ </Pressable>
+ </View>
)
}
const styles = StyleSheet.create({
+ disc: {
+ overflow: "hidden",
+ width: size.iconColumn,
+ height: size.iconColumn,
+ borderRadius: radius.md,
+ elevation: elevation.floating,
+ zIndex: 10
+ },
button: {
- position: "absolute",
- bottom: 30,
- width: 40,
- height: 40,
- borderRadius: 12,
+ width: size.iconColumn,
+ height: size.iconColumn,
justifyContent: "center",
- alignItems: "center",
- elevation: 5,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 2 },
- shadowOpacity: 0.25,
- shadowRadius: 3.84,
- zIndex: 10
+ alignItems: "center"
},
- right: { right: 16 },
- left: { left: 16 }
+ anchored: { position: "absolute", bottom: space.xxl },
+ right: { right: space.lg },
+ left: { left: space.lg }
})
export { styles as mapActionStyles }
diff --git a/apps/mobile/src/components/features/map/MapCenterButton.tsx b/apps/mobile/src/components/features/map/MapCenterButton.tsx
index 5e97d041..b426bdc7 100644
--- a/apps/mobile/src/components/features/map/MapCenterButton.tsx
+++ b/apps/mobile/src/components/features/map/MapCenterButton.tsx
@@ -8,6 +8,7 @@ import { ViewStyle, StyleProp, StyleSheet } from "react-native"
import { LocateFixed } from "lucide-react-native"
import { useTheme } from "../../../hooks/useTheme"
import { MapActionButton, mapActionStyles } from "./MapActionButton"
+import { size, space } from "../../../constants"
interface Props {
onPress: () => void
@@ -21,12 +22,17 @@ export const MapCenterButton: React.FC<Props> = ({ onPress, visible, style }) =>
if (!visible) return null
return (
- <MapActionButton onPress={onPress} style={[mapActionStyles.right, styles.position, style]}>
- <LocateFixed size={20} color={colors.textLight} />
+ <MapActionButton
+ onPress={onPress}
+ style={[mapActionStyles.right, styles.position, style]}
+ accessibilityRole="button"
+ accessibilityLabel="Centre map on my position"
+ >
+ <LocateFixed size={size.icon.md} color={colors.textLight} />
</MapActionButton>
)
}
const styles = StyleSheet.create({
- position: { bottom: 78 }
+ position: { bottom: space.xxl + size.iconColumn + space.lg }
})
diff --git a/apps/mobile/src/components/features/map/OfflinePackManager.ts b/apps/mobile/src/components/features/map/OfflinePackManager.ts
index febeb81f..2f812f45 100644
--- a/apps/mobile/src/components/features/map/OfflinePackManager.ts
+++ b/apps/mobile/src/components/features/map/OfflinePackManager.ts
@@ -38,9 +38,30 @@ export interface OfflinePackStatus {
export interface OfflineAreaInfo {
name: string
+ /** Null when the pack's status could not be read, which is not the same as an empty pack. */
sizeBytes: number | null
isComplete: boolean
isActive: boolean
+ /** `[west, south, east, north]` as the pack stores it; null only when native gave none. */
+ bounds: [number, number, number, number] | null
+}
+
+function boundsOf(pack: OfflinePack): OfflineAreaInfo["bounds"] {
+ const b = pack.bounds as unknown
+ return Array.isArray(b) && b.length === 4 && b.every((n) => typeof n === "number")
+ ? (b as [number, number, number, number])
+ : null
+}
+
+/** Only the terminal state is worth a line; progress fires continuously. */
+function progressListener(name: string, onProgress: (status: OfflinePackStatus) => void) {
+ return (_pack: unknown, status: unknown) => {
+ const s = status as OfflinePackStatus
+ if (s.state === DOWNLOAD_STATE.COMPLETE) {
+ logger.info(`[OfflinePackManager] Download complete: '${name}', ${formatBytes(s.completedResourceSize ?? 0)}`)
+ }
+ onProgress(s)
+ }
}
function lonToTileX(lon: number, z: number): number {
@@ -128,18 +149,29 @@ export async function createOfflinePack(
bounds: [sw[0], sw[1], ne[0], ne[1]],
metadata: { name }
},
- (_pack, status) => {
- const s = status as OfflinePackStatus
- // Progress fires continuously, so only the terminal state is worth a line.
- if (s.state === DOWNLOAD_STATE.COMPLETE) {
- logger.info(`[OfflinePackManager] Download complete: '${name}', ${formatBytes(s.completedResourceSize ?? 0)}`)
- }
- onProgress(s)
- },
+ progressListener(name, onProgress),
(_pack, err) => onError(err)
)
}
+/**
+ * Re-attaches to a download this JS instance did not start, and returns where it stands. Observing
+ * a pack sets it active natively, so this is only for a pack native already reports as active: on
+ * anything else it would start a download nobody asked for.
+ */
+export async function subscribeOfflinePack(
+ name: string,
+ onProgress: (status: OfflinePackStatus) => void,
+ onError: (err: unknown) => void
+): Promise<OfflinePackStatus | null> {
+ const pack = await findPackByName(name)
+ if (!pack) return null
+ const status = (await pack.status()) as OfflinePackStatus
+ await OfflineManager.addListener(pack.id, progressListener(name, onProgress), (_pack, err) => onError(err))
+ logger.info(`[OfflinePackManager] Re-attached to '${name}' at ${Math.round(status.percentage)}%`)
+ return status
+}
+
export async function loadOfflineAreas(): Promise<OfflineAreaInfo[]> {
const packs = await OfflineManager.getPacks()
@@ -153,11 +185,12 @@ export async function loadOfflineAreas(): Promise<OfflineAreaInfo[]> {
name,
sizeBytes: status?.completedResourceSize ?? null,
isComplete: status?.state === DOWNLOAD_STATE.COMPLETE,
- isActive: status?.state === DOWNLOAD_STATE.ACTIVE
+ isActive: status?.state === DOWNLOAD_STATE.ACTIVE,
+ bounds: boundsOf(pack)
}
} catch (err) {
logger.warn(`[OfflinePackManager] Status unreadable for pack '${name}':`, err)
- return { name, sizeBytes: null, isComplete: false, isActive: false }
+ return { name, sizeBytes: null, isComplete: false, isActive: false, bounds: boundsOf(pack) }
}
})
)
@@ -206,7 +239,7 @@ export interface OfflineAreaBounds {
ne: [number, number] // [lon, lat]
sw: [number, number] // [lon, lat]
styleUrl?: string
- downloadedAt?: number // Unix ms timestamp set when download starts
+ downloadedAt?: number // Unix ms, set when the download completes
}
/** Reads the stored list. Throws when it cannot be read, so a writer can tell empty from failed. */
@@ -270,3 +303,17 @@ export async function removeOfflineAreaBounds(name: string): Promise<void> {
const updated = existing.filter((b) => b.name !== name)
await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(updated))
}
+
+/** Drops entries whose pack is gone, in one write, so a list of orphans cannot race itself. */
+export async function pruneOfflineAreaBounds(keep: ReadonlySet<string>): Promise<void> {
+ let existing: OfflineAreaBounds[]
+ try {
+ existing = await readOfflineAreaBoundsOrThrow()
+ } catch (err) {
+ logger.error("[OfflinePackManager] Not pruning bounds, stored list unreadable:", err)
+ return
+ }
+ const kept = existing.filter((b) => keep.has(b.name))
+ if (kept.length === existing.length) return
+ await NativeLocationService.saveSetting(BOUNDS_KEY, JSON.stringify(kept))
+}
diff --git a/apps/mobile/src/components/features/map/TrackToggleButton.tsx b/apps/mobile/src/components/features/map/TrackToggleButton.tsx
index 91a6d2b1..2abd64ee 100644
--- a/apps/mobile/src/components/features/map/TrackToggleButton.tsx
+++ b/apps/mobile/src/components/features/map/TrackToggleButton.tsx
@@ -4,21 +4,34 @@
*/
import React from "react"
-import { Route } from "lucide-react-native"
+import { Route, RouteOff } from "lucide-react-native"
import { useTheme } from "../../../hooks/useTheme"
import { MapActionButton, mapActionStyles } from "./MapActionButton"
+import { size } from "../../../constants"
interface Props {
onPress: () => void
active: boolean
+ anchored?: boolean
}
-export function TrackToggleButton({ onPress, active }: Props) {
+export function TrackToggleButton({ onPress, active, anchored = true }: Props) {
const { colors } = useTheme()
return (
- <MapActionButton onPress={onPress} style={mapActionStyles.left}>
- <Route size={20} color={active ? colors.primary : colors.textLight} />
+ <MapActionButton
+ onPress={onPress}
+ style={anchored && mapActionStyles.left}
+ anchored={anchored}
+ accessibilityRole="button"
+ accessibilityLabel={active ? "Hide today's track" : "Show today's track"}
+ accessibilityState={{ selected: active }}
+ >
+ {active ? (
+ <Route size={size.icon.md} color={colors.primary} />
+ ) : (
+ <RouteOff size={size.icon.md} color={colors.textLight} />
+ )}
</MapActionButton>
)
}
diff --git a/apps/mobile/src/components/features/map/UserLocationOverlay.tsx b/apps/mobile/src/components/features/map/UserLocationOverlay.tsx
index 759a976d..8fc6b5f0 100644
--- a/apps/mobile/src/components/features/map/UserLocationOverlay.tsx
+++ b/apps/mobile/src/components/features/map/UserLocationOverlay.tsx
@@ -3,10 +3,12 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import { elevation } from "../../../constants"
import React, { useMemo } from "react"
import { View, StyleSheet } from "react-native"
import { GeoJSONSource, Layer, Marker } from "@maplibre/maplibre-react-native"
import type { LocationCoords, ThemeColors } from "../../../types/global"
+import { radius } from "@colota/shared"
/** meters-per-pixel at zoom 0 on the equator (Web Mercator constant) */
const METERS_PER_PX_Z0 = 156543.03
@@ -83,13 +85,9 @@ const styles = StyleSheet.create({
markerDot: {
width: 24,
height: 24,
- borderRadius: 12,
+ borderRadius: radius.pill,
borderWidth: 3,
borderColor: "white",
- elevation: 4,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 2 },
- shadowOpacity: 0.3,
- shadowRadius: 4
+ elevation: elevation.floating
}
})
diff --git a/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx
new file mode 100644
index 00000000..19168ad3
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/ColotaMapView.test.tsx
@@ -0,0 +1,230 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { HIT_SLOP_SM, size, space, MAX_MAP_ZOOM } from "../../../../constants"
+
+const mockSetStop = jest.fn()
+const mockCameraProps = jest.fn()
+
+jest.mock("@maplibre/maplibre-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return {
+ __esModule: true,
+ Map: (props: any) => R.createElement(View, { testID: "mapview", ...props }),
+ Camera: R.forwardRef(function MockCamera(props: any, ref: any) {
+ R.useImperativeHandle(ref, () => ({ setStop: mockSetStop }))
+ mockCameraProps(props)
+ return null
+ })
+ }
+})
+
+jest.mock("@react-navigation/native", () => ({
+ useIsFocused: () => true
+}))
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors, mode: "light" })
+}))
+
+jest.mock("../../../../services/NativeLocationService", () => ({
+ getSetting: jest.fn().mockResolvedValue(null)
+}))
+
+// The style fetch only feeds the attribution list; the fallback links are what the disc needs here.
+;(globalThis as any).fetch = jest.fn(() => new Promise(() => {}))
+
+import { ColotaMapView, attributionRole } from "../ColotaMapView"
+import { MapActionButton, mapActionStyles } from "../MapActionButton"
+
+const padding = { top: 40, right: 64, bottom: 200, left: 16 }
+const center: [number, number] = [11.5, 48.1]
+
+function rotateMap(getByTestId: (id: string) => any) {
+ fireEvent(getByTestId("mapview"), "regionDidChange", {
+ nativeEvent: { bearing: 90, userInteraction: true, bounds: [0, 0, 1, 1] }
+ })
+}
+
+// The disc's position lands on the wrapper that paints it, above the button a reader names.
+function positionOf(node: any, key: "bottom" | "right"): number | undefined {
+ for (let n = node; n; n = n.parent) {
+ const value = StyleSheet.flatten(n.props.style)?.[key]
+ if (value !== undefined) return value
+ }
+ return undefined
+}
+
+function bottomOf(node: any): number | undefined {
+ return positionOf(node, "bottom")
+}
+
+function rightOf(node: any): number | undefined {
+ return positionOf(node, "right")
+}
+
+describe("ColotaMapView camera padding", () => {
+ beforeEach(() => {
+ mockSetStop.mockClear()
+ mockCameraProps.mockClear()
+ })
+
+ it("frames the first camera inside the padding so the dock never covers the position dot", () => {
+ render(<ColotaMapView initialCenter={center} cameraPadding={padding} />)
+
+ expect(mockCameraProps.mock.calls[0][0].maxZoom).toBe(MAX_MAP_ZOOM)
+ expect(mockCameraProps.mock.calls[0][0].initialViewState).toEqual({
+ center,
+ zoom: expect.any(Number),
+ padding
+ })
+ })
+
+ it("reframes without animation when the padding changes, because a growing dock must not slide the map", () => {
+ const { rerender } = render(<ColotaMapView initialCenter={center} cameraPadding={padding} />)
+ mockSetStop.mockClear()
+
+ const grown = { ...padding, bottom: 260 }
+ rerender(<ColotaMapView initialCenter={center} cameraPadding={grown} />)
+
+ expect(mockSetStop).toHaveBeenCalledWith({ padding: grown, duration: 0 })
+ })
+
+ it("does not call the camera again for a new object holding the same insets", () => {
+ const { rerender } = render(<ColotaMapView initialCenter={center} cameraPadding={padding} />)
+ mockSetStop.mockClear()
+
+ rerender(<ColotaMapView initialCenter={center} cameraPadding={{ ...padding }} />)
+
+ expect(mockSetStop).not.toHaveBeenCalled()
+ })
+
+ it("leaves the camera untouched when no padding is given, so the other map screens keep their framing", () => {
+ render(<ColotaMapView initialCenter={center} />)
+
+ expect(mockCameraProps.mock.calls[0][0].initialViewState).not.toHaveProperty("padding")
+ expect(mockSetStop).not.toHaveBeenCalled()
+ })
+})
+
+describe("ColotaMapView control slots", () => {
+ const controlsBottom = 250
+
+ it("puts the attribution disc on the base line and the compass two slots above it", () => {
+ const { getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />)
+ rotateMap(getByTestId)
+
+ expect(bottomOf(getByRole("button", { name: "Show map attribution" }))).toBe(controlsBottom)
+ expect(bottomOf(getByRole("button", { name: "Reset map to north" }))).toBe(
+ controlsBottom + 2 * (size.iconColumn + space.lg)
+ )
+ })
+
+ it("moves both discs in from the right edge by the column end a screen gives, clear of a side navigation bar", () => {
+ const { getByRole, getByTestId } = render(
+ <ColotaMapView initialCenter={center} controlsBottom={controlsBottom} controlsEnd={64} />
+ )
+ rotateMap(getByTestId)
+
+ expect(rightOf(getByRole("button", { name: "Show map attribution" }))).toBe(64)
+ expect(rightOf(getByRole("button", { name: "Reset map to north" }))).toBe(64)
+ })
+
+ it("gives the attribution disc the same touch slop as every other disc in the column", () => {
+ const { getByRole } = render(<ColotaMapView initialCenter={center} controlsBottom={controlsBottom} />)
+
+ expect(getByRole("button", { name: "Show map attribution" }).props.hitSlop).toEqual(HIT_SLOP_SM)
+ })
+
+ it("keeps the fixed disc positions when no base line is given", () => {
+ const bare = render(
+ <MapActionButton
+ onPress={() => {}}
+ style={mapActionStyles.right}
+ accessibilityRole="button"
+ accessibilityLabel="bare"
+ >
+ {null}
+ </MapActionButton>
+ )
+ const defaultBottom = bottomOf(bare.getByRole("button", { name: "bare" }))
+ bare.unmount()
+
+ const { getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} />)
+ rotateMap(getByTestId)
+
+ expect(bottomOf(getByRole("button", { name: "Show map attribution" }))).toBe(defaultBottom)
+ expect(rightOf(getByRole("button", { name: "Show map attribution" }))).toBe(space.lg)
+ expect(bottomOf(getByRole("button", { name: "Reset map to north" }))).toBe(
+ space.xxl + 2 * (size.iconColumn + space.lg)
+ )
+ })
+
+ it("names the compass for a screen reader and hides it while the map points north", () => {
+ const { queryByRole, getByRole, getByTestId } = render(<ColotaMapView initialCenter={center} />)
+
+ expect(queryByRole("button", { name: "Reset map to north" })).toBeNull()
+ rotateMap(getByTestId)
+
+ fireEvent.press(getByRole("button", { name: "Reset map to north" }))
+ expect(mockSetStop).toHaveBeenCalledWith(expect.objectContaining({ bearing: 0 }))
+ })
+})
+
+describe("ColotaMapView attribution popup", () => {
+ function openPopup() {
+ const utils = render(<ColotaMapView initialCenter={center} />)
+ fireEvent.press(utils.getByRole("button", { name: "Show map attribution" }))
+ return utils
+ }
+
+ it("names the map data, lists every source as a link and ends with a Close button like the app's dialogs", () => {
+ const { getByText, getAllByRole, getByRole, queryByLabelText } = openPopup()
+
+ expect(getByText("Map credits")).toBeTruthy()
+ expect(getAllByRole("link")).toHaveLength(4)
+ expect(getByText("© OpenStreetMap contributors")).toBeTruthy()
+ expect(getByText("Map data")).toBeTruthy()
+ expect(getByText("Tile schema and base styles")).toBeTruthy()
+ expect(getByText("Planet tiles, rebuilt weekly")).toBeTruthy()
+ expect(getByText("Tile hosting and the Colota styles")).toBeTruthy()
+ expect(getByRole("button", { name: "Close" })).toBeTruthy()
+ expect(queryByLabelText("Close")).toBeNull()
+ })
+
+ it("holds the Close button 24 under the links like AppModal's button row, counting the 8 Button bakes in", () => {
+ const { getByRole } = openPopup()
+
+ let node: any = getByRole("button", { name: "Close" }).parent
+ while (node && StyleSheet.flatten(node.props.style)?.marginTop === undefined) node = node.parent
+ expect(StyleSheet.flatten(node.props.style).marginTop + space.sm).toBe(space.xl)
+ })
+
+ it("closes on the Close button so a reader is not left hunting for a corner glyph", () => {
+ const { getByRole, queryByText } = openPopup()
+
+ fireEvent.press(getByRole("button", { name: "Close" }))
+
+ expect(queryByText("Map credits")).toBeNull()
+ })
+})
+
+describe("attributionRole", () => {
+ it("names the role of a known source, its subdomains and any path", () => {
+ expect(attributionRole("https://www.openstreetmap.org/copyright")).toBe("Map data")
+ expect(attributionRole("https://tile.openstreetmap.org/tiles")).toBe("Map data")
+ expect(attributionRole("https://openmaptiles.org/")).toBe("Tile schema and base styles")
+ expect(attributionRole("https://maps.mxd.codes")).toBe("Tile hosting and the Colota styles")
+ })
+
+ it("credits a custom tile server's own sources without claiming a role for them", () => {
+ expect(attributionRole("https://tiles.example.com/style.json")).toBeUndefined()
+ })
+
+ it("refuses a host that only mentions a known one, since the style JSON supplies the link", () => {
+ expect(attributionRole("https://openstreetmap.org.example.com/")).toBeUndefined()
+ expect(attributionRole("https://example.com/?ref=openstreetmap.org")).toBeUndefined()
+ expect(attributionRole("https://[email protected]/")).toBeUndefined()
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/GeofenceLayers.test.tsx b/apps/mobile/src/components/features/map/__tests__/GeofenceLayers.test.tsx
new file mode 100644
index 00000000..006fd3b7
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/GeofenceLayers.test.tsx
@@ -0,0 +1,74 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { GeofenceLayers } from "../GeofenceLayers"
+
+jest.mock("@maplibre/maplibre-react-native", () => {
+ const R = require("react")
+ const { View, Pressable } = require("react-native")
+ return {
+ GeoJSONSource: ({ children, id, onPress, hitbox }: any) =>
+ R.createElement(
+ View,
+ { testID: id, hitbox },
+ onPress &&
+ R.createElement(Pressable, {
+ testID: `${id}-press`,
+ onPress: () =>
+ onPress({
+ nativeEvent: {
+ features: [
+ {
+ type: "Feature",
+ properties: { id: 1, radius: 500 },
+ geometry: { type: "Point", coordinates: [0, 0] }
+ },
+ {
+ type: "Feature",
+ properties: { id: 2, radius: 50 },
+ geometry: { type: "Point", coordinates: [0, 0] }
+ }
+ ]
+ }
+ })
+ }),
+ children
+ ),
+ Layer: ({ id }: any) => R.createElement(View, { testID: id })
+ }
+})
+
+const feature = (id: number) => ({
+ type: "Feature" as const,
+ properties: {
+ id,
+ name: `Z${id}`,
+ fillColor: "#000",
+ fillOpacity: 0.3,
+ strokeColor: "#000",
+ pauseTracking: true,
+ radius: id
+ },
+ geometry: { type: "Point" as const, coordinates: [0, 0] }
+})
+const fills = { type: "FeatureCollection" as const, features: [feature(1), feature(2)] }
+const labels = { type: "FeatureCollection" as const, features: [] }
+
+describe("GeofenceLayers", () => {
+ it("stays a drawing without a handler, so the Dashboard and Place Zone maps take no taps", () => {
+ const { getByTestId, queryByTestId } = render(<GeofenceLayers fills={fills} labels={labels} haloColor="#fff" />)
+
+ expect(getByTestId("geofence-fills").props.hitbox).toBeUndefined()
+ expect(queryByTestId("geofence-fills-press")).toBeNull()
+ })
+
+ it("hands the smallest circle under the finger to the screen with a 48 dp target when asked to", () => {
+ const onPressZone = jest.fn()
+ const { getByTestId } = render(
+ <GeofenceLayers fills={fills} labels={labels} haloColor="#fff" onPressZone={onPressZone} />
+ )
+
+ expect(getByTestId("geofence-fills").props.hitbox).toEqual({ top: 24, right: 24, bottom: 24, left: 24 })
+ fireEvent.press(getByTestId("geofence-fills-press"))
+ expect(onPressZone).toHaveBeenCalledWith(2)
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/MapActionButton.test.tsx b/apps/mobile/src/components/features/map/__tests__/MapActionButton.test.tsx
new file mode 100644
index 00000000..b0725bc1
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/MapActionButton.test.tsx
@@ -0,0 +1,142 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { Text } from "react-native"
+import { elevation, HIT_SLOP_SM, size, space, STATE_LAYER_ALPHA } from "../../../../constants"
+import { lightColors, radius } from "@colota/shared"
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { MapActionButton } from "../MapActionButton"
+
+const flat = (el: { props: { style?: unknown } }) =>
+ Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+
+type Node = {
+ type: unknown
+ parent: Node | null
+ props: { style?: unknown; android_ripple?: unknown; hitSlop?: unknown }
+}
+const disc = (el: Node) => {
+ let node = el.parent
+ while (node && node.type !== "View") node = node.parent
+ return node as Node
+}
+const rippleOf = (el: Node) => {
+ let node = el.parent
+ while (node && node.props.android_ripple === undefined) node = node.parent
+ return node?.props.android_ripple
+}
+
+describe("MapActionButton", () => {
+ it("floats over the tiles by default, so the map screens keep their disc where it was", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.position).toBe("absolute")
+ expect(style.bottom).toBe(space.xxl)
+ })
+
+ it("sits in flow when not anchored, so a flex row can place it beside the pill", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} anchored={false} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.position).toBeUndefined()
+ expect(style.bottom).toBeUndefined()
+ expect(style.width).toBe(size.iconColumn)
+ expect(style.height).toBe(size.iconColumn)
+ expect(style.borderRadius).toBe(radius.md)
+ expect(style.elevation).toBe(elevation.floating)
+ })
+
+ it("paints the elevated surface, so the disc matches the dock it floats beside in dark mode", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.backgroundColor).toBe(lightColors.surfaceRaised)
+ expect(style.overflow).toBe("hidden")
+ })
+
+ it("ripples inside a clipping parent, so the press feedback takes the corner instead of painting a square", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ const button = getByRole("button")
+ expect(rippleOf(button)).toEqual({ color: lightColors.text + STATE_LAYER_ALPHA })
+ expect(flat(button).backgroundColor).toBeUndefined()
+ expect(flat(button).width).toBe(size.iconColumn)
+ expect(flat(button).height).toBe(size.iconColumn)
+
+ const parent = flat(disc(button))
+ expect(parent.overflow).toBe("hidden")
+ expect(parent.borderRadius).toBe(radius.md)
+ })
+
+ it("lets the caller's bottom offset win over the anchor, which is how a disc takes its slot in a column", () => {
+ const bottom = space.lg + size.iconColumn
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} style={{ bottom }} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ expect(flat(disc(getByRole("button"))).bottom).toBe(bottom)
+ })
+
+ it("widens its 40 disc to the 48 touch target by default, so a caller cannot forget to", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ expect(getByRole("button").props.hitSlop).toEqual(HIT_SLOP_SM)
+ expect(disc(getByRole("button")).props.hitSlop).toEqual(HIT_SLOP_SM)
+ })
+
+ it("passes a caller's wider slop through to the wrapper, so the slop the caller sets is the one that lands", () => {
+ const { getByRole } = render(
+ <MapActionButton onPress={jest.fn()} hitSlop={12} accessibilityRole="button" accessibilityLabel="Do it">
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ expect(disc(getByRole("button")).props.hitSlop).toBe(12)
+ expect(getByRole("button").props.hitSlop).toBe(12)
+ })
+
+ it("forwards the press and the accessibility state to the disc", () => {
+ const onPress = jest.fn()
+ const { getByRole } = render(
+ <MapActionButton
+ onPress={onPress}
+ accessibilityRole="button"
+ accessibilityLabel="Do it"
+ accessibilityState={{ selected: true }}
+ >
+ <Text>x</Text>
+ </MapActionButton>
+ )
+
+ const el = getByRole("button")
+ fireEvent.press(el)
+ expect(onPress).toHaveBeenCalledTimes(1)
+ expect(el.props.accessibilityState).toEqual({ selected: true })
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/MapCenterButton.test.tsx b/apps/mobile/src/components/features/map/__tests__/MapCenterButton.test.tsx
new file mode 100644
index 00000000..097355fa
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/MapCenterButton.test.tsx
@@ -0,0 +1,56 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { size, space } from "../../../../constants"
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { MapCenterButton } from "../MapCenterButton"
+
+const flat = (el: { props: { style?: unknown } }) =>
+ Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+
+type Node = { type: unknown; parent: Node | null; props: { style?: unknown } }
+const disc = (el: Node) => {
+ let node = el.parent
+ while (node && node.type !== "View") node = node.parent
+ return node as Node
+}
+
+describe("MapCenterButton", () => {
+ it("is named for a screen reader, because the crosshair glyph carries no text", () => {
+ const { getByRole } = render(<MapCenterButton onPress={jest.fn()} visible />)
+
+ expect(getByRole("button").props.accessibilityLabel).toBe("Centre map on my position")
+ })
+
+ it("renders nothing while the map is already centred, so the disc is an offer and not a fixture", () => {
+ const { queryByRole } = render(<MapCenterButton onPress={jest.fn()} visible={false} />)
+
+ expect(queryByRole("button")).toBeNull()
+ })
+
+ it("stacks one slot above the attribution disc, far enough that the two touch targets meet without overlapping", () => {
+ const { getByRole } = render(<MapCenterButton onPress={jest.fn()} visible />)
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.right).toBe(space.lg)
+ expect(style.bottom).toBe(space.xxl + size.iconColumn + space.lg)
+ })
+
+ it("lets a screen move it into its own disc column", () => {
+ const bottom = space.lg + size.iconColumn
+ const { getByRole } = render(<MapCenterButton onPress={jest.fn()} visible style={{ bottom }} />)
+
+ expect(flat(disc(getByRole("button"))).bottom).toBe(bottom)
+ })
+
+ it("recentres on press", () => {
+ const onPress = jest.fn()
+ const { getByRole } = render(<MapCenterButton onPress={onPress} visible />)
+
+ fireEvent.press(getByRole("button"))
+ expect(onPress).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
index e08be548..d15796af 100644
--- a/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
+++ b/apps/mobile/src/components/features/map/__tests__/OfflinePackManager.test.ts
@@ -11,6 +11,7 @@ jest.mock("@maplibre/maplibre-react-native", () => ({
deletePack: jest.fn(),
setTileCountLimit: jest.fn(),
removeListener: jest.fn(),
+ addListener: jest.fn(),
resetDatabase: jest.fn()
}
}))
@@ -35,6 +36,8 @@ import {
saveOfflineAreaBounds,
removeOfflineAreaBounds,
unsubscribeOfflinePack,
+ subscribeOfflinePack,
+ pruneOfflineAreaBounds,
DOWNLOAD_STATE
} from "../OfflinePackManager"
@@ -316,7 +319,7 @@ describe("loadOfflineAreas", () => {
}
] as never)
expect(await loadOfflineAreas()).toEqual([
- { name: "downtown", sizeBytes: 5_000_000, isComplete: true, isActive: false }
+ { name: "downtown", sizeBytes: 5_000_000, isComplete: true, isActive: false, bounds: null }
])
})
@@ -328,7 +331,7 @@ describe("loadOfflineAreas", () => {
}
] as never)
expect(await loadOfflineAreas()).toEqual([
- { name: "in-progress", sizeBytes: 1_000_000, isComplete: false, isActive: true }
+ { name: "in-progress", sizeBytes: 1_000_000, isComplete: false, isActive: true, bounds: null }
])
})
@@ -337,10 +340,25 @@ describe("loadOfflineAreas", () => {
{ metadata: { name: "broken-pack" }, status: jest.fn().mockRejectedValue(new Error("status unavailable")) }
] as never)
expect(await loadOfflineAreas()).toEqual([
- { name: "broken-pack", sizeBytes: null, isComplete: false, isActive: false }
+ { name: "broken-pack", sizeBytes: null, isComplete: false, isActive: false, bounds: null }
])
})
+ // The extent comes from the pack itself, so a re-download never depends on the sidecar being there.
+ it("carries the pack's own bounds, and null when native reports none", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ {
+ metadata: { name: "boxed" },
+ bounds: [13.4, 52.5, 13.5, 52.6],
+ status: jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.COMPLETE, completedResourceSize: 10 })
+ },
+ { metadata: { name: "boxless" }, status: jest.fn().mockRejectedValue(new Error("no status")) }
+ ] as never)
+ const areas = await loadOfflineAreas()
+ expect(areas[0].bounds).toEqual([13.4, 52.5, 13.5, 52.6])
+ expect(areas[1].bounds).toBeNull()
+ })
+
it("handles null completedResourceSize as null sizeBytes", async () => {
mockOfflineManager.getPacks.mockResolvedValueOnce([
{ metadata: { name: "partial" }, status: jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.INACTIVE }) }
@@ -573,3 +591,72 @@ describe("removeOfflineAreaBounds", () => {
expect(mockSaveSetting).not.toHaveBeenCalled()
})
})
+
+// ============================================================================
+// subscribeOfflinePack
+// ============================================================================
+
+describe("subscribeOfflinePack", () => {
+ it("returns null when no pack carries the name, and attaches nothing", async () => {
+ mockOfflineManager.getPacks.mockResolvedValueOnce([] as never)
+ expect(await subscribeOfflinePack("gone", jest.fn(), jest.fn())).toBeNull()
+ expect(mockOfflineManager.addListener).not.toHaveBeenCalled()
+ })
+
+ /**
+ * The status is read before the listener attaches, so the caller can seed its progress and take
+ * the completion path if the pack finished while the screen was away.
+ */
+ it("reads the status, then attaches the listeners to the pack's id, and returns it", async () => {
+ const mockStatus = jest.fn().mockResolvedValue({ state: DOWNLOAD_STATE.ACTIVE, percentage: 42 })
+ mockOfflineManager.getPacks.mockResolvedValueOnce([
+ { id: "uuid-9", metadata: { name: "running" }, status: mockStatus }
+ ] as never)
+ mockOfflineManager.addListener.mockResolvedValueOnce(undefined as never)
+ const onProgress = jest.fn()
+ const onError = jest.fn()
+
+ const status = await subscribeOfflinePack("running", onProgress, onError)
+
+ expect(status).toEqual({ state: DOWNLOAD_STATE.ACTIVE, percentage: 42 })
+ expect(mockOfflineManager.addListener).toHaveBeenCalledWith("uuid-9", expect.any(Function), expect.any(Function))
+ const [, progress, error] = mockOfflineManager.addListener.mock.calls[0]
+ progress({} as never, { state: DOWNLOAD_STATE.ACTIVE, percentage: 50 } as never)
+ expect(onProgress).toHaveBeenCalledWith({ state: DOWNLOAD_STATE.ACTIVE, percentage: 50 })
+ error({} as never, new Error("tile") as never)
+ expect(onError).toHaveBeenCalledWith(expect.any(Error))
+ })
+})
+
+// ============================================================================
+// pruneOfflineAreaBounds
+// ============================================================================
+
+describe("pruneOfflineAreaBounds", () => {
+ const stored = (entries: object[]) => mockGetSetting.mockResolvedValueOnce(JSON.stringify(entries))
+ const entry = (name: string) => ({ name, ne: [1, 1], sw: [0, 0] })
+
+ // One write for any number of orphans: the old per-orphan read-modify-write lost all but the last.
+ it("drops every orphan in one write", async () => {
+ stored([entry("keep"), entry("gone-1"), entry("gone-2")])
+ mockSaveSetting.mockResolvedValueOnce(undefined)
+
+ await pruneOfflineAreaBounds(new Set(["keep"]))
+
+ expect(mockSaveSetting).toHaveBeenCalledTimes(1)
+ expect(JSON.parse(mockSaveSetting.mock.calls[0][1])).toEqual([entry("keep")])
+ })
+
+ it("writes nothing when nothing is orphaned", async () => {
+ stored([entry("keep")])
+ await pruneOfflineAreaBounds(new Set(["keep"]))
+ expect(mockSaveSetting).not.toHaveBeenCalled()
+ })
+
+ // A failed read must never become a write that empties the list.
+ it("refuses to write over a list it could not read", async () => {
+ mockGetSetting.mockRejectedValueOnce(new Error("db locked"))
+ await pruneOfflineAreaBounds(new Set())
+ expect(mockSaveSetting).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/TrackToggleButton.test.tsx b/apps/mobile/src/components/features/map/__tests__/TrackToggleButton.test.tsx
new file mode 100644
index 00000000..07d208b4
--- /dev/null
+++ b/apps/mobile/src/components/features/map/__tests__/TrackToggleButton.test.tsx
@@ -0,0 +1,66 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { space } from "../../../../constants"
+
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { TrackToggleButton } from "../TrackToggleButton"
+
+const flat = (el: { props: { style?: unknown } }) =>
+ Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+
+type Node = { type: unknown; parent: Node | null; props: { style?: unknown } }
+const disc = (el: Node) => {
+ let node = el.parent
+ while (node && node.type !== "View") node = node.parent
+ return node as Node
+}
+
+describe("TrackToggleButton", () => {
+ it("offers to show the track while it is hidden, with the struck glyph so colour is not the only signal", () => {
+ const { getByRole, getByTestId, queryByTestId } = render(<TrackToggleButton onPress={jest.fn()} active={false} />)
+
+ const el = getByRole("button")
+ expect(el.props.accessibilityLabel).toBe("Show today's track")
+ expect(el.props.accessibilityState).toEqual({ selected: false })
+ expect(getByTestId("icon-RouteOff")).toBeTruthy()
+ expect(queryByTestId("icon-Route")).toBeNull()
+ })
+
+ it("offers to hide the track while it is shown with the plain glyph and reads as selected", () => {
+ const { getByRole, getByTestId, queryByTestId } = render(<TrackToggleButton onPress={jest.fn()} active />)
+
+ const el = getByRole("button")
+ expect(el.props.accessibilityLabel).toBe("Hide today's track")
+ expect(el.props.accessibilityState).toEqual({ selected: true })
+ expect(getByTestId("icon-Route")).toBeTruthy()
+ expect(queryByTestId("icon-RouteOff")).toBeNull()
+ })
+
+ it("anchors to the map's bottom-left by default, where the map screens expect it", () => {
+ const { getByRole } = render(<TrackToggleButton onPress={jest.fn()} active={false} />)
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.position).toBe("absolute")
+ expect(style.left).toBe(space.lg)
+ })
+
+ it("drops the anchor and the left offset when placed in a row, so the row decides where it sits", () => {
+ const { getByRole } = render(<TrackToggleButton onPress={jest.fn()} active={false} anchored={false} />)
+
+ const style = flat(disc(getByRole("button")))
+ expect(style.position).toBeUndefined()
+ expect(style.bottom).toBeUndefined()
+ expect(style.left).toBeUndefined()
+ })
+
+ it("toggles on press", () => {
+ const onPress = jest.fn()
+ const { getByRole } = render(<TrackToggleButton onPress={onPress} active={false} />)
+
+ fireEvent.press(getByRole("button"))
+ expect(onPress).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
index 0639b6a6..15db4892 100644
--- a/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
+++ b/apps/mobile/src/components/features/map/__tests__/mapUtils.test.ts
@@ -6,7 +6,9 @@ import {
buildTrackPointsGeoJSON,
buildGeofencesGeoJSON,
computeTrackBounds,
- darkifyStyle
+ darkifyStyle,
+ TRACK_LINE_STYLE,
+ TRACK_CASING_STYLE
} from "../mapUtils"
import { haversine as haversineDistance } from "../../../../utils/geo"
@@ -197,6 +199,44 @@ describe("buildTrackSegmentsGeoJSON", () => {
const result = buildTrackSegmentsGeoJSON(locs, colors, { locationColors: ["#FF0000", "#00FF00"] })
expect(result.features[0].properties?.color).toBe("#00FF00")
})
+
+ it("starts a new feature where the trip changes even in one colour, so each trip can be styled on its own", () => {
+ const locs = [
+ { latitude: 52.52, longitude: 13.405 },
+ { latitude: 52.53, longitude: 13.406 },
+ { latitude: 52.54, longitude: 13.407 },
+ { latitude: 52.55, longitude: 13.408 }
+ ]
+ const result = buildTrackSegmentsGeoJSON(locs, colors, { defaultColor: "#FF0000", locationTrips: [1, 1, 2, 2] })
+ expect(result.features.map((f) => f.properties?.tripIndex)).toEqual([1, 2])
+ expect(result.features.map((f) => f.properties?.focused)).toEqual([false, false])
+ })
+
+ it("flags only the focused trip's features", () => {
+ const locs = [
+ { latitude: 52.52, longitude: 13.405 },
+ { latitude: 52.53, longitude: 13.406 },
+ { latitude: 52.54, longitude: 13.407 },
+ { latitude: 52.55, longitude: 13.408 }
+ ]
+ const result = buildTrackSegmentsGeoJSON(locs, colors, {
+ defaultColor: "#FF0000",
+ locationTrips: [1, 1, 2, 2],
+ focusedTrip: 2
+ })
+ expect(result.features.map((f) => f.properties?.focused)).toEqual([false, true])
+ })
+})
+
+describe("track line styles", () => {
+ it("colours the line per feature and draws the casing wider underneath it", () => {
+ expect(TRACK_LINE_STYLE).toEqual({ lineColor: ["get", "color"], lineWidth: 3, lineCap: "round", lineJoin: "round" })
+ expect(TRACK_CASING_STYLE).toEqual({
+ lineWidth: ["case", ["get", "focused"], 7, 5],
+ lineCap: "round",
+ lineJoin: "round"
+ })
+ })
})
// ============================================================================
@@ -469,3 +509,75 @@ describe("darkifyStyle", () => {
expect(result.version).toBe(8)
})
})
+
+describe("buildTripTerminalsGeoJSON", () => {
+ const { buildTripTerminalsGeoJSON } = require("../mapUtils")
+ const trip = (index: number, color: string, n: number) => ({
+ index,
+ color,
+ locations: Array.from({ length: n }, (_, i) => ({ latitude: index + i * 0.001, longitude: 10 + i * 0.001 }))
+ })
+
+ it("marks where each trip starts and ends in the trip's colour, so a day of trips can be read on the map", () => {
+ const fc = buildTripTerminalsGeoJSON([trip(1, "#111", 3), trip(2, "#222", 2)], null)
+
+ expect(fc.features.map((f: any) => [f.properties.kind, f.properties.trip, f.properties.color])).toEqual([
+ ["start", 1, "#111"],
+ ["end", 1, "#111"],
+ ["start", 2, "#222"],
+ ["end", 2, "#222"]
+ ])
+ expect(fc.features[1].geometry.coordinates).toEqual([10.002, 1.002])
+ })
+
+ it("flags the focused trip's terminals and skips a trip of one point, which has no end to mark", () => {
+ const fc = buildTripTerminalsGeoJSON([trip(1, "#111", 1), trip(2, "#222", 2)], 2)
+
+ expect(fc.features.map((f: any) => [f.properties.trip, f.properties.focused])).toEqual([
+ [2, true],
+ [2, true]
+ ])
+ })
+})
+
+describe("geofenceBounds and pickSmallestZone", () => {
+ const utils = require("../mapUtils")
+ const zone = (id: number, lat: number, lon: number, radius: number) => ({
+ id,
+ name: `Z${id}`,
+ lat,
+ lon,
+ radius,
+ enabled: true,
+ pauseTracking: true,
+ pauseOnWifi: false,
+ pauseOnMotionless: false,
+ motionlessTimeoutMinutes: 5,
+ heartbeatEnabled: false,
+ heartbeatIntervalMinutes: 15
+ })
+
+ it("boxes every circle, wider in longitude the further north it sits", () => {
+ const [west, south, east, north] = utils.geofenceBounds([zone(1, 60, 10, 1113.2)])
+ expect(north - south).toBeCloseTo(0.02, 4)
+ expect(east - west).toBeGreaterThan(0.03)
+ const two = utils.geofenceBounds([zone(1, 48, 11, 100), zone(2, 49, 12, 100)])
+ expect(two[0]).toBeLessThan(11)
+ expect(two[2]).toBeGreaterThan(12)
+ })
+
+ it("picks the smallest circle under a tap, since the larger ones cover it, and ignores features with no id", () => {
+ const hits = [
+ { type: "Feature", properties: { id: 1, radius: 500 }, geometry: { type: "Point", coordinates: [0, 0] } },
+ { type: "Feature", properties: { id: 2, radius: 50 }, geometry: { type: "Point", coordinates: [0, 0] } },
+ { type: "Feature", properties: { radius: 1 }, geometry: { type: "Point", coordinates: [0, 0] } }
+ ]
+ expect(utils.pickSmallestZone(hits)).toBe(2)
+ expect(utils.pickSmallestZone([])).toBeNull()
+ })
+
+ it("carries the radius on the fill feature so a tap can rank overlapping circles", () => {
+ const { fills } = utils.buildGeofencesGeoJSON([zone(7, 48, 11, 120)], require("@colota/shared").lightColors)
+ expect(fills.features[0].properties.radius).toBe(120)
+ })
+})
diff --git a/apps/mobile/src/components/features/map/mapUtils.ts b/apps/mobile/src/components/features/map/mapUtils.ts
index 8d2fc54e..8304834a 100644
--- a/apps/mobile/src/components/features/map/mapUtils.ts
+++ b/apps/mobile/src/components/features/map/mapUtils.ts
@@ -4,6 +4,7 @@
*/
import type { ThemeColors, Geofence } from "../../../types/global"
+import { size } from "../../../constants"
/** MapLibre line-layer style for colored track segments (`color` is a per-feature property). */
export const TRACK_LINE_STYLE: any = {
@@ -13,6 +14,13 @@ export const TRACK_LINE_STYLE: any = {
lineJoin: "round"
}
+/** Drawn under `TRACK_LINE_STYLE` on the same source; the caller adds `lineColor` from its theme. */
+export const TRACK_CASING_STYLE: any = {
+ lineWidth: ["case", ["get", "focused"], 7, 5],
+ lineCap: "round",
+ lineJoin: "round"
+}
+
// ============================================================================
// SPEED COLOR INTERPOLATION
// ============================================================================
@@ -97,34 +105,44 @@ interface TrackSegmentOptions {
skipIndices?: Set<number>
locationColors?: string[]
defaultColor?: string
+ /** Trip index per location, -1 outside any trip. */
+ locationTrips?: ArrayLike<number>
+ focusedTrip?: number | null
}
/** Build LineString features with a pre-computed `color` property.
* Consecutive segments of the same color are merged into a single multi-point LineString
* to keep feature count low on long trips (O(color changes) instead of O(points)).
* Pass `skipIndices` to leave gaps between trips (indices where a new trip starts).
- * Pass `locationColors` to override speed-based coloring with per-location colors. */
+ * Pass `locationColors` to override speed-based coloring with per-location colors.
+ * Pass `locationTrips` to stamp each feature with its `tripIndex` and a `focused` flag. */
export function buildTrackSegmentsGeoJSON(
locations: TrackLocation[],
colors: ThemeColors,
options?: TrackSegmentOptions
): GeoJSON.FeatureCollection {
- const { skipIndices, locationColors, defaultColor } = options ?? {}
+ const { skipIndices, locationColors, defaultColor, locationTrips, focusedTrip } = options ?? {}
const features: GeoJSON.Feature[] = []
let currentColor: string | null = null
+ let currentTrip = -1
let currentCoords: [number, number][] = []
const flush = () => {
if (currentCoords.length >= 2 && currentColor !== null) {
features.push({
type: "Feature",
- properties: { color: currentColor },
+ properties: {
+ color: currentColor,
+ tripIndex: currentTrip,
+ focused: focusedTrip != null && currentTrip === focusedTrip
+ },
geometry: { type: "LineString", coordinates: currentCoords }
})
}
currentCoords = []
currentColor = null
+ currentTrip = -1
}
for (let i = 1; i < locations.length; i++) {
@@ -138,18 +156,21 @@ export function buildTrackSegmentsGeoJSON(
: locationColors
? locationColors[i]
: getSpeedColor(((locations[i - 1].speed ?? 0) + (locations[i].speed ?? 0)) / 2, colors)
+ const trip = locationTrips ? locationTrips[i] : -1
if (currentColor === null) {
currentCoords.push([locations[i - 1].longitude, locations[i - 1].latitude])
currentCoords.push([locations[i].longitude, locations[i].latitude])
currentColor = color
- } else if (color === currentColor) {
+ currentTrip = trip
+ } else if (color === currentColor && trip === currentTrip) {
currentCoords.push([locations[i].longitude, locations[i].latitude])
} else {
flush()
currentCoords.push([locations[i - 1].longitude, locations[i - 1].latitude])
currentCoords.push([locations[i].longitude, locations[i].latitude])
currentColor = color
+ currentTrip = trip
}
}
flush()
@@ -157,6 +178,33 @@ export function buildTrackSegmentsGeoJSON(
return { type: "FeatureCollection", features }
}
+export type TerminalTrip = { index: number; color: string; locations: TrackLocation[] }
+
+/** Build one Point per trip end: a `start` and an `end`, in the trip's colour, flagged when focused. */
+export function buildTripTerminalsGeoJSON(
+ trips: TerminalTrip[],
+ focusedTrip?: number | null
+): GeoJSON.FeatureCollection {
+ const features: GeoJSON.Feature[] = []
+ for (const trip of trips) {
+ const first = trip.locations[0]
+ const last = trip.locations[trip.locations.length - 1]
+ if (!first || !last || first === last) continue
+ const focused = focusedTrip != null && trip.index === focusedTrip
+ for (const [kind, loc] of [
+ ["start", first],
+ ["end", last]
+ ] as const) {
+ features.push({
+ type: "Feature",
+ properties: { kind, trip: trip.index, color: trip.color, focused },
+ geometry: { type: "Point", coordinates: [loc.longitude, loc.latitude] }
+ })
+ }
+ }
+ return { type: "FeatureCollection", features }
+}
+
/** Build Point features for each track location with metadata properties.
* Pass `locationColors` to override speed-based dot coloring. */
export function buildTrackPointsGeoJSON(
@@ -203,7 +251,8 @@ export function buildGeofencesGeoJSON(
fillColor,
fillOpacity: 0.3,
strokeColor: fillColor,
- pauseTracking: zone.pauseTracking
+ pauseTracking: zone.pauseTracking,
+ radius: zone.radius
},
geometry: createCirclePolygon([zone.lon, zone.lat], zone.radius)
})
@@ -337,3 +386,37 @@ export function darkifyStyle(style: any): object {
return result
}
+
+const METERS_PER_DEGREE = 111_320
+
+/** The box around every zone's circle, for fitBounds. */
+export function geofenceBounds(geofences: Geofence[]): [number, number, number, number] {
+ let west = Infinity
+ let south = Infinity
+ let east = -Infinity
+ let north = -Infinity
+ for (const zone of geofences) {
+ const dLat = zone.radius / METERS_PER_DEGREE
+ const dLon = zone.radius / (METERS_PER_DEGREE * Math.cos((zone.lat * Math.PI) / 180))
+ west = Math.min(west, zone.lon - dLon)
+ east = Math.max(east, zone.lon + dLon)
+ south = Math.min(south, zone.lat - dLat)
+ north = Math.max(north, zone.lat + dLat)
+ }
+ return [west, south, east, north]
+}
+
+/** A zone circle takes a 48 dp target like a point does. */
+export const ZONE_HITBOX = { top: size.touch / 2, right: size.touch / 2, bottom: size.touch / 2, left: size.touch / 2 }
+
+/** Where circles overlap, the smallest is the one the finger meant; it is the one the others hide. */
+export function pickSmallestZone(features: GeoJSON.Feature[]): number | null {
+ let best: { id: number; radius: number } | null = null
+ for (const f of features) {
+ const id = f.properties?.id
+ const radius = f.properties?.radius ?? Infinity
+ if (typeof id !== "number") continue
+ if (!best || radius < best.radius) best = { id, radius }
+ }
+ return best?.id ?? null
+}
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 6c1b7aab..432934bb 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -16,34 +16,41 @@
export { Container } from "./ui/Container"
export { Card } from "./ui/Card"
export { Button } from "./ui/Button"
+export { IconButton } from "./ui/IconButton"
+export { HeaderAction } from "./ui/HeaderAction"
export { SectionTitle } from "./ui/SectionTitle"
export { Divider } from "./ui/Divider"
+export { EmptyState } from "./ui/EmptyState"
+export { TextField } from "./ui/TextField"
export { NumericInput } from "./ui/NumericInput"
export { TimePicker } from "./ui/TimePicker"
export { FloatingSaveIndicator } from "./ui/FloatingSaveIndicator"
-export { Footer } from "./ui/Footer"
export { SpinningLoader } from "./ui/SpinningLoader"
export { LoadingOverlay } from "./ui/LoadingOverlay"
export { LocationDisclosureModal } from "./ui/LocationDisclosureModal"
export { LocalNetworkDisclosureModal } from "./ui/LocalNetworkDisclosureModal"
export { AppModal } from "./ui/AppModal"
+export { DialogShell } from "./ui/DialogShell"
export { ChipGroup } from "./ui/ChipGroup"
-export { FormatOption } from "./ui/FormatOption"
-export { FormatSelector } from "./ui/FormatSelector"
+export { ExportFormatDialog } from "./ui/ExportFormatDialog"
export { RadioDot } from "./ui/RadioDot"
+export { RadioRow } from "./ui/RadioRow"
export { SettingRow } from "./ui/SettingRow"
+export { Toggle } from "./ui/Toggle"
export { FieldMessage } from "./ui/FieldMessage"
export { ListItem } from "./ui/ListItem"
-export { BottomTabBar } from "./ui/BottomTabBar"
+export { StateLine } from "./ui/StateLine"
+export { MapDock } from "./ui/MapDock"
+export { TrackMark } from "./ui/TrackMark"
+export { StepperHeader } from "./ui/StepperHeader"
+export { BottomTabBar, TAB_ROUTES } from "./ui/BottomTabBar"
// ============================================================================
// Feature Components - Dashboard
// ============================================================================
export { DashboardMap } from "./features/dashboard/DashboardMap"
-export { CoordinateDisplay } from "./features/dashboard/CoordinateDisplay"
export { ConnectionStatus } from "./features/dashboard/ConnectionStatus"
export { WelcomeCard } from "./features/dashboard/WelcomeCard"
-export { DatabaseStatistics } from "./features/dashboard/DatabaseStatistics"
// ============================================================================
// Feature Components - Map
@@ -58,6 +65,12 @@ export { TrackMap } from "./features/inspector/TrackMap"
// ============================================================================
// Feature Components - Settings
// ============================================================================
-export { StatsCard } from "./features/settings/StatsCard"
export { ConnectionSettings } from "./features/settings/ConnectionSettings"
export { SyncStrategySettings } from "./features/settings/SyncStrategySettings"
+export { StatRow } from "./ui/StatRow"
+export { Footer } from "./ui/Footer"
+export { FormatOption } from "./ui/FormatOption"
+export { FormatSelector } from "./ui/FormatSelector"
+export { CoordinateDisplay } from "./features/dashboard/CoordinateDisplay"
+export { DatabaseStatistics } from "./features/dashboard/DatabaseStatistics"
+export { StatsCard } from "./features/settings/StatsCard"
diff --git a/apps/mobile/src/components/ui/AppModal.tsx b/apps/mobile/src/components/ui/AppModal.tsx
index 1a5cd052..c6be67f4 100644
--- a/apps/mobile/src/components/ui/AppModal.tsx
+++ b/apps/mobile/src/components/ui/AppModal.tsx
@@ -4,23 +4,34 @@
*/
import React, { useState, useRef, useEffect, useCallback } from "react"
-import { Modal, View, Text, Pressable, StyleSheet, BackHandler } from "react-native"
-import { Info, AlertCircle, AlertTriangle, CheckCircle } from "lucide-react-native"
+import { View, Text, StyleSheet } from "react-native"
+import { Info, CircleAlert, TriangleAlert, CircleCheckBig } from "lucide-react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
-import { fontSizes } from "@colota/shared"
+import { fontSizes, fonts, lineHeights, type } from "../../styles/typography"
+import { radius } from "@colota/shared"
import { type ModalRequest, type AlertVariant, registerModalHandler } from "../../services/modalService"
+import { size, space } from "../../constants"
+import { Button } from "./Button"
+import { DialogShell } from "./DialogShell"
+import { TextField } from "./TextField"
const VARIANT_ICONS = {
info: Info,
- error: AlertCircle,
- warning: AlertTriangle,
- success: CheckCircle
+ error: CircleAlert,
+ warning: TriangleAlert,
+ success: CircleCheckBig
+} as const
+
+const BUTTON_VARIANTS = {
+ primary: "primary",
+ secondary: "ghost",
+ destructive: "danger"
} as const
export function AppModal() {
const { colors } = useTheme()
const [current, setCurrent] = useState<ModalRequest | null>(null)
+ const [draft, setDraft] = useState("")
const queueRef = useRef<ModalRequest[]>([])
const processNext = useCallback(() => {
@@ -42,57 +53,57 @@ export function AppModal() {
}, [current])
useEffect(() => {
- if (!current) return
- const handler = BackHandler.addEventListener("hardwareBackPress", () => true)
- return () => handler.remove()
+ setDraft(current?.input?.initialValue ?? "")
}, [current])
const handlePress = useCallback(
(index: number) => {
- current?.resolve(index)
+ current?.resolve(index, draft)
processNext()
},
- [current, processNext]
+ [current, draft, processNext]
)
if (!current) return null
const Icon = VARIANT_ICONS[current.variant]
const iconColor = getVariantColor(current.variant, colors)
+ const stacked = current.buttons.length > 2
return (
- <Modal visible transparent animationType="fade" statusBarTranslucent>
- <View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
- <View style={[styles.card, { backgroundColor: colors.cardElevated, borderRadius: colors.borderRadius + 4 }]}>
- <View style={[styles.iconContainer, { backgroundColor: iconColor + "15" }]}>
- <Icon size={28} color={iconColor} />
- </View>
+ <DialogShell
+ visible
+ dismissible={false}
+ onRequestClose={() => {}}
+ footer={
+ <View style={[styles.buttons, stacked && styles.buttonsStacked]}>
+ {current.buttons.map((btn, i) => (
+ <Button key={i} title={btn.text} variant={BUTTON_VARIANTS[btn.style]} onPress={() => handlePress(i)} />
+ ))}
+ </View>
+ }
+ >
+ <View style={[styles.iconContainer, { backgroundColor: iconColor + "15" }]}>
+ <Icon size={size.icon.lg} color={iconColor} />
+ </View>
- <Text style={[styles.title, { color: colors.text }]}>{current.title}</Text>
- <Text style={[styles.body, { color: colors.textSecondary }]}>{current.message}</Text>
+ <Text style={[styles.title, { color: colors.text }]}>{current.title}</Text>
+ {current.message ? <Text style={[styles.body, { color: colors.textSecondary }]}>{current.message}</Text> : null}
- <View style={[styles.buttons, current.buttons.length > 2 && styles.buttonsVertical]}>
- {current.buttons.map((btn, i) => {
- const btnStyles = getButtonStyles(btn.style, colors)
- return (
- <Pressable
- key={i}
- style={({ pressed }) => [
- styles.button,
- current.buttons.length > 2 && styles.buttonFullWidth,
- btnStyles.container,
- pressed && { opacity: colors.pressedOpacity }
- ]}
- onPress={() => handlePress(i)}
- >
- <Text style={[styles.buttonText, btnStyles.text]}>{btn.text}</Text>
- </Pressable>
- )
- })}
- </View>
+ {current.input && (
+ <View style={styles.input}>
+ <TextField
+ accessibilityLabel={current.title}
+ multiline={current.input.multiline}
+ autoFocus
+ value={draft}
+ onChangeText={setDraft}
+ placeholder={current.input.placeholder}
+ testID="prompt-input"
+ />
</View>
- </View>
- </Modal>
+ )}
+ </DialogShell>
)
}
@@ -109,85 +120,37 @@ function getVariantColor(variant: AlertVariant, colors: ReturnType<typeof useThe
}
}
-function getButtonStyles(
- style: "primary" | "secondary" | "destructive",
- colors: ReturnType<typeof useTheme>["colors"]
-) {
- switch (style) {
- case "destructive":
- return {
- container: { backgroundColor: colors.error } as const,
- text: { color: colors.textOnPrimary } as const
- }
- case "secondary":
- return {
- container: { borderWidth: 1.5, borderColor: colors.border } as const,
- text: { color: colors.textSecondary } as const
- }
- default:
- return {
- container: { backgroundColor: colors.primary } as const,
- text: { color: colors.textOnPrimary } as const
- }
- }
-}
-
const styles = StyleSheet.create({
- overlay: {
- flex: 1,
- justifyContent: "center",
- alignItems: "center",
- paddingHorizontal: 32
- },
- card: {
- width: "100%",
- padding: 24,
- elevation: 8,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.2,
- shadowRadius: 12
- },
iconContainer: {
- width: 56,
- height: 56,
- borderRadius: 28,
+ width: size.emptyIcon,
+ height: size.emptyIcon,
+ borderRadius: radius.pill,
justifyContent: "center",
alignItems: "center",
alignSelf: "center",
- marginBottom: 16
+ marginBottom: space.lg
},
title: {
- fontSize: fontSizes.cardTitle,
- ...fonts.bold,
+ ...type.title,
textAlign: "center",
- marginBottom: 12
+ marginBottom: space.md
},
body: {
fontSize: fontSizes.body,
...fonts.regular,
- lineHeight: 20,
+ lineHeight: lineHeights.body,
textAlign: "center"
},
+ input: {
+ marginTop: space.lg
+ },
buttons: {
flexDirection: "row",
- gap: 12,
- marginTop: 24
- },
- buttonsVertical: {
- flexDirection: "column"
+ gap: space.sm
},
- buttonFullWidth: {
- flex: 0
- },
- button: {
+ buttonsStacked: {
flex: 1,
- paddingVertical: 14,
- borderRadius: 8,
- alignItems: "center"
- },
- buttonText: {
- fontSize: fontSizes.label,
- ...fonts.semiBold
+ flexDirection: "column",
+ alignItems: "stretch"
}
})
diff --git a/apps/mobile/src/components/ui/BottomTabBar.tsx b/apps/mobile/src/components/ui/BottomTabBar.tsx
index 57814e71..d8564020 100644
--- a/apps/mobile/src/components/ui/BottomTabBar.tsx
+++ b/apps/mobile/src/components/ui/BottomTabBar.tsx
@@ -5,30 +5,39 @@
import React from "react"
import { View, Pressable, Text, StyleSheet } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
-import { Settings, LucideIcon, House, MapPinHouse, Waypoints } from "lucide-react-native"
+import { Settings, House, CircleDot } from "lucide-react-native"
+import { TrackMark } from "./TrackMark"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space, STATE_LAYER_ALPHA, elevation } from "../../constants"
+import type { RootStackRoute } from "../../types/navigation"
+
+type TabIcon = React.ComponentType<{ size?: number; color?: string; strokeWidth?: number }>
interface Tab {
name: string
label: string
- icon: LucideIcon
- route: string
+ icon: TabIcon
+ route: RootStackRoute
}
const TABS: Tab[] = [
{ name: "dashboard", label: "Dashboard", icon: House, route: "Dashboard" },
- { name: "history", label: "History", icon: Waypoints, route: "Location History" },
- { name: "geofences", label: "Geofences", icon: MapPinHouse, route: "Geofences" },
+ { name: "history", label: "History", icon: TrackMark, route: "Location History" },
+ { name: "geofences", label: "Geofences", icon: CircleDot, route: "Geofences" },
{ name: "settings", label: "Settings", icon: Settings, route: "Settings" }
]
-/** Routes where the tab bar is visible. */
-const TAB_ROUTES = new Set(TABS.map((t) => t.route))
+/** Routes where the tab bar is visible. The one list; App.tsx reads it rather than repeating it. */
+// Typed loosely on purpose: lookups come from navigation state, which is a bare string.
+export const TAB_ROUTES: Set<string> = new Set(TABS.map((t) => t.route))
+
+/** The semibold of a glyph: with no filled variants in the set, weight carries the active tab. */
+const ACTIVE_STROKE = 2.25
interface BottomTabBarProps {
currentRoute: string | undefined
- onNavigate: (route: string) => void
+ onNavigate: (route: RootStackRoute) => void
}
export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
@@ -43,21 +52,28 @@ export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
styles.container,
{
backgroundColor: colors.background,
- paddingBottom: insets.bottom + 8
+ paddingBottom: insets.bottom + space.sm
}
]}
>
{TABS.map((tab) => {
const active = currentRoute === tab.route
- const color = active ? colors.primary : colors.textLight
+ const color = active ? colors.primary : colors.textSecondary
return (
<Pressable
key={tab.name}
- style={({ pressed }) => [styles.tab, pressed && { opacity: 0.6 }]}
+ accessibilityRole="tab"
+ accessibilityState={{ selected: active }}
+ accessibilityLabel={tab.label}
+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
+ style={styles.tab}
onPress={() => onNavigate(tab.route)}
>
- <tab.icon size={22} color={color} />
- <Text style={[styles.label, { color }]}>{tab.label}</Text>
+ {/* The set has no filled variants, so weight is what marks the active glyph. */}
+ <tab.icon size={size.icon.lg} color={color} strokeWidth={active ? ACTIVE_STROKE : undefined} />
+ <Text numberOfLines={2} style={[styles.label, active && fonts.semiBold, { color }]}>
+ {tab.label}
+ </Text>
</Pressable>
)
})}
@@ -65,25 +81,22 @@ export function BottomTabBar({ currentRoute, onNavigate }: BottomTabBarProps) {
)
}
-export { TAB_ROUTES }
-
const styles = StyleSheet.create({
container: {
flexDirection: "row",
- paddingTop: 8,
- paddingBottom: 6,
- elevation: 0,
- shadowOpacity: 0,
- shadowRadius: 0
+ paddingTop: space.sm,
+ paddingBottom: space.sm,
+ elevation: elevation.flat
},
tab: {
flex: 1,
+ minHeight: size.row,
alignItems: "center",
justifyContent: "center",
- gap: 3
+ gap: space.xs
},
label: {
- fontSize: 11,
+ fontSize: fontSizes.small,
...fonts.medium
}
})
diff --git a/apps/mobile/src/components/ui/Button.tsx b/apps/mobile/src/components/ui/Button.tsx
index 90f8df6d..7d04cf17 100644
--- a/apps/mobile/src/components/ui/Button.tsx
+++ b/apps/mobile/src/components/ui/Button.tsx
@@ -3,12 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useRef, useCallback } from "react"
+import React from "react"
import {
Pressable,
Text,
View,
- Animated,
ActivityIndicator,
StyleSheet,
GestureResponderEvent,
@@ -16,21 +15,30 @@ import {
ViewStyle
} from "react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
import { type LucideIcon } from "lucide-react-native"
+import { elevation, size, space, STATE_LAYER_ALPHA } from "../../constants"
+import { radius } from "@colota/shared"
type ButtonVariant = "primary" | "secondary" | "ghost" | "danger"
+type ButtonShape = "rounded" | "pill"
type Props = {
+ activeOpacity?: number
title: string
onPress: (event: GestureResponderEvent) => void
disabled?: boolean
style?: StyleProp<ViewStyle>
- activeOpacity?: number
color?: string
variant?: ButtonVariant
+ /** The corner is painted inside, so a caller cannot set it through `style`. */
+ shape?: ButtonShape
icon?: LucideIcon
loading?: boolean
+ expanded?: boolean
+ /** Lifts the painted Pressable; a shadow on the wrapper draws nothing because it has no fill. */
+ floating?: boolean
+ testID?: string
}
export function Button({
@@ -38,116 +46,85 @@ export function Button({
onPress,
disabled = false,
style,
- activeOpacity,
color,
variant = "primary",
+ shape = "rounded",
icon: Icon,
- loading = false
+ loading = false,
+ expanded,
+ floating = false,
+ testID
}: Props) {
const { colors } = useTheme()
- const scale = useRef(new Animated.Value(1)).current
-
- const handlePressIn = useCallback(() => {
- Animated.spring(scale, {
- toValue: 0.97,
- useNativeDriver: true,
- speed: 50,
- bounciness: 4
- }).start()
- }, [scale])
-
- const handlePressOut = useCallback(() => {
- Animated.spring(scale, {
- toValue: 1,
- useNativeDriver: true,
- speed: 50,
- bounciness: 4
- }).start()
- }, [scale])
-
const getVariantStyles = () => {
+ // Disabled recedes: the container drops to the recessed fill and the content to the disabled
+ // token. Painting the fill itself disabled left a filled button wearing its enabled label.
+ if (disabled) {
+ return { bg: variant === "ghost" ? "transparent" : colors.well, text: colors.textDisabled }
+ }
switch (variant) {
case "primary":
- return {
- bg: disabled ? colors.textDisabled : colors.primary,
- text: color ?? colors.textOnPrimary,
- borderColor: "transparent",
- borderWidth: 0
- }
+ return { bg: colors.primary, text: color ?? colors.textOnPrimary }
case "secondary":
- return {
- bg: "transparent",
- text: color ?? colors.primaryDark,
- borderColor: colors.primary,
- borderWidth: 1.5
- }
+ return { bg: colors.primaryContainer, text: color ?? colors.onPrimaryContainer }
case "ghost":
- return {
- bg: "transparent",
- text: color ?? colors.primaryDark,
- borderColor: "transparent",
- borderWidth: 0
- }
+ return { bg: "transparent", text: color ?? colors.primaryDark }
case "danger":
- return {
- bg: disabled ? colors.textDisabled : colors.error,
- text: color ?? colors.textOnPrimary,
- borderColor: "transparent",
- borderWidth: 0
- }
+ return { bg: colors.error, text: color ?? colors.textOnPrimary }
}
}
const v = getVariantStyles()
return (
- <Animated.View style={[{ transform: [{ scale }] }, style]}>
+ <View style={style}>
<Pressable
- style={({ pressed }) => [
+ testID={testID}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: disabled || loading, expanded }}
+ android_ripple={disabled || loading ? undefined : { color: v.text + STATE_LAYER_ALPHA }}
+ style={[
styles.button,
- {
- backgroundColor: v.bg,
- borderColor: v.borderColor,
- borderWidth: v.borderWidth,
- borderRadius: colors.borderRadius,
- opacity: pressed ? (activeOpacity ?? colors.pressedOpacity) : 1
- }
+ { backgroundColor: v.bg, borderRadius: shape === "pill" ? radius.pill : radius.sm },
+ floating && { elevation: elevation.floating }
]}
onPress={onPress}
- onPressIn={handlePressIn}
- onPressOut={handlePressOut}
disabled={disabled || loading}
>
<View style={styles.content}>
{loading ? (
<ActivityIndicator size="small" color={v.text} style={styles.icon} />
) : Icon ? (
- <Icon size={18} color={v.text} style={styles.icon} />
+ <Icon size={size.icon.md} color={v.text} style={styles.icon} />
) : null}
<Text style={[styles.text, { color: v.text }]}>{title}</Text>
</View>
</Pressable>
- </Animated.View>
+ </View>
)
}
const styles = StyleSheet.create({
button: {
- paddingVertical: 12,
- paddingHorizontal: 24,
+ // Android's minimum touch target; padding alone leaves this at about 43.
+ minHeight: size.touch,
+ overflow: "hidden",
+ justifyContent: "center",
+ paddingVertical: space.md,
+ paddingHorizontal: space.xl,
alignItems: "center",
- marginVertical: 8
+ marginVertical: space.sm
},
content: {
flexDirection: "row",
alignItems: "center",
- gap: 8
+ gap: space.sm
},
text: {
- fontSize: 16,
+ fontSize: fontSizes.label,
...fonts.semiBold
},
icon: {
- marginRight: 0
+ marginEnd: 0
}
})
diff --git a/apps/mobile/src/components/ui/Card.tsx b/apps/mobile/src/components/ui/Card.tsx
index 1953bf87..322be987 100644
--- a/apps/mobile/src/components/ui/Card.tsx
+++ b/apps/mobile/src/components/ui/Card.tsx
@@ -6,14 +6,22 @@
import React from "react"
import { View, Pressable, StyleSheet, ViewStyle, StyleProp, AccessibilityRole, AccessibilityState } from "react-native"
import { useTheme } from "../../hooks/useTheme"
+import { space, STATE_LAYER_ALPHA, elevation } from "../../constants"
+import { radius } from "@colota/shared"
type CardVariant = "default" | "elevated" | "outlined" | "interactive"
type CardProps = {
children: React.ReactNode
+ /** Lands on the surface inside the Pressable, so a margin here grows the ripple box past the
+ * card it paints. Spacing between cards belongs to the list. */
style?: StyleProp<ViewStyle>
+ testID?: string
danger?: boolean
variant?: CardVariant
+ /** A card that is nothing but rows: it gives up its vertical padding so the first and last
+ * row's state layer reaches its edge. The rows already carry the spacing. */
+ rows?: boolean
onPress?: () => void
onLongPress?: () => void
accessibilityRole?: AccessibilityRole
@@ -27,12 +35,14 @@ export function Card({
style,
danger = false,
variant = "default",
+ rows = false,
onPress,
onLongPress,
accessibilityRole,
accessibilityLabel,
accessibilityHint,
- accessibilityState
+ accessibilityState,
+ testID
}: CardProps) {
const { colors } = useTheme()
@@ -48,37 +58,35 @@ export function Card({
switch (variant) {
case "default":
return {
- backgroundColor: colors.card,
- borderColor: colors.border,
- borderWidth: 1
+ backgroundColor: colors.card
}
case "elevated":
return {
- backgroundColor: colors.cardElevated,
+ backgroundColor: colors.surfaceRaised,
borderColor: "transparent",
borderWidth: 0,
- elevation: 1,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 2 },
- shadowOpacity: 0.15,
- shadowRadius: 6
+ elevation: elevation.raised
}
case "outlined":
return {
backgroundColor: "transparent",
borderColor: colors.border,
- borderWidth: 1.5
+ // Material's outlined card is 1dp. It was 1.5 only to stay visible while border sat at
+ // 1.18:1; the token clears the outline floor now, so the weight goes back to the spec.
+ borderWidth: 1
}
case "interactive":
return {
- backgroundColor: colors.card,
- borderColor: colors.border,
- borderWidth: 1
+ backgroundColor: colors.card
}
}
}
- const cardView = <View style={[styles.card, getVariantStyles(), style]}>{children}</View>
+ const cardView = (
+ <View style={[styles.card, rows && styles.rowsCard, getVariantStyles(), style]} testID={testID}>
+ {children}
+ </View>
+ )
if (variant === "interactive" && (onPress || onLongPress)) {
return (
@@ -89,7 +97,8 @@ export function Card({
accessibilityLabel={accessibilityLabel}
accessibilityHint={accessibilityHint}
accessibilityState={accessibilityState}
- style={({ pressed }) => ({ opacity: pressed ? colors.pressedOpacity : 1 })}
+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
+ style={styles.pressable}
>
{cardView}
</Pressable>
@@ -101,10 +110,17 @@ export function Card({
const styles = StyleSheet.create({
card: {
- flex: 1,
- padding: 16,
- borderRadius: 12,
- borderWidth: 1,
- width: "100%"
+ padding: space.lg,
+ borderRadius: radius.md,
+ width: "100%",
+ // A row inside the card ripples to its own bounds, so the card has to clip the corners.
+ overflow: "hidden"
+ },
+ rowsCard: {
+ paddingVertical: 0
+ },
+ pressable: {
+ borderRadius: radius.md,
+ overflow: "hidden"
}
})
diff --git a/apps/mobile/src/components/ui/ChipGroup.tsx b/apps/mobile/src/components/ui/ChipGroup.tsx
index e644cdc0..f7ccdadf 100644
--- a/apps/mobile/src/components/ui/ChipGroup.tsx
+++ b/apps/mobile/src/components/ui/ChipGroup.tsx
@@ -5,37 +5,55 @@
import React from "react"
import { View, Pressable, Text, StyleSheet } from "react-native"
+import { Check } from "lucide-react-native"
import { ThemeColors } from "../../types/global"
-import { fonts } from "../../styles/typography"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts } from "../../styles/typography"
+import { HIT_SLOP_MD, STATE_LAYER_ALPHA, size, space } from "../../constants"
+import { radius } from "@colota/shared"
interface ChipGroupProps<T extends string> {
- options: readonly { value: T; label: string }[]
+ options: readonly { value: T; label: string; testID?: string }[]
selected: T
onSelect: (value: T) => void
- colors: ThemeColors
disabled?: ReadonlySet<T>
+ accessibilityLabel?: string
+ colors?: ThemeColors
}
-export function ChipGroup<T extends string>({ options, selected, onSelect, colors, disabled }: ChipGroupProps<T>) {
+export function ChipGroup<T extends string>({
+ options,
+ selected,
+ onSelect,
+ disabled,
+ accessibilityLabel
+}: ChipGroupProps<T>) {
+ const { colors } = useTheme()
+
return (
- <View style={styles.row}>
- {options.map(({ value, label }) => {
+ // The chips carry the radio role, so the row has to be the group or a screen reader reads
+ // loose radios with nothing binding them.
+ <View style={styles.row} accessibilityRole="radiogroup" accessibilityLabel={accessibilityLabel}>
+ {options.map(({ value, label, testID }) => {
const isSelected = selected === value
const isDisabled = disabled?.has(value) ?? false
+ // Disabled recolours the content rather than fading the chip, so the fill still reads
+ // as a chip and the selected one still says which it is.
+ const content = isDisabled ? colors.textDisabled : isSelected ? colors.onPrimaryContainer : colors.text
return (
<Pressable
key={value}
+ testID={testID}
disabled={isDisabled}
- style={({ pressed }) => [
- styles.chip,
- { borderColor: colors.border, backgroundColor: colors.background },
- isSelected && { borderColor: colors.primary, backgroundColor: colors.primary + "20" },
- isDisabled && { opacity: 0.4 },
- pressed && !isDisabled && { opacity: colors.pressedOpacity }
- ]}
+ hitSlop={HIT_SLOP_MD}
+ accessibilityRole="radio"
+ accessibilityState={{ checked: isSelected, disabled: isDisabled }}
+ android_ripple={isDisabled ? undefined : { color: content + STATE_LAYER_ALPHA }}
+ style={[styles.chip, { backgroundColor: isSelected ? colors.primaryContainer : colors.well }]}
onPress={() => onSelect(value)}
>
- <Text style={[styles.label, { color: isSelected ? colors.primary : colors.text }]}>{label}</Text>
+ {isSelected ? <Check size={size.icon.sm} color={content} strokeWidth={2} /> : null}
+ <Text style={[styles.label, isSelected && styles.labelSelected, { color: content }]}>{label}</Text>
</Pressable>
)
})}
@@ -47,17 +65,24 @@ const styles = StyleSheet.create({
row: {
flexDirection: "row",
flexWrap: "wrap",
- gap: 8
+ gap: space.sm
},
chip: {
- borderWidth: 2,
- borderRadius: 10,
- paddingVertical: 10,
- paddingHorizontal: 14,
- alignItems: "center"
+ overflow: "hidden",
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.xs,
+ minHeight: size.chip,
+ borderRadius: radius.sm,
+ paddingVertical: space.sm,
+ paddingHorizontal: space.md
},
label: {
- fontSize: 12,
- ...fonts.bold
+ fontSize: fontSizes.caption,
+ ...fonts.medium
+ },
+ // Selection is a check and a weight step as well as the fill, so it does not rest on colour alone.
+ labelSelected: {
+ ...fonts.semiBold
}
})
diff --git a/apps/mobile/src/components/ui/DialogShell.tsx b/apps/mobile/src/components/ui/DialogShell.tsx
new file mode 100644
index 00000000..15d930ff
--- /dev/null
+++ b/apps/mobile/src/components/ui/DialogShell.tsx
@@ -0,0 +1,101 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Modal, Pressable, StyleSheet, Text, View } from "react-native"
+import { radius } from "@colota/shared"
+import { useTheme } from "../../hooks/useTheme"
+import { type } from "../../styles/typography"
+import { elevation, space } from "../../constants"
+
+interface DialogShellProps {
+ visible: boolean
+ onRequestClose: () => void
+ title?: string
+ children: React.ReactNode
+ footer?: React.ReactNode
+ gutter?: "default" | "picker"
+ /** False for a dialog the caller must answer: no scrim tap, hardware back does nothing. */
+ dismissible?: boolean
+}
+
+export function DialogShell({
+ visible,
+ onRequestClose,
+ title,
+ children,
+ footer,
+ gutter = "default",
+ dismissible = true
+}: DialogShellProps) {
+ const { colors } = useTheme()
+ const picker = gutter === "picker"
+ const dismiss = dismissible ? onRequestClose : () => {}
+
+ return (
+ <Modal transparent statusBarTranslucent visible={visible} animationType="fade" onRequestClose={dismiss}>
+ <Pressable
+ accessibilityRole="none"
+ testID="dialog-scrim"
+ style={[styles.scrim, picker ? styles.scrimPicker : styles.scrimDefault, { backgroundColor: colors.overlay }]}
+ onPress={dismiss}
+ >
+ <Pressable
+ accessibilityRole="none"
+ testID="dialog-card"
+ onPress={() => {}}
+ style={[
+ styles.card,
+ picker ? styles.cardPicker : styles.cardDefault,
+ { backgroundColor: colors.surfaceRaised }
+ ]}
+ >
+ {title ? (
+ <Text accessibilityRole="header" style={[styles.title, { color: colors.text }]}>
+ {title}
+ </Text>
+ ) : null}
+ {children}
+ {footer ? <View style={styles.footer}>{footer}</View> : null}
+ </Pressable>
+ </Pressable>
+ </Modal>
+ )
+}
+
+const styles = StyleSheet.create({
+ scrim: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center"
+ },
+ scrimDefault: {
+ paddingHorizontal: space.xxl
+ },
+ scrimPicker: {
+ paddingHorizontal: space.lg
+ },
+ card: {
+ width: "100%",
+ borderRadius: radius.lg,
+ elevation: elevation.overlay
+ },
+ cardDefault: {
+ padding: space.xl
+ },
+ cardPicker: {
+ padding: space.md
+ },
+ title: {
+ ...type.title,
+ marginBottom: space.md
+ },
+ footer: {
+ flexDirection: "row",
+ justifyContent: "flex-end",
+ gap: space.sm,
+ marginTop: space.lg
+ }
+})
diff --git a/apps/mobile/src/components/ui/DisclosureModal.tsx b/apps/mobile/src/components/ui/DisclosureModal.tsx
index 39777e37..a170fcbe 100644
--- a/apps/mobile/src/components/ui/DisclosureModal.tsx
+++ b/apps/mobile/src/components/ui/DisclosureModal.tsx
@@ -6,8 +6,9 @@
import React, { useState, useRef, useEffect, useCallback } from "react"
import { Modal, View, Text, Pressable, StyleSheet, BackHandler } from "react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
-import { fontSizes } from "@colota/shared"
+import { fontSizes, fonts, lineHeights, type } from "../../styles/typography"
+import { radius } from "@colota/shared"
+import { size, space, STATE_LAYER_ALPHA, elevation } from "../../constants"
interface DisclosureModalProps {
icon: React.ReactNode
@@ -60,7 +61,7 @@ export function DisclosureModal({ icon, title, paragraphs, confirmLabel, registe
return (
<Modal visible={visible} transparent animationType="fade" statusBarTranslucent>
<View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
- <View style={[styles.card, { backgroundColor: colors.cardElevated, borderRadius: colors.borderRadius + 4 }]}>
+ <View style={[styles.card, { backgroundColor: colors.card, borderRadius: radius.lg }]}>
{/* Icon */}
<View style={[styles.iconContainer, { backgroundColor: colors.primary + "15" }]}>{icon}</View>
@@ -77,24 +78,18 @@ export function DisclosureModal({ icon, title, paragraphs, confirmLabel, registe
{/* Buttons */}
<View style={styles.buttons}>
<Pressable
- style={({ pressed }) => [
- styles.button,
- styles.secondaryButton,
- { borderColor: colors.border },
- pressed && { opacity: colors.pressedOpacity }
- ]}
+ accessibilityRole="button"
+ android_ripple={{ color: colors.textSecondary + STATE_LAYER_ALPHA }}
+ style={styles.button}
onPress={handleNotNow}
>
- <Text style={[styles.buttonText, { color: colors.textSecondary }]}>Not Now</Text>
+ <Text style={[styles.buttonText, { color: colors.textSecondary }]}>Not now</Text>
</Pressable>
<Pressable
- style={({ pressed }) => [
- styles.button,
- styles.primaryButton,
- { backgroundColor: colors.primary },
- pressed && { opacity: colors.pressedOpacity }
- ]}
+ accessibilityRole="button"
+ android_ripple={{ color: colors.textOnPrimary + STATE_LAYER_ALPHA }}
+ style={[styles.button, { backgroundColor: colors.primary }]}
onPress={handleConfirm}
>
<Text style={[styles.buttonText, { color: colors.textOnPrimary }]}>{confirmLabel}</Text>
@@ -111,54 +106,49 @@ const styles = StyleSheet.create({
flex: 1,
justifyContent: "center",
alignItems: "center",
- paddingHorizontal: 32
+ paddingHorizontal: space.xxl
},
card: {
width: "100%",
- padding: 24,
- elevation: 8,
- shadowColor: "#000",
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.2,
- shadowRadius: 12
+ padding: space.xl,
+ elevation: elevation.overlay
},
iconContainer: {
- width: 56,
- height: 56,
- borderRadius: 28,
+ width: size.emptyIcon,
+ height: size.emptyIcon,
+ borderRadius: radius.pill,
justifyContent: "center",
alignItems: "center",
alignSelf: "center",
- marginBottom: 16
+ marginBottom: space.lg
},
title: {
- fontSize: fontSizes.cardTitle,
- ...fonts.bold,
+ ...type.title,
textAlign: "center",
- marginBottom: 16
+ marginBottom: space.lg
},
body: {
fontSize: fontSizes.body,
...fonts.regular,
- lineHeight: 20
+ lineHeight: lineHeights.body
},
bodySpaced: {
- marginTop: 8
+ marginTop: space.sm
},
buttons: {
flexDirection: "row",
- gap: 12,
- marginTop: 24
+ gap: space.md,
+ marginTop: space.xl
},
button: {
flex: 1,
- paddingVertical: 14,
- borderRadius: 8,
- alignItems: "center"
- },
- primaryButton: {},
- secondaryButton: {
- borderWidth: 1.5
+ // 14 was holding the 48 target by itself: on the scale that only works with the minimum stated
+ minHeight: size.touch,
+ paddingVertical: space.md,
+ borderRadius: radius.sm,
+ overflow: "hidden",
+ alignItems: "center",
+ justifyContent: "center"
},
buttonText: {
fontSize: fontSizes.label,
diff --git a/apps/mobile/src/components/ui/Divider.tsx b/apps/mobile/src/components/ui/Divider.tsx
index d2cf2c28..bc5ca143 100644
--- a/apps/mobile/src/components/ui/Divider.tsx
+++ b/apps/mobile/src/components/ui/Divider.tsx
@@ -3,18 +3,38 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import React from "react"
import { View, StyleSheet } from "react-native"
import { useTheme } from "../../hooks/useTheme"
+import { space, size } from "../../constants"
-export const Divider = () => {
+/** Where a ListItem's text starts inside its card: past the icon and the gap after it. */
+const TEXT_COLUMN = size.icon.md + space.lg
+
+type DividerProps = {
+ /** Between rows of one group, where the rows already carry their own vertical padding. */
+ tight?: boolean
+ /** Starts at the text column, for a group whose rows have a leading icon. */
+ inset?: boolean
+}
+
+export const Divider = ({ tight = false, inset = false }: DividerProps) => {
const { colors } = useTheme()
- return <View style={[styles.divider, { backgroundColor: colors.divider }]} />
+ return (
+ <View style={[styles.divider, tight && styles.tight, inset && styles.inset, { backgroundColor: colors.divider }]} />
+ )
}
const styles = StyleSheet.create({
divider: {
- height: 1,
- marginVertical: 16
+ height: StyleSheet.hairlineWidth,
+ marginVertical: space.lg
+ },
+ tight: {
+ marginVertical: 0
+ },
+ inset: {
+ marginStart: TEXT_COLUMN
}
})
diff --git a/apps/mobile/src/components/ui/EmptyState.tsx b/apps/mobile/src/components/ui/EmptyState.tsx
new file mode 100644
index 00000000..aa7b9a57
--- /dev/null
+++ b/apps/mobile/src/components/ui/EmptyState.tsx
@@ -0,0 +1,87 @@
+/**
+ * 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, type StyleProp, type ViewStyle } from "react-native"
+import { type LucideIcon } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts, lineHeights } from "../../styles/typography"
+import { size, space } from "../../constants"
+import { Button } from "./Button"
+
+type EmptyStateProps = {
+ title: string
+ /** Why it is empty, or what fills it. Omit when the title already says both. */
+ hint?: string
+ /** Only when the empty state owns the screen: the glyph also centres the block. */
+ icon?: LucideIcon
+ /** For a container that already insets its rows, which would otherwise double the padding. */
+ style?: StyleProp<ViewStyle>
+ action?: { label: string; onPress: () => void }
+}
+
+// Two shapes, and the icon picks between them. An empty tab or screen gets the glyph and
+// centres, so it reads as new rather than broken. An empty section inside a populated screen
+// stays one left-aligned line, where a glyph would be louder than the content around it.
+export function EmptyState({ title, hint, icon: Icon, style, action }: EmptyStateProps) {
+ const { colors } = useTheme()
+ const centred = Boolean(Icon)
+
+ return (
+ <View style={[styles.container, centred && styles.centred, style]}>
+ {Icon ? (
+ <View style={[styles.iconCircle, { backgroundColor: colors.well }]}>
+ <Icon size={size.icon.lg} color={colors.textSecondary} />
+ </View>
+ ) : null}
+ <Text style={[styles.title, centred && styles.centredText, { color: colors.text }]}>{title}</Text>
+ {hint ? (
+ <Text style={[styles.hint, centred && styles.centredText, { color: colors.textSecondary }]}>{hint}</Text>
+ ) : null}
+ {action ? <Button variant="ghost" title={action.label} onPress={action.onPress} style={styles.action} /> : null}
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ // Most of these sit in a bare FlatList, so the state pays its own inset rather than relying
+ // on a container that may or may not have one.
+ container: {
+ paddingHorizontal: space.lg,
+ paddingVertical: space.lg
+ },
+ // A screen that is entirely empty can afford the room; an empty section under other content
+ // cannot, because the block above it has already paid its own bottom margin.
+ centred: {
+ flex: 1,
+ alignItems: "center",
+ justifyContent: "center",
+ paddingVertical: space.xxl
+ },
+ centredText: {
+ textAlign: "center"
+ },
+ iconCircle: {
+ width: size.emptyIcon,
+ height: size.emptyIcon,
+ borderRadius: size.emptyIcon / 2,
+ alignItems: "center",
+ justifyContent: "center",
+ marginBottom: space.lg
+ },
+ title: {
+ fontSize: fontSizes.body,
+ ...fonts.semiBold
+ },
+ hint: {
+ fontSize: fontSizes.description,
+ ...fonts.regular,
+ lineHeight: lineHeights.description,
+ marginTop: space.xs
+ },
+ action: {
+ alignSelf: "center"
+ }
+})
diff --git a/apps/mobile/src/components/ui/ErrorBoundary.tsx b/apps/mobile/src/components/ui/ErrorBoundary.tsx
index af32a8b4..b31f3e33 100644
--- a/apps/mobile/src/components/ui/ErrorBoundary.tsx
+++ b/apps/mobile/src/components/ui/ErrorBoundary.tsx
@@ -3,11 +3,14 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
import React, { Component } from "react"
-import { View, Text, StyleSheet, Pressable } from "react-native"
+import { View, Text, StyleSheet } from "react-native"
import { ThemeColors } from "../../types/global"
import { useTheme } from "../../hooks/useTheme"
import { logger } from "../../utils/logger"
-import { fonts, fontSizes } from "../../styles/typography"
+import { fontSizes, type } from "../../styles/typography"
+import { space } from "../../constants"
+
+import { Button } from "./Button"
interface ErrorBoundaryInternalProps {
children: React.ReactNode
@@ -47,16 +50,7 @@ class ErrorBoundaryInternal extends Component<ErrorBoundaryInternalProps, ErrorB
<Text style={[styles.errorMessage, { color: colors.textSecondary }]}>
{this.state.error?.message || "An unexpected error occurred"}
</Text>
- <Pressable
- style={({ pressed }) => [
- styles.errorButton,
- { backgroundColor: colors.primary },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- onPress={this.handleReset}
- >
- <Text style={[styles.errorButtonText, { color: colors.textOnPrimary }]}>Try Again</Text>
- </Pressable>
+ <Button title="Try again" onPress={this.handleReset} />
</View>
)
}
@@ -79,26 +73,16 @@ const styles = StyleSheet.create({
flex: 1,
justifyContent: "center",
alignItems: "center",
- padding: 20
+ padding: space.lg
},
errorTitle: {
- fontSize: fontSizes.screenTitle,
- ...fonts.bold,
- marginBottom: 10
+ ...type.display,
+ marginBottom: space.md
},
errorMessage: {
fontSize: fontSizes.label,
textAlign: "center",
- marginBottom: 20,
- paddingHorizontal: 20
- },
- errorButton: {
- paddingHorizontal: 24,
- paddingVertical: 12,
- borderRadius: 8
- },
- errorButtonText: {
- fontSize: fontSizes.label,
- ...fonts.semiBold
+ marginBottom: space.lg,
+ paddingHorizontal: space.lg
}
})
diff --git a/apps/mobile/src/components/ui/ExportFormatDialog.tsx b/apps/mobile/src/components/ui/ExportFormatDialog.tsx
new file mode 100644
index 00000000..e33bd346
--- /dev/null
+++ b/apps/mobile/src/components/ui/ExportFormatDialog.tsx
@@ -0,0 +1,66 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { StyleSheet, Text, View } from "react-native"
+import { Upload } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { space } from "../../constants"
+import { fonts, fontSizes, lineHeights } from "../../styles/typography"
+import { EXPORT_FORMAT_KEYS, EXPORT_FORMATS, type ExportFormat } from "../../utils/exportConverters"
+import { Button } from "./Button"
+import { DialogShell } from "./DialogShell"
+import { Divider } from "./Divider"
+import { ListItem } from "./ListItem"
+
+type ExportFormatDialogProps = {
+ visible: boolean
+ title: string
+ message: string
+ onSelect: (format: ExportFormat) => void
+ onRequestClose: () => void
+}
+
+export function ExportFormatDialog({ visible, title, message, onSelect, onRequestClose }: ExportFormatDialogProps) {
+ const { colors } = useTheme()
+
+ return (
+ <DialogShell
+ visible={visible}
+ title={title}
+ onRequestClose={onRequestClose}
+ footer={<Button variant="ghost" title="Cancel" onPress={onRequestClose} testID="export-cancel" />}
+ >
+ <Text style={[styles.message, { color: colors.textSecondary }]}>{message}</Text>
+ <View style={styles.rows}>
+ {EXPORT_FORMAT_KEYS.map((key, i) => (
+ <React.Fragment key={key}>
+ {i > 0 && <Divider tight />}
+ <ListItem
+ label={EXPORT_FORMATS[key].label}
+ sub={EXPORT_FORMATS[key].description}
+ trailingIcon={Upload}
+ onPress={() => onSelect(key)}
+ testID={`export-${key}`}
+ />
+ </React.Fragment>
+ ))}
+ </View>
+ </DialogShell>
+ )
+}
+
+const styles = StyleSheet.create({
+ message: {
+ fontSize: fontSizes.body,
+ lineHeight: lineHeights.body,
+ ...fonts.regular,
+ marginBottom: space.sm
+ },
+ // A row cancels a card's lg inset; the dialog pads xl, so the rows step out the remaining sm to reach its edge.
+ rows: {
+ marginHorizontal: -space.sm
+ }
+})
diff --git a/apps/mobile/src/components/ui/FieldMessage.tsx b/apps/mobile/src/components/ui/FieldMessage.tsx
index b380ca77..b17ee583 100644
--- a/apps/mobile/src/components/ui/FieldMessage.tsx
+++ b/apps/mobile/src/components/ui/FieldMessage.tsx
@@ -6,7 +6,8 @@
import React from "react"
import { Text, StyleSheet, StyleProp, TextStyle } from "react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
+import { space } from "../../constants"
type FieldMessageVariant = "info" | "warning" | "error"
@@ -25,8 +26,8 @@ export function FieldMessage({ children, variant = "info", style }: FieldMessage
const styles = StyleSheet.create({
message: {
- fontSize: 12,
- marginTop: 6,
+ fontSize: fontSizes.caption,
+ marginTop: space.sm,
...fonts.medium
}
})
diff --git a/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx b/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx
index 1f3535a9..22dc1fce 100644
--- a/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx
+++ b/apps/mobile/src/components/ui/FloatingSaveIndicator.tsx
@@ -3,29 +3,29 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import type { ThemeColors } from "../../types/global"
import React, { useEffect, useRef } from "react"
+import { radius } from "@colota/shared"
import { View, Text, StyleSheet, Animated } from "react-native"
-import { Check } from "lucide-react-native"
+import { Check, CircleAlert } from "lucide-react-native"
import { SpinningLoader } from "./SpinningLoader"
-import { fonts } from "../../styles/typography"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space, elevation } from "../../constants"
interface Props {
+ success?: boolean
+ colors?: ThemeColors
saving: boolean
- success: boolean
- /** Optional custom message. When provided, controls visibility instead of saving/success. */
+ /** Shown once the work is done; absent when there is nothing to report. */
message?: string | null
isError?: boolean
- colors: {
- info: string
- success: string
- error: string
- text: string
- }
}
-export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, message, isError, colors }) => {
+export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, message, isError }) => {
+ const { colors } = useTheme()
const hasMessage = message != null
- const visible = hasMessage || saving || success
+ const visible = hasMessage || saving || success === true
const translateY = useRef(new Animated.Value(60)).current
const opacity = useRef(new Animated.Value(0)).current
@@ -44,24 +44,22 @@ export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, messag
}
}, [visible, translateY, opacity])
- const displayText = hasMessage ? message : saving ? "Saving & restarting..." : "Saved"
+ const displayText = hasMessage ? message : saving ? "Saving..." : "Saved"
return (
- <Animated.View style={[styles.container, { opacity, transform: [{ translateY }] }]} pointerEvents="none">
- <View
- style={[
- styles.badge,
- {
- backgroundColor: saving ? colors.info : isError ? colors.error : colors.success,
- shadowColor: saving ? colors.info : isError ? colors.error : colors.success
- }
- ]}
- >
+ <Animated.View
+ style={[styles.container, { opacity, transform: [{ translateY }] }]}
+ pointerEvents="none"
+ testID="floating-save-indicator"
+ >
+ <View style={[styles.badge, { backgroundColor: colors.surfaceRaised }]} testID="floating-save-indicator-pill">
{saving ? (
- <SpinningLoader size={16} color={colors.text} />
- ) : !hasMessage ? (
- <Check size={16} color={colors.text} />
- ) : null}
+ <SpinningLoader size={size.icon.sm} color={colors.textSecondary} />
+ ) : isError ? (
+ <CircleAlert size={size.icon.sm} color={colors.error} />
+ ) : (
+ <Check size={size.icon.sm} color={colors.success} />
+ )}
<Text style={[styles.text, { color: colors.text }]}>{displayText}</Text>
</View>
</Animated.View>
@@ -71,24 +69,20 @@ export const FloatingSaveIndicator: React.FC<Props> = ({ saving, success, messag
const styles = StyleSheet.create({
container: {
position: "absolute",
- bottom: 20,
+ bottom: space.xl,
left: 0,
right: 0,
alignItems: "center",
- zIndex: 1000,
pointerEvents: "none"
},
badge: {
flexDirection: "row",
alignItems: "center",
- gap: 8,
- paddingHorizontal: 20,
- paddingVertical: 12,
- borderRadius: 24,
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.3,
- shadowRadius: 8,
- elevation: 8
+ gap: space.sm,
+ paddingHorizontal: space.xl,
+ paddingVertical: space.md,
+ borderRadius: radius.pill,
+ elevation: elevation.overlay
},
- text: { fontSize: 14, ...fonts.semiBold }
+ text: { fontSize: fontSizes.body, ...fonts.semiBold }
})
diff --git a/apps/mobile/src/components/ui/HeaderAction.tsx b/apps/mobile/src/components/ui/HeaderAction.tsx
new file mode 100644
index 00000000..c316b067
--- /dev/null
+++ b/apps/mobile/src/components/ui/HeaderAction.tsx
@@ -0,0 +1,52 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Pressable, StyleSheet } from "react-native"
+import { type LucideIcon } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { size, space, STATE_LAYER_ALPHA } from "../../constants"
+
+type HeaderActionProps = {
+ icon: LucideIcon
+ /** Required: the glyph carries no text, so nothing else names this control. */
+ label: string
+ hint?: string
+ /** The glyph colour; `text` unless the action is destructive or explains itself when pressed. */
+ color?: string
+ disabled?: boolean
+ onPress: () => void
+ testID?: string
+}
+
+/** An icon-only action for the app bar: a 24 glyph inside 12 of padding, so the 48 target sits on the grid. */
+export function HeaderAction({ icon: Icon, label, hint, color, disabled = false, onPress, testID }: HeaderActionProps) {
+ const { colors } = useTheme()
+ const tint = disabled ? colors.textDisabled : (color ?? colors.text)
+
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={label}
+ accessibilityHint={hint}
+ accessibilityState={{ disabled }}
+ disabled={disabled}
+ onPress={onPress}
+ android_ripple={
+ disabled ? undefined : { color: colors.text + STATE_LAYER_ALPHA, borderless: true, radius: size.touch / 2 }
+ }
+ style={styles.action}
+ testID={testID}
+ >
+ <Icon size={size.icon.lg} color={tint} />
+ </Pressable>
+ )
+}
+
+const styles = StyleSheet.create({
+ action: {
+ padding: space.md
+ }
+})
diff --git a/apps/mobile/src/components/ui/IconButton.tsx b/apps/mobile/src/components/ui/IconButton.tsx
new file mode 100644
index 00000000..8f8043f5
--- /dev/null
+++ b/apps/mobile/src/components/ui/IconButton.tsx
@@ -0,0 +1,76 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Pressable, ActivityIndicator, StyleSheet, StyleProp, ViewStyle } from "react-native"
+import { type LucideIcon } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { size, space, HIT_SLOP_MD, STATE_LAYER_ALPHA } from "../../constants"
+import { radius } from "@colota/shared"
+
+type IconButtonTone = "neutral" | "primary" | "danger"
+
+type IconButtonProps = {
+ icon: LucideIcon
+ onPress: () => void
+ /** Required: the glyph carries no text, so nothing else names this control. */
+ accessibilityLabel: string
+ tone?: IconButtonTone
+ disabled?: boolean
+ loading?: boolean
+ style?: StyleProp<ViewStyle>
+ testID?: string
+}
+
+/**
+ * The disc stays at size.iconButton so it fits the rows it sits in; hitSlop takes the touch
+ * target to size.touch without reflowing them.
+ */
+export function IconButton({
+ icon: Icon,
+ onPress,
+ accessibilityLabel,
+ tone = "neutral",
+ disabled = false,
+ loading = false,
+ style,
+ testID
+}: IconButtonProps) {
+ const { colors } = useTheme()
+ const hue = tone === "danger" ? colors.error : tone === "primary" ? colors.primary : colors.textSecondary
+ const fill = tone === "neutral" ? colors.well : hue + "15"
+ const content = disabled ? colors.textDisabled : hue
+
+ return (
+ <Pressable
+ testID={testID}
+ onPress={onPress}
+ disabled={disabled || loading}
+ hitSlop={HIT_SLOP_MD}
+ accessibilityRole="button"
+ accessibilityLabel={accessibilityLabel}
+ accessibilityState={{ disabled: disabled || loading }}
+ android_ripple={
+ disabled || loading
+ ? undefined
+ : { color: content + STATE_LAYER_ALPHA, borderless: true, radius: size.touch / 2 }
+ }
+ style={[styles.button, { backgroundColor: fill }, style]}
+ >
+ {loading ? <ActivityIndicator size="small" color={content} /> : <Icon size={size.icon.sm} color={content} />}
+ </Pressable>
+ )
+}
+
+const styles = StyleSheet.create({
+ button: {
+ width: size.iconButton,
+ height: size.iconButton,
+ borderRadius: radius.lg,
+ alignItems: "center",
+ justifyContent: "center",
+ padding: space.xs
+ }
+})
diff --git a/apps/mobile/src/components/ui/ListItem.tsx b/apps/mobile/src/components/ui/ListItem.tsx
index 4cd41024..d1839161 100644
--- a/apps/mobile/src/components/ui/ListItem.tsx
+++ b/apps/mobile/src/components/ui/ListItem.tsx
@@ -7,7 +7,8 @@ import React from "react"
import { Text, StyleSheet, View, Pressable } from "react-native"
import { ChevronRight } from "lucide-react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space, STATE_LAYER_ALPHA } from "../../constants"
type IconComponent = React.ComponentType<{ size?: number; color?: string; strokeWidth?: number }>
@@ -15,73 +16,125 @@ type ListItemProps = {
label: string
sub?: string
icon?: IconComponent
+ /** Tints the leading icon; the default is `textLight`, or `textDisabled` while disabled. */
+ iconColor?: string
trailingIcon?: IconComponent
+ /** A control of its own beside the body, behind a hairline: the row opens, the control allows. Replaces the chevron. */
+ trailing?: React.ReactNode
+ /** The sub wraps once when 2, for a row that must carry a full sentence beside a control. */
+ subLines?: 1 | 2
onPress: () => void
testID?: string
accessibilityRole?: "button" | "link"
accessibilityHint?: string
+ disabled?: boolean
+ expanded?: boolean
+}
+
+/** A link row says it leaves the app, so About and the map credits dialog inherit the wording. */
+function defaultHint(label: string, role: "button" | "link"): string {
+ return role === "link" ? `Opens ${label} in the browser` : `Opens ${label}`
}
export function ListItem({
label,
sub,
icon: Icon,
+ iconColor,
trailingIcon: TrailingIcon = ChevronRight,
+ trailing,
+ subLines = 1,
onPress,
testID,
accessibilityRole = "button",
- accessibilityHint
+ accessibilityHint,
+ disabled = false,
+ expanded
}: ListItemProps) {
const { colors } = useTheme()
- return (
+ const body = (
<Pressable
testID={testID}
accessibilityRole={accessibilityRole}
- accessibilityLabel={label}
- accessibilityHint={accessibilityHint ?? `Opens ${label}`}
- android_ripple={{ color: colors.border }}
+ accessibilityLabel={sub ? `${label}, ${sub}` : label}
+ accessibilityHint={accessibilityHint ?? defaultHint(label, accessibilityRole)}
+ accessibilityState={{ disabled, expanded }}
+ android_ripple={disabled ? undefined : { color: colors.text + STATE_LAYER_ALPHA }}
+ disabled={disabled}
onPress={onPress}
- style={({ pressed }) => [styles.row, pressed && { opacity: colors.pressedOpacity }]}
+ style={[styles.row, trailing !== undefined && styles.body]}
>
{Icon && (
<View style={styles.icon}>
- <Icon size={22} color={colors.textLight} />
+ <Icon size={size.icon.md} color={disabled ? colors.textDisabled : (iconColor ?? colors.textLight)} />
</View>
)}
<View style={styles.content}>
- <Text style={[styles.label, { color: colors.text }]}>{label}</Text>
+ <Text style={[styles.label, { color: disabled ? colors.textDisabled : colors.text }]}>{label}</Text>
{sub ? (
- <Text style={[styles.sub, { color: colors.textSecondary }]} numberOfLines={1}>
+ <Text
+ style={[styles.sub, { color: disabled ? colors.textDisabled : colors.textSecondary }]}
+ numberOfLines={subLines}
+ >
{sub}
</Text>
) : null}
</View>
- <TrailingIcon size={20} color={colors.textLight} />
+ {trailing === undefined && (
+ <TrailingIcon size={size.icon.md} color={disabled ? colors.textDisabled : colors.textLight} />
+ )}
</Pressable>
)
+ if (trailing === undefined) return body
+ return (
+ <View style={styles.split}>
+ {body}
+ <View style={[styles.rule, { backgroundColor: colors.divider }]} />
+ {trailing}
+ </View>
+ )
}
const styles = StyleSheet.create({
row: {
flexDirection: "row",
alignItems: "center",
- minHeight: 56,
- paddingVertical: 10
+ minHeight: size.row,
+ paddingVertical: space.lg,
+ marginHorizontal: -space.lg,
+ paddingHorizontal: space.lg
+ },
+ // The body keeps the row's inset on its start edge only; the control after the rule sits at the card's own inset.
+ split: {
+ flexDirection: "row",
+ alignItems: "center",
+ marginEnd: -space.lg,
+ paddingEnd: space.lg
+ },
+ body: {
+ flex: 1,
+ marginEnd: 0,
+ paddingEnd: 0
+ },
+ rule: {
+ width: StyleSheet.hairlineWidth,
+ height: size.iconButton,
+ marginHorizontal: space.md
},
icon: {
- marginRight: 16
+ marginEnd: space.lg
},
content: {
flex: 1,
- paddingRight: 8
+ paddingEnd: space.sm
},
label: {
- fontSize: 16,
+ fontSize: fontSizes.label,
...fonts.semiBold,
- marginBottom: 2
+ marginBottom: space.xxs
},
sub: {
- fontSize: 13,
+ fontSize: fontSizes.description,
...fonts.regular
}
})
diff --git a/apps/mobile/src/components/ui/LoadingOverlay.tsx b/apps/mobile/src/components/ui/LoadingOverlay.tsx
index 2f4181b3..eeef8e98 100644
--- a/apps/mobile/src/components/ui/LoadingOverlay.tsx
+++ b/apps/mobile/src/components/ui/LoadingOverlay.tsx
@@ -3,9 +3,11 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import { ActivityIndicator, StyleSheet, Text, View } from "react-native"
+import { ActivityIndicator, Modal, StyleSheet, Text, View } from "react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
+import { space, elevation } from "../../constants"
+import { radius } from "@colota/shared"
type Props = {
visible: boolean
@@ -17,45 +19,39 @@ export function LoadingOverlay({ visible, title, message }: Props) {
const { colors } = useTheme()
if (!visible) return null
return (
- <View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
- <View style={[styles.card, { backgroundColor: colors.card }]}>
- <ActivityIndicator size="large" color={colors.primary} />
- <Text style={[styles.title, { color: colors.text }]}>{title}</Text>
- {message ? <Text style={[styles.message, { color: colors.textSecondary }]}>{message}</Text> : null}
+ <Modal visible transparent animationType="fade" statusBarTranslucent>
+ <View style={[styles.overlay, { backgroundColor: colors.overlay }]}>
+ <View style={[styles.card, { backgroundColor: colors.card }]}>
+ <ActivityIndicator size="large" color={colors.primary} />
+ <Text style={[styles.title, { color: colors.text }]}>{title}</Text>
+ {message ? <Text style={[styles.message, { color: colors.textSecondary }]}>{message}</Text> : null}
+ </View>
</View>
- </View>
+ </Modal>
)
}
const styles = StyleSheet.create({
overlay: {
- position: "absolute",
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- zIndex: 999,
+ flex: 1,
justifyContent: "center",
alignItems: "center"
},
card: {
- padding: 32,
- borderRadius: 16,
+ padding: space.xxl,
+ borderRadius: radius.lg,
alignItems: "center",
- shadowOffset: { width: 0, height: 4 },
- shadowOpacity: 0.3,
- shadowRadius: 8,
- elevation: 8,
+ elevation: elevation.overlay,
minWidth: 240
},
title: {
- fontSize: 16,
+ fontSize: fontSizes.label,
...fonts.semiBold,
- marginTop: 16,
- marginBottom: 8
+ marginTop: space.lg,
+ marginBottom: space.sm
},
message: {
- fontSize: 13,
+ fontSize: fontSizes.description,
textAlign: "center"
}
})
diff --git a/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx b/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx
index 37aa6cfb..d58b6a35 100644
--- a/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx
+++ b/apps/mobile/src/components/ui/LocalNetworkDisclosureModal.tsx
@@ -5,6 +5,7 @@
import React from "react"
import { Wifi } from "lucide-react-native"
+import { size } from "../../constants"
import { useTheme } from "../../hooks/useTheme"
import { registerLocalNetworkDisclosureCallback } from "../../services/LocationServicePermission"
import { DisclosureModal } from "./DisclosureModal"
@@ -18,8 +19,8 @@ export function LocalNetworkDisclosureModal() {
return (
<DisclosureModal
- icon={<Wifi size={28} color={colors.primary} />}
- title="Local Network Access"
+ icon={<Wifi size={size.icon.lg} color={colors.primary} />}
+ title="Local network access"
paragraphs={[
"Your server is on the local network. Colota needs local network access permission to reach it.",
"This permission is only used to connect to your self-hosted server. No device scanning or discovery is performed."
diff --git a/apps/mobile/src/components/ui/LocationDisclosureModal.tsx b/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
index 72da760c..a0d4bd88 100644
--- a/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
+++ b/apps/mobile/src/components/ui/LocationDisclosureModal.tsx
@@ -5,6 +5,7 @@
import React from "react"
import { MapPin } from "lucide-react-native"
+import { size } from "../../constants"
import { useTheme } from "../../hooks/useTheme"
import { registerDisclosureCallback } from "../../services/LocationServicePermission"
import { DisclosureModal } from "./DisclosureModal"
@@ -18,8 +19,8 @@ export function LocationDisclosureModal() {
return (
<DisclosureModal
- icon={<MapPin size={28} color={colors.primary} />}
- title="Location Data Collection"
+ icon={<MapPin size={size.icon.lg} color={colors.primary} />}
+ title="Location data collection"
paragraphs={[
"Colota collects location data to enable GPS tracking and sending your position to your configured server, even when the app is closed or not in use.",
"This data is sent only to the server you set up. No data is shared with third parties.",
diff --git a/apps/mobile/src/components/ui/MapDock.tsx b/apps/mobile/src/components/ui/MapDock.tsx
new file mode 100644
index 00000000..98c74717
--- /dev/null
+++ b/apps/mobile/src/components/ui/MapDock.tsx
@@ -0,0 +1,39 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { ScrollView, StyleSheet } from "react-native"
+import { space } from "../../constants"
+import { Card } from "./Card"
+
+type MapDockProps = {
+ maxHeight: number
+ children: React.ReactNode
+}
+
+/** The card that docks over a map's bottom edge: rows on the elevated surface, scrolling once it hits its cap. */
+export function MapDock({ maxHeight, children }: MapDockProps) {
+ return (
+ <Card variant="elevated" rows>
+ <ScrollView
+ style={[styles.scroll, { maxHeight }]}
+ contentContainerStyle={styles.scrollContent}
+ showsVerticalScrollIndicator={false}
+ >
+ {children}
+ </ScrollView>
+ </Card>
+ )
+}
+
+const styles = StyleSheet.create({
+ // The ScrollView clips, so it spans the card and insets its content or a row's ripple stops at the padding.
+ scroll: {
+ marginHorizontal: -space.lg
+ },
+ scrollContent: {
+ paddingHorizontal: space.lg
+ }
+})
diff --git a/apps/mobile/src/components/ui/NumericInput.tsx b/apps/mobile/src/components/ui/NumericInput.tsx
index 389cc700..b86071e7 100644
--- a/apps/mobile/src/components/ui/NumericInput.tsx
+++ b/apps/mobile/src/components/ui/NumericInput.tsx
@@ -3,12 +3,17 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import type { ThemeColors } from "../../types/global"
import React from "react"
-import { View, Text, StyleSheet, TextInput } from "react-native"
-import { ThemeColors } from "../../types/global"
-import { fonts } from "../../styles/typography"
+import { View, Text, StyleSheet } from "react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts, lineHeights } from "../../styles/typography"
+import { space } from "../../constants"
+import { TextField } from "./TextField"
+import { FieldMessage } from "./FieldMessage"
interface NumericInputProps {
+ colors?: ThemeColors
label: string
value: string
onChange: (value: string) => void
@@ -16,21 +21,17 @@ interface NumericInputProps {
unit: string
placeholder?: string
min?: number
- colors: ThemeColors
hint?: string
+ /** Shown under the box while the text would not be stored; the box takes the error ring. */
+ error?: string
+ /** A transient note under the box, such as the value a blur clamped to. */
+ message?: string
+ testID?: string
}
/**
- * NumericInput Component
- *
- * A validated numeric input field with:
- * - Label and optional hint text
- * - Unit display (e.g., "seconds", "meters")
- * - Numeric keyboard
- * - Change and blur handlers for validation
- * - Themed styling
- *
- * Used for interval, distance, and threshold inputs.
+ * A validated numeric field with its own label, an optional hint and a unit beside it. The
+ * label stays here rather than on the TextField because the unit sits in the same row.
*/
export function NumericInput({
label,
@@ -39,71 +40,63 @@ export function NumericInput({
onBlur,
unit,
placeholder = "0",
- colors,
- hint
+ hint,
+ error,
+ message,
+ testID
}: NumericInputProps) {
+ const { colors } = useTheme()
+
return (
<View style={styles.container}>
- {/* Label */}
- <Text style={[styles.label, { color: colors.text }]}>{label}</Text>
-
- {/* Hint (optional) */}
+ <Text style={[styles.label, { color: colors.textSecondary }]}>{label}</Text>
{hint && <Text style={[styles.hint, { color: colors.textSecondary }]}>{hint}</Text>}
- {/* Input Row */}
<View style={styles.inputRow}>
- <TextInput
- style={[
- styles.input,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.backgroundElevated
- }
- ]}
+ <TextField
+ accessibilityLabel={label}
+ testID={testID}
+ figure
+ style={styles.field}
keyboardType="numeric"
value={value}
onChangeText={onChange}
onBlur={onBlur}
placeholder={placeholder}
- placeholderTextColor={colors.placeholder}
+ error={error}
/>
<Text style={[styles.unit, { color: colors.textSecondary }]}>{unit}</Text>
</View>
+ {message ? <FieldMessage>{message}</FieldMessage> : null}
</View>
)
}
const styles = StyleSheet.create({
container: {
- marginBottom: 16
+ marginBottom: space.lg
},
label: {
- fontSize: 14,
- ...fonts.semiBold,
- marginBottom: 8
+ fontSize: fontSizes.description,
+ ...fonts.medium,
+ marginBottom: space.sm
},
hint: {
- fontSize: 13,
+ fontSize: fontSizes.description,
...fonts.regular,
- marginBottom: 12,
- lineHeight: 18
+ marginBottom: space.md,
+ lineHeight: lineHeights.description
},
inputRow: {
flexDirection: "row",
alignItems: "center",
- gap: 12
+ gap: space.md
},
- input: {
- flex: 1,
- borderWidth: 1,
- padding: 14,
- borderRadius: 12,
- fontSize: 15,
- textAlign: "center"
+ field: {
+ flex: 1
},
unit: {
- fontSize: 15,
+ fontSize: fontSizes.input,
...fonts.medium,
minWidth: 64
}
diff --git a/apps/mobile/src/components/ui/RadioDot.tsx b/apps/mobile/src/components/ui/RadioDot.tsx
index 8780777d..df8cf9dc 100644
--- a/apps/mobile/src/components/ui/RadioDot.tsx
+++ b/apps/mobile/src/components/ui/RadioDot.tsx
@@ -6,16 +6,18 @@
import React from "react"
import { View, StyleSheet } from "react-native"
import { useTheme } from "../../hooks/useTheme"
+import { radius } from "@colota/shared"
-export function RadioDot({ selected }: { selected: boolean }) {
+export function RadioDot({ selected, disabled = false }: { selected: boolean; disabled?: boolean }) {
const { colors } = useTheme()
+ const tint = disabled ? colors.textDisabled : colors.primary
return (
<View
- style={[styles.radio, { borderColor: selected ? colors.primary : colors.border }]}
+ style={[styles.radio, { borderColor: selected ? tint : colors.border }]}
importantForAccessibility="no"
accessibilityElementsHidden
>
- {selected && <View style={[styles.inner, { backgroundColor: colors.primary }]} />}
+ {selected && <View style={[styles.inner, { backgroundColor: tint }]} />}
</View>
)
}
@@ -24,7 +26,7 @@ const styles = StyleSheet.create({
radio: {
width: 24,
height: 24,
- borderRadius: 12,
+ borderRadius: radius.pill,
borderWidth: 2,
justifyContent: "center",
alignItems: "center"
@@ -32,6 +34,6 @@ const styles = StyleSheet.create({
inner: {
width: 12,
height: 12,
- borderRadius: 6
+ borderRadius: radius.pill
}
})
diff --git a/apps/mobile/src/components/ui/RadioRow.tsx b/apps/mobile/src/components/ui/RadioRow.tsx
new file mode 100644
index 00000000..658d08b4
--- /dev/null
+++ b/apps/mobile/src/components/ui/RadioRow.tsx
@@ -0,0 +1,77 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { View, Pressable, Text, StyleSheet } from "react-native"
+import { type LucideIcon } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space, STATE_LAYER_ALPHA } from "../../constants"
+import { RadioDot } from "./RadioDot"
+
+type RadioRowProps = {
+ label: string
+ selected: boolean
+ onPress: () => void
+ sub?: string
+ icon?: LucideIcon
+ disabled?: boolean
+ testID?: string
+}
+
+/**
+ * The whole row is the radio; RadioDot is decoration, which is why it is hidden from
+ * accessibility and the state lives here.
+ */
+export function RadioRow({ label, selected, onPress, sub, icon: Icon, disabled = false, testID }: RadioRowProps) {
+ const { colors } = useTheme()
+
+ return (
+ <Pressable
+ testID={testID}
+ onPress={onPress}
+ accessibilityRole="radio"
+ accessibilityState={{ checked: selected, disabled }}
+ accessibilityLabel={sub ? `${label}, ${sub}` : label}
+ android_ripple={disabled ? undefined : { color: colors.text + STATE_LAYER_ALPHA }}
+ disabled={disabled}
+ style={styles.row}
+ >
+ <RadioDot selected={selected} disabled={disabled} />
+ {Icon ? <Icon size={size.icon.md} color={disabled ? colors.textDisabled : colors.textSecondary} /> : null}
+ <View style={styles.text}>
+ <Text style={[styles.label, { color: disabled ? colors.textDisabled : colors.text }]}>{label}</Text>
+ {sub ? (
+ <Text style={[styles.sub, { color: disabled ? colors.textDisabled : colors.textSecondary }]}>{sub}</Text>
+ ) : null}
+ </View>
+ </Pressable>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.md,
+ minHeight: size.row,
+ paddingVertical: space.lg,
+ // See ListItem: the card's inset is cancelled and reapplied so a press fills its width.
+ marginHorizontal: -space.lg,
+ paddingHorizontal: space.lg
+ },
+ text: {
+ flex: 1
+ },
+ label: {
+ fontSize: fontSizes.input,
+ ...fonts.medium
+ },
+ sub: {
+ fontSize: fontSizes.description,
+ ...fonts.regular,
+ marginTop: space.xxs
+ }
+})
diff --git a/apps/mobile/src/components/ui/SectionTitle.tsx b/apps/mobile/src/components/ui/SectionTitle.tsx
index d1aa0ad8..6afd43c2 100644
--- a/apps/mobile/src/components/ui/SectionTitle.tsx
+++ b/apps/mobile/src/components/ui/SectionTitle.tsx
@@ -6,31 +6,30 @@
import React from "react"
import { View, StyleSheet, ViewStyle, StyleProp, Text } from "react-native"
import { useTheme } from "../../hooks/useTheme"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts } from "../../styles/typography"
+import { space } from "../../constants"
type SectionTitleProps = {
children: React.ReactNode
style?: StyleProp<ViewStyle>
- color?: string
}
-export function SectionTitle({ children, style, color }: SectionTitleProps) {
+export function SectionTitle({ children, style }: SectionTitleProps) {
const { colors } = useTheme()
return (
<View style={style}>
- <Text style={[styles.sectionTitle, { color: color ? color : colors.primary }]}>{children}</Text>
+ <Text accessibilityRole="header" style={[styles.sectionTitle, { color: colors.textSecondary }]}>
+ {children}
+ </Text>
</View>
)
}
const styles = StyleSheet.create({
sectionTitle: {
- fontSize: 11,
- textTransform: "uppercase",
- ...fonts.bold,
- letterSpacing: 1.2,
- marginBottom: 12,
- paddingHorizontal: 4
+ fontSize: fontSizes.label,
+ ...fonts.semiBold,
+ marginBottom: space.md
}
})
diff --git a/apps/mobile/src/components/ui/SettingRow.tsx b/apps/mobile/src/components/ui/SettingRow.tsx
index 8a88574f..d96cac35 100644
--- a/apps/mobile/src/components/ui/SettingRow.tsx
+++ b/apps/mobile/src/components/ui/SettingRow.tsx
@@ -5,23 +5,29 @@
import React from "react"
import { View, Text, StyleSheet, type StyleProp, type ViewStyle } from "react-native"
-import { fonts } from "../../styles/typography"
+import { fontSizes, fonts, lineHeights } from "../../styles/typography"
import { useTheme } from "../../hooks/useTheme"
+import { space, size } from "../../constants"
interface SettingRowProps {
label: string
hint?: string
children: React.ReactNode
style?: StyleProp<ViewStyle>
+ disabled?: boolean
}
-export function SettingRow({ label, hint, children, style }: SettingRowProps) {
+export function SettingRow({ label, hint, children, style, disabled = false }: SettingRowProps) {
const { colors } = useTheme()
return (
<View style={[styles.settingRow, style]}>
<View style={styles.settingContent}>
- <Text style={[styles.settingLabel, { color: colors.text }]}>{label}</Text>
- {hint && <Text style={[styles.settingHint, { color: colors.textSecondary }]}>{hint}</Text>}
+ <Text style={[styles.settingLabel, { color: disabled ? colors.textDisabled : colors.text }]}>{label}</Text>
+ {hint && (
+ <Text style={[styles.settingHint, { color: disabled ? colors.textDisabled : colors.textSecondary }]}>
+ {hint}
+ </Text>
+ )}
</View>
{children}
</View>
@@ -33,20 +39,24 @@ const styles = StyleSheet.create({
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
- paddingVertical: 4
+ minHeight: size.row,
+ paddingVertical: space.lg,
+ // See ListItem: the inset is cancelled and reapplied so a press fills the card's width.
+ marginHorizontal: -space.lg,
+ paddingHorizontal: space.lg
},
settingContent: {
flex: 1,
- marginRight: 16
+ marginEnd: space.lg
},
settingLabel: {
- fontSize: 16,
+ fontSize: fontSizes.label,
...fonts.semiBold,
- marginBottom: 2
+ marginBottom: space.xxs
},
settingHint: {
- fontSize: 13,
+ fontSize: fontSizes.description,
...fonts.regular,
- lineHeight: 18
+ lineHeight: lineHeights.description
}
})
diff --git a/apps/mobile/src/components/ui/StatRow.tsx b/apps/mobile/src/components/ui/StatRow.tsx
new file mode 100644
index 00000000..318d12ca
--- /dev/null
+++ b/apps/mobile/src/components/ui/StatRow.tsx
@@ -0,0 +1,84 @@
+/**
+ * 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 { type LucideIcon } from "lucide-react-native"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space } from "../../constants"
+
+type StatRowProps = {
+ /** A glyph is recognised before the label is read, which is what a column of numbers loses. */
+ icon?: LucideIcon
+ label: string
+ value: string
+ /** A trailing glyph or control. The value keeps its own place to the left of it. */
+ children?: React.ReactNode
+ testID?: string
+}
+
+/**
+ * A label and the number it names, on one line. Four screens drew this by hand with four
+ * different type steps; the value is tabular so a figure that updates does not jitter.
+ */
+export function StatRow({ icon: Icon, label, value, children, testID }: StatRowProps) {
+ const { colors } = useTheme()
+
+ return (
+ <View style={styles.row} testID={testID} accessibilityRole="text" accessibilityLabel={`${label}, ${value}`}>
+ <View style={styles.leading}>
+ {Icon && (
+ <View style={styles.icon}>
+ <Icon size={size.icon.sm} color={colors.textLight} />
+ </View>
+ )}
+ <Text style={[styles.label, { color: colors.textSecondary }]}>{label}</Text>
+ </View>
+ <View style={styles.trailing}>
+ <Text numberOfLines={1} style={[styles.value, { color: colors.text }]}>
+ {value}
+ </Text>
+ {children}
+ </View>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "center",
+ paddingVertical: space.sm
+ },
+ leading: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.lg
+ },
+ icon: {
+ width: size.icon.md,
+ alignItems: "center"
+ },
+ label: {
+ fontSize: fontSizes.body,
+ ...fonts.regular
+ },
+ trailing: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.sm,
+ flexShrink: 1,
+ minWidth: 0
+ },
+ value: {
+ fontSize: fontSizes.label,
+ ...fonts.medium,
+ fontVariant: ["tabular-nums"],
+ flexShrink: 1,
+ textAlign: "right"
+ }
+})
diff --git a/apps/mobile/src/components/ui/StateLine.tsx b/apps/mobile/src/components/ui/StateLine.tsx
new file mode 100644
index 00000000..ad05ef53
--- /dev/null
+++ b/apps/mobile/src/components/ui/StateLine.tsx
@@ -0,0 +1,68 @@
+/**
+ * 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 { type LucideIcon } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts, lineHeights } from "../../styles/typography"
+import { size, space } from "../../constants"
+
+type StateLineProps = {
+ icon: LucideIcon | React.ReactNode
+ iconColor: string
+ label: string
+ caption: string
+ testID?: string
+}
+
+export function StateLine({ icon, iconColor, label, caption, testID }: StateLineProps) {
+ const { colors } = useTheme()
+ const Icon = icon as LucideIcon
+
+ return (
+ <View style={styles.row} testID={testID} accessibilityRole="text" accessibilityLabel={`${label}, ${caption}`}>
+ <View style={styles.glyph}>
+ {React.isValidElement(icon) ? icon : <Icon size={size.icon.md} color={iconColor} />}
+ </View>
+ <View style={styles.column}>
+ <Text style={[styles.label, { color: colors.text }]} numberOfLines={1}>
+ {label}
+ </Text>
+ <Text style={[styles.caption, { color: colors.textSecondary }]} numberOfLines={1}>
+ {caption}
+ </Text>
+ </View>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.lg,
+ paddingVertical: space.md,
+ minHeight: size.row
+ },
+ glyph: {
+ width: size.icon.md,
+ alignItems: "center"
+ },
+ column: {
+ flex: 1
+ },
+ label: {
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
+ },
+ caption: {
+ fontSize: fontSizes.caption,
+ lineHeight: lineHeights.caption,
+ ...fonts.regular,
+ fontVariant: ["tabular-nums"],
+ marginTop: space.xxs
+ }
+})
diff --git a/apps/mobile/src/components/ui/StepperHeader.tsx b/apps/mobile/src/components/ui/StepperHeader.tsx
new file mode 100644
index 00000000..b8bd2abb
--- /dev/null
+++ b/apps/mobile/src/components/ui/StepperHeader.tsx
@@ -0,0 +1,161 @@
+/**
+ * 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, Pressable, StyleSheet } from "react-native"
+import { ChevronLeft, ChevronRight, ChevronDown } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts, lineHeights } from "../../styles/typography"
+import { size, space, STATE_LAYER_ALPHA } from "../../constants"
+
+type StepperHeaderProps = {
+ title: string
+ caption: string
+ /** A mark before the title, such as a trip's swatch. */
+ leading?: React.ReactNode
+ onPrevious: () => void
+ onNext: () => void
+ previousLabel: string
+ nextLabel: string
+ previousDisabled?: boolean
+ nextDisabled?: boolean
+ /** Makes the title a button, with a chevron saying it opens something. */
+ onPress?: () => void
+ accessibilityLabel?: string
+ accessibilityHint?: string
+ testID: string
+}
+
+/**
+ * The History family's spine: what you are looking at between two chevrons that step it, with one
+ * caption saying what it holds. A day, a trip or a period.
+ */
+export function StepperHeader({
+ title,
+ caption,
+ leading,
+ onPrevious,
+ onNext,
+ previousLabel,
+ nextLabel,
+ previousDisabled = false,
+ nextDisabled = false,
+ onPress,
+ accessibilityLabel,
+ accessibilityHint,
+ testID
+}: StepperHeaderProps) {
+ const { colors } = useTheme()
+ const ripple = { color: colors.text + STATE_LAYER_ALPHA }
+ const chevronRipple = { ...ripple, borderless: true, radius: size.touch / 2 }
+
+ const centre = (
+ <>
+ <View style={styles.titleRow}>
+ {leading}
+ <Text style={[styles.title, { color: colors.text }]} numberOfLines={1}>
+ {title}
+ </Text>
+ {onPress && <ChevronDown size={size.icon.sm} color={colors.textSecondary} />}
+ </View>
+ <Text style={[styles.caption, { color: colors.textSecondary }]} numberOfLines={2}>
+ {caption}
+ </Text>
+ </>
+ )
+
+ return (
+ <View style={[styles.row, { backgroundColor: colors.background }]} testID={`${testID}-header`}>
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={previousLabel}
+ accessibilityState={{ disabled: previousDisabled }}
+ disabled={previousDisabled}
+ onPress={onPrevious}
+ android_ripple={previousDisabled ? undefined : chevronRipple}
+ style={styles.chevron}
+ testID={`${testID}-previous`}
+ >
+ <ChevronLeft size={size.icon.md} color={previousDisabled ? colors.textDisabled : colors.text} />
+ </Pressable>
+
+ {onPress ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={accessibilityLabel ?? `${title}, ${caption}`}
+ accessibilityHint={accessibilityHint}
+ onPress={onPress}
+ android_ripple={ripple}
+ style={styles.centre}
+ testID={`${testID}-title`}
+ >
+ {centre}
+ </Pressable>
+ ) : (
+ <View
+ accessibilityRole="header"
+ accessibilityLabel={accessibilityLabel ?? `${title}, ${caption}`}
+ style={styles.centre}
+ testID={`${testID}-title`}
+ >
+ {centre}
+ </View>
+ )}
+
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={nextLabel}
+ accessibilityState={{ disabled: nextDisabled }}
+ disabled={nextDisabled}
+ onPress={onNext}
+ android_ripple={nextDisabled ? undefined : chevronRipple}
+ style={styles.chevron}
+ testID={`${testID}-next`}
+ >
+ <ChevronRight size={size.icon.md} color={nextDisabled ? colors.textDisabled : colors.text} />
+ </Pressable>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({
+ row: {
+ flexDirection: "row",
+ alignItems: "center",
+ minHeight: size.row,
+ paddingHorizontal: space.sm,
+ paddingVertical: space.xs
+ },
+ chevron: {
+ width: size.touch,
+ minHeight: size.touch,
+ alignSelf: "stretch",
+ justifyContent: "center",
+ alignItems: "center"
+ },
+ centre: {
+ flex: 1,
+ minHeight: size.touch,
+ alignItems: "center",
+ justifyContent: "center",
+ paddingHorizontal: space.sm
+ },
+ titleRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.xs
+ },
+ title: {
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
+ },
+ caption: {
+ fontSize: fontSizes.caption,
+ lineHeight: lineHeights.caption,
+ ...fonts.regular,
+ fontVariant: ["tabular-nums"],
+ marginTop: space.xxs
+ }
+})
diff --git a/apps/mobile/src/components/ui/Tab.tsx b/apps/mobile/src/components/ui/Tab.tsx
index 403dbc1a..2368ca8a 100644
--- a/apps/mobile/src/components/ui/Tab.tsx
+++ b/apps/mobile/src/components/ui/Tab.tsx
@@ -4,9 +4,11 @@
*/
import React from "react"
-import { Pressable, Text, StyleSheet } from "react-native"
-import { fonts } from "../../styles/typography"
+import { Pressable, Text, View, StyleSheet } from "react-native"
+import { fontSizes, fonts } from "../../styles/typography"
import { ThemeColors } from "../../types/global"
+import { size, space, STATE_LAYER_ALPHA } from "../../constants"
+import { radius } from "@colota/shared"
interface TabProps {
label: string
@@ -17,15 +19,20 @@ interface TabProps {
export function Tab({ label, active, onPress, colors }: TabProps) {
const borderBottomColor = active ? colors.primary : "transparent"
- const textColor = active ? colors.primary : colors.textSecondary
+ const textColor = active ? colors.text : colors.textSecondary
return (
<Pressable
onPress={onPress}
- style={({ pressed }) => [styles.tab, { borderBottomColor }, pressed && { opacity: colors.pressedOpacity }]}
+ accessibilityRole="tab"
+ accessibilityState={{ selected: active }}
+ android_ripple={{ color: colors.text + STATE_LAYER_ALPHA }}
+ style={styles.tab}
>
- <Text style={[styles.tabText, active ? styles.tabTextActive : styles.tabTextInactive, { color: textColor }]}>
- {label}
- </Text>
+ <View style={[styles.indicator, { borderBottomColor }]}>
+ <Text style={[styles.label, active ? styles.labelActive : styles.labelInactive, { color: textColor }]}>
+ {label}
+ </Text>
+ </View>
</Pressable>
)
}
@@ -33,17 +40,24 @@ export function Tab({ label, active, onPress, colors }: TabProps) {
const styles = StyleSheet.create({
tab: {
flex: 1,
+ minHeight: size.touch,
alignItems: "center",
- padding: 12,
- borderBottomWidth: 2
+ justifyContent: "center",
+ padding: space.md
},
- tabText: {
- fontSize: 14
+ indicator: {
+ paddingHorizontal: space.xs,
+ borderBottomWidth: 2,
+ borderTopLeftRadius: radius.xs,
+ borderTopRightRadius: radius.xs
},
- tabTextActive: {
+ label: {
+ fontSize: fontSizes.body
+ },
+ labelActive: {
...fonts.bold
},
- tabTextInactive: {
+ labelInactive: {
...fonts.regular
}
})
diff --git a/apps/mobile/src/components/ui/TextField.tsx b/apps/mobile/src/components/ui/TextField.tsx
new file mode 100644
index 00000000..63531ebd
--- /dev/null
+++ b/apps/mobile/src/components/ui/TextField.tsx
@@ -0,0 +1,174 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { forwardRef, useState } from "react"
+import { View, Text, TextInput, Pressable, StyleSheet, StyleProp, ViewStyle } from "react-native"
+import type { TextInputProps, TextInputInstance } from "react-native"
+import { Eye, EyeOff, CircleAlert } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts } from "../../styles/typography"
+import { size, space, HIT_SLOP_MD } from "../../constants"
+import { radius } from "@colota/shared"
+import { FieldMessage } from "./FieldMessage"
+
+/**
+ * Distance from the outer edge to the text. The resting field has no border, only a fill; the
+ * ring appears on focus and on error, so the padding shrinks by the same amount it grows or
+ * the text jumps sideways as you tap in.
+ */
+const FIELD_INSET = 15
+
+/** The three-line box a pasted token or note needs, which one touch target does not give it. */
+const MULTILINE_MIN_HEIGHT = 80
+
+type BaseProps = Omit<TextInputProps, "style" | "editable" | "secureTextEntry"> & {
+ error?: string | boolean
+ disabled?: boolean
+ secure?: boolean
+ mono?: boolean
+ border?: boolean
+ figure?: boolean
+ style?: StyleProp<ViewStyle>
+ testID?: string
+}
+
+type TextFieldProps = BaseProps &
+ ({ label: string; accessibilityLabel?: string } | { label?: undefined; accessibilityLabel: string })
+
+export const TextField = forwardRef<TextInputInstance, TextFieldProps>(function TextFieldInput(
+ {
+ label,
+ accessibilityLabel,
+ error,
+ disabled = false,
+ secure = false,
+ mono = false,
+ border = false,
+ figure = false,
+ style,
+ testID,
+ onFocus,
+ onBlur,
+ multiline = false,
+ ...inputProps
+ },
+ ref
+) {
+ const { colors } = useTheme()
+ const [focused, setFocused] = useState(false)
+ const [revealed, setRevealed] = useState(false)
+
+ const name = label ?? accessibilityLabel ?? ""
+ const borderWidth = error || (focused && !disabled) ? 2 : border ? 1 : 0
+ const borderColor = error ? colors.error : focused && !disabled ? colors.primary : colors.border
+ const RevealIcon = revealed ? EyeOff : Eye
+ const labelColor = disabled ? colors.textDisabled : focused ? colors.primary : colors.textSecondary
+
+ return (
+ <View style={style}>
+ {label ? <Text style={[styles.label, { color: labelColor }]}>{label}</Text> : null}
+ <View
+ testID={testID ? `${testID}-box` : undefined}
+ style={[
+ styles.box,
+ multiline && styles.boxMultiline,
+ {
+ borderWidth,
+ borderColor,
+ paddingHorizontal: FIELD_INSET - borderWidth,
+ backgroundColor: colors.well
+ }
+ ]}
+ >
+ <TextInput
+ ref={ref}
+ testID={testID}
+ editable={!disabled}
+ secureTextEntry={secure && !revealed}
+ accessibilityLabel={typeof error === "string" ? `${name}, ${error}` : name}
+ placeholderTextColor={colors.textLight}
+ onFocus={(e) => {
+ setFocused(true)
+ onFocus?.(e)
+ }}
+ onBlur={(e) => {
+ setFocused(false)
+ onBlur?.(e)
+ }}
+ multiline={multiline}
+ numberOfLines={multiline ? undefined : 1}
+ style={[
+ styles.input,
+ mono && styles.mono,
+ figure && styles.figure,
+ multiline && styles.multiline,
+ { color: disabled ? colors.textDisabled : colors.text }
+ ]}
+ {...inputProps}
+ />
+ {secure ? (
+ <Pressable
+ testID={testID ? `${testID}-reveal` : undefined}
+ onPressIn={() => setRevealed(true)}
+ onPressOut={() => setRevealed(false)}
+ disabled={disabled}
+ hitSlop={HIT_SLOP_MD}
+ accessibilityRole="button"
+ accessibilityLabel={`Hold to show ${name}`}
+ >
+ <RevealIcon size={size.icon.md} color={disabled ? colors.textDisabled : colors.textSecondary} />
+ </Pressable>
+ ) : error ? (
+ <CircleAlert
+ size={size.icon.md}
+ color={colors.error}
+ accessibilityElementsHidden
+ importantForAccessibility="no"
+ />
+ ) : null}
+ </View>
+ {typeof error === "string" ? <FieldMessage variant="error">{error}</FieldMessage> : null}
+ </View>
+ )
+})
+
+const styles = StyleSheet.create({
+ label: {
+ fontSize: fontSizes.description,
+ ...fonts.medium,
+ marginBottom: space.sm
+ },
+ box: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: space.sm,
+ minHeight: size.touch,
+ borderRadius: radius.sm
+ },
+ input: {
+ flex: 1,
+ paddingVertical: 0,
+ paddingHorizontal: 0,
+ textAlignVertical: "center",
+ fontSize: fontSizes.input,
+ ...fonts.regular
+ },
+ mono: {
+ fontFamily: "monospace"
+ },
+ figure: {
+ textAlign: "center",
+ ...fonts.medium,
+ fontVariant: ["tabular-nums"]
+ },
+ boxMultiline: {
+ alignItems: "flex-start",
+ minHeight: MULTILINE_MIN_HEIGHT,
+ paddingVertical: space.md
+ },
+ multiline: {
+ textAlignVertical: "top"
+ }
+})
diff --git a/apps/mobile/src/components/ui/TimePicker.tsx b/apps/mobile/src/components/ui/TimePicker.tsx
index 31e387a6..7a86274d 100644
--- a/apps/mobile/src/components/ui/TimePicker.tsx
+++ b/apps/mobile/src/components/ui/TimePicker.tsx
@@ -3,16 +3,20 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
+import type { ThemeColors } from "../../types/global"
import React, { useCallback, useEffect, useMemo, useState } from "react"
-import { View, Text, TextInput, StyleSheet } from "react-native"
-import { ThemeColors } from "../../types/global"
-import { fonts } from "../../styles/typography"
+import { View, Text, StyleSheet } from "react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fontSizes, fonts } from "../../styles/typography"
import { clamp, pad2 } from "../../utils/format"
+import { space } from "../../constants"
+import { TextField } from "./TextField"
interface TimePickerProps {
+ colors?: ThemeColors
+ label?: string
value: string
onChange: (value: string) => void
- colors: ThemeColors
}
const HOUR_MIN = 0
@@ -30,7 +34,8 @@ function format(h: number, m: number): string {
return `${pad2(h)}:${pad2(m)}`
}
-export function TimePicker({ value, onChange, colors }: TimePickerProps) {
+export function TimePicker({ label, value, onChange }: TimePickerProps) {
+ const { colors } = useTheme()
const { h, m } = useMemo(() => parse(value), [value])
const [hourText, setHourText] = useState(pad2(h))
@@ -61,60 +66,57 @@ export function TimePicker({ value, onChange, colors }: TimePickerProps) {
}, [minuteText, h, m, onChange])
return (
- <View style={styles.row}>
- <TextInput
- testID="timepicker-hour-value"
- accessibilityLabel="Hours"
- value={hourText}
- onChangeText={onHourChange}
- onBlur={commitHour}
- keyboardType="number-pad"
- maxLength={2}
- selectTextOnFocus
- style={[
- styles.input,
- { borderColor: colors.border, backgroundColor: colors.backgroundElevated, color: colors.text }
- ]}
- />
- <Text style={[styles.separator, { color: colors.text }]}>:</Text>
- <TextInput
- testID="timepicker-minute-value"
- accessibilityLabel="Minutes"
- value={minuteText}
- onChangeText={onMinuteChange}
- onBlur={commitMinute}
- keyboardType="number-pad"
- maxLength={2}
- selectTextOnFocus
- style={[
- styles.input,
- { borderColor: colors.border, backgroundColor: colors.backgroundElevated, color: colors.text }
- ]}
- />
+ <View>
+ <Text style={[styles.label, { color: colors.textSecondary }]}>{label}</Text>
+ <View style={styles.row}>
+ <TextField
+ testID="timepicker-hour-value"
+ accessibilityLabel={`${label}, hours`}
+ figure
+ style={styles.field}
+ value={hourText}
+ onChangeText={onHourChange}
+ onBlur={commitHour}
+ keyboardType="number-pad"
+ maxLength={2}
+ selectTextOnFocus
+ />
+ <Text style={[styles.separator, { color: colors.text }]}>:</Text>
+ <TextField
+ testID="timepicker-minute-value"
+ accessibilityLabel={`${label}, minutes`}
+ figure
+ style={styles.field}
+ value={minuteText}
+ onChangeText={onMinuteChange}
+ onBlur={commitMinute}
+ keyboardType="number-pad"
+ maxLength={2}
+ selectTextOnFocus
+ />
+ </View>
</View>
)
}
const styles = StyleSheet.create({
+ label: {
+ fontSize: fontSizes.description,
+ ...fonts.medium,
+ marginBottom: space.sm
+ },
row: {
flexDirection: "row",
alignItems: "center",
- gap: 8,
- paddingVertical: 4
+ gap: space.sm,
+ paddingVertical: space.xs
},
- input: {
- minWidth: 64,
- padding: 14,
- borderRadius: 12,
- borderWidth: 1,
- fontSize: 15,
- ...fonts.semiBold,
- fontVariant: ["tabular-nums"],
- textAlign: "center"
+ field: {
+ minWidth: 64
},
separator: {
- fontSize: 15,
+ fontSize: fontSizes.input,
...fonts.semiBold,
- paddingHorizontal: 2
+ paddingHorizontal: space.xxs
}
})
diff --git a/apps/mobile/src/components/ui/Toggle.tsx b/apps/mobile/src/components/ui/Toggle.tsx
new file mode 100644
index 00000000..2773991c
--- /dev/null
+++ b/apps/mobile/src/components/ui/Toggle.tsx
@@ -0,0 +1,37 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import { Switch } from "react-native"
+import { useTheme } from "../../hooks/useTheme"
+
+type ToggleProps = {
+ value: boolean
+ onValueChange: (value: boolean) => void
+ /** In the row's own visible words, so Voice Access can resolve it. */
+ accessibilityLabel: string
+ disabled?: boolean
+ testID?: string
+}
+
+/**
+ * The one switch. Thirteen call sites each built the same two colour objects by hand, so the
+ * track and thumb live here instead. Every switch takes the same hue: a semantic colour marks
+ * a state, and a toggle being on is not a warning.
+ */
+export function Toggle({ value, onValueChange, accessibilityLabel, disabled = false, testID }: ToggleProps) {
+ const { colors } = useTheme()
+ return (
+ <Switch
+ testID={testID}
+ value={value}
+ onValueChange={onValueChange}
+ disabled={disabled}
+ accessibilityLabel={accessibilityLabel}
+ trackColor={{ false: undefined, true: colors.primaryContainer }}
+ thumbColor={value ? colors.primary : undefined}
+ />
+ )
+}
diff --git a/apps/mobile/src/components/ui/TrackMark.tsx b/apps/mobile/src/components/ui/TrackMark.tsx
new file mode 100644
index 00000000..96a502fb
--- /dev/null
+++ b/apps/mobile/src/components/ui/TrackMark.tsx
@@ -0,0 +1,33 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React from "react"
+import Svg, { Circle, Path } from "react-native-svg"
+
+type TrackMarkProps = {
+ size?: number
+ color?: string
+ strokeWidth?: number
+}
+
+/**
+ * The app's mark on Lucide's 24 grid: a track that starts as a solid disc and ends as a ring, the
+ * same two terminals the map draws on every trip.
+ */
+export function TrackMark({ size = 24, color = "currentColor", strokeWidth = 1.5 }: TrackMarkProps) {
+ return (
+ <Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
+ <Path
+ d="M16 5.07 9.81 3.81 5.21 8.08 3.68 12 6.51 17.49 10.57 20.11 12.72 19.65"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ <Circle cx="16" cy="5.07" r="2" fill={color} />
+ <Circle cx="16" cy="18.93" r="2.4" stroke={color} strokeWidth={strokeWidth} />
+ </Svg>
+ )
+}
diff --git a/apps/mobile/src/components/ui/__tests__/AppModal.test.tsx b/apps/mobile/src/components/ui/__tests__/AppModal.test.tsx
new file mode 100644
index 00000000..d9a57258
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/AppModal.test.tsx
@@ -0,0 +1,79 @@
+import React from "react"
+import { render, act, fireEvent } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { lightColors } from "@colota/shared"
+
+jest.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
+}))
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { AppModal } from "../AppModal"
+import { showConfirm, showPrompt } from "../../../services/modalService"
+
+describe("AppModal", () => {
+ it("announces every choice as a button", async () => {
+ // The buttons were bare Pressables, so TalkBack read the words and said nothing about them
+ // being pressable. AppModal is every alert and confirm in the app, destructive ones included.
+ const { getByRole } = render(<AppModal />)
+
+ await act(async () => {
+ showConfirm({ title: "Delete all data", message: "This cannot be undone.", confirmText: "Delete" })
+ })
+
+ expect(getByRole("button", { name: "Delete" })).toBeTruthy()
+ expect(getByRole("button", { name: "Cancel" })).toBeTruthy()
+ })
+
+ it("paints a destructive confirm in the error colour", async () => {
+ // showConfirm renders the confirming button last, on the right, and marks it destructive, so
+ // the colour is what separates it from the dismissal beside it.
+ const { getByRole } = render(<AppModal />)
+
+ await act(async () => {
+ showConfirm({ title: "Delete zone", message: "This cannot be undone.", confirmText: "Delete", destructive: true })
+ })
+
+ const style = StyleSheet.flatten(getByRole("button", { name: "Delete" }).props.style)
+ expect(style.backgroundColor).toBe(lightColors.error)
+ })
+
+ it("asks for text through a field seeded with the current value and resolves the trimmed answer on confirm", async () => {
+ const { getByTestId, getByRole } = render(<AppModal />)
+
+ let answer: Promise<string | null> = Promise.resolve(null)
+ await act(async () => {
+ answer = showPrompt({
+ title: "Note",
+ initialValue: "Coffee stop",
+ placeholder: "Add a note",
+ cancelText: "Close"
+ })
+ })
+
+ expect(getByTestId("prompt-input").props.value).toBe("Coffee stop")
+ fireEvent.changeText(getByTestId("prompt-input"), " Lunch ")
+ await act(async () => {
+ fireEvent.press(getByRole("button", { name: "Save" }))
+ })
+
+ await expect(answer).resolves.toBe("Lunch")
+ })
+
+ it("resolves null when the prompt is dismissed, so a caller can tell a cleared note from a closed dialog", async () => {
+ const { getByRole } = render(<AppModal />)
+
+ let answer: Promise<string | null> = Promise.resolve("unset")
+ await act(async () => {
+ answer = showPrompt({ title: "Note", cancelText: "Close" })
+ })
+ await act(async () => {
+ fireEvent.press(getByRole("button", { name: "Close" }))
+ })
+
+ await expect(answer).resolves.toBeNull()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx b/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx
new file mode 100644
index 00000000..646bc240
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/BottomTabBar.test.tsx
@@ -0,0 +1,70 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+
+jest.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
+}))
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { lightColors } from "@colota/shared"
+import { BottomTabBar, TAB_ROUTES } from "../BottomTabBar"
+
+function renderBar(currentRoute: string | undefined) {
+ return render(<BottomTabBar currentRoute={currentRoute} onNavigate={jest.fn()} />)
+}
+
+describe("BottomTabBar", () => {
+ it("hides itself off the four tab routes, so a pushed screen is not framed as one", () => {
+ expect(renderBar("Connection").toJSON()).toBeNull()
+ expect(renderBar(undefined).toJSON()).toBeNull()
+ expect(renderBar("Dashboard").toJSON()).not.toBeNull()
+ })
+
+ it("marks the current tab selected, which is the whole announcement for a screen reader", () => {
+ // Without accessibilityRole tab and a selected state TalkBack reads four plain buttons and
+ // never says which screen you are on.
+ const { getByLabelText } = renderBar("Geofences")
+
+ expect(getByLabelText("Geofences").props.accessibilityRole).toBe("tab")
+ expect(getByLabelText("Geofences").props.accessibilityState.selected).toBe(true)
+ expect(getByLabelText("Dashboard").props.accessibilityState.selected).toBe(false)
+ })
+
+ it("weights the active glyph, because the icon set has no filled variants to switch to", () => {
+ const { getByLabelText } = renderBar("Dashboard")
+
+ const active = getByLabelText("Dashboard").findByProps({ strokeWidth: 2.25 })
+ expect(active).toBeTruthy()
+ expect(getByLabelText("Geofences").findAllByProps({ strokeWidth: 2.25 })).toHaveLength(0)
+ })
+
+ it("colours the active tab with the accent and the rest with secondary ink", () => {
+ const { getByText } = renderBar("Settings")
+
+ expect(getByText("Settings").props.style).toEqual(
+ expect.arrayContaining([expect.objectContaining({ color: lightColors.primary })])
+ )
+ expect(getByText("History").props.style).toEqual(
+ expect.arrayContaining([expect.objectContaining({ color: lightColors.textSecondary })])
+ )
+ })
+
+ it("lets a label wrap to two lines rather than truncate at a large font scale", () => {
+ const { getByText } = renderBar("Dashboard")
+ expect(getByText("Dashboard").props.numberOfLines).toBe(2)
+ })
+
+ it("exports the routes it covers, so App.tsx does not keep a second list", () => {
+ expect(TAB_ROUTES).toEqual(new Set(["Dashboard", "Location History", "Geofences", "Settings"]))
+ })
+
+ it("draws the History tab with the app's own mark, the track between a disc and a ring", () => {
+ const { getByLabelText } = renderBar("Dashboard")
+ const { TrackMark } = require("../TrackMark")
+
+ expect(getByLabelText("History").findByType(TrackMark)).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/Button.test.tsx b/apps/mobile/src/components/ui/__tests__/Button.test.tsx
new file mode 100644
index 00000000..043d927c
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/Button.test.tsx
@@ -0,0 +1,98 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet, Text } from "react-native"
+import { lightColors, radius } from "@colota/shared"
+import { elevation } from "../../../constants"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { Button } from "../Button"
+
+const flat = (el: any) => StyleSheet.flatten(el.props.style)
+
+describe("Button variants", () => {
+ it("fills a secondary rather than outlining it", () => {
+ // The two + Add controls were dashed boxes, which is the one border style the app had
+ // nowhere else. A fill keeps them reading as controls without inventing a stroke.
+ const { getByTestId } = render(
+ <Button title="+ Add Header" onPress={jest.fn()} variant="secondary" testID="add-btn" />
+ )
+
+ const style = flat(getByTestId("add-btn"))
+ expect(style.backgroundColor).toBe(lightColors.primaryContainer)
+ expect(style.borderWidth).toBeUndefined()
+ })
+
+ it("recedes when disabled instead of wearing an enabled label", () => {
+ // The fill itself went to textDisabled while the label stayed textOnPrimary, so Offline maps'
+ // disabled download button was white on grey and still read as a filled button you could press.
+ const { getByTestId } = render(<Button title="Download area" onPress={jest.fn()} disabled testID="download-btn" />)
+
+ expect(flat(getByTestId("download-btn")).backgroundColor).toBe(lightColors.well)
+ expect(StyleSheet.flatten(getByTestId("download-btn").findByType(Text).props.style).color).toBe(
+ lightColors.textDisabled
+ )
+ })
+
+ it("greys a disabled ghost without giving it a fill to recede into", () => {
+ // A ghost is transparent by role, so the recessed fill would draw it a box it never had.
+ const { getByTestId, rerender } = render(
+ <Button title="Reset all" onPress={jest.fn()} variant="ghost" testID="reset-btn" />
+ )
+ const label = () => getByTestId("reset-btn").findByType(Text).props.style
+
+ expect(StyleSheet.flatten(label()).color).toBe(lightColors.primaryDark)
+
+ rerender(<Button title="Reset all" onPress={jest.fn()} variant="ghost" disabled testID="reset-btn" />)
+ expect(StyleSheet.flatten(label()).color).toBe(lightColors.textDisabled)
+ expect(flat(getByTestId("reset-btn")).backgroundColor).toBe("transparent")
+ })
+
+ it("paints the corner itself, because a caller's style lands on the outer view", () => {
+ const { getByTestId } = render(
+ <Button title="Start tracking" onPress={jest.fn()} shape="pill" testID="start-btn" />
+ )
+
+ expect(flat(getByTestId("start-btn")).borderRadius).toBe(radius.pill)
+ })
+
+ it("keeps a plain button on the shape scale rather than the retired alias", () => {
+ const { getByTestId } = render(<Button title="Save" onPress={jest.fn()} testID="save-btn" />)
+
+ expect(flat(getByTestId("save-btn")).borderRadius).toBe(radius.sm)
+ })
+
+ it("keeps the touch target at the Android minimum", () => {
+ const { getByTestId } = render(<Button title="Save profile" onPress={jest.fn()} testID="save-btn" />)
+
+ expect(flat(getByTestId("save-btn")).minHeight).toBe(48)
+ })
+
+ it("says whether the panel it opens is showing", () => {
+ // The Trip Detail export button opens a format row; its TripList twin already announces
+ // this, so a screen reader got two different experiences for the same control.
+ const { getByTestId, rerender } = render(
+ <Button title="Export trip" onPress={jest.fn()} expanded={false} testID="export-btn" />
+ )
+ expect(getByTestId("export-btn").props.accessibilityState.expanded).toBe(false)
+
+ rerender(<Button title="Export trip" onPress={jest.fn()} expanded testID="export-btn" />)
+ expect(getByTestId("export-btn").props.accessibilityState.expanded).toBe(true)
+ })
+
+ it("lifts the painted node when floating, because Android draws no shadow on an unfilled wrapper", () => {
+ const { getByTestId } = render(<Button title="Start tracking" onPress={jest.fn()} floating testID="start-btn" />)
+
+ const style = flat(getByTestId("start-btn"))
+ expect(style.backgroundColor).toBe(lightColors.primary)
+ expect(style.elevation).toBe(elevation.floating)
+ })
+
+ it("sits flat on its ground unless asked to float", () => {
+ const { getByTestId } = render(<Button title="Save" onPress={jest.fn()} testID="save-btn" />)
+
+ expect(flat(getByTestId("save-btn")).elevation).toBeUndefined()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/Card.test.tsx b/apps/mobile/src/components/ui/__tests__/Card.test.tsx
new file mode 100644
index 00000000..d7fcb2ff
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/Card.test.tsx
@@ -0,0 +1,81 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { View, Text, StyleSheet } from "react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { lightColors } from "@colota/shared"
+import { space } from "../../../constants"
+import { Card } from "../Card"
+
+function surfaceOf(tree: ReturnType<typeof render>) {
+ // The interactive variant wraps the surface in a Pressable, so take the inner View both ways.
+ const views = tree.UNSAFE_getAllByType(View)
+ return StyleSheet.flatten(views[views.length - 1].props.style)
+}
+
+describe("Card", () => {
+ it("still clips, because a row inside ripples to the card's own bounds", () => {
+ const tree = render(
+ <Card>
+ <Text>Body</Text>
+ </Card>
+ )
+
+ expect(surfaceOf(tree).overflow).toBe("hidden")
+ })
+
+ it("keeps its content mounted when pressable, which is where the clipping bit", () => {
+ const { getByText } = render(
+ <Card variant="interactive" onPress={jest.fn()}>
+ <Text>Trip 1</Text>
+ </Card>
+ )
+
+ expect(getByText("Trip 1")).toBeTruthy()
+ })
+
+ it("takes the caller's style on the surface, which is why a margin there spills the ripple", () => {
+ // The trip row spaced itself with marginBottom, which grew the Pressable 8 past the card and
+ // the ripple with it. The margin belongs to the list, and this pins where the style lands.
+ const tree = render(
+ <Card variant="interactive" onPress={jest.fn()} style={{ backgroundColor: lightColors.primaryContainer }}>
+ <Text>Trip 1</Text>
+ </Card>
+ )
+
+ const rippleBox = tree.UNSAFE_getAllByType(View)[0]
+ expect(StyleSheet.flatten(rippleBox.props.style).backgroundColor).toBeUndefined()
+ expect(surfaceOf(tree).backgroundColor).toBe(lightColors.primaryContainer)
+ })
+
+ it("pays its own padding unless rows are told to carry it", () => {
+ const padded = render(
+ <Card>
+ <Text>a</Text>
+ </Card>
+ )
+ expect(surfaceOf(padded).padding).toBe(space.lg)
+
+ const rows = render(
+ <Card rows>
+ <Text>a</Text>
+ </Card>
+ )
+ expect(surfaceOf(rows).paddingVertical).toBe(0)
+ })
+
+ it("paints a fill and no border, so an outline is left to mean state", () => {
+ const tree = render(
+ <Card>
+ <Text>a</Text>
+ </Card>
+ )
+ const style = surfaceOf(tree)
+
+ expect(style.backgroundColor).toBe(lightColors.card)
+ expect(style.borderWidth).toBeUndefined()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/ChipGroup.test.tsx b/apps/mobile/src/components/ui/__tests__/ChipGroup.test.tsx
new file mode 100644
index 00000000..f5f43292
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/ChipGroup.test.tsx
@@ -0,0 +1,66 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { size } from "../../../constants"
+import { lightColors } from "@colota/shared"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { ChipGroup } from "../ChipGroup"
+
+const OPTIONS = [
+ { value: "a", label: "None", testID: "chip-a" },
+ { value: "b", label: "Basic auth", testID: "chip-b" }
+] as const
+
+describe("ChipGroup", () => {
+ it("fills the selected chip and recesses the rest, so neither carries a stroke", () => {
+ const { getByTestId } = render(<ChipGroup options={OPTIONS} selected="b" onSelect={jest.fn()} />)
+
+ const flat = (el: any) => Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+ expect(flat(getByTestId("chip-b")).backgroundColor).toBe(lightColors.primaryContainer)
+ expect(flat(getByTestId("chip-a")).backgroundColor).toBe(lightColors.well)
+ expect(flat(getByTestId("chip-a")).borderWidth).toBeUndefined()
+ })
+
+ it("recolours a disabled chip instead of fading the whole thing", () => {
+ const { getByTestId, getByText } = render(
+ <ChipGroup options={OPTIONS} selected="b" onSelect={jest.fn()} disabled={new Set(["a"] as const)} />
+ )
+
+ const flat = (el: any) => Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+ expect(flat(getByTestId("chip-a")).opacity).toBeUndefined()
+ expect(flat(getByTestId("chip-a")).backgroundColor).toBe(lightColors.well)
+ expect(flat(getByText("None")).color).toBe(lightColors.textDisabled)
+ })
+
+ it("marks selection with a check and a state, not colour alone", () => {
+ // Colour-only selection fails a colour-blind user and is an Accessibility Scanner finding.
+ const { getByTestId } = render(<ChipGroup options={OPTIONS} selected="b" onSelect={jest.fn()} />)
+
+ expect(getByTestId("chip-b").props.accessibilityState.checked).toBe(true)
+ expect(getByTestId("chip-a").props.accessibilityState.checked).toBe(false)
+ })
+
+ it("clears the 48 touch target with its slop, which the chip alone does not", () => {
+ const { getByTestId } = render(
+ <ChipGroup options={[{ value: "a", label: "Metric", testID: "chip-a" }]} selected="a" onSelect={jest.fn()} />
+ )
+ const chip = getByTestId("chip-a")
+ const style = StyleSheet.flatten(chip.props.style)
+ const slop = chip.props.hitSlop
+
+ expect(style.minHeight).toBe(size.chip)
+ expect(style.minHeight + slop.top + slop.bottom).toBeGreaterThanOrEqual(size.touch)
+ })
+
+ it("binds the chips into a group, because a loose radio has nothing to belong to", () => {
+ const { getByLabelText } = render(
+ <ChipGroup options={OPTIONS} selected="b" onSelect={jest.fn()} accessibilityLabel="Period" />
+ )
+
+ expect(getByLabelText("Period").props.accessibilityRole).toBe("radiogroup")
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/DialogShell.test.tsx b/apps/mobile/src/components/ui/__tests__/DialogShell.test.tsx
new file mode 100644
index 00000000..c579c593
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/DialogShell.test.tsx
@@ -0,0 +1,108 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { Modal, StyleSheet, Text } from "react-native"
+import { lightColors } from "@colota/shared"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { DialogShell } from "../DialogShell"
+import { space } from "../../../constants"
+
+describe("DialogShell", () => {
+ it("renders nothing while it is closed", () => {
+ const { queryByText } = render(
+ <DialogShell visible={false} onRequestClose={jest.fn()} title="Note">
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ expect(queryByText("Note")).toBeNull()
+ expect(queryByText("Body")).toBeNull()
+ })
+
+ it("shows the title as a heading, the content and the footer row", () => {
+ const { getByRole, getByText } = render(
+ <DialogShell visible onRequestClose={jest.fn()} title="Note" footer={<Text>Close</Text>}>
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ expect(getByRole("header", { name: "Note" })).toBeTruthy()
+ expect(getByText("Body")).toBeTruthy()
+ expect(getByText("Close")).toBeTruthy()
+ })
+
+ it("keeps the alert geometry by default: a 32 gutter and a 24 inset", () => {
+ // The same card AppModal and the attribution dialog draw, so a dialog on the shell lines up with them.
+ const { getByTestId } = render(
+ <DialogShell visible onRequestClose={jest.fn()}>
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ const scrim = StyleSheet.flatten(getByTestId("dialog-scrim").props.style)
+ const card = StyleSheet.flatten(getByTestId("dialog-card").props.style)
+ expect(scrim.paddingHorizontal).toBe(space.xxl)
+ expect(scrim.backgroundColor).toBe(lightColors.overlay)
+ expect(card.padding).toBe(space.xl)
+ expect(card.backgroundColor).toBe(lightColors.surfaceRaised)
+ })
+
+ it("gives the calendar grid the width of Material's own picker with the picker gutter", () => {
+ // 360 minus twice 16 minus twice 12 leaves 304 for the day grid, seven of the picker's 43 dp cells.
+ const { getByTestId } = render(
+ <DialogShell visible onRequestClose={jest.fn()} gutter="picker">
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ const scrim = StyleSheet.flatten(getByTestId("dialog-scrim").props.style)
+ const card = StyleSheet.flatten(getByTestId("dialog-card").props.style)
+ expect(scrim.paddingHorizontal).toBe(space.lg)
+ expect(card.padding).toBe(space.md)
+ expect(360 - 2 * (scrim.paddingHorizontal + card.padding)).toBe(304)
+ })
+
+ it("closes on a tap outside the card and on hardware back", () => {
+ const onRequestClose = jest.fn()
+ const { getByTestId, UNSAFE_getByType } = render(
+ <DialogShell visible onRequestClose={onRequestClose}>
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ fireEvent.press(getByTestId("dialog-scrim"))
+ expect(onRequestClose).toHaveBeenCalledTimes(1)
+
+ UNSAFE_getByType(Modal).props.onRequestClose()
+ expect(onRequestClose).toHaveBeenCalledTimes(2)
+ })
+
+ it("stays open when the tap lands inside the card", () => {
+ // A tap on the card's own padding must not dismiss a half-written note.
+ const onRequestClose = jest.fn()
+ const { getByTestId } = render(
+ <DialogShell visible onRequestClose={onRequestClose}>
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ fireEvent.press(getByTestId("dialog-card"))
+ expect(onRequestClose).not.toHaveBeenCalled()
+ })
+
+ it("ignores the scrim and hardware back when it is not dismissible, because an alert has to be answered", () => {
+ const onRequestClose = jest.fn()
+ const { getByTestId, UNSAFE_getByType } = render(
+ <DialogShell visible dismissible={false} onRequestClose={onRequestClose}>
+ <Text>Body</Text>
+ </DialogShell>
+ )
+
+ fireEvent.press(getByTestId("dialog-scrim"))
+ UNSAFE_getByType(Modal).props.onRequestClose()
+ expect(onRequestClose).not.toHaveBeenCalled()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx b/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx
index 8b0a98fa..6d648665 100644
--- a/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx
+++ b/apps/mobile/src/components/ui/__tests__/DisclosureModal.test.tsx
@@ -6,8 +6,6 @@ jest.mock("../../../hooks/useTheme", () => ({
useTheme: () => ({
colors: {
overlay: "rgba(0,0,0,0.5)",
- cardElevated: "#fff",
- borderRadius: 12,
primary: "#0d9488",
text: "#000",
textSecondary: "#666",
@@ -51,15 +49,28 @@ describe("DisclosureModal", () => {
expect(getByText("First paragraph.")).toBeTruthy()
expect(getByText("Second paragraph.")).toBeTruthy()
expect(getByText("Confirm")).toBeTruthy()
- expect(getByText("Not Now")).toBeTruthy()
+ expect(getByText("Not now")).toBeTruthy()
// Clean up by dismissing
await act(async () => {
- fireEvent.press(getByText("Not Now"))
+ fireEvent.press(getByText("Not now"))
})
expect(await resultPromise!).toBe(false)
})
+ it("announces both choices as buttons", async () => {
+ // Both were bare Pressables, so TalkBack read "Not now" and the confirm label as text and
+ // said nothing about them being pressable. This is the disclosure a location grant depends on.
+ const { getByRole } = render(<DisclosureModal {...defaultProps} />)
+
+ await act(async () => {
+ triggerModal()
+ })
+
+ expect(getByRole("button", { name: "Not now" })).toBeTruthy()
+ expect(getByRole("button", { name: "Confirm" })).toBeTruthy()
+ })
+
it("resolves true when confirm is pressed", async () => {
const { getByText } = render(<DisclosureModal {...defaultProps} />)
@@ -84,7 +95,7 @@ describe("DisclosureModal", () => {
})
await act(async () => {
- fireEvent.press(getByText("Not Now"))
+ fireEvent.press(getByText("Not now"))
})
expect(await resultPromise!).toBe(false)
diff --git a/apps/mobile/src/components/ui/__tests__/EmptyState.test.tsx b/apps/mobile/src/components/ui/__tests__/EmptyState.test.tsx
new file mode 100644
index 00000000..178d0e3a
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/EmptyState.test.tsx
@@ -0,0 +1,33 @@
+import React from "react"
+import { fireEvent, render } from "@testing-library/react-native"
+import { EmptyState } from "../EmptyState"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: jest.requireActual("@colota/shared").lightColors })
+}))
+
+describe("EmptyState", () => {
+ it("offers the next step as a button under the hint, so an empty day is not a dead end", () => {
+ const onPress = jest.fn()
+ const { getByRole } = render(
+ <EmptyState
+ title="Nothing recorded"
+ hint="Wednesday, September 3"
+ action={{ label: "Last day with data", onPress }}
+ />
+ )
+
+ const button = getByRole("button", { name: "Last day with data" })
+ fireEvent.press(button)
+
+ expect(onPress).toHaveBeenCalledTimes(1)
+ })
+
+ it("renders no button when the state has no next step, so the title and hint stand alone", () => {
+ const { queryByRole, getByText } = render(<EmptyState title="No locations yet" hint="Tracking is on." />)
+
+ expect(getByText("No locations yet")).toBeTruthy()
+ expect(getByText("Tracking is on.")).toBeTruthy()
+ expect(queryByRole("button")).toBeNull()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx b/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx
index dcc24526..104b1856 100644
--- a/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx
+++ b/apps/mobile/src/components/ui/__tests__/ErrorBoundary.test.tsx
@@ -64,7 +64,7 @@ describe("ErrorBoundary", () => {
expect(getByText("Something went wrong")).toBeTruthy()
expect(getByText("Test error message")).toBeTruthy()
- expect(getByText("Try Again")).toBeTruthy()
+ expect(getByText("Try again")).toBeTruthy()
})
it("logs error via logger.error", () => {
@@ -101,7 +101,7 @@ describe("ErrorBoundary", () => {
shouldThrow = false
- fireEvent.press(getByText("Try Again"))
+ fireEvent.press(getByText("Try again"))
expect(getByText("Recovered")).toBeTruthy()
})
diff --git a/apps/mobile/src/components/ui/__tests__/ExportFormatDialog.test.tsx b/apps/mobile/src/components/ui/__tests__/ExportFormatDialog.test.tsx
new file mode 100644
index 00000000..98bccc53
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/ExportFormatDialog.test.tsx
@@ -0,0 +1,56 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { EXPORT_FORMAT_KEYS, EXPORT_FORMATS } from "../../../utils/exportConverters"
+import { ExportFormatDialog } from "../ExportFormatDialog"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+function renderDialog(overrides: Partial<React.ComponentProps<typeof ExportFormatDialog>> = {}) {
+ const props = {
+ visible: true,
+ title: "Export day",
+ message: "Wed, Sep 3 · 3 trips · 12.4 km",
+ onSelect: jest.fn(),
+ onRequestClose: jest.fn(),
+ ...overrides
+ }
+ return { ...render(<ExportFormatDialog {...props} />), props }
+}
+
+describe("ExportFormatDialog", () => {
+ it("lists every export format as a row with what it is for, so the choice is not four bare words", () => {
+ const { getByText } = renderDialog()
+
+ expect(getByText("Export day")).toBeTruthy()
+ expect(getByText("Wed, Sep 3 · 3 trips · 12.4 km")).toBeTruthy()
+ for (const key of EXPORT_FORMAT_KEYS) {
+ expect(getByText(EXPORT_FORMATS[key].label)).toBeTruthy()
+ expect(getByText(EXPORT_FORMATS[key].description)).toBeTruthy()
+ }
+ })
+
+ it("hands back the tapped format, because a list dialog acts on the tap", () => {
+ const { getByTestId, props } = renderDialog()
+
+ fireEvent.press(getByTestId("export-gpx"))
+
+ expect(props.onSelect).toHaveBeenCalledWith("gpx")
+ })
+
+ it("closes without a format from Cancel", () => {
+ const { getByTestId, props } = renderDialog()
+
+ fireEvent.press(getByTestId("export-cancel"))
+
+ expect(props.onRequestClose).toHaveBeenCalled()
+ expect(props.onSelect).not.toHaveBeenCalled()
+ })
+
+ it("renders nothing while hidden", () => {
+ const { queryByText } = renderDialog({ visible: false })
+
+ expect(queryByText("Export day")).toBeNull()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/FloatingSaveIndicator.test.tsx b/apps/mobile/src/components/ui/__tests__/FloatingSaveIndicator.test.tsx
new file mode 100644
index 00000000..def167b4
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/FloatingSaveIndicator.test.tsx
@@ -0,0 +1,59 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { lightColors } from "@colota/shared"
+import { space } from "../../../constants"
+import { FloatingSaveIndicator } from "../FloatingSaveIndicator"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ const stub = (name: string) => (props: Record<string, unknown>) =>
+ R.createElement(View, { testID: `icon-${name}`, ...props })
+ return { Check: stub("check"), CircleAlert: stub("alert"), Loader: stub("loader") }
+})
+
+const fill = (testID: string, api: ReturnType<typeof render>) =>
+ StyleSheet.flatten(api.getByTestId(testID).props.style).backgroundColor
+
+describe("FloatingSaveIndicator", () => {
+ it("paints the one raised surface in every state, so the verdict is never a fill colour", () => {
+ expect(fill("floating-save-indicator-pill", render(<FloatingSaveIndicator saving />))).toBe(
+ lightColors.surfaceRaised
+ )
+ expect(fill("floating-save-indicator-pill", render(<FloatingSaveIndicator saving={false} message="Saved" />))).toBe(
+ lightColors.surfaceRaised
+ )
+ expect(
+ fill(
+ "floating-save-indicator-pill",
+ render(<FloatingSaveIndicator saving={false} message="Could not save" isError />)
+ )
+ ).toBe(lightColors.surfaceRaised)
+ })
+
+ it("carries the state in the glyph and the word: a spinner, then a check or an alert", () => {
+ const saving = render(<FloatingSaveIndicator saving />)
+ expect(saving.getByTestId("icon-loader").props.color).toBe(lightColors.textSecondary)
+ expect(saving.getByText("Saving...")).toBeTruthy()
+
+ const done = render(<FloatingSaveIndicator saving={false} message="Tracking restarted" />)
+ expect(done.getByTestId("icon-check").props.color).toBe(lightColors.success)
+ expect(done.getByText("Tracking restarted")).toBeTruthy()
+
+ const failed = render(<FloatingSaveIndicator saving={false} message="Could not save" isError />)
+ expect(failed.getByTestId("icon-alert").props.color).toBe(lightColors.error)
+ expect(failed.queryByTestId("icon-check")).toBeNull()
+ })
+
+ it("floats at the 24 dp rhythm above the bottom edge and lets touches through", () => {
+ const { getByTestId } = render(<FloatingSaveIndicator saving />)
+ const container = StyleSheet.flatten(getByTestId("floating-save-indicator").props.style)
+ expect(container.bottom).toBe(space.xl)
+ expect(container.pointerEvents).toBe("none")
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/HeaderAction.test.tsx b/apps/mobile/src/components/ui/__tests__/HeaderAction.test.tsx
new file mode 100644
index 00000000..897e31ea
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/HeaderAction.test.tsx
@@ -0,0 +1,55 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { lightColors } from "@colota/shared"
+import { size, space } from "../../../constants"
+import { HeaderAction } from "../HeaderAction"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+jest.mock("lucide-react-native", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { Upload: (props: Record<string, unknown>) => R.createElement(View, { testID: "glyph", ...props }) }
+})
+
+import { Upload } from "lucide-react-native"
+
+describe("HeaderAction", () => {
+ it("is a 24 glyph inside 12 of padding, so the 48 target sits on the grid", () => {
+ const { getByTestId } = render(<HeaderAction icon={Upload} label="Export day" onPress={() => {}} testID="act" />)
+
+ expect(StyleSheet.flatten(getByTestId("act").props.style).padding).toBe(space.md)
+ expect(getByTestId("glyph").props.size).toBe(size.icon.lg)
+ })
+
+ it("is named for a screen reader and presses through", () => {
+ const onPress = jest.fn()
+ const { getByLabelText } = render(
+ <HeaderAction icon={Upload} label="Export day" hint="Opens the format dialog" onPress={onPress} />
+ )
+
+ const action = getByLabelText("Export day")
+ expect(action.props.accessibilityRole).toBe("button")
+ expect(action.props.accessibilityHint).toBe("Opens the format dialog")
+ fireEvent.press(action)
+ expect(onPress).toHaveBeenCalled()
+ })
+
+ it("takes the text colour unless told otherwise, and recedes to textDisabled when disabled", () => {
+ const plain = render(<HeaderAction icon={Upload} label="Export" onPress={() => {}} />)
+ expect(plain.getByTestId("glyph").props.color).toBe(lightColors.text)
+
+ const danger = render(<HeaderAction icon={Upload} label="Delete" color={lightColors.error} onPress={() => {}} />)
+ expect(danger.getByTestId("glyph").props.color).toBe(lightColors.error)
+
+ const off = render(
+ <HeaderAction icon={Upload} label="Delete" color={lightColors.error} disabled onPress={() => {}} />
+ )
+ expect(off.getByTestId("glyph").props.color).toBe(lightColors.textDisabled)
+ expect(off.getByLabelText("Delete").props.accessibilityState).toEqual({ disabled: true })
+ expect(off.getByLabelText("Delete").props.android_ripple).toBeUndefined()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/IconButton.test.tsx b/apps/mobile/src/components/ui/__tests__/IconButton.test.tsx
new file mode 100644
index 00000000..6e9c62cc
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/IconButton.test.tsx
@@ -0,0 +1,42 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { X } from "lucide-react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { IconButton } from "../IconButton"
+
+describe("IconButton", () => {
+ it("reaches the 48 Android touch target without growing the disc", () => {
+ // Six controls sat at 32 to 44 inside tight rows. Growing them would reflow every row,
+ // so the painted disc stays and hitSlop makes up the difference.
+ const { getByTestId } = render(
+ <IconButton icon={X} onPress={jest.fn()} accessibilityLabel="Remove this header" testID="rm" />
+ )
+
+ const el = getByTestId("rm")
+ const style = Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+ expect(style.width + el.props.hitSlop.left + el.props.hitSlop.right).toBe(48)
+ expect(style.height + el.props.hitSlop.top + el.props.hitSlop.bottom).toBe(48)
+ })
+
+ it("is named for a screen reader, because the glyph carries no text", () => {
+ const { getByLabelText } = render(
+ <IconButton icon={X} onPress={jest.fn()} accessibilityLabel="Remove this header" />
+ )
+ expect(getByLabelText("Remove this header")).toBeTruthy()
+ })
+
+ it("swallows the press while loading", () => {
+ const onPress = jest.fn()
+ const { getByTestId } = render(
+ <IconButton icon={X} onPress={onPress} accessibilityLabel="Refresh" loading testID="rf" />
+ )
+
+ fireEvent.press(getByTestId("rf"))
+ expect(onPress).not.toHaveBeenCalled()
+ expect(getByTestId("rf").props.accessibilityState.disabled).toBe(true)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/ListItem.test.tsx b/apps/mobile/src/components/ui/__tests__/ListItem.test.tsx
new file mode 100644
index 00000000..95ff7c60
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/ListItem.test.tsx
@@ -0,0 +1,124 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { StyleSheet, Switch } from "react-native"
+import { lightColors } from "@colota/shared"
+import { size, space } from "../../../constants"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { ListItem } from "../ListItem"
+
+describe("ListItem", () => {
+ it("says whether the panel it opens is showing", () => {
+ // Without the expanded state TalkBack announces a plain button and the panel opening
+ // below is silent. A hint is not a substitute: it is read late and never on the change.
+ const { getByTestId, rerender } = render(
+ <ListItem label="Map tile server" onPress={jest.fn()} expanded={false} testID="row" />
+ )
+ expect(getByTestId("row").props.accessibilityState.expanded).toBe(false)
+
+ rerender(<ListItem label="Map tile server" onPress={jest.fn()} expanded testID="row" />)
+ expect(getByTestId("row").props.accessibilityState.expanded).toBe(true)
+ })
+
+ it("speaks the sub after the label, because an Android label replaces the row's text", () => {
+ const { getByTestId, rerender } = render(
+ <ListItem label="Note" sub="Coffee stop" onPress={jest.fn()} testID="row" />
+ )
+ expect(getByTestId("row").props.accessibilityLabel).toBe("Note, Coffee stop")
+ expect(getByTestId("row").props.accessibilityHint).toBe("Opens Note")
+
+ rerender(<ListItem label="Note" onPress={jest.fn()} testID="row" />)
+ expect(getByTestId("row").props.accessibilityLabel).toBe("Note")
+ })
+
+ it("says a link row leaves the app, so every caller inherits it instead of writing its own hint", () => {
+ const { getByTestId, rerender } = render(
+ <ListItem label="Feedback & help" onPress={jest.fn()} accessibilityRole="link" testID="row" />
+ )
+ expect(getByTestId("row").props.accessibilityHint).toBe("Opens Feedback & help in the browser")
+
+ // An explicit hint still wins: the Play row is not a browser.
+ rerender(
+ <ListItem
+ label="Rate the app"
+ onPress={jest.fn()}
+ accessibilityRole="link"
+ accessibilityHint="Opens Colota in Google Play"
+ testID="row"
+ />
+ )
+ expect(getByTestId("row").props.accessibilityHint).toBe("Opens Colota in Google Play")
+ })
+
+ it("leaves expanded unset on a row that opens nothing", () => {
+ const { getByTestId } = render(<ListItem label="Connection" onPress={jest.fn()} testID="row" />)
+ expect(getByTestId("row").props.accessibilityState.expanded).toBeUndefined()
+ })
+
+ it("cancels the card's inset and reapplies it, so a press fills the card's width", () => {
+ // The two must stay equal and opposite. If Card's padding ever stops being space.lg the
+ // row silently shifts, which is the failure this pins: the content sits where the card
+ // put it, and only the ripple reaches further.
+ const { getByTestId } = render(<ListItem label="Connection" onPress={jest.fn()} testID="row" />)
+ const style = StyleSheet.flatten(getByTestId("row").props.style)
+
+ expect(style.marginHorizontal).toBe(-space.lg)
+ expect(style.paddingHorizontal).toBe(space.lg)
+ expect(style.marginHorizontal + style.paddingHorizontal).toBe(0)
+ })
+
+ it("seats a trailing control outside the body behind a hairline, so the row opens and the control allows", () => {
+ const onPress = jest.fn()
+ const onValueChange = jest.fn()
+ const { getByTestId, getByRole, UNSAFE_getAllByType } = render(
+ <ListItem
+ label="Driving"
+ sub="When charging"
+ onPress={onPress}
+ testID="row"
+ trailing={<Switch testID="use" value onValueChange={onValueChange} />}
+ />
+ )
+
+ fireEvent.press(getByTestId("row"))
+ expect(onPress).toHaveBeenCalledTimes(1)
+ fireEvent(getByRole("switch"), "valueChange", false)
+ expect(onValueChange).toHaveBeenCalledWith(false)
+ expect(onPress).toHaveBeenCalledTimes(1)
+
+ const { View } = require("react-native")
+ const rule = UNSAFE_getAllByType(View).find(
+ (v: any) => StyleSheet.flatten(v.props.style)?.width === StyleSheet.hairlineWidth
+ )
+ expect(StyleSheet.flatten(rule?.props.style).height).toBe(size.iconButton)
+ expect(StyleSheet.flatten(rule?.props.style).backgroundColor).toBe(lightColors.divider)
+ })
+
+ it("tints the leading glyph on request and lets the sub wrap once when asked", () => {
+ const Icon = (props: any) => {
+ const { Text } = require("react-native")
+ return (
+ <Text testID="glyph" {...props}>
+ i
+ </Text>
+ )
+ }
+ const { getByTestId, getByText } = render(
+ <ListItem
+ label="Driving"
+ sub="Active · when charging"
+ icon={Icon}
+ iconColor="#123456"
+ subLines={2}
+ onPress={jest.fn()}
+ testID="row"
+ />
+ )
+
+ expect(getByTestId("glyph").props.color).toBe("#123456")
+ expect(getByText("Active · when charging").props.numberOfLines).toBe(2)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/LoadingOverlay.test.tsx b/apps/mobile/src/components/ui/__tests__/LoadingOverlay.test.tsx
new file mode 100644
index 00000000..5ee9d21d
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/LoadingOverlay.test.tsx
@@ -0,0 +1,30 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { Modal } from "react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { LoadingOverlay } from "../LoadingOverlay"
+
+describe("LoadingOverlay", () => {
+ it("renders nothing until it is asked to", () => {
+ const { queryByText, UNSAFE_queryAllByType } = render(<LoadingOverlay visible={false} title="Importing" />)
+
+ expect(queryByText("Importing")).toBeNull()
+ expect(UNSAFE_queryAllByType(Modal)).toHaveLength(0)
+ })
+
+ it("covers the header too, which an overlay inside the screen cannot", () => {
+ // Import and export run for minutes. Drawn as an absolute View it stopped at the screen's own
+ // tree, leaving the stack's back arrow live and the job navigable out from under.
+ const { getByText, UNSAFE_getByType } = render(
+ <LoadingOverlay visible title="Importing" message="1,204 of 8,000" />
+ )
+
+ expect(UNSAFE_getByType(Modal).props.transparent).toBe(true)
+ expect(getByText("Importing")).toBeTruthy()
+ expect(getByText("1,204 of 8,000")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx b/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx
index 71fec407..8aec2989 100644
--- a/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx
+++ b/apps/mobile/src/components/ui/__tests__/NumericInput.test.tsx
@@ -1,15 +1,10 @@
import React from "react"
import { render, fireEvent } from "@testing-library/react-native"
-import { NumericInput } from "../NumericInput"
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
-const mockColors = {
- text: "#000",
- textLight: "#9ca3af",
- textSecondary: "#6b7280",
- border: "#e5e7eb",
- backgroundElevated: "#f9fafb",
- placeholder: "#9ca3af"
-} as any
+import { NumericInput } from "../NumericInput"
describe("NumericInput", () => {
const mockOnChange = jest.fn()
@@ -22,12 +17,11 @@ describe("NumericInput", () => {
function renderInput(overrides: Partial<React.ComponentProps<typeof NumericInput>> = {}) {
return render(
<NumericInput
- label="Test Label"
+ label="Test label"
value="10"
onChange={mockOnChange}
onBlur={mockOnBlur}
unit="seconds"
- colors={mockColors}
{...overrides}
/>
)
@@ -36,7 +30,7 @@ describe("NumericInput", () => {
it("renders label, value, and unit", () => {
const { getByText, getByDisplayValue } = renderInput()
- expect(getByText("Test Label")).toBeTruthy()
+ expect(getByText("Test label")).toBeTruthy()
expect(getByDisplayValue("10")).toBeTruthy()
expect(getByText("seconds")).toBeTruthy()
})
@@ -90,4 +84,13 @@ describe("NumericInput", () => {
expect(getByText("meters")).toBeTruthy()
})
+
+ it("hands an error to the box and a message under it, so a clamp and a rejection read in place", () => {
+ const withError = renderInput({ error: "A whole number" })
+ expect(withError.getByText("A whole number")).toBeTruthy()
+ expect(withError.getByLabelText("Test label, A whole number")).toBeTruthy()
+
+ const withMessage = renderInput({ message: "Set to 1 s" })
+ expect(withMessage.getByText("Set to 1 s")).toBeTruthy()
+ })
})
diff --git a/apps/mobile/src/components/ui/__tests__/RadioRow.test.tsx b/apps/mobile/src/components/ui/__tests__/RadioRow.test.tsx
new file mode 100644
index 00000000..2cdb2fde
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/RadioRow.test.tsx
@@ -0,0 +1,56 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { RadioRow } from "../RadioRow"
+
+describe("RadioRow", () => {
+ it("makes the whole row the radio, not the dot", () => {
+ // RadioDot is hidden from accessibility, so the state has to live on the row or a
+ // screen reader has no way to know what is selected.
+ const { getByTestId } = render(
+ <RadioRow testID="r" label="Charging" sub="Phone is plugged in" selected onPress={jest.fn()} />
+ )
+
+ const row = getByTestId("r")
+ expect(row.props.accessibilityState.checked).toBe(true)
+ expect(row.props.accessibilityLabel).toBe("Charging, Phone is plugged in")
+ })
+
+ it("selects on a press anywhere in the row", () => {
+ const onPress = jest.fn()
+ const { getByTestId } = render(<RadioRow testID="r" label="Car mode" selected={false} onPress={onPress} />)
+
+ fireEvent.press(getByTestId("r"))
+ expect(onPress).toHaveBeenCalled()
+ })
+
+ it("names itself by the label alone when there is no sub line", () => {
+ const { getByTestId } = render(<RadioRow testID="r" label="Stationary" selected={false} onPress={jest.fn()} />)
+
+ expect(getByTestId("r").props.accessibilityLabel).toBe("Stationary")
+ })
+
+ it("keeps a disabled option on screen with its sub, so it can say why it is unavailable", () => {
+ const onPress = jest.fn()
+ const { getByTestId, getByText } = render(
+ <RadioRow
+ testID="r"
+ label="Batch"
+ sub="Needs the POST method, not GET"
+ selected={false}
+ disabled
+ onPress={onPress}
+ />
+ )
+
+ fireEvent.press(getByTestId("r"))
+
+ expect(onPress).not.toHaveBeenCalled()
+ expect(getByTestId("r").props.accessibilityState).toEqual({ checked: false, disabled: true })
+ expect(getByText("Needs the POST method, not GET")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/SectionTitle.test.tsx b/apps/mobile/src/components/ui/__tests__/SectionTitle.test.tsx
new file mode 100644
index 00000000..1b11e48d
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/SectionTitle.test.tsx
@@ -0,0 +1,52 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { lightColors, darkColors } from "@colota/shared"
+import { SectionTitle } from "../SectionTitle"
+
+let mockColors = lightColors
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: mockColors })
+}))
+
+/** WCAG AA for text under 18pt, which a 16px semiBold heading is. */
+const AA = 4.5
+
+function ratio(fg: string, bg: string): number {
+ const lum = (hex: string) => {
+ const c = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
+ const [r, g, b] = c.map((v) => (v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4)))
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b
+ }
+ const [hi, lo] = [lum(fg), lum(bg)].sort((a, b) => b - a)
+ return (hi + 0.05) / (lo + 0.05)
+}
+
+describe("SectionTitle", () => {
+ afterEach(() => {
+ mockColors = lightColors
+ })
+
+ it("reads its colour from the theme, so a heading is legible in both", () => {
+ const { getByText, rerender } = render(<SectionTitle>Tracking</SectionTitle>)
+ expect(getByText("Tracking").props.style).toEqual(expect.arrayContaining([{ color: lightColors.textSecondary }]))
+
+ mockColors = darkColors
+ rerender(<SectionTitle>Tracking</SectionTitle>)
+
+ expect(getByText("Tracking").props.style).toEqual(expect.arrayContaining([{ color: darkColors.textSecondary }]))
+ })
+
+ it("announces itself as a heading, so a screen reader can jump between sections", () => {
+ const { getByText } = render(<SectionTitle>Tracking</SectionTitle>)
+
+ expect(getByText("Tracking").props.accessibilityRole).toBe("header")
+ })
+
+ it("keeps the arithmetic true: the heading clears AA on both surfaces", () => {
+ for (const theme of [lightColors, darkColors]) {
+ expect(ratio(theme.textSecondary, theme.background)).toBeGreaterThanOrEqual(AA)
+ expect(ratio(theme.textSecondary, theme.card)).toBeGreaterThanOrEqual(AA)
+ }
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/SettingRow.test.tsx b/apps/mobile/src/components/ui/__tests__/SettingRow.test.tsx
new file mode 100644
index 00000000..a5d4e28e
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/SettingRow.test.tsx
@@ -0,0 +1,37 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { Text } from "react-native"
+import { lightColors } from "@colota/shared"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { SettingRow } from "../SettingRow"
+
+describe("SettingRow", () => {
+ it("drops the label and hint to the disabled token when disabled", () => {
+ // Three geofence rows dimmed the whole row at 0.45 instead, which also faded the
+ // control inside it and told a screen reader nothing.
+ const { getByText } = render(
+ <SettingRow label="WiFi/Ethernet pause" hint="Stop GPS on unmetered networks" disabled>
+ <Text>child</Text>
+ </SettingRow>
+ )
+
+ const flat = (el: any) => Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+ expect(flat(getByText("WiFi/Ethernet pause")).color).toBe(lightColors.textDisabled)
+ expect(flat(getByText("Stop GPS on unmetered networks")).color).toBe(lightColors.textDisabled)
+ })
+
+ it("uses the normal ink otherwise", () => {
+ const { getByText } = render(
+ <SettingRow label="WiFi/Ethernet pause">
+ <Text>child</Text>
+ </SettingRow>
+ )
+
+ const flat = (el: any) => Object.assign({}, ...[el.props.style].flat(Infinity).filter(Boolean))
+ expect(flat(getByText("WiFi/Ethernet pause")).color).toBe(lightColors.text)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/StatRow.test.tsx b/apps/mobile/src/components/ui/__tests__/StatRow.test.tsx
new file mode 100644
index 00000000..ad1495b3
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/StatRow.test.tsx
@@ -0,0 +1,50 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet, Text, View } from "react-native"
+import { Timer } from "lucide-react-native"
+import { size, space } from "../../../constants"
+import { StatRow } from "../StatRow"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: jest.requireActual("@colota/shared").lightColors })
+}))
+
+describe("StatRow", () => {
+ it("reads as one thing, so a screen reader does not split the label from its number", () => {
+ const { getByLabelText } = render(<StatRow label="Distance" value="4.2 km" />)
+
+ expect(getByLabelText("Distance, 4.2 km")).toBeTruthy()
+ })
+
+ it("gives the value tabular figures, so a number that updates does not jitter", () => {
+ const { getByText } = render(<StatRow label="Points" value="1,204" />)
+
+ expect(StyleSheet.flatten(getByText("1,204").props.style).fontVariant).toEqual(["tabular-nums"])
+ })
+
+ it("keeps the value beside a trailing control rather than behind it", () => {
+ const { getByText } = render(
+ <StatRow label="Queued" value="7">
+ <Text>badge</Text>
+ </StatRow>
+ )
+
+ expect(getByText("7")).toBeTruthy()
+ expect(getByText("badge")).toBeTruthy()
+ })
+
+ it("centres its icon in ListItem's icon column, so its label starts where a ListItem's does", () => {
+ const { UNSAFE_getAllByType } = render(<StatRow icon={Timer} label="Interval" value="30 s" />)
+
+ const styles = UNSAFE_getAllByType(View).map((v) => StyleSheet.flatten(v.props.style) ?? {})
+ const box = styles.find((style) => style.width === size.icon.md)
+ expect(box?.alignItems).toBe("center")
+ expect(styles.find((style) => style.gap === space.lg)?.flexDirection).toBe("row")
+ })
+
+ it("draws no icon column without an icon, so a plain figure list keeps its label at the edge", () => {
+ const { UNSAFE_getAllByType } = render(<StatRow label="Points" value="1,204" />)
+
+ expect(UNSAFE_getAllByType(View).some((v) => StyleSheet.flatten(v.props.style)?.width === size.icon.md)).toBe(false)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/StateLine.test.tsx b/apps/mobile/src/components/ui/__tests__/StateLine.test.tsx
new file mode 100644
index 00000000..2c5b565b
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/StateLine.test.tsx
@@ -0,0 +1,74 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet, Text, View } from "react-native"
+import { CircleDot } from "lucide-react-native"
+import { size, space } from "../../../constants"
+import { StateLine } from "../StateLine"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+describe("StateLine", () => {
+ it("renders the label and its caption as two lines, so the dock keeps one height in every state", () => {
+ const { getByText } = render(
+ <StateLine icon={CircleDot} iconColor="#000" label="Tracking" caption="±4 m · 20:58" />
+ )
+
+ expect(getByText("Tracking")).toBeTruthy()
+ expect(getByText("±4 m · 20:58")).toBeTruthy()
+ })
+
+ it("reads as one thing to a screen reader, the state and its detail together", () => {
+ const { getByLabelText } = render(
+ <StateLine icon={CircleDot} iconColor="#000" label="Ready" caption="No fixes yet" testID="state-line" />
+ )
+
+ expect(getByLabelText("Ready, No fixes yet").props.accessibilityRole).toBe("text")
+ })
+
+ it("accepts a ready-made element as the glyph, which is how the Searching state spins", () => {
+ const { getByText } = render(
+ <StateLine icon={<Text>spinner</Text>} iconColor="#000" label="Searching for GPS" caption="No fix yet" />
+ )
+
+ expect(getByText("spinner")).toBeTruthy()
+ })
+
+ it("keeps a long caption on one line, so a verbose reason cannot grow the row", () => {
+ const caption = "Home WiFi · resumes when you leave the zone and the phone starts moving again"
+ const { getByText } = render(
+ <StateLine icon={CircleDot} iconColor="#000" label="Paused in Home" caption={caption} />
+ )
+
+ expect(getByText(caption).props.numberOfLines).toBe(1)
+ expect(getByText("Paused in Home").props.numberOfLines).toBe(1)
+ })
+
+ it("gives the caption tabular figures, so an updating accuracy or time does not jitter", () => {
+ const { getByText } = render(
+ <StateLine icon={CircleDot} iconColor="#000" label="Tracking" caption="±4 m · 20:58" />
+ )
+
+ expect(StyleSheet.flatten(getByText("±4 m · 20:58").props.style).fontVariant).toEqual(["tabular-nums"])
+ })
+
+ it("centres the glyph in ListItem's icon column, so the dock's text lines up with its inset seams", () => {
+ const { getByLabelText, UNSAFE_getAllByType } = render(
+ <StateLine icon={CircleDot} iconColor="#000" label="Tracking" caption="±4 m · 20:58" />
+ )
+
+ const box = UNSAFE_getAllByType(View).find((v) => StyleSheet.flatten(v.props.style)?.width === size.icon.md)
+ expect(StyleSheet.flatten(box?.props.style).alignItems).toBe("center")
+ expect(StyleSheet.flatten(getByLabelText("Tracking, ±4 m · 20:58").props.style).gap).toBe(space.lg)
+ })
+
+ it("centres a ready-made glyph in the same column, so the spinner does not sit off the others", () => {
+ const { UNSAFE_getAllByType } = render(
+ <StateLine icon={<Text>spinner</Text>} iconColor="#000" label="Searching for GPS" caption="No fix yet" />
+ )
+
+ const box = UNSAFE_getAllByType(View).find((v) => StyleSheet.flatten(v.props.style)?.width === size.icon.md)
+ expect(StyleSheet.flatten(box?.props.style).alignItems).toBe("center")
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/StepperHeader.test.tsx b/apps/mobile/src/components/ui/__tests__/StepperHeader.test.tsx
new file mode 100644
index 00000000..aaad6e5a
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/StepperHeader.test.tsx
@@ -0,0 +1,73 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { Text } from "react-native"
+import { StepperHeader } from "../StepperHeader"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+function renderHeader(overrides: Partial<React.ComponentProps<typeof StepperHeader>> = {}) {
+ const props = {
+ title: "Trip 2",
+ caption: "Wed, Sep 3 · 12:05 - 12:21",
+ onPrevious: jest.fn(),
+ onNext: jest.fn(),
+ previousLabel: "Previous trip",
+ nextLabel: "Next trip",
+ testID: "trip",
+ ...overrides
+ }
+ return { ...render(<StepperHeader {...props} />), props }
+}
+
+describe("StepperHeader", () => {
+ it("steps with each chevron and names what it steps for a screen reader", () => {
+ const { getByLabelText, props } = renderHeader()
+
+ fireEvent.press(getByLabelText("Previous trip"))
+ fireEvent.press(getByLabelText("Next trip"))
+
+ expect(props.onPrevious).toHaveBeenCalledTimes(1)
+ expect(props.onNext).toHaveBeenCalledTimes(1)
+ })
+
+ it("disables either end and dims its glyph, so the first trip has no previous and the last no next", () => {
+ const { getByLabelText, getByTestId, props } = renderHeader({ previousDisabled: true, nextDisabled: true })
+
+ fireEvent.press(getByLabelText("Previous trip"))
+ fireEvent.press(getByLabelText("Next trip"))
+
+ expect(props.onPrevious).not.toHaveBeenCalled()
+ expect(props.onNext).not.toHaveBeenCalled()
+ expect(getByLabelText("Previous trip").props.accessibilityState).toEqual({ disabled: true })
+ expect(getByTestId("icon-ChevronLeft").props.color).toBe(require("@colota/shared").lightColors.textDisabled)
+ })
+
+ it("reads the title and caption as one heading when the title opens nothing, with no chevron promising a picker", () => {
+ const { getByTestId, queryByTestId } = renderHeader()
+
+ const centre = getByTestId("trip-title")
+ expect(centre.props.accessibilityRole).toBe("header")
+ expect(centre.props.accessibilityLabel).toBe("Trip 2, Wed, Sep 3 · 12:05 - 12:21")
+ expect(queryByTestId("icon-ChevronDown")).toBeNull()
+ })
+
+ it("makes the title a button with a down chevron when it opens a picker", () => {
+ const onPress = jest.fn()
+ const { getByTestId } = renderHeader({ onPress, accessibilityHint: "Opens the calendar" })
+
+ const centre = getByTestId("trip-title")
+ expect(centre.props.accessibilityRole).toBe("button")
+ expect(centre.props.accessibilityHint).toBe("Opens the calendar")
+ expect(getByTestId("icon-ChevronDown")).toBeTruthy()
+ fireEvent.press(centre)
+ expect(onPress).toHaveBeenCalledTimes(1)
+ })
+
+ it("draws a leading mark before the title, so a trip carries its swatch into the header", () => {
+ const { getByText } = renderHeader({ leading: <Text>swatch</Text> })
+
+ expect(getByText("swatch")).toBeTruthy()
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/Tab.test.tsx b/apps/mobile/src/components/ui/__tests__/Tab.test.tsx
new file mode 100644
index 00000000..0d9f6dca
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/Tab.test.tsx
@@ -0,0 +1,74 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { lightColors, radius } from "@colota/shared"
+import { size, space } from "../../../constants"
+import { fonts } from "../../../styles/typography"
+
+import { Tab } from "../Tab"
+
+const props = { label: "Trips", onPress: jest.fn(), colors: lightColors as never }
+
+type Node = { type: unknown; parent: Node | null; props: { style?: unknown } }
+
+function wrapperStyle(label: Node) {
+ let node = label.parent
+ while (node && node.type !== "View") node = node.parent
+ return StyleSheet.flatten(node!.props.style as never)
+}
+
+describe("Tab", () => {
+ it("says it is a tab and which one is selected", () => {
+ const { getByRole, rerender } = render(<Tab {...props} active />)
+
+ expect(getByRole("tab", { name: "Trips" }).props.accessibilityState.selected).toBe(true)
+
+ rerender(<Tab {...props} active={false} />)
+ expect(getByRole("tab", { name: "Trips" }).props.accessibilityState.selected).toBe(false)
+ })
+
+ it("is at least a 48 dp target with the label centred in it", () => {
+ // A tab is a screen's sole switcher, so a short label must not shrink its target below the touch floor.
+ const { getByRole } = render(<Tab {...props} active={false} />)
+ const style = StyleSheet.flatten(getByRole("tab").props.style)
+
+ expect(style.minHeight).toBe(size.touch)
+ expect(style.justifyContent).toBe("center")
+ expect(style.flex).toBe(1)
+ })
+
+ it("underlines the label, not the whole tab, so the indicator reads as the word's width", () => {
+ const { getByRole, getByText, rerender } = render(<Tab {...props} active />)
+
+ const tab = StyleSheet.flatten(getByRole("tab").props.style)
+ expect(tab.borderBottomWidth).toBeUndefined()
+ expect(tab.borderTopLeftRadius).toBeUndefined()
+
+ const wrapper = wrapperStyle(getByText("Trips"))
+ expect(wrapper.borderBottomWidth).toBe(2)
+ expect(wrapper.borderBottomColor).toBe(lightColors.primary)
+ expect(wrapper.borderTopLeftRadius).toBe(radius.xs)
+ expect(wrapper.borderTopRightRadius).toBe(radius.xs)
+ expect(wrapper.paddingHorizontal).toBe(space.xs)
+
+ rerender(<Tab {...props} active={false} />)
+ // The rule stays drawn and only its colour changes, so the label does not jump when the tab is chosen.
+ const resting = wrapperStyle(getByText("Trips"))
+ expect(resting.borderBottomWidth).toBe(2)
+ expect(resting.borderBottomColor).toBe("transparent")
+ })
+
+ it("marks the shown tab with weight and the text colour, not the accent", () => {
+ // Primary as text is under the contrast floor on the ground; the rule and the weight already carry the state.
+ const { getByText, rerender } = render(<Tab {...props} active />)
+
+ const active = StyleSheet.flatten(getByText("Trips").props.style)
+ expect(active.color).toBe(lightColors.text)
+ expect(active.fontFamily).toBe(fonts.bold.fontFamily)
+
+ rerender(<Tab {...props} active={false} />)
+ const inactive = StyleSheet.flatten(getByText("Trips").props.style)
+ expect(inactive.color).toBe(lightColors.textSecondary)
+ expect(inactive.fontFamily).toBe(fonts.regular.fontFamily)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/TextField.test.tsx b/apps/mobile/src/components/ui/__tests__/TextField.test.tsx
new file mode 100644
index 00000000..1192e8d2
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/TextField.test.tsx
@@ -0,0 +1,113 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { StyleSheet } from "react-native"
+import { lightColors } from "@colota/shared"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { TextField } from "../TextField"
+
+const flat = (el: any) => StyleSheet.flatten(el.props.style)
+
+describe("TextField", () => {
+ it("keeps the text a constant distance from the edge as the border grows", () => {
+ // Focus takes the border from 1 to 2. Without the matching padding drop the caret and
+ // every character shift a pixel sideways the moment you tap in.
+ const { getByTestId } = render(<TextField label="Server address" testID="server-input" />)
+
+ const rest = flat(getByTestId("server-input-box"))
+ expect(rest.borderWidth + rest.paddingHorizontal).toBe(15)
+
+ fireEvent(getByTestId("server-input"), "focus")
+ const focused = flat(getByTestId("server-input-box"))
+ expect(focused.borderWidth).toBe(2)
+ expect(focused.borderWidth + focused.paddingHorizontal).toBe(15)
+ })
+
+ it("rests without a ring and grows one on focus and on error", () => {
+ // A border marks state, so the resting field is a fill. The ring's width is what the box
+ // gives back in padding, or the text would jump sideways as you tap in.
+ const { getByTestId, rerender } = render(<TextField label="Server address" testID="server-input" />)
+ expect(flat(getByTestId("server-input-box")).borderWidth).toBe(0)
+
+ fireEvent(getByTestId("server-input"), "focus")
+ expect(flat(getByTestId("server-input-box")).borderWidth).toBe(2)
+ expect(flat(getByTestId("server-input-box")).borderColor).toBe(lightColors.primary)
+
+ rerender(<TextField label="Server address" testID="server-input" error="Public hosts need https" />)
+ expect(flat(getByTestId("server-input-box")).borderColor).toBe(lightColors.error)
+ })
+
+ it("can be asked for a resting outline, which it does not draw otherwise", () => {
+ const { getByTestId } = render(<TextField label="Server address" testID="server-input" border />)
+ const style = flat(getByTestId("server-input-box"))
+
+ expect(style.borderWidth).toBe(1)
+ expect(style.borderColor).toBe(lightColors.border)
+ })
+
+ it("reads the error out with the field name, because the ring alone is colour", () => {
+ const { getByTestId, getByText } = render(
+ <TextField label="Password" testID="pw-input" error="At least 8 characters" />
+ )
+
+ expect(getByTestId("pw-input").props.accessibilityLabel).toBe("Password, At least 8 characters")
+ expect(getByText("At least 8 characters")).toBeTruthy()
+ })
+
+ it("stops taking input and drops its ink when disabled", () => {
+ const { getByTestId } = render(<TextField label="Server address" testID="server-input" disabled />)
+
+ const input = getByTestId("server-input")
+ expect(input.props.editable).toBe(false)
+ expect(flat(input).color).toBe(lightColors.textDisabled)
+ expect(flat(getByTestId("server-input-box")).borderWidth).toBe(0)
+ })
+
+ it("passes keyboard and autofill props through to the input", () => {
+ // The union type lets a field skip the visible label only when a row already names it.
+ const { getByTestId } = render(
+ <TextField accessibilityLabel="Port" testID="port-input" keyboardType="numeric" autoComplete="off" />
+ )
+
+ const input = getByTestId("port-input")
+ expect(input.props.keyboardType).toBe("numeric")
+ expect(input.props.autoComplete).toBe("off")
+ expect(input.props.accessibilityLabel).toBe("Port")
+ })
+
+ it("reveals a secure field only while the eye is held", () => {
+ // Hold, not toggle: the password cannot be left on screen by a stray tap.
+ const { getByTestId } = render(<TextField label="Password" testID="pw-input" secure />)
+
+ expect(getByTestId("pw-input").props.secureTextEntry).toBe(true)
+ fireEvent(getByTestId("pw-input-reveal"), "pressIn")
+ expect(getByTestId("pw-input").props.secureTextEntry).toBe(false)
+ fireEvent(getByTestId("pw-input-reveal"), "pressOut")
+ expect(getByTestId("pw-input").props.secureTextEntry).toBe(true)
+ })
+
+ it("lifts the label to primary on focus, so the field you are in is named", () => {
+ const { getByTestId, getByText } = render(<TextField label="Server address" testID="server-input" />)
+ expect(flat(getByText("Server address")).color).toBe(lightColors.textSecondary)
+
+ fireEvent(getByTestId("server-input"), "focus")
+ expect(flat(getByText("Server address")).color).toBe(lightColors.primary)
+ })
+
+ it("sets an endpoint in monospace so a typo in a URL is findable", () => {
+ const { getByTestId } = render(<TextField label="Server address" testID="server-input" mono />)
+ expect(flat(getByTestId("server-input")).fontFamily).toBe("monospace")
+ })
+
+ it("recesses into its card rather than punching through to the ground behind it", () => {
+ // The fill was colors.background, so a field cut a hole the colour of the screen behind
+ // its card and a card holding fields read as a different tone from one that did not.
+ const { getByTestId } = render(<TextField label="Server address" testID="server-input" />)
+
+ expect(flat(getByTestId("server-input-box")).backgroundColor).toBe(lightColors.well)
+ expect(flat(getByTestId("server-input-box")).backgroundColor).not.toBe(lightColors.background)
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/TimePicker.test.tsx b/apps/mobile/src/components/ui/__tests__/TimePicker.test.tsx
new file mode 100644
index 00000000..a655bf41
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/TimePicker.test.tsx
@@ -0,0 +1,59 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { TimePicker } from "../TimePicker"
+
+describe("TimePicker", () => {
+ const onChange = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ function renderPicker(value = "14:05") {
+ return render(<TimePicker label="Time (24h)" value={value} onChange={onChange} />)
+ }
+
+ it("draws the label itself, so a caller does not hand-roll one beside it", () => {
+ const { getByText } = renderPicker()
+
+ expect(getByText("Time (24h)")).toBeTruthy()
+ })
+
+ it("names both fields with the label, because Hours alone does not say which time", () => {
+ const { getByLabelText } = renderPicker()
+
+ expect(getByLabelText("Time (24h), hours")).toBeTruthy()
+ expect(getByLabelText("Time (24h), minutes")).toBeTruthy()
+ })
+
+ it("pads a single digit on blur, so the value always round-trips as HH:mm", () => {
+ const { getByTestId } = renderPicker()
+
+ fireEvent.changeText(getByTestId("timepicker-hour-value"), "7")
+ fireEvent(getByTestId("timepicker-hour-value"), "blur")
+
+ expect(onChange).toHaveBeenCalledWith("07:05")
+ })
+
+ it("clamps an hour past 23 rather than storing an unparseable time", () => {
+ const { getByTestId } = renderPicker()
+
+ fireEvent.changeText(getByTestId("timepicker-hour-value"), "99")
+ fireEvent(getByTestId("timepicker-hour-value"), "blur")
+
+ expect(onChange).toHaveBeenCalledWith("23:05")
+ })
+
+ it("clamps a minute past 59 the same way", () => {
+ const { getByTestId } = renderPicker()
+
+ fireEvent.changeText(getByTestId("timepicker-minute-value"), "70")
+ fireEvent(getByTestId("timepicker-minute-value"), "blur")
+
+ expect(onChange).toHaveBeenCalledWith("14:59")
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/Toggle.test.tsx b/apps/mobile/src/components/ui/__tests__/Toggle.test.tsx
new file mode 100644
index 00000000..e3c41843
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/Toggle.test.tsx
@@ -0,0 +1,68 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+import { lightColors } from "@colota/shared"
+
+jest.mock("../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
+}))
+
+import { Toggle } from "../Toggle"
+
+describe("Toggle", () => {
+ it("puts the thumb on the container, not on its own colour at half alpha", () => {
+ const { getByTestId } = render(
+ <Toggle testID="t" value={true} onValueChange={jest.fn()} accessibilityLabel="Offline mode" />
+ )
+
+ // RN resolves trackColor and thumbColor into these before they reach the platform. The track
+ // was the accent at 50 percent, which left the thumb 2.4:1 against its own bar; the container
+ // takes that to 4.1 in light and 6.6 in dark.
+ const el = getByTestId("t")
+ expect(el.props.onTintColor).toBe(lightColors.primaryContainer)
+ expect(el.props.thumbTintColor).toBe(lightColors.primary)
+ })
+
+ it("leaves the off state to Android, so the thumb is not the colour of its own track", () => {
+ // Tinting both with colors.border made them identical at 1.00:1, so an off switch was a
+ // uniform pill with no visible thumb. Undefined clears the colour filter and restores the
+ // platform drawable, which also fixes how a disabled switch renders.
+ const { getByTestId } = render(
+ <Toggle testID="t" value={false} onValueChange={jest.fn()} accessibilityLabel="Offline mode" />
+ )
+
+ const el = getByTestId("t")
+ expect(el.props.thumbTintColor).toBeUndefined()
+ expect(el.props.tintColor).toBeUndefined()
+ })
+
+ it("gives every switch the same hue, because being on is not a warning", () => {
+ // The geofence pause toggle used to paint warning. It was the only one, it was not applied
+ // to the three sibling toggles that also stop GPS, and orange reads as a fault rather than
+ // as the setting working.
+ const { getByTestId } = render(
+ <Toggle testID="t" value={true} onValueChange={jest.fn()} accessibilityLabel="Pause" />
+ )
+
+ const el = getByTestId("t")
+ expect(el.props.onTintColor).toBe(lightColors.primaryContainer)
+ expect(el.props.thumbTintColor).toBe(lightColors.primary)
+ })
+
+ it("reports the change so a caller can persist it", () => {
+ const onValueChange = jest.fn()
+ const { getByTestId } = render(
+ <Toggle testID="t" value={false} onValueChange={onValueChange} accessibilityLabel="Offline mode" />
+ )
+
+ fireEvent(getByTestId("t"), "valueChange", true)
+ expect(onValueChange).toHaveBeenCalledWith(true)
+ })
+
+ it("carries the label so Voice Access can resolve the row by its visible words", () => {
+ const { getByTestId } = render(
+ <Toggle testID="t" value={false} onValueChange={jest.fn()} accessibilityLabel="Offline mode" />
+ )
+
+ expect(getByTestId("t").props.accessibilityLabel).toBe("Offline mode")
+ })
+})
diff --git a/apps/mobile/src/components/ui/__tests__/TrackMark.test.tsx b/apps/mobile/src/components/ui/__tests__/TrackMark.test.tsx
new file mode 100644
index 00000000..38d4582e
--- /dev/null
+++ b/apps/mobile/src/components/ui/__tests__/TrackMark.test.tsx
@@ -0,0 +1,19 @@
+import React from "react"
+import { render } from "@testing-library/react-native"
+import { TrackMark } from "../TrackMark"
+
+describe("TrackMark", () => {
+ it("draws a track that starts as a solid disc and ends as a ring, in the colour and weight it is given", () => {
+ const { UNSAFE_getAllByType } = render(<TrackMark size={24} color="#0B7D73" strokeWidth={2.25} />)
+ const { Circle, Path } = require("react-native-svg")
+
+ const path = UNSAFE_getAllByType(Path)[0]
+ expect(path.props.stroke).toBe("#0B7D73")
+ expect(path.props.strokeWidth).toBe(2.25)
+
+ const [disc, ring] = UNSAFE_getAllByType(Circle)
+ expect(disc.props.fill).toBe("#0B7D73")
+ expect(ring.props.fill).toBeUndefined()
+ expect(ring.props.stroke).toBe("#0B7D73")
+ })
+})
diff --git a/apps/mobile/src/hooks/__tests__/useTheme.test.tsx b/apps/mobile/src/hooks/__tests__/useTheme.test.tsx
index 124195be..482172f3 100644
--- a/apps/mobile/src/hooks/__tests__/useTheme.test.tsx
+++ b/apps/mobile/src/hooks/__tests__/useTheme.test.tsx
@@ -1,19 +1,23 @@
import React from "react"
import { renderHook, act, waitFor } from "@testing-library/react-native"
-import { Appearance } from "react-native"
+import { Appearance, AppState, Platform } from "react-native"
+import { lightColors, darkColors } from "@colota/shared"
import NativeLocationService from "../../services/NativeLocationService"
+import type { SystemPalette } from "../../styles/dynamicColors"
import { ThemeProvider, useTheme } from "../useTheme"
jest.mock("../../services/NativeLocationService", () => ({
__esModule: true,
default: {
getSetting: jest.fn().mockResolvedValue(null),
- saveSetting: jest.fn().mockResolvedValue(undefined)
+ saveSetting: jest.fn().mockResolvedValue(undefined),
+ getSystemPalette: jest.fn().mockResolvedValue(null)
}
}))
let appearanceListener: ((prefs: { colorScheme: string | null }) => void) | null = null
+let appStateListener: ((state: string) => void) | null = null
jest.spyOn(Appearance, "getColorScheme").mockReturnValue("light")
jest.spyOn(Appearance, "addChangeListener").mockImplementation((cb: any) => {
@@ -21,13 +25,47 @@ jest.spyOn(Appearance, "addChangeListener").mockImplementation((cb: any) => {
return { remove: jest.fn() }
})
+const palette: SystemPalette = {
+ accent1_100: "#D6E3FF",
+ accent1_200: "#ABC7FF",
+ accent1_300: "#8AB4F8",
+ accent1_600: "#2B5CB8",
+ accent1_700: "#12459E",
+ accent1_800: "#002E6B",
+ accent1_900: "#001B3F",
+ neutral1_0: "#FFFFFF",
+ neutral1_50: "#F3F3F6",
+ neutral1_600: "#5B5C63",
+ neutral1_700: "#43444B",
+ neutral1_800: "#2C2D33",
+ neutral1_900: "#1A1B1F",
+ neutral2_100: "#E3E2E9",
+ neutral2_200: "#C7C6CE",
+ neutral2_300: "#ABAAB2",
+ neutral2_400: "#909097",
+ neutral2_500: "#76767D",
+ neutral2_600: "#5E5E65",
+ neutral2_700: "#46464D",
+ neutral2_800: "#2F2F35"
+}
+
+const settings = (values: Record<string, string | null>) => {
+ ;(NativeLocationService.getSetting as jest.Mock).mockImplementation(async (key: string) => values[key] ?? null)
+}
+
const wrapper = ({ children }: { children: React.ReactNode }) => <ThemeProvider>{children}</ThemeProvider>
beforeEach(() => {
appearanceListener = null
+ appStateListener = null
;(Appearance.getColorScheme as jest.Mock).mockReturnValue("light")
;(NativeLocationService.getSetting as jest.Mock).mockResolvedValue(null)
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockClear().mockResolvedValue(null)
;(NativeLocationService.saveSetting as jest.Mock).mockClear()
+ ;(AppState.addEventListener as jest.Mock).mockImplementation((_: string, cb: (state: string) => void) => {
+ appStateListener = cb
+ return { remove: jest.fn() }
+ })
})
describe("useTheme", () => {
@@ -67,65 +105,70 @@ describe("useTheme", () => {
expect(result.current.mode).toBe("light")
})
- it("toggleTheme switches from light to dark", () => {
+ it("picking a mode overrides the system, which is the point of picking one", () => {
const { result } = renderHook(() => useTheme(), { wrapper })
act(() => {
- result.current.toggleTheme()
+ result.current.setPreference("dark")
})
expect(result.current.mode).toBe("dark")
expect(result.current.isDark).toBe(true)
})
- it("toggleTheme switches back from dark to light", () => {
+ it("keeps following the system until something is picked", () => {
const { result } = renderHook(() => useTheme(), { wrapper })
+ expect(result.current.preference).toBe("system")
+
act(() => {
- result.current.toggleTheme()
- })
- act(() => {
- result.current.toggleTheme()
+ appearanceListener!({ colorScheme: "dark" })
})
- expect(result.current.mode).toBe("light")
- expect(result.current.isDark).toBe(false)
+ expect(result.current.mode).toBe("dark")
})
- it("follows system theme changes when no manual override", () => {
- renderHook(() => useTheme(), { wrapper })
-
- expect(appearanceListener).not.toBeNull()
+ it("stops following the system once a mode is picked", () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
act(() => {
- appearanceListener!({ colorScheme: "dark" })
+ result.current.setPreference("dark")
+ })
+ act(() => {
+ appearanceListener?.({ colorScheme: "light" })
})
- expect(appearanceListener).toBeDefined()
+ expect(result.current.mode).toBe("dark")
})
- it("ignores system theme changes after manual toggle", () => {
+ it("follows the system again when system is picked back, which a toggle could not express", () => {
const { result } = renderHook(() => useTheme(), { wrapper })
act(() => {
- result.current.toggleTheme()
+ result.current.setPreference("dark")
+ })
+ act(() => {
+ result.current.setPreference("system")
})
- expect(result.current.mode).toBe("dark")
act(() => {
appearanceListener?.({ colorScheme: "light" })
})
- expect(result.current.mode).toBe("dark")
+ expect(result.current.mode).toBe("light")
})
- it("persists theme mode when toggled", () => {
+ it("persists the choice, system included, so a restart does not lose it", () => {
const { result } = renderHook(() => useTheme(), { wrapper })
act(() => {
- result.current.toggleTheme()
+ result.current.setPreference("dark")
})
-
expect(NativeLocationService.saveSetting).toHaveBeenCalledWith("themeMode", "dark")
+
+ act(() => {
+ result.current.setPreference("system")
+ })
+ expect(NativeLocationService.saveSetting).toHaveBeenCalledWith("themeMode", "system")
})
it("restores persisted dark theme on mount", async () => {
@@ -153,14 +196,142 @@ describe("useTheme", () => {
it("provides different color objects for light and dark modes", () => {
const { result } = renderHook(() => useTheme(), { wrapper })
- const lightColors = result.current.colors
+ const before = result.current.colors
act(() => {
- result.current.toggleTheme()
+ result.current.setPreference("dark")
})
- const darkColors = result.current.colors
+ expect(before).not.toBe(result.current.colors)
+ })
+})
+
+describe("wallpaper colors", () => {
+ it("separates what the platform offers from whether a palette arrived", async () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(NativeLocationService.getSystemPalette).toHaveBeenCalled()
+ })
+ expect(result.current.wallpaperPaletteReady).toBe(false)
+ expect(result.current.wallpaperColorsAvailable).toBe(Platform.OS === "android" && Number(Platform.Version) >= 31)
+ })
+
+ it("still offers the setting when the platform supports it but the read failed", async () => {
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(null)
+ // Version is a getter with no setter under the preset, so it is redefined rather than assigned.
+ const version = Object.getOwnPropertyDescriptor(Platform, "Version")
+ Object.defineProperty(Platform, "Version", { configurable: true, get: () => 34 })
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(NativeLocationService.getSystemPalette).toHaveBeenCalled()
+ })
+ expect(result.current.wallpaperColorsAvailable).toBe(Platform.OS === "android")
+ expect(result.current.wallpaperPaletteReady).toBe(false)
+ if (version) Object.defineProperty(Platform, "Version", version)
+ })
+
+ it("keeps the brand palette while the toggle is off, so having one is not using one", async () => {
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(palette)
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.wallpaperPaletteReady).toBe(true)
+ })
+ expect(result.current.colors.primary).toBe(lightColors.primary)
+ })
+
+ it("paints from the wallpaper once it is turned on", async () => {
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(palette)
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.wallpaperPaletteReady).toBe(true)
+ })
+ act(() => {
+ result.current.setWallpaperColors(true)
+ })
+
+ expect(result.current.colors.primary).toBe(palette.accent1_600)
+ })
+
+ it("stays on the brand palette when the bridge answers with nothing to map", async () => {
+ settings({ wallpaperColors: "true" })
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.wallpaperColors).toBe(true)
+ })
+ expect(result.current.colors).toBe(lightColors)
+ })
+
+ it("applies to dark as well, because the palette is not a fourth mode", async () => {
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(palette)
+ settings({ themeMode: "dark", wallpaperColors: "true" })
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.isDark).toBe(true)
+ })
+ expect(result.current.colors.primary).toBe(palette.accent1_200)
+ expect(result.current.colors.error).toBe(darkColors.error)
+ })
+
+ it("restores the saved choice on mount", async () => {
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(palette)
+ settings({ wallpaperColors: "true" })
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.wallpaperColors).toBe(true)
+ })
+ })
+
+ it("persists the choice, so a restart does not lose it", async () => {
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ act(() => {
+ result.current.setWallpaperColors(true)
+ })
+
+ expect(NativeLocationService.saveSetting).toHaveBeenCalledWith("wallpaperColors", "true")
+ })
+
+ it("re-reads the palette on foreground, because the wallpaper changes outside the app", async () => {
+ settings({ wallpaperColors: "true" })
+
+ const { result } = renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(result.current.wallpaperColors).toBe(true)
+ })
+ ;(NativeLocationService.getSystemPalette as jest.Mock).mockResolvedValue(palette)
+
+ await act(async () => {
+ appStateListener!("active")
+ })
+
+ expect(result.current.colors.primary).toBe(palette.accent1_600)
+ })
+
+ it("ignores a background transition, which cannot have changed the wallpaper on screen", async () => {
+ renderHook(() => useTheme(), { wrapper })
+
+ await waitFor(() => {
+ expect(NativeLocationService.getSystemPalette).toHaveBeenCalledTimes(1)
+ })
+
+ await act(async () => {
+ appStateListener!("background")
+ })
- expect(lightColors).not.toBe(darkColors)
+ expect(NativeLocationService.getSystemPalette).toHaveBeenCalledTimes(1)
})
})
diff --git a/apps/mobile/src/hooks/useTheme.tsx b/apps/mobile/src/hooks/useTheme.tsx
index 3a55ea52..4097d737 100644
--- a/apps/mobile/src/hooks/useTheme.tsx
+++ b/apps/mobile/src/hooks/useTheme.tsx
@@ -4,12 +4,16 @@
*/
import React, { useState, useEffect, useContext, createContext, ReactNode, useMemo, useCallback } from "react"
-import { Appearance, ColorSchemeName } from "react-native"
+import { Appearance, AppState, ColorSchemeName, Platform } from "react-native"
import { ThemeColors, ThemeMode } from "../types/global"
import { darkColors, lightColors } from "../styles/colors"
+import { buildDynamicColors, type SystemPalette } from "../styles/dynamicColors"
import NativeLocationService from "../services/NativeLocationService"
const THEME_MODE_KEY = "themeMode"
+const WALLPAPER_COLORS_KEY = "wallpaperColors"
+
+export type ThemePreference = "system" | "light" | "dark"
/**
* Extended theme context with additional utilities
@@ -17,8 +21,16 @@ const THEME_MODE_KEY = "themeMode"
interface ThemeContextType {
colors: ThemeColors
mode: ThemeMode
+ preference: ThemePreference
+ setPreference: (preference: ThemePreference) => void
toggleTheme: () => void
isDark: boolean
+ wallpaperColors: boolean
+ setWallpaperColors: (enabled: boolean) => void
+ /** False below API 31, where the platform has no wallpaper palette to offer. */
+ wallpaperColorsAvailable: boolean
+ /** Whether a palette has been read. Separate from availability, so a failed read still offers the switch. */
+ wallpaperPaletteReady: boolean
}
/**
@@ -34,8 +46,9 @@ const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
* Theme provider managing theme state and system theme synchronization.
*
* Features:
- * - Automatically follows system theme unless manually overridden
- * - Manual theme toggle support
+ * - Follows the system scheme until the user picks light or dark
+ * - The choice persists; picking "system" hands control back
+ * - Light, dark and the wallpaper palette are separate choices, so the palette applies to all three modes
* - Memoized values for optimal performance
*
* @example
@@ -46,52 +59,80 @@ const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
* ```
*/
export const ThemeProvider = ({ children }: { children: ReactNode }) => {
- const [hasManualOverride, setHasManualOverride] = useState(false)
- const [mode, setMode] = useState<ThemeMode>(() => normalizeScheme(Appearance.getColorScheme()))
+ const [preference, setPreferenceState] = useState<ThemePreference>("system")
+ const [systemScheme, setSystemScheme] = useState<ThemeMode>(() => normalizeScheme(Appearance.getColorScheme()))
+ const [wallpaperColors, setWallpaperColorsState] = useState(false)
+ const [palette, setPalette] = useState<SystemPalette | null>(null)
- // Restore persisted theme preference on mount
+ // A stored value is an explicit choice; nothing stored means the system decides.
useEffect(() => {
NativeLocationService.getSetting(THEME_MODE_KEY).then((saved) => {
- if (saved === "light" || saved === "dark") {
- setHasManualOverride(true)
- setMode(saved)
+ if (saved === "light" || saved === "dark" || saved === "system") {
+ setPreferenceState(saved)
}
})
+ NativeLocationService.getSetting(WALLPAPER_COLORS_KEY).then((saved) => {
+ if (saved === "true") setWallpaperColorsState(true)
+ })
}, [])
- // Listen to system theme changes
useEffect(() => {
const subscription = Appearance.addChangeListener(({ colorScheme }) => {
- if (!hasManualOverride) {
- setMode(normalizeScheme(colorScheme))
- }
+ setSystemScheme(normalizeScheme(colorScheme))
})
return () => subscription.remove()
- }, [hasManualOverride])
-
- /**
- * Toggles between light and dark theme
- */
- const toggleTheme = useCallback(() => {
- setHasManualOverride(true)
- setMode((prev: string) => {
- const next = prev === "light" ? "dark" : "light"
- NativeLocationService.saveSetting(THEME_MODE_KEY, next)
- return next
+ }, [])
+
+ // The palette changes with the wallpaper, which happens outside the app, so it is re-read on
+ // every foreground rather than once on mount. A null answer keeps the last palette: the API
+ // level cannot drop mid-process, so null after a success is a failed read, not a lost palette.
+ useEffect(() => {
+ const read = () =>
+ NativeLocationService.getSystemPalette().then((next) => {
+ if (next) setPalette(next)
+ })
+ read()
+ const subscription = AppState.addEventListener("change", (state) => {
+ if (state === "active") read()
})
+
+ return () => subscription.remove()
+ }, [])
+
+ const setPreference = useCallback((next: ThemePreference) => {
+ setPreferenceState(next)
+ NativeLocationService.saveSetting(THEME_MODE_KEY, next)
}, [])
- const colors = useMemo(() => (mode === "dark" ? darkColors : lightColors), [mode])
+ const setWallpaperColors = useCallback((enabled: boolean) => {
+ setWallpaperColorsState(enabled)
+ NativeLocationService.saveSetting(WALLPAPER_COLORS_KEY, String(enabled))
+ }, [])
+
+ const mode: ThemeMode = preference === "system" ? systemScheme : preference
+
+ const colors = useMemo(() => {
+ if (wallpaperColors && palette) return buildDynamicColors(palette, mode === "dark")
+ return mode === "dark" ? darkColors : lightColors
+ }, [mode, wallpaperColors, palette])
+
+ const toggleTheme = useCallback(() => setPreference(mode === "dark" ? "light" : "dark"), [mode, setPreference])
const contextValue = useMemo(
() => ({
colors,
mode,
+ preference,
+ setPreference,
toggleTheme,
- isDark: mode === "dark"
+ isDark: mode === "dark",
+ wallpaperColors,
+ setWallpaperColors,
+ wallpaperColorsAvailable: Platform.OS === "android" && Number(Platform.Version) >= 31,
+ wallpaperPaletteReady: palette !== null
}),
- [colors, mode, toggleTheme]
+ [colors, mode, preference, setPreference, wallpaperColors, setWallpaperColors, palette, toggleTheme]
)
return <ThemeContext.Provider value={contextValue}>{children}</ThemeContext.Provider>
@@ -100,15 +141,16 @@ export const ThemeProvider = ({ children }: { children: ReactNode }) => {
/**
* Hook to access theme context.
*
- * Provides colors, mode, toggleTheme, and isDark.
+ * Provides colors, mode, preference, setPreference, isDark, wallpaperColors, setWallpaperColors
+ * wallpaperColorsAvailable and wallpaperPaletteReady.
*
* @throws If used outside ThemeProvider
*
* @example
* ```tsx
- * const { colors, mode, toggleTheme } = useTheme();
+ * const { colors, mode, setPreference } = useTheme();
* <View style={{ backgroundColor: colors.background }}>
- * <Button onPress={toggleTheme} title="Toggle Theme" />
+ * <Button onPress={() => setPreference("dark")} title="Dark" />
* </View>
* ```
*/
diff --git a/apps/mobile/src/i18n/__tests__/i18n.test.ts b/apps/mobile/src/i18n/__tests__/i18n.test.ts
index e8c8118f..8f7cb03a 100644
--- a/apps/mobile/src/i18n/__tests__/i18n.test.ts
+++ b/apps/mobile/src/i18n/__tests__/i18n.test.ts
@@ -46,7 +46,7 @@ describe("initI18n", () => {
initI18n()
- expect(t("appearance.darkMode")).toBe("Dark Mode")
+ expect(t("appearance.theme")).toBe("Theme")
})
it("returns the key itself when it is missing, rather than empty text", () => {
diff --git a/apps/mobile/src/i18n/index.ts b/apps/mobile/src/i18n/index.ts
index 378ed23f..a96282e6 100644
--- a/apps/mobile/src/i18n/index.ts
+++ b/apps/mobile/src/i18n/index.ts
@@ -54,7 +54,7 @@ export function initI18n(): SupportedLanguage {
// starts mattering the day the screen-config and preset constants become keys.
initI18n()
-/** The non-React entry point. Nothing calls it yet; modalService and setupConfig are the ones that will. */
+/** The non-React entry point, for a caller with no hook available. `utils/appearance` uses it. */
export function t(key: string, options?: Record<string, unknown>): string {
return i18next.t(key, options) as string
}
diff --git a/apps/mobile/src/i18n/locales/en.json b/apps/mobile/src/i18n/locales/en.json
index 2be07253..e9ab63a7 100644
--- a/apps/mobile/src/i18n/locales/en.json
+++ b/apps/mobile/src/i18n/locales/en.json
@@ -1,14 +1,23 @@
{
- "appearance.darkMode": "Dark Mode",
+ "appearance.theme": "Theme",
+ "appearance.theme.system": "System",
+ "appearance.theme.light": "Light",
+ "appearance.theme.dark": "Dark",
+ "appearance.wallpaperColors": "Wallpaper colors",
+ "appearance.wallpaperColors.hint": "Accents and surfaces follow the Android wallpaper. Warnings and errors keep their color.",
"appearance.units": "Units",
"appearance.units.metric": "Metric",
"appearance.units.imperial": "Imperial",
- "appearance.timeFormat": "Time Format",
- "appearance.mapTileServer": "Map Tile Server",
+ "appearance.timeFormat": "Time format",
+ "appearance.timeFormat.24h": "24h",
+ "appearance.timeFormat.12h": "12h",
+ "appearance.mapTileServer": "Map tile server",
"appearance.mapStyle.placeholder": "Default",
- "appearance.mapStyle.emptyHint": "Leave empty to use the default",
+ "appearance.mapStyle.emptyHint": "Leave empty for the default. Offline areas download from the light style.",
"appearance.mapStyle.reset": "Reset to default",
- "appearance.mapStyle.subtitle": "Override the default map tile source",
"appearance.mapStyle.light": "Light style URL",
- "appearance.mapStyle.dark": "Dark style URL"
+ "appearance.mapStyle.dark": "Dark style URL",
+ "appearance.mapStyle.error": "Starts with http:// or https:// and names a host.",
+ "appearance.darkMode": "Dark Mode",
+ "appearance.mapStyle.subtitle": "Override the default map tile source"
}
diff --git a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx
index 39c03ee4..f1692266 100644
--- a/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/AppearanceScreen.test.tsx
@@ -66,7 +66,7 @@ describe("AppearanceScreen", () => {
expect(getByText("Dark Mode")).toBeTruthy()
expect(getByText("Units")).toBeTruthy()
- expect(getByText("Time Format")).toBeTruthy()
+ expect(getByText("Time format")).toBeTruthy()
expect(getByTestId("dark-mode-switch")).toBeTruthy()
})
diff --git a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
index 5de1e911..c6fdedfa 100644
--- a/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/LocationHistoryScreen.test.tsx
@@ -174,6 +174,7 @@ jest.mock("../../components/features/inspector/LocationTable", () => {
})
jest.mock("../../styles/typography", () => ({
+ ...jest.requireActual("../../styles/typography"),
fonts: { regular: {}, bold: {}, semiBold: {} }
}))
diff --git a/apps/mobile/src/styles/typography.ts b/apps/mobile/src/styles/typography.ts
index ddefa973..2535b7af 100644
--- a/apps/mobile/src/styles/typography.ts
+++ b/apps/mobile/src/styles/typography.ts
@@ -7,9 +7,21 @@
*/
import { TextStyle } from "react-native"
-import { fontFamily } from "@colota/shared"
+import { fontFamily, fontSizes } from "@colota/shared"
-export { fontSizes } from "@colota/shared"
+export { fontSizes }
+
+/**
+ * Keys are `fontSizes` names, minus the seven sizes that set no line height and run on the platform
+ * default. `mono` is the exception: it sits at caption size and takes more leading.
+ */
+export const lineHeights = {
+ body: 20,
+ description: 18,
+ caption: 16,
+ small: 16,
+ mono: 18
+} as const
export const fonts: Record<string, Pick<TextStyle, "fontFamily">> = {
regular: { fontFamily: `${fontFamily}-Regular` },
@@ -17,3 +29,22 @@ export const fonts: Record<string, Pick<TextStyle, "fontFamily">> = {
semiBold: { fontFamily: `${fontFamily}-SemiBold` },
bold: { fontFamily: `${fontFamily}-Bold` }
}
+
+/**
+ * A role is a size and everything that always travels with it, so a caller names the job rather
+ * than composing one. Only the sizes that are used at a single weight across the app are roles:
+ * `body`, `description` and `caption` are each used at three or four weights, so a role for them
+ * would pick a weight for call sites that disagree. Those keep composing `fontSizes` by hand.
+ */
+export const type = {
+ /** The one screen-owning number or title, as on About and the error boundary. */
+ display: { fontSize: fontSizes.screenTitle, ...fonts.bold },
+ /** A stat's value. Tabular so the digits do not jitter as it counts. */
+ figure: { fontSize: fontSizes.statValue, ...fonts.bold, fontVariant: ["tabular-nums"] },
+ /** A card or dialog title. */
+ title: { fontSize: fontSizes.cardTitle, ...fonts.bold },
+ /** A heading inside a screen, above a block rather than a group of rows. */
+ heading: { fontSize: fontSizes.heading, ...fonts.bold },
+ /** A block of code, a log line or a payload: the platform monospace, never Inter. */
+ mono: { fontSize: fontSizes.caption, fontFamily: "monospace", lineHeight: lineHeights.mono }
+} as const satisfies Record<string, TextStyle>
diff --git a/apps/mobile/src/testing/componentStubs.tsx b/apps/mobile/src/testing/componentStubs.tsx
new file mode 100644
index 00000000..f2c84a09
--- /dev/null
+++ b/apps/mobile/src/testing/componentStubs.tsx
@@ -0,0 +1,52 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ *
+ * Stubs shared by the barrel mocks in `__tests__`. A jest.mock factory cannot close over
+ * anything, so each one requires this by path from inside the factory.
+ */
+
+import React from "react"
+import { View, Text, TextInput, Pressable } from "react-native"
+
+/** Mirrors TextField: the label above, the input, and the message only when error is a string. */
+export function TextFieldStub({ label, error, secure: _secure, mono: _mono, style: _style, ...rest }: any) {
+ return (
+ <View>
+ {label ? <Text>{label}</Text> : null}
+ <TextInput {...rest} />
+ {typeof error === "string" ? <Text>{error}</Text> : null}
+ </View>
+ )
+}
+
+/** Mirrors ListItem: label, sub, and the press target the test fires. */
+export function ListItemStub({ label, sub, onPress, testID, disabled, expanded }: any) {
+ return (
+ <Pressable testID={testID} onPress={onPress} disabled={disabled} accessibilityState={{ disabled, expanded }}>
+ <Text>{label}</Text>
+ {sub ? <Text>{sub}</Text> : null}
+ </Pressable>
+ )
+}
+
+/** Mirrors IconButton: a press target the test can find by testID, named for TalkBack. */
+export function IconButtonStub({ onPress, testID, accessibilityLabel, disabled, loading }: any) {
+ return (
+ <Pressable
+ testID={testID}
+ onPress={onPress}
+ disabled={disabled || loading}
+ accessibilityLabel={accessibilityLabel}
+ />
+ )
+}
+
+export function EmptyStateStub({ title, hint }: any) {
+ return React.createElement(
+ View,
+ null,
+ React.createElement(Text, null, title),
+ hint ? React.createElement(Text, null, hint) : null
+ )
+}
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index 9e64f1aa..4dd35441 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -41,7 +41,6 @@ export type RootStackRoute = keyof RootStackParamList
export type RootScreenProps<Route extends RootStackRoute> = NativeStackScreenProps<RootStackParamList, Route>
declare global {
- // eslint-disable-next-line @typescript-eslint/no-namespace
namespace ReactNavigation {
interface RootParamList extends RootStackParamList {}
}
diff --git a/package-lock.json b/package-lock.json
index d439e435..a2fde7aa 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -49,7 +49,7 @@
"@react-navigation/native": "^7.2.5",
"@react-navigation/native-stack": "^7.16.0",
"i18next": "^26.4.2",
- "lucide-react-native": "^1.17.0",
+ "lucide-react-native": "^1.31.0",
"react": "19.2.8",
"react-native": "0.87.0",
"react-native-safe-area-context": "^5.8.0",