feat: Sprint 5 — PIN lock, biometric auth, sync screen, QR code, merge logic
- lib/pinService.ts: PIN storage/verification via expo-secure-store - lib/syncService.ts: sync abstraction with full merge logic (mDNS/TCP stubbed) - app/lock.tsx: full-screen PIN lock with biometric support - components/ui/PinPad.tsx: reusable 6-digit PIN pad component - components/sync/QRScanner.tsx: QR code scanner via expo-camera - app/(tabs)/sync.tsx: Sync tab with QR display, partner input, history - app/sync-progress.tsx: animated sync progress screen with summary - app/(tabs)/settings.tsx: full settings with PIN setup, security, data sections - app/(tabs)/_layout.tsx: added Sync tab (RefreshCw icon) - app/_layout.tsx: AppState listener locks app after 60s background - package.json: added expo-secure-store, react-native-qrcode-svg
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
// app/(tabs)/_layout.tsx
|
||||
import { Tabs, router } from 'expo-router';
|
||||
import { useEffect } from 'react';
|
||||
import { Home, Users, Map, Settings, MapPin } from 'lucide-react-native';
|
||||
import { Home, Users, Map, Settings, MapPin, RefreshCw } from 'lucide-react-native';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
|
||||
export default function TabLayout() {
|
||||
@@ -21,11 +21,48 @@ export default function TabLayout() {
|
||||
headerShown: false,
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen name="index" options={{ title: 'Home', tabBarIcon: ({ color, size }) => <Home size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="contacts" options={{ title: 'Contacts', tabBarIcon: ({ color, size }) => <Users size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="territories" options={{ title: 'Territories', tabBarIcon: ({ color, size }) => <MapPin size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="map" options={{ title: 'Map', tabBarIcon: ({ color, size }) => <Map size={size} color={color} /> }} />
|
||||
<Tabs.Screen name="settings" options={{ title: 'Settings', tabBarIcon: ({ color, size }) => <Settings size={size} color={color} /> }} />
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
title: 'Home',
|
||||
tabBarIcon: ({ color, size }) => <Home size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="contacts"
|
||||
options={{
|
||||
title: 'Contacts',
|
||||
tabBarIcon: ({ color, size }) => <Users size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="territories"
|
||||
options={{
|
||||
title: 'Territories',
|
||||
tabBarIcon: ({ color, size }) => <MapPin size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="map"
|
||||
options={{
|
||||
title: 'Map',
|
||||
tabBarIcon: ({ color, size }) => <Map size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="sync"
|
||||
options={{
|
||||
title: 'Sync',
|
||||
tabBarIcon: ({ color, size }) => <RefreshCw size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="settings"
|
||||
options={{
|
||||
title: 'Settings',
|
||||
tabBarIcon: ({ color, size }) => <Settings size={size} color={color} />,
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,574 @@
|
||||
import { View, Text } from 'react-native';
|
||||
// app/(tabs)/settings.tsx — Full Settings Screen with PIN setup
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
ScrollView,
|
||||
Switch,
|
||||
TouchableOpacity,
|
||||
Alert,
|
||||
Modal,
|
||||
SafeAreaView,
|
||||
ActivityIndicator,
|
||||
} from 'react-native';
|
||||
import { router } from 'expo-router';
|
||||
import {
|
||||
User,
|
||||
Shield,
|
||||
Fingerprint,
|
||||
RefreshCw,
|
||||
BookOpen,
|
||||
Download,
|
||||
Upload,
|
||||
Trash2,
|
||||
Info,
|
||||
ChevronRight,
|
||||
X,
|
||||
} from 'lucide-react-native';
|
||||
import * as LocalAuthentication from 'expo-local-authentication';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
import {
|
||||
isPinEnabled,
|
||||
setPin,
|
||||
verifyPin,
|
||||
disablePin,
|
||||
isBiometricEnabled,
|
||||
setBiometricEnabled,
|
||||
} from '@/lib/pinService';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import PinPad from '@/components/ui/PinPad';
|
||||
|
||||
// ── PIN Flow Modal ────────────────────────────────────────────────────────────
|
||||
type PinFlowMode = 'set' | 'verify';
|
||||
|
||||
interface PinFlowProps {
|
||||
mode: PinFlowMode;
|
||||
onSuccess: (pin?: string) => void;
|
||||
onCancel: () => void;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
}
|
||||
|
||||
function PinFlowModal({ mode, onSuccess, onCancel, title, subtitle }: PinFlowProps) {
|
||||
const [step, setStep] = useState<'enter' | 'confirm'>('enter');
|
||||
const [pin, setCurrentPin] = useState('');
|
||||
const [firstPin, setFirstPin] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handlePinChange = async (newPin: string) => {
|
||||
setCurrentPin(newPin);
|
||||
setError('');
|
||||
|
||||
if (newPin.length < 6) return;
|
||||
|
||||
if (mode === 'verify') {
|
||||
const ok = await verifyPin(newPin);
|
||||
if (ok) {
|
||||
onSuccess(newPin);
|
||||
} else {
|
||||
setError('Incorrect PIN. Try again.');
|
||||
setTimeout(() => setCurrentPin(''), 600);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// mode === 'set'
|
||||
if (step === 'enter') {
|
||||
setFirstPin(newPin);
|
||||
setCurrentPin('');
|
||||
setStep('confirm');
|
||||
} else {
|
||||
// confirm step
|
||||
if (newPin === firstPin) {
|
||||
onSuccess(newPin);
|
||||
} else {
|
||||
setError('PINs do not match. Try again.');
|
||||
setStep('enter');
|
||||
setFirstPin('');
|
||||
setTimeout(() => setCurrentPin(''), 400);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const displayTitle = mode === 'set'
|
||||
? step === 'enter' ? 'Set PIN' : 'Confirm PIN'
|
||||
: title;
|
||||
|
||||
const displaySubtitle = mode === 'set'
|
||||
? step === 'enter'
|
||||
? 'Enter a 6-digit PIN'
|
||||
: 'Re-enter your PIN to confirm'
|
||||
: subtitle;
|
||||
|
||||
export default function SettingsScreen() {
|
||||
return (
|
||||
<View className="flex-1 items-center justify-center bg-secondary">
|
||||
<Text className="text-xl text-charcoal">Settings</Text>
|
||||
<Text className="text-gray-500 mt-2">Coming in Sprint 6</Text>
|
||||
</View>
|
||||
<Modal visible animationType="slide" onRequestClose={onCancel}>
|
||||
<SafeAreaView style={pinStyles.container}>
|
||||
<View style={pinStyles.header}>
|
||||
<TouchableOpacity onPress={onCancel} style={pinStyles.closeBtn}>
|
||||
<X size={22} color="#9CA3AF" />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<View style={pinStyles.content}>
|
||||
<Text style={pinStyles.title}>{displayTitle}</Text>
|
||||
{displaySubtitle ? (
|
||||
<Text style={pinStyles.subtitle}>{displaySubtitle}</Text>
|
||||
) : null}
|
||||
{error ? <Text style={pinStyles.error}>{error}</Text> : null}
|
||||
<PinPad pin={pin} onPinChange={handlePinChange} maxLength={6} />
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const pinStyles = StyleSheet.create({
|
||||
container: { flex: 1, backgroundColor: '#0F172A' },
|
||||
header: { alignItems: 'flex-end', padding: 16 },
|
||||
closeBtn: {
|
||||
width: 36, height: 36, borderRadius: 18,
|
||||
backgroundColor: 'rgba(255,255,255,0.08)',
|
||||
justifyContent: 'center', alignItems: 'center',
|
||||
},
|
||||
content: {
|
||||
flex: 1, alignItems: 'center', justifyContent: 'center',
|
||||
paddingHorizontal: 24, gap: 28,
|
||||
},
|
||||
title: { fontSize: 24, fontWeight: '700', color: '#F9FAFB' },
|
||||
subtitle: { fontSize: 15, color: '#9CA3AF', textAlign: 'center' },
|
||||
error: { fontSize: 14, color: '#F87171', textAlign: 'center' },
|
||||
});
|
||||
|
||||
// ── Settings Screen ───────────────────────────────────────────────────────────
|
||||
|
||||
export default function SettingsScreen() {
|
||||
const user = useUserStore((s) => s.user);
|
||||
const clearUser = useUserStore((s) => s.clearUser);
|
||||
|
||||
const [pinEnabled, setPinEnabledState] = useState(false);
|
||||
const [biometricEnabled, setBiometricEnabledState] = useState(false);
|
||||
const [biometricSupported, setBiometricSupported] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const [pinFlowVisible, setPinFlowVisible] = useState(false);
|
||||
const [pinFlowMode, setPinFlowMode] = useState<'set' | 'verify'>('set');
|
||||
const [pinFlowCallback, setPinFlowCallback] = useState<((pin?: string) => void) | null>(null);
|
||||
const [pinFlowTitle, setPinFlowTitle] = useState('');
|
||||
const [pinFlowSubtitle, setPinFlowSubtitle] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadSecurityState();
|
||||
}, []);
|
||||
|
||||
const loadSecurityState = async () => {
|
||||
try {
|
||||
const [pinOn, bioOn, hw, enrolled] = await Promise.all([
|
||||
isPinEnabled(),
|
||||
isBiometricEnabled(),
|
||||
LocalAuthentication.hasHardwareAsync(),
|
||||
LocalAuthentication.isEnrolledAsync(),
|
||||
]);
|
||||
setPinEnabledState(pinOn);
|
||||
setBiometricEnabledState(bioOn);
|
||||
setBiometricSupported(hw && enrolled);
|
||||
} catch {
|
||||
// ignore
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const openPinFlow = useCallback(
|
||||
(
|
||||
mode: 'set' | 'verify',
|
||||
title: string,
|
||||
subtitle: string,
|
||||
callback: (pin?: string) => void
|
||||
) => {
|
||||
setPinFlowMode(mode);
|
||||
setPinFlowTitle(title);
|
||||
setPinFlowSubtitle(subtitle);
|
||||
setPinFlowCallback(() => callback);
|
||||
setPinFlowVisible(true);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleTogglePin = async (value: boolean) => {
|
||||
if (value) {
|
||||
// Turning ON: show Set PIN flow
|
||||
openPinFlow('set', 'Set PIN', 'Enter a 6-digit PIN', async (pin) => {
|
||||
if (pin) {
|
||||
await setPin(pin);
|
||||
setPinEnabledState(true);
|
||||
setPinFlowVisible(false);
|
||||
Alert.alert('PIN Set', 'Your app is now protected with a PIN.');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Turning OFF: verify first
|
||||
openPinFlow(
|
||||
'verify',
|
||||
'Disable PIN Lock',
|
||||
'Enter your current PIN to disable',
|
||||
async () => {
|
||||
await disablePin();
|
||||
setPinEnabledState(false);
|
||||
setBiometricEnabledState(false);
|
||||
setPinFlowVisible(false);
|
||||
Alert.alert('PIN Disabled', 'App lock has been turned off.');
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleBiometric = async (value: boolean) => {
|
||||
await setBiometricEnabled(value);
|
||||
setBiometricEnabledState(value);
|
||||
};
|
||||
|
||||
const handleClearData = () => {
|
||||
Alert.alert(
|
||||
'Clear All Data',
|
||||
'This will permanently delete all contacts, visits, territories, and sync history. This cannot be undone.',
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Delete Everything',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
await db.execAsync(`
|
||||
DELETE FROM contacts;
|
||||
DELETE FROM visits;
|
||||
DELETE FROM territories;
|
||||
DELETE FROM sync_log;
|
||||
`);
|
||||
Alert.alert('Done', 'All data has been cleared.');
|
||||
} catch {
|
||||
Alert.alert('Error', 'Failed to clear data.');
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
const handleExportBackup = () => {
|
||||
Alert.alert('Export Backup', 'Export feature coming in a future sprint.');
|
||||
};
|
||||
|
||||
const handleImportBackup = () => {
|
||||
Alert.alert('Import Backup', 'Import feature coming in a future sprint.');
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<View style={styles.loadingContainer}>
|
||||
<ActivityIndicator color="#1A6B72" />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.safe}>
|
||||
<ScrollView
|
||||
style={styles.container}
|
||||
contentContainerStyle={styles.content}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{/* Header */}
|
||||
<Text style={styles.pageTitle}>Settings</Text>
|
||||
|
||||
{/* ── Profile ── */}
|
||||
<SectionHeader title="Profile" />
|
||||
<View style={styles.card}>
|
||||
<View style={styles.profileRow}>
|
||||
<View style={styles.avatar}>
|
||||
<User size={28} color="#1A6B72" />
|
||||
</View>
|
||||
<View style={{ flex: 1, gap: 2 }}>
|
||||
<Text style={styles.profileName}>{user?.displayName ?? '—'}</Text>
|
||||
<Text style={styles.profileShareId}>
|
||||
Share ID: <Text style={styles.shareIdMono}>{user?.shareId ?? '—'}</Text>
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* ── Security ── */}
|
||||
<SectionHeader title="Security" />
|
||||
<View style={styles.card}>
|
||||
<SettingsRow
|
||||
icon={<Shield size={18} color="#1A6B72" />}
|
||||
label="App Lock (PIN)"
|
||||
right={
|
||||
<Switch
|
||||
value={pinEnabled}
|
||||
onValueChange={handleTogglePin}
|
||||
trackColor={{ false: '#D1D5DB', true: '#1A6B72' }}
|
||||
thumbColor="#fff"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{pinEnabled && biometricSupported && (
|
||||
<>
|
||||
<Divider />
|
||||
<SettingsRow
|
||||
icon={<Fingerprint size={18} color="#1A6B72" />}
|
||||
label="Biometric Unlock"
|
||||
right={
|
||||
<Switch
|
||||
value={biometricEnabled}
|
||||
onValueChange={handleToggleBiometric}
|
||||
trackColor={{ false: '#D1D5DB', true: '#1A6B72' }}
|
||||
thumbColor="#fff"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* ── Sync ── */}
|
||||
<SectionHeader title="Sync" />
|
||||
<View style={styles.card}>
|
||||
<SettingsRow
|
||||
icon={<RefreshCw size={18} color="#1A6B72" />}
|
||||
label="Sync with Device"
|
||||
right={<ChevronRight size={16} color="#9CA3AF" />}
|
||||
onPress={() => router.push('/(tabs)/sync')}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* ── Data ── */}
|
||||
<SectionHeader title="Data" />
|
||||
<View style={styles.card}>
|
||||
<SettingsRow
|
||||
icon={<BookOpen size={18} color="#1A6B72" />}
|
||||
label="Topic Library"
|
||||
right={<ChevronRight size={16} color="#9CA3AF" />}
|
||||
onPress={() =>
|
||||
Alert.alert('Topic Library', 'Manage visit topics in a future update.')
|
||||
}
|
||||
/>
|
||||
<Divider />
|
||||
<SettingsRow
|
||||
icon={<Download size={18} color="#1A6B72" />}
|
||||
label="Export Backup"
|
||||
right={<ChevronRight size={16} color="#9CA3AF" />}
|
||||
onPress={handleExportBackup}
|
||||
/>
|
||||
<Divider />
|
||||
<SettingsRow
|
||||
icon={<Upload size={18} color="#1A6B72" />}
|
||||
label="Import Backup"
|
||||
right={<ChevronRight size={16} color="#9CA3AF" />}
|
||||
onPress={handleImportBackup}
|
||||
/>
|
||||
<Divider />
|
||||
<SettingsRow
|
||||
icon={<Trash2 size={18} color="#EF4444" />}
|
||||
label="Clear All Data"
|
||||
labelStyle={{ color: '#EF4444' }}
|
||||
right={<ChevronRight size={16} color="#9CA3AF" />}
|
||||
onPress={handleClearData}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* ── About ── */}
|
||||
<SectionHeader title="About" />
|
||||
<View style={styles.card}>
|
||||
<SettingsRow
|
||||
icon={<Info size={18} color="#1A6B72" />}
|
||||
label="TerritoryLog"
|
||||
right={<Text style={styles.versionText}>v1.0.0 (Sprint 5)</Text>}
|
||||
/>
|
||||
<Divider />
|
||||
<View style={styles.aboutRow}>
|
||||
<Text style={styles.aboutText}>
|
||||
A local-first ministry record keeping app. All data stays on your device.
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View style={{ height: 32 }} />
|
||||
</ScrollView>
|
||||
|
||||
{/* PIN Flow Modal */}
|
||||
{pinFlowVisible && pinFlowCallback && (
|
||||
<PinFlowModal
|
||||
mode={pinFlowMode}
|
||||
title={pinFlowTitle}
|
||||
subtitle={pinFlowSubtitle}
|
||||
onSuccess={(pin) => pinFlowCallback(pin)}
|
||||
onCancel={() => setPinFlowVisible(false)}
|
||||
/>
|
||||
)}
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Sub-components ──────────────────────────────────────────────────────────
|
||||
|
||||
function SectionHeader({ title }: { title: string }) {
|
||||
return <Text style={styles.sectionHeader}>{title}</Text>;
|
||||
}
|
||||
|
||||
function Divider() {
|
||||
return <View style={styles.divider} />;
|
||||
}
|
||||
|
||||
interface SettingsRowProps {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
labelStyle?: object;
|
||||
right?: React.ReactNode;
|
||||
onPress?: () => void;
|
||||
}
|
||||
|
||||
function SettingsRow({ icon, label, labelStyle, right, onPress }: SettingsRowProps) {
|
||||
const Row = onPress ? TouchableOpacity : View;
|
||||
return (
|
||||
<Row
|
||||
style={styles.settingsRow}
|
||||
onPress={onPress}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.settingsRowLeft}>
|
||||
<View style={styles.rowIcon}>{icon}</View>
|
||||
<Text style={[styles.rowLabel, labelStyle]}>{label}</Text>
|
||||
</View>
|
||||
{right && <View style={styles.settingsRowRight}>{right}</View>}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Styles ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
safe: {
|
||||
flex: 1,
|
||||
backgroundColor: '#F8F4EF',
|
||||
},
|
||||
loadingContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: '#F8F4EF',
|
||||
},
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
content: {
|
||||
paddingBottom: 16,
|
||||
},
|
||||
pageTitle: {
|
||||
fontSize: 28,
|
||||
fontWeight: '700',
|
||||
color: '#111827',
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 20,
|
||||
paddingBottom: 4,
|
||||
},
|
||||
sectionHeader: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
color: '#6B7280',
|
||||
letterSpacing: 0.8,
|
||||
textTransform: 'uppercase',
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 20,
|
||||
paddingBottom: 6,
|
||||
},
|
||||
card: {
|
||||
backgroundColor: '#fff',
|
||||
marginHorizontal: 16,
|
||||
borderRadius: 16,
|
||||
paddingVertical: 4,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowOpacity: 0.05,
|
||||
shadowRadius: 4,
|
||||
elevation: 2,
|
||||
},
|
||||
profileRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
padding: 16,
|
||||
gap: 14,
|
||||
},
|
||||
avatar: {
|
||||
width: 52,
|
||||
height: 52,
|
||||
borderRadius: 26,
|
||||
backgroundColor: '#EFF9F9',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
borderWidth: 2,
|
||||
borderColor: '#B2DFDF',
|
||||
},
|
||||
profileName: {
|
||||
fontSize: 17,
|
||||
fontWeight: '700',
|
||||
color: '#111827',
|
||||
},
|
||||
profileShareId: {
|
||||
fontSize: 13,
|
||||
color: '#6B7280',
|
||||
},
|
||||
shareIdMono: {
|
||||
fontFamily: 'monospace',
|
||||
color: '#1A6B72',
|
||||
fontWeight: '600',
|
||||
},
|
||||
settingsRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
settingsRowLeft: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
flex: 1,
|
||||
},
|
||||
rowIcon: {
|
||||
width: 32,
|
||||
height: 32,
|
||||
borderRadius: 8,
|
||||
backgroundColor: '#F3F4F6',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
rowLabel: {
|
||||
fontSize: 15,
|
||||
color: '#111827',
|
||||
fontWeight: '500',
|
||||
},
|
||||
settingsRowRight: {
|
||||
flexShrink: 0,
|
||||
marginLeft: 8,
|
||||
},
|
||||
divider: {
|
||||
height: 1,
|
||||
backgroundColor: '#F3F4F6',
|
||||
marginHorizontal: 16,
|
||||
},
|
||||
versionText: {
|
||||
fontSize: 13,
|
||||
color: '#9CA3AF',
|
||||
},
|
||||
aboutRow: {
|
||||
paddingHorizontal: 16,
|
||||
paddingVertical: 12,
|
||||
},
|
||||
aboutText: {
|
||||
fontSize: 13,
|
||||
color: '#6B7280',
|
||||
lineHeight: 20,
|
||||
},
|
||||
});
|
||||
|
||||
599
app/(tabs)/sync.tsx
Normal file
599
app/(tabs)/sync.tsx
Normal file
@@ -0,0 +1,599 @@
|
||||
// app/(tabs)/sync.tsx — Sync Tab
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
ScrollView,
|
||||
TouchableOpacity,
|
||||
TextInput,
|
||||
Alert,
|
||||
Modal,
|
||||
SafeAreaView,
|
||||
ActivityIndicator,
|
||||
} from 'react-native';
|
||||
import { router } from 'expo-router';
|
||||
import {
|
||||
RefreshCw,
|
||||
QrCode,
|
||||
Camera,
|
||||
Wifi,
|
||||
Clock,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Share2,
|
||||
AlertCircle,
|
||||
} from 'lucide-react-native';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
import { getSyncHistory, SyncLogEntry } from '@/lib/syncService';
|
||||
import QRScanner from '@/components/sync/QRScanner';
|
||||
|
||||
// Lazy-load QRCode to handle missing package gracefully
|
||||
let QRCode: any = null;
|
||||
try {
|
||||
QRCode = require('react-native-qrcode-svg').default;
|
||||
} catch {
|
||||
QRCode = null;
|
||||
}
|
||||
|
||||
function formatDate(ts: number): string {
|
||||
return new Date(ts * 1000).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
export default function SyncScreen() {
|
||||
const user = useUserStore((s) => s.user);
|
||||
const shareId = user?.shareId ?? 'TL-????????';
|
||||
|
||||
const [syncHistory, setSyncHistory] = useState<SyncLogEntry[]>([]);
|
||||
const [loadingHistory, setLoadingHistory] = useState(true);
|
||||
const [partnerShareId, setPartnerShareId] = useState('');
|
||||
const [showScanner, setShowScanner] = useState(false);
|
||||
const [showHowTo, setShowHowTo] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, []);
|
||||
|
||||
const loadHistory = async () => {
|
||||
try {
|
||||
const history = await getSyncHistory();
|
||||
setSyncHistory(history);
|
||||
} catch (e) {
|
||||
console.error('Failed to load sync history:', e);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleScanned = useCallback((scannedId: string) => {
|
||||
setShowScanner(false);
|
||||
setPartnerShareId(scannedId);
|
||||
}, []);
|
||||
|
||||
const handleStartSync = () => {
|
||||
const trimmed = partnerShareId.trim().toUpperCase();
|
||||
if (!trimmed.match(/^TL-[A-Z0-9]{8}$/)) {
|
||||
Alert.alert(
|
||||
'Invalid Share ID',
|
||||
'Please enter a valid Share ID in the format TL-XXXXXXXX'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (trimmed === shareId) {
|
||||
Alert.alert('Same Device', 'You cannot sync with yourself.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigate to sync-progress (actual sync requires bare workflow)
|
||||
Alert.alert(
|
||||
'WiFi Sync Not Available',
|
||||
'Direct WiFi sync requires expo-dev-client and bare workflow.\n\nShare IDs can be exchanged manually. Network sync will be available in a future release.',
|
||||
[
|
||||
{ text: 'OK' },
|
||||
{
|
||||
text: 'View Progress Demo',
|
||||
onPress: () =>
|
||||
router.push({
|
||||
pathname: '/sync-progress',
|
||||
params: {
|
||||
partnerName: trimmed,
|
||||
sentCount: '0',
|
||||
receivedCount: '0',
|
||||
conflictCount: '0',
|
||||
},
|
||||
}),
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.safe}>
|
||||
<ScrollView
|
||||
style={styles.container}
|
||||
contentContainerStyle={styles.content}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{/* Header */}
|
||||
<View style={styles.header}>
|
||||
<RefreshCw size={24} color="#1A6B72" />
|
||||
<Text style={styles.headerTitle}>Sync</Text>
|
||||
</View>
|
||||
|
||||
{/* ── Your Share ID ── */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Your Share ID</Text>
|
||||
<View style={styles.qrCard}>
|
||||
{QRCode ? (
|
||||
<View style={styles.qrCodeWrapper}>
|
||||
<QRCode
|
||||
value={shareId}
|
||||
size={180}
|
||||
color="#111827"
|
||||
backgroundColor="#FFFFFF"
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View style={styles.qrPlaceholder}>
|
||||
<QrCode size={64} color="#9CA3AF" />
|
||||
<Text style={styles.qrPlaceholderText}>QR Code</Text>
|
||||
<Text style={styles.qrPlaceholderSub}>
|
||||
Install react-native-qrcode-svg to display
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.shareIdRow}>
|
||||
<Text style={styles.shareIdLabel}>Share ID</Text>
|
||||
<View style={styles.shareIdBadge}>
|
||||
<Share2 size={14} color="#1A6B72" />
|
||||
<Text style={styles.shareIdText}>{shareId}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<Text style={styles.shareIdHint}>
|
||||
Show this QR code to your partner so they can connect to you.
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* ── Connect to Partner ── */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Connect to Partner</Text>
|
||||
<View style={styles.card}>
|
||||
{/* Scan QR button */}
|
||||
<TouchableOpacity
|
||||
style={styles.scanBtn}
|
||||
onPress={() => setShowScanner(true)}
|
||||
>
|
||||
<Camera size={20} color="#fff" />
|
||||
<Text style={styles.scanBtnText}>Scan Partner QR Code</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={styles.orRow}>
|
||||
<View style={styles.orLine} />
|
||||
<Text style={styles.orText}>or enter manually</Text>
|
||||
<View style={styles.orLine} />
|
||||
</View>
|
||||
|
||||
{/* Manual input */}
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
placeholder="TL-XXXXXXXX"
|
||||
placeholderTextColor="#9CA3AF"
|
||||
value={partnerShareId}
|
||||
onChangeText={setPartnerShareId}
|
||||
autoCapitalize="characters"
|
||||
maxLength={11}
|
||||
/>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[
|
||||
styles.connectBtn,
|
||||
!partnerShareId && styles.connectBtnDisabled,
|
||||
]}
|
||||
onPress={handleStartSync}
|
||||
disabled={!partnerShareId}
|
||||
>
|
||||
<RefreshCw size={18} color="#fff" />
|
||||
<Text style={styles.connectBtnText}>Start Sync</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* ── Discovered Devices ── */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Discovered Devices</Text>
|
||||
<View style={[styles.card, styles.wifiNotice]}>
|
||||
<AlertCircle size={20} color="#F59E0B" />
|
||||
<View style={{ flex: 1, gap: 4 }}>
|
||||
<Text style={styles.wifiNoticeTitle}>WiFi Sync Requires Setup</Text>
|
||||
<Text style={styles.wifiNoticeText}>
|
||||
Automatic device discovery (mDNS) requires expo-dev-client and
|
||||
bare workflow. Exchange Share IDs manually for now.
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* ── Sync History ── */}
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionTitle}>Sync History</Text>
|
||||
<View style={styles.card}>
|
||||
{loadingHistory ? (
|
||||
<ActivityIndicator color="#1A6B72" style={{ padding: 16 }} />
|
||||
) : syncHistory.length === 0 ? (
|
||||
<View style={styles.emptyHistory}>
|
||||
<Clock size={32} color="#D1D5DB" />
|
||||
<Text style={styles.emptyHistoryText}>No syncs yet</Text>
|
||||
</View>
|
||||
) : (
|
||||
syncHistory.map((entry) => (
|
||||
<View key={entry.id} style={styles.historyItem}>
|
||||
<View style={styles.historyLeft}>
|
||||
<Text style={styles.historyPartner}>
|
||||
{entry.partner_name ?? entry.partner_id}
|
||||
</Text>
|
||||
<Text style={styles.historyDate}>
|
||||
{formatDate(entry.synced_at)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.historyRight}>
|
||||
<Text style={styles.historySent}>↑ {entry.sent_count}</Text>
|
||||
<Text style={styles.historyReceived}>↓ {entry.received_count}</Text>
|
||||
</View>
|
||||
</View>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* ── How to Sync ── */}
|
||||
<View style={styles.section}>
|
||||
<TouchableOpacity
|
||||
style={styles.howToToggle}
|
||||
onPress={() => setShowHowTo(!showHowTo)}
|
||||
>
|
||||
<Text style={styles.sectionTitle}>How to Sync</Text>
|
||||
{showHowTo ? (
|
||||
<ChevronUp size={18} color="#6B7280" />
|
||||
) : (
|
||||
<ChevronDown size={18} color="#6B7280" />
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
|
||||
{showHowTo && (
|
||||
<View style={styles.card}>
|
||||
{HOW_TO_STEPS.map((step, i) => (
|
||||
<View key={i} style={styles.howToStep}>
|
||||
<View style={styles.howToNumber}>
|
||||
<Text style={styles.howToNumberText}>{i + 1}</Text>
|
||||
</View>
|
||||
<View style={{ flex: 1, gap: 2 }}>
|
||||
<Text style={styles.howToStepTitle}>{step.title}</Text>
|
||||
<Text style={styles.howToStepBody}>{step.body}</Text>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
{/* QR Scanner Modal */}
|
||||
<Modal
|
||||
visible={showScanner}
|
||||
animationType="slide"
|
||||
onRequestClose={() => setShowScanner(false)}
|
||||
>
|
||||
<QRScanner
|
||||
onScanned={handleScanned}
|
||||
onCancel={() => setShowScanner(false)}
|
||||
/>
|
||||
</Modal>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const HOW_TO_STEPS = [
|
||||
{
|
||||
title: 'Open TerritoryLog on both devices',
|
||||
body: 'Both devices must have TerritoryLog installed and be on the same WiFi network.',
|
||||
},
|
||||
{
|
||||
title: 'Share your QR code or Share ID',
|
||||
body: 'Show the QR code above to your partner, or tell them your Share ID (TL-XXXXXXXX).',
|
||||
},
|
||||
{
|
||||
title: 'Scan or enter their Share ID',
|
||||
body: "Use the scanner or type their Share ID into the input field on one device.",
|
||||
},
|
||||
{
|
||||
title: 'Start sync',
|
||||
body: 'Tap "Start Sync". Records are merged intelligently — the most recently updated version of each record wins.',
|
||||
},
|
||||
{
|
||||
title: 'Done!',
|
||||
body: 'Both devices will have the same up-to-date data. No cloud required.',
|
||||
},
|
||||
];
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
safe: {
|
||||
flex: 1,
|
||||
backgroundColor: '#F8F4EF',
|
||||
},
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
content: {
|
||||
paddingBottom: 32,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 20,
|
||||
paddingBottom: 8,
|
||||
},
|
||||
headerTitle: {
|
||||
fontSize: 26,
|
||||
fontWeight: '700',
|
||||
color: '#111827',
|
||||
},
|
||||
section: {
|
||||
marginTop: 20,
|
||||
paddingHorizontal: 16,
|
||||
gap: 8,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
color: '#6B7280',
|
||||
letterSpacing: 0.6,
|
||||
textTransform: 'uppercase',
|
||||
},
|
||||
card: {
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: 16,
|
||||
padding: 16,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowOpacity: 0.05,
|
||||
shadowRadius: 4,
|
||||
elevation: 2,
|
||||
gap: 12,
|
||||
},
|
||||
qrCard: {
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: 16,
|
||||
padding: 20,
|
||||
alignItems: 'center',
|
||||
gap: 16,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowOpacity: 0.05,
|
||||
shadowRadius: 4,
|
||||
elevation: 2,
|
||||
},
|
||||
qrCodeWrapper: {
|
||||
padding: 12,
|
||||
backgroundColor: '#fff',
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: '#E5E7EB',
|
||||
},
|
||||
qrPlaceholder: {
|
||||
width: 180,
|
||||
height: 180,
|
||||
backgroundColor: '#F3F4F6',
|
||||
borderRadius: 12,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
borderWidth: 2,
|
||||
borderColor: '#E5E7EB',
|
||||
borderStyle: 'dashed',
|
||||
},
|
||||
qrPlaceholderText: {
|
||||
color: '#6B7280',
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
},
|
||||
qrPlaceholderSub: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 11,
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 12,
|
||||
},
|
||||
shareIdRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
},
|
||||
shareIdLabel: {
|
||||
color: '#6B7280',
|
||||
fontSize: 13,
|
||||
},
|
||||
shareIdBadge: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
backgroundColor: '#EFF9F9',
|
||||
paddingVertical: 6,
|
||||
paddingHorizontal: 12,
|
||||
borderRadius: 20,
|
||||
borderWidth: 1,
|
||||
borderColor: '#B2DFDF',
|
||||
},
|
||||
shareIdText: {
|
||||
color: '#1A6B72',
|
||||
fontSize: 15,
|
||||
fontWeight: '700',
|
||||
letterSpacing: 1,
|
||||
fontFamily: 'monospace',
|
||||
},
|
||||
shareIdHint: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 12,
|
||||
textAlign: 'center',
|
||||
},
|
||||
scanBtn: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
backgroundColor: '#1A6B72',
|
||||
borderRadius: 12,
|
||||
paddingVertical: 13,
|
||||
},
|
||||
scanBtnText: {
|
||||
color: '#fff',
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
orRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
},
|
||||
orLine: {
|
||||
flex: 1,
|
||||
height: 1,
|
||||
backgroundColor: '#E5E7EB',
|
||||
},
|
||||
orText: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 12,
|
||||
},
|
||||
input: {
|
||||
borderWidth: 1,
|
||||
borderColor: '#E5E7EB',
|
||||
borderRadius: 12,
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 16,
|
||||
fontSize: 16,
|
||||
color: '#111827',
|
||||
letterSpacing: 1,
|
||||
fontFamily: 'monospace',
|
||||
},
|
||||
connectBtn: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: 8,
|
||||
backgroundColor: '#115E67',
|
||||
borderRadius: 12,
|
||||
paddingVertical: 13,
|
||||
},
|
||||
connectBtnDisabled: {
|
||||
backgroundColor: '#D1D5DB',
|
||||
},
|
||||
connectBtnText: {
|
||||
color: '#fff',
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
wifiNotice: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'flex-start',
|
||||
gap: 12,
|
||||
backgroundColor: '#FFFBEB',
|
||||
borderWidth: 1,
|
||||
borderColor: '#FDE68A',
|
||||
},
|
||||
wifiNoticeTitle: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: '#92400E',
|
||||
},
|
||||
wifiNoticeText: {
|
||||
fontSize: 12,
|
||||
color: '#92400E',
|
||||
lineHeight: 18,
|
||||
},
|
||||
emptyHistory: {
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
paddingVertical: 16,
|
||||
},
|
||||
emptyHistoryText: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 14,
|
||||
},
|
||||
historyItem: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
paddingVertical: 8,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: '#F3F4F6',
|
||||
},
|
||||
historyLeft: {
|
||||
gap: 2,
|
||||
},
|
||||
historyPartner: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: '#111827',
|
||||
},
|
||||
historyDate: {
|
||||
fontSize: 12,
|
||||
color: '#9CA3AF',
|
||||
},
|
||||
historyRight: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
},
|
||||
historySent: {
|
||||
fontSize: 13,
|
||||
color: '#1A6B72',
|
||||
fontWeight: '600',
|
||||
},
|
||||
historyReceived: {
|
||||
fontSize: 13,
|
||||
color: '#10B981',
|
||||
fontWeight: '600',
|
||||
},
|
||||
howToToggle: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
},
|
||||
howToStep: {
|
||||
flexDirection: 'row',
|
||||
gap: 12,
|
||||
alignItems: 'flex-start',
|
||||
},
|
||||
howToNumber: {
|
||||
width: 24,
|
||||
height: 24,
|
||||
borderRadius: 12,
|
||||
backgroundColor: '#1A6B72',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
flexShrink: 0,
|
||||
marginTop: 1,
|
||||
},
|
||||
howToNumberText: {
|
||||
color: '#fff',
|
||||
fontSize: 12,
|
||||
fontWeight: '700',
|
||||
},
|
||||
howToStepTitle: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: '#111827',
|
||||
},
|
||||
howToStepBody: {
|
||||
fontSize: 13,
|
||||
color: '#6B7280',
|
||||
lineHeight: 18,
|
||||
},
|
||||
});
|
||||
@@ -1,25 +1,38 @@
|
||||
// app/_layout.tsx
|
||||
import { Stack } from 'expo-router';
|
||||
import { Stack, router } from 'expo-router';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { View, ActivityIndicator } from 'react-native';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { View, ActivityIndicator, AppState, AppStateStatus } from 'react-native';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { isPinEnabled } from '@/lib/pinService';
|
||||
import '../global.css';
|
||||
|
||||
const LOCK_AFTER_SECONDS = 60;
|
||||
|
||||
export default function RootLayout() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const setUser = useUserStore((s) => s.setUser);
|
||||
|
||||
// Track when app was backgrounded
|
||||
const backgroundedAt = useRef<number | null>(null);
|
||||
const appState = useRef<AppStateStatus>(AppState.currentState);
|
||||
|
||||
useEffect(() => {
|
||||
async function bootstrap() {
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
const user = await db.getFirstAsync<{ id: string; display_name: string; share_id: string }>(
|
||||
'SELECT id, display_name, share_id FROM users WHERE is_self = 1 LIMIT 1'
|
||||
);
|
||||
const user = await db.getFirstAsync<{
|
||||
id: string;
|
||||
display_name: string;
|
||||
share_id: string;
|
||||
}>('SELECT id, display_name, share_id FROM users WHERE is_self = 1 LIMIT 1');
|
||||
if (user) {
|
||||
setUser({ id: user.id, displayName: user.display_name, shareId: user.share_id });
|
||||
setUser({
|
||||
id: user.id,
|
||||
displayName: user.display_name,
|
||||
shareId: user.share_id,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Bootstrap error:', e);
|
||||
@@ -30,9 +43,56 @@ export default function RootLayout() {
|
||||
bootstrap();
|
||||
}, []);
|
||||
|
||||
// PIN lock on resume
|
||||
useEffect(() => {
|
||||
const subscription = AppState.addEventListener(
|
||||
'change',
|
||||
async (nextState: AppStateStatus) => {
|
||||
const prev = appState.current;
|
||||
|
||||
if (
|
||||
(prev === 'active' || prev === 'inactive') &&
|
||||
nextState === 'background'
|
||||
) {
|
||||
// App going to background — record timestamp
|
||||
backgroundedAt.current = Date.now();
|
||||
}
|
||||
|
||||
if (
|
||||
(prev === 'background' || prev === 'inactive') &&
|
||||
nextState === 'active'
|
||||
) {
|
||||
// App coming to foreground
|
||||
const bgAt = backgroundedAt.current;
|
||||
if (bgAt !== null) {
|
||||
const elapsedSec = (Date.now() - bgAt) / 1000;
|
||||
if (elapsedSec >= LOCK_AFTER_SECONDS) {
|
||||
const pinOn = await isPinEnabled();
|
||||
if (pinOn) {
|
||||
router.replace('/lock');
|
||||
}
|
||||
}
|
||||
}
|
||||
backgroundedAt.current = null;
|
||||
}
|
||||
|
||||
appState.current = nextState;
|
||||
}
|
||||
);
|
||||
|
||||
return () => subscription.remove();
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F8F4EF' }}>
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: '#F8F4EF',
|
||||
}}
|
||||
>
|
||||
<ActivityIndicator size="large" color="#1A6B72" />
|
||||
</View>
|
||||
);
|
||||
@@ -43,6 +103,21 @@ export default function RootLayout() {
|
||||
<Stack screenOptions={{ headerShown: false }}>
|
||||
<Stack.Screen name="onboarding" />
|
||||
<Stack.Screen name="(tabs)" />
|
||||
<Stack.Screen
|
||||
name="lock"
|
||||
options={{
|
||||
presentation: 'fullScreenModal',
|
||||
animation: 'fade',
|
||||
gestureEnabled: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="sync-progress"
|
||||
options={{
|
||||
presentation: 'fullScreenModal',
|
||||
animation: 'slide_from_bottom',
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
|
||||
205
app/lock.tsx
Normal file
205
app/lock.tsx
Normal file
@@ -0,0 +1,205 @@
|
||||
// app/lock.tsx — Full-screen PIN lock screen
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
Alert,
|
||||
TouchableOpacity,
|
||||
SafeAreaView,
|
||||
} from 'react-native';
|
||||
import { router } from 'expo-router';
|
||||
import * as LocalAuthentication from 'expo-local-authentication';
|
||||
import { Shield } from 'lucide-react-native';
|
||||
import PinPad from '@/components/ui/PinPad';
|
||||
import { verifyPin, disablePin } from '@/lib/pinService';
|
||||
import { getDatabase } from '@/lib/database';
|
||||
import { useUserStore } from '@/store/useUserStore';
|
||||
|
||||
export default function LockScreen() {
|
||||
const [pin, setPin] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [biometricAvailable, setBiometricAvailable] = useState(false);
|
||||
const clearUser = useUserStore((s) => s.clearUser);
|
||||
|
||||
useEffect(() => {
|
||||
checkBiometric();
|
||||
}, []);
|
||||
|
||||
const checkBiometric = async () => {
|
||||
try {
|
||||
const hardware = await LocalAuthentication.hasHardwareAsync();
|
||||
const enrolled = await LocalAuthentication.isEnrolledAsync();
|
||||
setBiometricAvailable(hardware && enrolled);
|
||||
} catch {
|
||||
setBiometricAvailable(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBiometric = useCallback(async () => {
|
||||
try {
|
||||
const result = await LocalAuthentication.authenticateAsync({
|
||||
promptMessage: 'Unlock TerritoryLog',
|
||||
fallbackLabel: 'Use PIN',
|
||||
cancelLabel: 'Cancel',
|
||||
});
|
||||
if (result.success) {
|
||||
router.replace('/(tabs)');
|
||||
} else {
|
||||
setError('Biometric authentication failed. Use your PIN.');
|
||||
}
|
||||
} catch {
|
||||
setError('Biometric not available.');
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Auto-trigger biometric on mount if available
|
||||
useEffect(() => {
|
||||
if (biometricAvailable) {
|
||||
handleBiometric();
|
||||
}
|
||||
}, [biometricAvailable, handleBiometric]);
|
||||
|
||||
const handlePinChange = async (newPin: string) => {
|
||||
setPin(newPin);
|
||||
setError('');
|
||||
|
||||
if (newPin.length === 6) {
|
||||
const ok = await verifyPin(newPin);
|
||||
if (ok) {
|
||||
router.replace('/(tabs)');
|
||||
} else {
|
||||
setError('Incorrect PIN. Try again.');
|
||||
setTimeout(() => setPin(''), 600);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleForgotPin = () => {
|
||||
Alert.alert(
|
||||
'Forgot PIN?',
|
||||
'Resetting your PIN will clear ALL app data. This cannot be undone.',
|
||||
[
|
||||
{ text: 'Cancel', style: 'cancel' },
|
||||
{
|
||||
text: 'Clear & Reset',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
try {
|
||||
const db = await getDatabase();
|
||||
await db.execAsync(`
|
||||
DELETE FROM contacts;
|
||||
DELETE FROM visits;
|
||||
DELETE FROM territories;
|
||||
DELETE FROM users;
|
||||
DELETE FROM sync_log;
|
||||
DELETE FROM topics;
|
||||
`);
|
||||
await disablePin();
|
||||
clearUser();
|
||||
router.replace('/onboarding');
|
||||
} catch (e) {
|
||||
Alert.alert('Error', 'Could not clear data. Please try again.');
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<View style={styles.content}>
|
||||
{/* Logo */}
|
||||
<View style={styles.logoArea}>
|
||||
<View style={styles.iconCircle}>
|
||||
<Shield size={40} color="#1A6B72" />
|
||||
</View>
|
||||
<Text style={styles.appName}>TerritoryLog</Text>
|
||||
<Text style={styles.subtitle}>Enter your PIN to continue</Text>
|
||||
</View>
|
||||
|
||||
{/* Error */}
|
||||
{error ? <Text style={styles.error}>{error}</Text> : null}
|
||||
|
||||
{/* PIN Pad */}
|
||||
<PinPad pin={pin} onPinChange={handlePinChange} maxLength={6} />
|
||||
|
||||
{/* Biometric button */}
|
||||
{biometricAvailable && (
|
||||
<TouchableOpacity style={styles.biometricBtn} onPress={handleBiometric}>
|
||||
<Text style={styles.biometricText}>Use Biometrics</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
{/* Forgot PIN */}
|
||||
<TouchableOpacity style={styles.forgotBtn} onPress={handleForgotPin}>
|
||||
<Text style={styles.forgotText}>Forgot PIN? (Clear App Data)</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#111827',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: 24,
|
||||
gap: 32,
|
||||
},
|
||||
logoArea: {
|
||||
alignItems: 'center',
|
||||
gap: 12,
|
||||
},
|
||||
iconCircle: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
borderRadius: 40,
|
||||
backgroundColor: 'rgba(26,107,114,0.15)',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
borderWidth: 2,
|
||||
borderColor: 'rgba(26,107,114,0.4)',
|
||||
},
|
||||
appName: {
|
||||
fontSize: 28,
|
||||
fontWeight: '700',
|
||||
color: '#F9FAFB',
|
||||
letterSpacing: 0.5,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 15,
|
||||
color: '#9CA3AF',
|
||||
},
|
||||
error: {
|
||||
color: '#F87171',
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
},
|
||||
biometricBtn: {
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 28,
|
||||
borderRadius: 24,
|
||||
borderWidth: 1,
|
||||
borderColor: '#1A6B72',
|
||||
},
|
||||
biometricText: {
|
||||
color: '#1A6B72',
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
forgotBtn: {
|
||||
marginTop: 8,
|
||||
},
|
||||
forgotText: {
|
||||
color: '#6B7280',
|
||||
fontSize: 13,
|
||||
textDecorationLine: 'underline',
|
||||
},
|
||||
});
|
||||
333
app/sync-progress.tsx
Normal file
333
app/sync-progress.tsx
Normal file
@@ -0,0 +1,333 @@
|
||||
// app/sync-progress.tsx — Full-screen active sync progress
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
StyleSheet,
|
||||
TouchableOpacity,
|
||||
SafeAreaView,
|
||||
Animated,
|
||||
Easing,
|
||||
} from 'react-native';
|
||||
import { router, useLocalSearchParams } from 'expo-router';
|
||||
import { CheckCircle, RefreshCw } from 'lucide-react-native';
|
||||
|
||||
type SyncPhase =
|
||||
| 'connecting'
|
||||
| 'sending'
|
||||
| 'receiving'
|
||||
| 'done'
|
||||
| 'error';
|
||||
|
||||
export default function SyncProgressScreen() {
|
||||
const params = useLocalSearchParams<{
|
||||
partnerName?: string;
|
||||
sentCount?: string;
|
||||
receivedCount?: string;
|
||||
conflictCount?: string;
|
||||
error?: string;
|
||||
}>();
|
||||
|
||||
const [phase, setPhase] = useState<SyncPhase>('connecting');
|
||||
const [sendProgress] = useState(new Animated.Value(0));
|
||||
const [receiveProgress] = useState(new Animated.Value(0));
|
||||
const spinAnim = useState(new Animated.Value(0))[0];
|
||||
|
||||
const sentCount = parseInt(params.sentCount ?? '0', 10);
|
||||
const receivedCount = parseInt(params.receivedCount ?? '0', 10);
|
||||
const conflictCount = parseInt(params.conflictCount ?? '0', 10);
|
||||
const partnerName = params.partnerName ?? 'Partner';
|
||||
const errorMsg = params.error;
|
||||
|
||||
useEffect(() => {
|
||||
if (errorMsg) {
|
||||
setPhase('error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Simulate sync animation sequence
|
||||
const connectTimer = setTimeout(() => {
|
||||
setPhase('sending');
|
||||
Animated.timing(sendProgress, {
|
||||
toValue: 1,
|
||||
duration: 1200,
|
||||
useNativeDriver: false,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}).start(() => {
|
||||
setPhase('receiving');
|
||||
Animated.timing(receiveProgress, {
|
||||
toValue: 1,
|
||||
duration: 1200,
|
||||
useNativeDriver: false,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}).start(() => {
|
||||
setPhase('done');
|
||||
});
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
return () => clearTimeout(connectTimer);
|
||||
}, []);
|
||||
|
||||
// Spinning icon animation
|
||||
useEffect(() => {
|
||||
if (phase === 'connecting' || phase === 'sending' || phase === 'receiving') {
|
||||
Animated.loop(
|
||||
Animated.timing(spinAnim, {
|
||||
toValue: 1,
|
||||
duration: 1000,
|
||||
useNativeDriver: true,
|
||||
easing: Easing.linear,
|
||||
})
|
||||
).start();
|
||||
} else {
|
||||
spinAnim.stopAnimation();
|
||||
}
|
||||
}, [phase]);
|
||||
|
||||
const spin = spinAnim.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: ['0deg', '360deg'],
|
||||
});
|
||||
|
||||
const sendWidth = sendProgress.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: ['0%', '100%'],
|
||||
});
|
||||
|
||||
const receiveWidth = receiveProgress.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: ['0%', '100%'],
|
||||
});
|
||||
|
||||
const phaseLabel = {
|
||||
connecting: `Connecting to ${partnerName}…`,
|
||||
sending: `Sending records…`,
|
||||
receiving: `Receiving records…`,
|
||||
done: 'Sync Complete!',
|
||||
error: 'Sync Failed',
|
||||
}[phase];
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container}>
|
||||
<View style={styles.content}>
|
||||
{/* Icon */}
|
||||
<View style={styles.iconArea}>
|
||||
{phase === 'done' ? (
|
||||
<CheckCircle size={64} color="#22C55E" />
|
||||
) : phase === 'error' ? (
|
||||
<View style={styles.errorCircle}>
|
||||
<Text style={styles.errorX}>✕</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Animated.View style={{ transform: [{ rotate: spin }] }}>
|
||||
<RefreshCw size={56} color="#1A6B72" />
|
||||
</Animated.View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Phase label */}
|
||||
<Text style={styles.phaseLabel}>{phaseLabel}</Text>
|
||||
|
||||
{errorMsg ? (
|
||||
<Text style={styles.errorDetail}>{errorMsg}</Text>
|
||||
) : null}
|
||||
|
||||
{/* Progress bars */}
|
||||
{phase !== 'done' && phase !== 'error' && (
|
||||
<View style={styles.progressArea}>
|
||||
<View style={styles.progressRow}>
|
||||
<Text style={styles.progressLabel}>Sending</Text>
|
||||
<View style={styles.progressBar}>
|
||||
<Animated.View
|
||||
style={[styles.progressFill, styles.sendFill, { width: sendWidth }]}
|
||||
/>
|
||||
</View>
|
||||
<Text style={styles.progressCount}>{sentCount}</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.progressRow}>
|
||||
<Text style={styles.progressLabel}>Receiving</Text>
|
||||
<View style={styles.progressBar}>
|
||||
<Animated.View
|
||||
style={[styles.progressFill, styles.receiveFill, { width: receiveWidth }]}
|
||||
/>
|
||||
</View>
|
||||
<Text style={styles.progressCount}>{receivedCount}</Text>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Summary card */}
|
||||
{phase === 'done' && (
|
||||
<View style={styles.summaryCard}>
|
||||
<Text style={styles.summaryTitle}>Sync Summary</Text>
|
||||
<View style={styles.summaryRow}>
|
||||
<Text style={styles.summaryKey}>Partner</Text>
|
||||
<Text style={styles.summaryValue}>{partnerName}</Text>
|
||||
</View>
|
||||
<View style={styles.summaryRow}>
|
||||
<Text style={styles.summaryKey}>Sent</Text>
|
||||
<Text style={[styles.summaryValue, styles.sentColor]}>{sentCount} records</Text>
|
||||
</View>
|
||||
<View style={styles.summaryRow}>
|
||||
<Text style={styles.summaryKey}>Received</Text>
|
||||
<Text style={[styles.summaryValue, styles.receivedColor]}>{receivedCount} records</Text>
|
||||
</View>
|
||||
{conflictCount > 0 && (
|
||||
<View style={styles.summaryRow}>
|
||||
<Text style={styles.summaryKey}>Conflicts</Text>
|
||||
<Text style={[styles.summaryValue, styles.conflictColor]}>
|
||||
{conflictCount} resolved
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Done button */}
|
||||
{(phase === 'done' || phase === 'error') && (
|
||||
<TouchableOpacity
|
||||
style={[styles.doneBtn, phase === 'error' && styles.errorBtn]}
|
||||
onPress={() => router.back()}
|
||||
>
|
||||
<Text style={styles.doneBtnText}>
|
||||
{phase === 'done' ? 'Done' : 'Go Back'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
</SafeAreaView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#0F172A',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: 24,
|
||||
gap: 24,
|
||||
},
|
||||
iconArea: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
errorCircle: {
|
||||
width: 64,
|
||||
height: 64,
|
||||
borderRadius: 32,
|
||||
backgroundColor: '#FEE2E2',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
errorX: {
|
||||
fontSize: 28,
|
||||
color: '#EF4444',
|
||||
fontWeight: '700',
|
||||
},
|
||||
phaseLabel: {
|
||||
fontSize: 22,
|
||||
fontWeight: '700',
|
||||
color: '#F9FAFB',
|
||||
textAlign: 'center',
|
||||
},
|
||||
errorDetail: {
|
||||
fontSize: 14,
|
||||
color: '#F87171',
|
||||
textAlign: 'center',
|
||||
paddingHorizontal: 16,
|
||||
},
|
||||
progressArea: {
|
||||
width: '100%',
|
||||
gap: 16,
|
||||
backgroundColor: 'rgba(255,255,255,0.05)',
|
||||
borderRadius: 16,
|
||||
padding: 20,
|
||||
},
|
||||
progressRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
},
|
||||
progressLabel: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 13,
|
||||
width: 72,
|
||||
},
|
||||
progressBar: {
|
||||
flex: 1,
|
||||
height: 8,
|
||||
backgroundColor: 'rgba(255,255,255,0.1)',
|
||||
borderRadius: 4,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
progressFill: {
|
||||
height: '100%',
|
||||
borderRadius: 4,
|
||||
},
|
||||
sendFill: {
|
||||
backgroundColor: '#1A6B72',
|
||||
},
|
||||
receiveFill: {
|
||||
backgroundColor: '#10B981',
|
||||
},
|
||||
progressCount: {
|
||||
color: '#D1D5DB',
|
||||
fontSize: 13,
|
||||
width: 32,
|
||||
textAlign: 'right',
|
||||
},
|
||||
summaryCard: {
|
||||
width: '100%',
|
||||
backgroundColor: 'rgba(255,255,255,0.06)',
|
||||
borderRadius: 16,
|
||||
padding: 20,
|
||||
gap: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: 'rgba(255,255,255,0.1)',
|
||||
},
|
||||
summaryTitle: {
|
||||
color: '#F9FAFB',
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
marginBottom: 4,
|
||||
},
|
||||
summaryRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
summaryKey: {
|
||||
color: '#9CA3AF',
|
||||
fontSize: 14,
|
||||
},
|
||||
summaryValue: {
|
||||
color: '#F9FAFB',
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
},
|
||||
sentColor: { color: '#1A6B72' },
|
||||
receivedColor: { color: '#10B981' },
|
||||
conflictColor: { color: '#F59E0B' },
|
||||
doneBtn: {
|
||||
paddingVertical: 14,
|
||||
paddingHorizontal: 48,
|
||||
backgroundColor: '#1A6B72',
|
||||
borderRadius: 14,
|
||||
marginTop: 8,
|
||||
},
|
||||
errorBtn: {
|
||||
backgroundColor: '#6B7280',
|
||||
},
|
||||
doneBtnText: {
|
||||
color: '#fff',
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user