Skip to content

Colota - Android GPS Location tracker

Replace Alert.alert with themed AppModal across the app

Max Dietrich26e695a6cffd
diff --git a/apps/mobile/src/components/index.ts b/apps/mobile/src/components/index.ts
index 5f1fcb7b..04425337 100644
--- a/apps/mobile/src/components/index.ts
+++ b/apps/mobile/src/components/index.ts
@@ -23,6 +23,7 @@ export { FloatingSaveIndicator } from "./ui/FloatingSaveIndicator"
export { Footer } from "./ui/Footer"
export { SpinningLoader } from "./ui/SpinningLoader"
export { LocationDisclosureModal } from "./ui/LocationDisclosureModal"
+export { AppModal } from "./ui/AppModal"
// ============================================================================
// Feature Components - Dashboard
diff --git a/apps/mobile/src/components/ui/AppModal.tsx b/apps/mobile/src/components/ui/AppModal.tsx
new file mode 100644
index 00000000..463eb5ce
--- /dev/null
+++ b/apps/mobile/src/components/ui/AppModal.tsx
@@ -0,0 +1,183 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useState, useRef, useEffect, useCallback } from "react"
+import { Modal, View, Text, TouchableOpacity, StyleSheet, BackHandler } from "react-native"
+import { Info, AlertCircle, AlertTriangle, CheckCircle } from "lucide-react-native"
+import { useTheme } from "../../hooks/useTheme"
+import { fonts } from "../../styles/typography"
+import { fontSizes } from "@colota/shared"
+import { type ModalRequest, type AlertVariant, registerModalHandler } from "../../services/modalService"
+
+const VARIANT_ICONS = {
+ info: Info,
+ error: AlertCircle,
+ warning: AlertTriangle,
+ success: CheckCircle
+} as const
+
+export function AppModal() {
+ const { colors } = useTheme()
+ const [current, setCurrent] = useState<ModalRequest | null>(null)
+ const queueRef = useRef<ModalRequest[]>([])
+
+ const processNext = useCallback(() => {
+ if (queueRef.current.length > 0) {
+ setCurrent(queueRef.current.shift()!)
+ } else {
+ setCurrent(null)
+ }
+ }, [])
+
+ useEffect(() => {
+ registerModalHandler((request) => {
+ if (current) {
+ queueRef.current.push(request)
+ } else {
+ setCurrent(request)
+ }
+ })
+ }, [current])
+
+ useEffect(() => {
+ if (!current) return
+ const handler = BackHandler.addEventListener("hardwareBackPress", () => true)
+ return () => handler.remove()
+ }, [current])
+
+ const handlePress = useCallback(
+ (index: number) => {
+ current?.resolve(index)
+ processNext()
+ },
+ [current, processNext]
+ )
+
+ if (!current) return null
+
+ const Icon = VARIANT_ICONS[current.variant]
+ const iconColor = getVariantColor(current.variant, colors)
+
+ 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>
+
+ <Text style={[styles.title, { color: colors.text }]}>{current.title}</Text>
+ <Text style={[styles.body, { color: colors.textSecondary }]}>{current.message}</Text>
+
+ <View style={styles.buttons}>
+ {current.buttons.map((btn, i) => {
+ const btnStyles = getButtonStyles(btn.style, colors)
+ return (
+ <TouchableOpacity
+ key={i}
+ style={[styles.button, btnStyles.container]}
+ onPress={() => handlePress(i)}
+ activeOpacity={0.7}
+ >
+ <Text style={[styles.buttonText, btnStyles.text]}>{btn.text}</Text>
+ </TouchableOpacity>
+ )
+ })}
+ </View>
+ </View>
+ </View>
+ </Modal>
+ )
+}
+
+function getVariantColor(variant: AlertVariant, colors: ReturnType<typeof useTheme>["colors"]): string {
+ switch (variant) {
+ case "error":
+ return colors.error
+ case "warning":
+ return colors.warning
+ case "success":
+ return colors.success
+ default:
+ return colors.info
+ }
+}
+
+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,
+ justifyContent: "center",
+ alignItems: "center",
+ alignSelf: "center",
+ marginBottom: 16
+ },
+ title: {
+ fontSize: fontSizes.cardTitle,
+ ...fonts.bold,
+ textAlign: "center",
+ marginBottom: 12
+ },
+ body: {
+ fontSize: fontSizes.body,
+ ...fonts.regular,
+ lineHeight: 20,
+ textAlign: "center"
+ },
+ buttons: {
+ flexDirection: "row",
+ gap: 12,
+ marginTop: 24
+ },
+ button: {
+ flex: 1,
+ paddingVertical: 14,
+ borderRadius: 8,
+ alignItems: "center"
+ },
+ buttonText: {
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
+ }
+})
diff --git a/apps/mobile/src/contexts/TrackingProvider.tsx b/apps/mobile/src/contexts/TrackingProvider.tsx
index cf449e84..be9af2ef 100644
--- a/apps/mobile/src/contexts/TrackingProvider.tsx
+++ b/apps/mobile/src/contexts/TrackingProvider.tsx
@@ -9,6 +9,7 @@ import { useLocationTracking } from "../hooks/useLocationTracking"
import NativeLocationService from "../services/NativeLocationService"
import SettingsService from "../services/SettingsService"
import { LocationDisclosureModal } from "../components/ui/LocationDisclosureModal"
+import { AppModal } from "../components/ui/AppModal"
import { logger } from "../utils/logger"
type TrackingContextType = {
@@ -259,6 +260,7 @@ export function TrackingProvider({ children }: { children: React.ReactNode }) {
return (
<TrackingContext.Provider value={value}>
<LocationDisclosureModal />
+ <AppModal />
{children}
</TrackingContext.Provider>
)
diff --git a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
index 714eaf7d..3d16b9bc 100644
--- a/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
+++ b/apps/mobile/src/contexts/__tests__/TrackingProvider.test.tsx
@@ -20,6 +20,10 @@ jest.mock("../../components/ui/LocationDisclosureModal", () => ({
LocationDisclosureModal: () => null
}))
+jest.mock("../../components/ui/AppModal", () => ({
+ AppModal: () => null
+}))
+
const mockStartTracking = jest.fn().mockResolvedValue(undefined)
const mockStopTracking = jest.fn()
const mockRestartTracking = jest.fn().mockResolvedValue(undefined)
diff --git a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts
index f627244a..23c7adea 100644
--- a/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts
+++ b/apps/mobile/src/hooks/__tests__/useLocationTracking.test.ts
@@ -1,6 +1,11 @@
import { renderHook, act } from "@testing-library/react-native"
-import { Alert } from "react-native"
import { DEFAULT_SETTINGS } from "../../types/global"
+import { showAlert } from "../../services/modalService"
+
+jest.mock("../../services/modalService", () => ({
+ showAlert: jest.fn(),
+ showConfirm: jest.fn()
+}))
// Mock NativeLocationService
const mockStart = jest.fn().mockResolvedValue(undefined)
@@ -36,7 +41,6 @@ import { useLocationTracking } from "../useLocationTracking"
beforeEach(() => {
jest.clearAllMocks()
- jest.spyOn(Alert, "alert").mockImplementation()
jest.spyOn(console, "log").mockImplementation()
jest.spyOn(console, "error").mockImplementation()
})
@@ -91,7 +95,7 @@ describe("useLocationTracking", () => {
await result.current.startTracking(DEFAULT_SETTINGS)
})
- expect(Alert.alert).toHaveBeenCalledWith("Permission Required", expect.any(String))
+ expect(showAlert).toHaveBeenCalledWith("Permission Required", expect.any(String), "warning")
expect(mockStart).not.toHaveBeenCalled()
expect(result.current.tracking).toBe(false)
})
@@ -105,7 +109,7 @@ describe("useLocationTracking", () => {
})
expect(result.current.tracking).toBe(false)
- expect(Alert.alert).toHaveBeenCalledWith("Error", expect.any(String))
+ expect(showAlert).toHaveBeenCalledWith("Error", expect.any(String), "error")
})
})
diff --git a/apps/mobile/src/hooks/useLocationTracking.ts b/apps/mobile/src/hooks/useLocationTracking.ts
index fc0e52fb..6b21626d 100644
--- a/apps/mobile/src/hooks/useLocationTracking.ts
+++ b/apps/mobile/src/hooks/useLocationTracking.ts
@@ -4,8 +4,9 @@
*/
import { useState, useEffect, useRef, useCallback } from "react"
-import { NativeEventEmitter, NativeModules, Alert } from "react-native"
+import { NativeEventEmitter, NativeModules } from "react-native"
import NativeLocationService from "../services/NativeLocationService"
+import { showAlert } from "../services/modalService"
import { LocationCoords, Settings, LocationTrackingResult } from "../types/global"
import { ensurePermissions } from "../services/LocationServicePermission"
import { logger } from "../utils/logger"
@@ -153,7 +154,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult
const granted = await ensurePermissions()
if (!granted) {
- Alert.alert("Permission Required", "Background location permission is required for tracking.")
+ showAlert("Permission Required", "Background location permission is required for tracking.", "warning")
return
}
@@ -165,7 +166,7 @@ export function useLocationTracking(settings: Settings): LocationTrackingResult
} catch (error) {
setTracking(false)
logger.error("[useLocationTracking] Failed to start:", error)
- Alert.alert("Error", "Failed to start location tracking.")
+ showAlert("Error", "Failed to start location tracking.", "error")
}
}, [])
diff --git a/apps/mobile/src/screens/ExportDataScreen.tsx b/apps/mobile/src/screens/ExportDataScreen.tsx
index df725966..f3599eb9 100644
--- a/apps/mobile/src/screens/ExportDataScreen.tsx
+++ b/apps/mobile/src/screens/ExportDataScreen.tsx
@@ -4,7 +4,7 @@
*/
import React, { useState, useEffect, useCallback, useRef } from "react"
-import { Text, StyleSheet, View, Alert, ActivityIndicator, ScrollView, TouchableOpacity } from "react-native"
+import { Text, StyleSheet, View, ActivityIndicator, ScrollView, TouchableOpacity } from "react-native"
import { fonts } from "../styles/typography"
import { Download, type LucideIcon } from "lucide-react-native"
import { Container, Card, SectionTitle, Divider } from "../components"
@@ -13,6 +13,7 @@ import { ThemeColors, LocationCoords } from "../types/global"
import NativeLocationService from "../services/NativeLocationService"
import { LARGE_FILE_THRESHOLD, formatBytes, getByteSize, EXPORT_FORMATS, ExportFormat } from "../utils/exportConverters"
import { logger } from "../utils/logger"
+import { showAlert, showConfirm } from "../services/modalService"
interface ExportStats {
totalLocations: number
@@ -62,7 +63,7 @@ export function ExportDataScreen() {
const handleExport = async (format: ExportFormat) => {
if (stats.totalLocations === 0) {
- Alert.alert("No Data", "There are no locations in the database to export.")
+ showAlert("No Data", "There are no locations in the database to export.", "info")
return
}
@@ -85,20 +86,10 @@ export function ExportDataScreen() {
setExporting(false)
setExportProgress("")
- const confirmed = await new Promise<boolean>((resolve) => {
- Alert.alert(
- "Large Export",
- `The export file is ${formatBytes(exportSize)}. This may take a moment to save and share. Continue?`,
- [
- {
- text: "Cancel",
- style: "cancel",
- onPress: () => resolve(false)
- },
- { text: "Continue", onPress: () => resolve(true) }
- ],
- { cancelable: false }
- )
+ const confirmed = await showConfirm({
+ title: "Large Export",
+ message: `The export file is ${formatBytes(exportSize)}. This may take a moment to save and share. Continue?`,
+ confirmText: "Continue"
})
if (!confirmed) {
@@ -127,7 +118,7 @@ export function ExportDataScreen() {
}
} catch (error) {
logger.error("[ExportDataScreen] Export failed:", error)
- Alert.alert("Export Failed", "Unable to export your data. Please try again.")
+ showAlert("Export Failed", "Unable to export your data. Please try again.", "error")
} finally {
setExporting(false)
setExportProgress("")
diff --git a/apps/mobile/src/screens/GeofenceScreen.tsx b/apps/mobile/src/screens/GeofenceScreen.tsx
index 8f3db09a..b20dd057 100644
--- a/apps/mobile/src/screens/GeofenceScreen.tsx
+++ b/apps/mobile/src/screens/GeofenceScreen.tsx
@@ -4,20 +4,11 @@
*/
import React, { useState, useEffect, useRef, useMemo, useCallback } from "react"
-import {
- View,
- Text,
- StyleSheet,
- TextInput,
- TouchableOpacity,
- FlatList,
- Alert,
- Switch,
- DeviceEventEmitter
-} from "react-native"
+import { View, Text, StyleSheet, TextInput, TouchableOpacity, FlatList, Switch, DeviceEventEmitter } from "react-native"
import { WebView } from "react-native-webview"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
+import { showAlert, showConfirm } from "../services/modalService"
import { Geofence, ScreenProps } from "../types/global"
import { useTracking } from "../contexts/TrackingProvider"
import { fonts } from "../styles/typography"
@@ -170,7 +161,7 @@ export function GeofenceScreen({}: ScreenProps) {
await loadGeofences()
DeviceEventEmitter.emit("geofenceUpdated")
} catch {
- Alert.alert("Error", "Failed to create geofence.")
+ showAlert("Error", "Failed to create geofence.", "error")
}
}
} catch (err) {
@@ -182,13 +173,13 @@ export function GeofenceScreen({}: ScreenProps) {
const startPlacingGeofence = useCallback(() => {
if (!newName.trim()) {
- Alert.alert("Missing Name", "Please enter a name.")
+ showAlert("Missing Name", "Please enter a name.", "warning")
return
}
const radius = Number(newRadius)
if (!radius || radius <= 0) {
- Alert.alert("Invalid Radius", "Please enter a valid radius.")
+ showAlert("Invalid Radius", "Please enter a valid radius.", "warning")
return
}
@@ -213,7 +204,7 @@ export function GeofenceScreen({}: ScreenProps) {
DeviceEventEmitter.emit("geofenceUpdated")
await NativeLocationService.recheckZoneSettings()
} catch {
- Alert.alert("Error", "Failed to update geofence.")
+ showAlert("Error", "Failed to update geofence.", "error")
}
},
[loadGeofences]
@@ -233,23 +224,23 @@ export function GeofenceScreen({}: ScreenProps) {
}, [])
const handleDelete = useCallback(
- (item: Geofence) => {
- Alert.alert("Delete Geofence", `Delete "${item.name}"?`, [
- { text: "Cancel", style: "cancel" },
- {
- text: "Delete",
- style: "destructive",
- onPress: async () => {
- try {
- await NativeLocationService.deleteGeofence(item.id!)
- await loadGeofences()
- DeviceEventEmitter.emit("geofenceUpdated")
- } catch {
- Alert.alert("Error", "Failed to delete geofence.")
- }
- }
- }
- ])
+ async (item: Geofence) => {
+ const confirmed = await showConfirm({
+ title: "Delete Geofence",
+ message: `Delete "${item.name}"?`,
+ confirmText: "Delete",
+ destructive: true
+ })
+
+ if (!confirmed) return
+
+ try {
+ await NativeLocationService.deleteGeofence(item.id!)
+ await loadGeofences()
+ DeviceEventEmitter.emit("geofenceUpdated")
+ } catch {
+ showAlert("Error", "Failed to delete geofence.", "error")
+ }
},
[loadGeofences]
)
diff --git a/apps/mobile/src/services/LocationServicePermission.ts b/apps/mobile/src/services/LocationServicePermission.ts
index ee4697a7..91714132 100644
--- a/apps/mobile/src/services/LocationServicePermission.ts
+++ b/apps/mobile/src/services/LocationServicePermission.ts
@@ -5,6 +5,7 @@
import { Platform, PermissionsAndroid, Alert } from "react-native"
import NativeLocationService from "./NativeLocationService"
+import { showAlert } from "./modalService"
import { logger } from "../utils/logger"
/**
@@ -84,7 +85,7 @@ export async function ensurePermissions(): Promise<boolean> {
return true
} catch (err) {
logger.error("[PermissionService] Permission request error:", err)
- Alert.alert("Permission Error", "Failed to request permissions. Please try again.", [{ text: "OK" }])
+ showAlert("Permission Error", "Failed to request permissions. Please try again.", "error")
return false
}
}
diff --git a/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts b/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
index 874c02b7..e737b15b 100644
--- a/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
+++ b/apps/mobile/src/services/__tests__/LocationServicePermission.test.ts
@@ -1,5 +1,11 @@
import { Platform, PermissionsAndroid, Alert } from "react-native"
import { ensurePermissions, checkPermissions, registerDisclosureCallback } from "../LocationServicePermission"
+import { showAlert } from "../modalService"
+
+jest.mock("../modalService", () => ({
+ showAlert: jest.fn(),
+ showConfirm: jest.fn()
+}))
// Mock NativeLocationService
jest.mock("../NativeLocationService", () => ({
@@ -196,7 +202,7 @@ describe("ensurePermissions", () => {
const result = await ensurePermissions()
expect(result).toBe(false)
- expect(alertSpy).toHaveBeenCalledWith("Permission Error", expect.any(String), expect.any(Array))
+ expect(showAlert).toHaveBeenCalledWith("Permission Error", expect.any(String), "error")
})
it("uses fallback Alert disclosure if no callback registered", async () => {
diff --git a/apps/mobile/src/services/modalService.ts b/apps/mobile/src/services/modalService.ts
new file mode 100644
index 00000000..7fe1da10
--- /dev/null
+++ b/apps/mobile/src/services/modalService.ts
@@ -0,0 +1,78 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import { Alert } from "react-native"
+
+export type AlertVariant = "info" | "error" | "warning" | "success"
+
+export interface ModalRequest {
+ title: string
+ message: string
+ variant: AlertVariant
+ buttons: Array<{
+ text: string
+ style: "primary" | "secondary" | "destructive"
+ }>
+ resolve: (buttonIndex: number) => void
+}
+
+type ModalHandler = (request: ModalRequest) => void
+
+let _handler: ModalHandler | null = null
+
+export function registerModalHandler(handler: ModalHandler) {
+ _handler = handler
+}
+
+export function showAlert(title: string, message: string, variant: AlertVariant = "info"): void {
+ if (!_handler) {
+ Alert.alert(title, message)
+ return
+ }
+
+ _handler({
+ title,
+ message,
+ variant,
+ buttons: [{ text: "OK", style: "primary" }],
+ resolve: () => {}
+ })
+}
+
+export function showConfirm(options: {
+ title: string
+ message: string
+ confirmText?: string
+ cancelText?: string
+ destructive?: boolean
+}): Promise<boolean> {
+ const { title, message, confirmText = "OK", cancelText = "Cancel", destructive = false } = options
+
+ return new Promise((resolve) => {
+ if (!_handler) {
+ Alert.alert(
+ title,
+ message,
+ [
+ { text: cancelText, style: "cancel", onPress: () => resolve(false) },
+ { text: confirmText, onPress: () => resolve(true) }
+ ],
+ { cancelable: false }
+ )
+ return
+ }
+
+ _handler({
+ title,
+ message,
+ variant: destructive ? "error" : "info",
+ buttons: [
+ { text: cancelText, style: "secondary" },
+ { text: confirmText, style: destructive ? "destructive" : "primary" }
+ ],
+ resolve: (index) => resolve(index === 1)
+ })
+ })
+}