Delete mobile
Browse filesFiles changed (23)
- mobile/.env.exampleDeleted-10
- mobile/app.jsonDeleted-60
- mobile/app/(auth)/_layout.tsxDeleted-12
- mobile/app/(auth)/forgot-password.tsxDeleted-94
- mobile/app/(auth)/login.tsxDeleted-207
- mobile/app/(auth)/register.tsxDeleted-176
- mobile/app/(tabs)/_layout.tsxDeleted-60
- mobile/app/(tabs)/albums.tsxDeleted-182
- mobile/app/(tabs)/gallery.tsxDeleted-270
- mobile/app/(tabs)/settings.tsxDeleted-258
- mobile/app/_layout.tsxDeleted-60
- mobile/hooks/useAlbums.tsDeleted-49
- mobile/hooks/usePhotos.tsDeleted-70
- mobile/hooks/useSync.tsDeleted-26
- mobile/package.jsonDeleted-47
- mobile/services/api.tsDeleted-164
- mobile/services/backgroundSync.tsDeleted-73
- mobile/services/hashUtil.tsDeleted-38
- mobile/services/supabase.tsDeleted-16
- mobile/services/syncEngine.tsDeleted-157
- mobile/store/authStore.tsDeleted-84
- mobile/store/syncStore.tsDeleted-92
- mobile/tsconfig.jsonDeleted-9
12345678910# Mobile App Environment Variables# Copy this file to .env and fill in your values
# KeyStone Backend API URLEXPO_PUBLIC_API_URL=https://dpv007-keystone.hf.space
# SupabaseEXPO_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtmZmFuaGtiZGJhYnhhbndubW1lIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODQyMTExNTYsImV4cCI6MjA5OTc4NzE1Nn0.W4LgjVQekUxlkz2ZPTg4BpckCBp_Z7QEKXN-XOH1CvEEXPO_PUBLIC_SUPABASE_URL=https://kffanhkbdbabxanwnmme.supabase.coEXPO_PUBLIC_SUPABASE_KEY=sb_publishable_pTshogCZaZas2Im0POcPDw_fkMdTqSe123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960{ "expo": { "name": "KeyStone", "slug": "keystone", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/icon.png", "scheme": "keystone", "userInterfaceStyle": "automatic", "splash": { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#0f0f23" }, "assetBundlePatterns": ["**/*"], "ios": { "supportsTablet": true, "bundleIdentifier": "com.dpv007.keystone", "infoPlist": { "NSPhotoLibraryUsageDescription": "KeyStone needs access to your photo library to back up your photos.", "NSPhotoLibraryAddUsageDescription": "KeyStone needs access to save photos.", "UIBackgroundModes": ["fetch", "processing"] } }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", "backgroundColor": "#0f0f23" }, "package": "com.dpv007.keystone", "permissions": [ "android.permission.READ_MEDIA_IMAGES", "android.permission.READ_MEDIA_VIDEO", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.ACCESS_NETWORK_STATE", "android.permission.RECEIVE_BOOT_COMPLETED", "android.permission.FOREGROUND_SERVICE" ] }, "web": { "bundler": "metro", "output": "static", "favicon": "./assets/favicon.png" }, "plugins": [ "expo-router", [ "expo-media-library", { "photosPermission": "Allow KeyStone to access your photos.", "savePhotosPermission": "Allow KeyStone to save photos.", "isAccessMediaLocationEnabled": true } ] ], "experiments": { "typedRoutes": true } }}123456789101112/** * KeyStone – Auth Layout * Wraps all auth screens with a shared gradient background. */
import { Stack } from 'expo-router';
export default function AuthLayout() { return ( <Stack screenOptions={{ headerShown: false }} /> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394/** * KeyStone – Forgot Password Screen */
import { View, Text, TextInput, TouchableOpacity, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, ActivityIndicator,} from 'react-native';import { useState } from 'react';import { Link } from 'expo-router';import { LinearGradient } from 'expo-linear-gradient';import { useAuthStore } from '../../store/authStore';
export default function ForgotPasswordScreen() { const [email, setEmail] = useState(''); const [error, setError] = useState(''); const [sent, setSent] = useState(false); const { resetPassword, isLoading } = useAuthStore();
const handleReset = async () => { setError(''); if (!email) { setError('Please enter your email address.'); return; } try { await resetPassword(email); setSent(true); } catch (err: any) { setError(err.message || 'Failed to send reset email.'); } };
return ( <LinearGradient colors={['#0f0f23', '#1a0a2e', '#16213e']} style={styles.gradient}> <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.flex}> <ScrollView contentContainerStyle={styles.scroll}> <View style={styles.container}> <View style={styles.card}> <Text style={styles.cardTitle}>{sent ? '📨 Email sent!' : '🔑 Reset password'}</Text> <Text style={styles.cardSubtitle}> {sent ? `We sent a password reset link to ${email}.` : "Enter your email and we'll send you a reset link."} </Text>
{!sent && ( <> {error ? <View style={styles.errorBox}><Text style={styles.errorText}>{error}</Text></View> : null} <View style={styles.inputGroup}> <Text style={styles.label}>Email</Text> <TextInput style={styles.input} placeholder="you@example.com" placeholderTextColor="#4a4a6a" value={email} onChangeText={setEmail} autoCapitalize="none" keyboardType="email-address" /> </View> <TouchableOpacity style={[styles.btn, isLoading && styles.btnDisabled]} onPress={handleReset} disabled={isLoading} activeOpacity={0.85}> <LinearGradient colors={['#7c3aed', '#4f46e5']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.btnGradient}> {isLoading ? <ActivityIndicator color="#fff" /> : <Text style={styles.btnText}>Send Reset Link</Text>} </LinearGradient> </TouchableOpacity> </> )}
<Link href="/(auth)/login" style={styles.backLink}>← Back to Sign In</Link> </View> </View> </ScrollView> </KeyboardAvoidingView> </LinearGradient> );}
const styles = StyleSheet.create({ gradient: { flex: 1 }, flex: { flex: 1 }, scroll: { flexGrow: 1, justifyContent: 'center' }, container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 20 }, card: { width: '100%', maxWidth: 420, backgroundColor: 'rgba(255,255,255,0.04)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.08)', borderRadius: 24, padding: 28 }, cardTitle: { fontSize: 22, fontWeight: '700', color: '#fff', marginBottom: 8 }, cardSubtitle: { fontSize: 14, color: '#8888aa', marginBottom: 24, lineHeight: 20 }, errorBox: { backgroundColor: 'rgba(239,68,68,0.15)', borderWidth: 1, borderColor: 'rgba(239,68,68,0.3)', borderRadius: 10, padding: 12, marginBottom: 16 }, errorText: { color: '#fca5a5', fontSize: 13 }, inputGroup: { marginBottom: 16 }, label: { fontSize: 13, fontWeight: '600', color: '#c4c4d4', marginBottom: 8 }, input: { backgroundColor: 'rgba(255,255,255,0.06)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.1)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 13, color: '#fff', fontSize: 15 }, btn: { borderRadius: 14, overflow: 'hidden', marginBottom: 20 }, btnDisabled: { opacity: 0.6 }, btnGradient: { paddingVertical: 15, alignItems: 'center', borderRadius: 14 }, btnText: { color: '#fff', fontWeight: '700', fontSize: 16 }, backLink: { color: '#7c3aed', fontSize: 14, textAlign: 'center', marginTop: 8 },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/** * KeyStone – Login Screen * Works on Android, iOS, and Web (React Native Web). */
import { View, Text, TextInput, TouchableOpacity, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, ActivityIndicator, Alert, Dimensions,} from 'react-native';import { useState } from 'react';import { Link, useRouter } from 'expo-router';import { LinearGradient } from 'expo-linear-gradient';import { useAuthStore } from '../../store/authStore';
const { width } = Dimensions.get('window');const isWeb = Platform.OS === 'web';
export default function LoginScreen() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const { signIn, isLoading } = useAuthStore(); const router = useRouter();
const handleLogin = async () => { setError(''); if (!email || !password) { setError('Please fill in all fields.'); return; } try { await signIn(email, password); router.replace('/(tabs)/gallery'); } catch (err: any) { setError(err.message || 'Login failed. Please try again.'); } };
return ( <LinearGradient colors={['#0f0f23', '#1a0a2e', '#16213e']} style={styles.gradient}> <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.flex} > <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled"> <View style={styles.container}>
{/* Logo / Brand */} <View style={styles.logoArea}> <View style={styles.logoIcon}> <Text style={styles.logoEmoji}>🔷</Text> </View> <Text style={styles.brandName}>KeyStone</Text> <Text style={styles.brandTagline}>Your private photo cloud</Text> </View>
{/* Card */} <View style={styles.card}> <Text style={styles.cardTitle}>Welcome back</Text> <Text style={styles.cardSubtitle}>Sign in to your account</Text>
{error ? ( <View style={styles.errorBox}> <Text style={styles.errorText}>{error}</Text> </View> ) : null}
<View style={styles.inputGroup}> <Text style={styles.label}>Email</Text> <TextInput style={styles.input} placeholder="you@example.com" placeholderTextColor="#4a4a6a" value={email} onChangeText={setEmail} autoCapitalize="none" keyboardType="email-address" autoComplete="email" /> </View>
<View style={styles.inputGroup}> <View style={styles.labelRow}> <Text style={styles.label}>Password</Text> <Link href="/(auth)/forgot-password" style={styles.forgotLink}> Forgot password? </Link> </View> <TextInput style={styles.input} placeholder="••••••••" placeholderTextColor="#4a4a6a" value={password} onChangeText={setPassword} secureTextEntry autoComplete="current-password" /> </View>
<TouchableOpacity style={[styles.btn, isLoading && styles.btnDisabled]} onPress={handleLogin} disabled={isLoading} activeOpacity={0.85} > <LinearGradient colors={['#7c3aed', '#4f46e5']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.btnGradient} > {isLoading ? ( <ActivityIndicator color="#fff" /> ) : ( <Text style={styles.btnText}>Sign In</Text> )} </LinearGradient> </TouchableOpacity>
<View style={styles.footerRow}> <Text style={styles.footerText}>Don't have an account? </Text> <Link href="/(auth)/register" style={styles.footerLink}> Sign up </Link> </View> </View>
</View> </ScrollView> </KeyboardAvoidingView> </LinearGradient> );}
const styles = StyleSheet.create({ gradient: { flex: 1 }, flex: { flex: 1 }, scroll: { flexGrow: 1, justifyContent: 'center' }, container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 20, paddingVertical: 40, }, logoArea: { alignItems: 'center', marginBottom: 40 }, logoIcon: { width: 72, height: 72, borderRadius: 20, backgroundColor: 'rgba(124,58,237,0.2)', borderWidth: 1, borderColor: 'rgba(124,58,237,0.5)', alignItems: 'center', justifyContent: 'center', marginBottom: 12, }, logoEmoji: { fontSize: 36 }, brandName: { fontSize: 32, fontWeight: '800', color: '#fff', letterSpacing: -0.5 }, brandTagline: { fontSize: 14, color: '#8888aa', marginTop: 4 },
card: { width: '100%', maxWidth: 420, backgroundColor: 'rgba(255,255,255,0.04)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.08)', borderRadius: 24, padding: 28, }, cardTitle: { fontSize: 24, fontWeight: '700', color: '#fff', marginBottom: 4 }, cardSubtitle: { fontSize: 14, color: '#8888aa', marginBottom: 24 },
errorBox: { backgroundColor: 'rgba(239,68,68,0.15)', borderWidth: 1, borderColor: 'rgba(239,68,68,0.3)', borderRadius: 10, padding: 12, marginBottom: 16, }, errorText: { color: '#fca5a5', fontSize: 13 },
inputGroup: { marginBottom: 16 }, labelRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }, label: { fontSize: 13, fontWeight: '600', color: '#c4c4d4', marginBottom: 8 }, forgotLink: { fontSize: 12, color: '#7c3aed' }, input: { backgroundColor: 'rgba(255,255,255,0.06)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.1)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 13, color: '#fff', fontSize: 15, },
btn: { borderRadius: 14, overflow: 'hidden', marginTop: 8 }, btnDisabled: { opacity: 0.6 }, btnGradient: { paddingVertical: 15, alignItems: 'center' }, btnText: { color: '#fff', fontWeight: '700', fontSize: 16 },
footerRow: { flexDirection: 'row', justifyContent: 'center', marginTop: 20 }, footerText: { color: '#8888aa', fontSize: 13 }, footerLink: { color: '#7c3aed', fontWeight: '600', fontSize: 13 },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176/** * KeyStone – Register Screen */
import { View, Text, TextInput, TouchableOpacity, StyleSheet, KeyboardAvoidingView, Platform, ScrollView, ActivityIndicator,} from 'react-native';import { useState } from 'react';import { Link, useRouter } from 'expo-router';import { LinearGradient } from 'expo-linear-gradient';import { useAuthStore } from '../../store/authStore';
export default function RegisterScreen() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [confirm, setConfirm] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(false); const { signUp, isLoading } = useAuthStore(); const router = useRouter();
const handleRegister = async () => { setError(''); if (!email || !password || !confirm) { setError('Please fill in all fields.'); return; } if (password.length < 8) { setError('Password must be at least 8 characters.'); return; } if (password !== confirm) { setError('Passwords do not match.'); return; } try { await signUp(email, password); setSuccess(true); } catch (err: any) { setError(err.message || 'Registration failed. Please try again.'); } };
if (success) { return ( <LinearGradient colors={['#0f0f23', '#1a0a2e', '#16213e']} style={styles.gradient}> <View style={styles.successContainer}> <Text style={styles.successEmoji}>📬</Text> <Text style={styles.successTitle}>Check your email!</Text> <Text style={styles.successText}> We've sent a confirmation link to {email}. Click it to activate your account. </Text> <TouchableOpacity onPress={() => router.replace('/(auth)/login')}> <LinearGradient colors={['#7c3aed', '#4f46e5']} style={styles.btnGradient}> <Text style={styles.btnText}>Back to Sign In</Text> </LinearGradient> </TouchableOpacity> </View> </LinearGradient> ); }
return ( <LinearGradient colors={['#0f0f23', '#1a0a2e', '#16213e']} style={styles.gradient}> <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.flex}> <ScrollView contentContainerStyle={styles.scroll} keyboardShouldPersistTaps="handled"> <View style={styles.container}> <View style={styles.logoArea}> <View style={styles.logoIcon}> <Text style={styles.logoEmoji}>🔷</Text> </View> <Text style={styles.brandName}>KeyStone</Text> <Text style={styles.brandTagline}>Create your private cloud</Text> </View>
<View style={styles.card}> <Text style={styles.cardTitle}>Create account</Text> <Text style={styles.cardSubtitle}>Start backing up your photos today</Text>
{error ? ( <View style={styles.errorBox}> <Text style={styles.errorText}>{error}</Text> </View> ) : null}
<View style={styles.inputGroup}> <Text style={styles.label}>Email</Text> <TextInput style={styles.input} placeholder="you@example.com" placeholderTextColor="#4a4a6a" value={email} onChangeText={setEmail} autoCapitalize="none" keyboardType="email-address" /> </View>
<View style={styles.inputGroup}> <Text style={styles.label}>Password</Text> <TextInput style={styles.input} placeholder="Min. 8 characters" placeholderTextColor="#4a4a6a" value={password} onChangeText={setPassword} secureTextEntry /> </View>
<View style={styles.inputGroup}> <Text style={styles.label}>Confirm Password</Text> <TextInput style={styles.input} placeholder="Repeat password" placeholderTextColor="#4a4a6a" value={confirm} onChangeText={setConfirm} secureTextEntry /> </View>
<TouchableOpacity style={[styles.btn, isLoading && styles.btnDisabled]} onPress={handleRegister} disabled={isLoading} activeOpacity={0.85} > <LinearGradient colors={['#7c3aed', '#4f46e5']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.btnGradient}> {isLoading ? <ActivityIndicator color="#fff" /> : <Text style={styles.btnText}>Create Account</Text>} </LinearGradient> </TouchableOpacity>
<View style={styles.footerRow}> <Text style={styles.footerText}>Already have an account? </Text> <Link href="/(auth)/login" style={styles.footerLink}>Sign in</Link> </View> </View> </View> </ScrollView> </KeyboardAvoidingView> </LinearGradient> );}
const styles = StyleSheet.create({ gradient: { flex: 1 }, flex: { flex: 1 }, scroll: { flexGrow: 1, justifyContent: 'center' }, container: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 20, paddingVertical: 40 }, logoArea: { alignItems: 'center', marginBottom: 32 }, logoIcon: { width: 64, height: 64, borderRadius: 18, backgroundColor: 'rgba(124,58,237,0.2)', borderWidth: 1, borderColor: 'rgba(124,58,237,0.5)', alignItems: 'center', justifyContent: 'center', marginBottom: 10 }, logoEmoji: { fontSize: 30 }, brandName: { fontSize: 28, fontWeight: '800', color: '#fff' }, brandTagline: { fontSize: 13, color: '#8888aa', marginTop: 4 }, card: { width: '100%', maxWidth: 420, backgroundColor: 'rgba(255,255,255,0.04)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.08)', borderRadius: 24, padding: 28 }, cardTitle: { fontSize: 22, fontWeight: '700', color: '#fff', marginBottom: 4 }, cardSubtitle: { fontSize: 13, color: '#8888aa', marginBottom: 20 }, errorBox: { backgroundColor: 'rgba(239,68,68,0.15)', borderWidth: 1, borderColor: 'rgba(239,68,68,0.3)', borderRadius: 10, padding: 12, marginBottom: 16 }, errorText: { color: '#fca5a5', fontSize: 13 }, inputGroup: { marginBottom: 14 }, label: { fontSize: 13, fontWeight: '600', color: '#c4c4d4', marginBottom: 8 }, input: { backgroundColor: 'rgba(255,255,255,0.06)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.1)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 13, color: '#fff', fontSize: 15 }, btn: { borderRadius: 14, overflow: 'hidden', marginTop: 8 }, btnDisabled: { opacity: 0.6 }, btnGradient: { paddingVertical: 15, alignItems: 'center', borderRadius: 14 }, btnText: { color: '#fff', fontWeight: '700', fontSize: 16 }, footerRow: { flexDirection: 'row', justifyContent: 'center', marginTop: 20 }, footerText: { color: '#8888aa', fontSize: 13 }, footerLink: { color: '#7c3aed', fontWeight: '600', fontSize: 13 }, successContainer: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 }, successEmoji: { fontSize: 64, marginBottom: 20 }, successTitle: { fontSize: 26, fontWeight: '800', color: '#fff', marginBottom: 12 }, successText: { fontSize: 15, color: '#8888aa', textAlign: 'center', marginBottom: 32, lineHeight: 22 },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960/** * KeyStone – Tabs Layout * Bottom tab navigator for Gallery, Albums, and Settings. * On web, renders as a sidebar navigation instead. */
import { Tabs } from 'expo-router';import { Platform, View, StyleSheet } from 'react-native';import { Ionicons } from '@expo/vector-icons';
const TAB_BAR_STYLE = { backgroundColor: '#12122a', borderTopColor: 'rgba(255,255,255,0.08)', borderTopWidth: 1, paddingBottom: Platform.OS === 'ios' ? 20 : 8, paddingTop: 8, height: Platform.OS === 'ios' ? 84 : 64,};
export default function TabsLayout() { return ( <Tabs screenOptions={{ headerShown: false, tabBarStyle: TAB_BAR_STYLE, tabBarActiveTintColor: '#7c3aed', tabBarInactiveTintColor: '#555577', tabBarLabelStyle: { fontSize: 11, fontWeight: '600', marginTop: 2 }, }} > <Tabs.Screen name="gallery" options={{ title: 'Gallery', tabBarIcon: ({ color, size }) => ( <Ionicons name="images-outline" size={size} color={color} /> ), }} /> <Tabs.Screen name="albums" options={{ title: 'Albums', tabBarIcon: ({ color, size }) => ( <Ionicons name="albums-outline" size={size} color={color} /> ), }} /> <Tabs.Screen name="settings" options={{ title: 'Settings', tabBarIcon: ({ color, size }) => ( <Ionicons name="settings-outline" size={size} color={color} /> ), }} /> </Tabs> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182/** * KeyStone – Albums Screen */
import { View, Text, StyleSheet, TouchableOpacity, FlatList, Modal, TextInput, ActivityIndicator, Alert,} from 'react-native';import { useState } from 'react';import { Image } from 'expo-image';import { SafeAreaView } from 'react-native-safe-area-context';import { Ionicons } from '@expo/vector-icons';import { LinearGradient } from 'expo-linear-gradient';import { useAlbums, useCreateAlbum } from '../../hooks/useAlbums';import { Album } from '../../services/api';
function AlbumCard({ album }: { album: Album }) { return ( <TouchableOpacity style={styles.albumCard} activeOpacity={0.8}> <View style={styles.albumCover}> {album.cover_photo_id ? ( <Image source={{ uri: `cover` }} style={styles.albumImage} contentFit="cover" /> ) : ( <LinearGradient colors={['#2d1b69', '#1e1458']} style={styles.albumImagePlaceholder} > <Ionicons name="albums" size={32} color="rgba(124,58,237,0.6)" /> </LinearGradient> )} <View style={styles.albumOverlay}> <Text style={styles.albumCount}>{album.photo_count}</Text> </View> </View> <Text style={styles.albumName} numberOfLines={1}>{album.name}</Text> {album.description ? ( <Text style={styles.albumDesc} numberOfLines={1}>{album.description}</Text> ) : null} </TouchableOpacity> );}
function CreateAlbumModal({ visible, onClose,}: { visible: boolean; onClose: () => void }) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const { mutate, isPending } = useCreateAlbum();
const handleCreate = () => { if (!name.trim()) return; mutate({ name: name.trim(), description: description.trim() || undefined }, { onSuccess: () => { setName(''); setDescription(''); onClose(); }, }); };
return ( <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}> <View style={styles.modalOverlay}> <View style={styles.modalCard}> <Text style={styles.modalTitle}>New Album</Text> <TextInput style={styles.input} placeholder="Album name" placeholderTextColor="#4a4a6a" value={name} onChangeText={setName} /> <TextInput style={[styles.input, styles.inputDesc]} placeholder="Description (optional)" placeholderTextColor="#4a4a6a" value={description} onChangeText={setDescription} multiline numberOfLines={3} /> <View style={styles.modalActions}> <TouchableOpacity style={styles.cancelBtn} onPress={onClose}> <Text style={styles.cancelBtnText}>Cancel</Text> </TouchableOpacity> <TouchableOpacity style={[styles.createBtn, isPending && { opacity: 0.6 }]} onPress={handleCreate} disabled={isPending} > <LinearGradient colors={['#7c3aed', '#4f46e5']} style={styles.createBtnGradient}> {isPending ? <ActivityIndicator color="#fff" size="small" /> : <Text style={styles.createBtnText}>Create</Text>} </LinearGradient> </TouchableOpacity> </View> </View> </View> </Modal> );}
export default function AlbumsScreen() { const [showCreate, setShowCreate] = useState(false); const { data: albums = [], isLoading, refetch, isRefetching } = useAlbums();
return ( <SafeAreaView style={styles.safeArea} edges={['top']}> <View style={styles.container}>
<View style={styles.header}> <Text style={styles.headerTitle}>Albums</Text> <TouchableOpacity style={styles.addBtn} onPress={() => setShowCreate(true)}> <Ionicons name="add" size={22} color="#fff" /> </TouchableOpacity> </View>
{isLoading ? ( <View style={styles.centered}> <ActivityIndicator size="large" color="#7c3aed" /> </View> ) : albums.length === 0 ? ( <View style={styles.centered}> <Text style={styles.emptyEmoji}>🗂️</Text> <Text style={styles.emptyTitle}>No albums yet</Text> <Text style={styles.emptyText}>Organize your photos into albums.</Text> <TouchableOpacity style={styles.emptyBtn} onPress={() => setShowCreate(true)}> <Text style={styles.emptyBtnText}>Create Album</Text> </TouchableOpacity> </View> ) : ( <FlatList data={albums} renderItem={({ item }) => <AlbumCard album={item} />} keyExtractor={(item) => item.id} numColumns={2} columnWrapperStyle={styles.row} contentContainerStyle={styles.grid} showsVerticalScrollIndicator={false} /> )}
<CreateAlbumModal visible={showCreate} onClose={() => setShowCreate(false)} /> </View> </SafeAreaView> );}
const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: '#0f0f23' }, container: { flex: 1, backgroundColor: '#0f0f23' }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 14 }, headerTitle: { fontSize: 24, fontWeight: '800', color: '#fff' }, addBtn: { width: 36, height: 36, borderRadius: 10, backgroundColor: '#7c3aed', alignItems: 'center', justifyContent: 'center' }, centered: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 }, emptyEmoji: { fontSize: 56, marginBottom: 16 }, emptyTitle: { fontSize: 20, fontWeight: '700', color: '#fff', marginBottom: 8 }, emptyText: { fontSize: 14, color: '#8888aa', textAlign: 'center', marginBottom: 20 }, emptyBtn: { backgroundColor: '#7c3aed', paddingHorizontal: 24, paddingVertical: 12, borderRadius: 12 }, emptyBtnText: { color: '#fff', fontWeight: '700' }, grid: { paddingHorizontal: 12, paddingBottom: 20 }, row: { justifyContent: 'space-between', marginBottom: 16 }, albumCard: { width: '48%', backgroundColor: 'rgba(255,255,255,0.04)', borderRadius: 16, overflow: 'hidden', borderWidth: 1, borderColor: 'rgba(255,255,255,0.06)' }, albumCover: { width: '100%', aspectRatio: 1, backgroundColor: '#1a1a2e', position: 'relative' }, albumImage: { width: '100%', height: '100%' }, albumImagePlaceholder: { width: '100%', height: '100%', alignItems: 'center', justifyContent: 'center' }, albumOverlay: { position: 'absolute', bottom: 6, right: 8 }, albumCount: { color: 'rgba(255,255,255,0.7)', fontSize: 11, fontWeight: '700' }, albumName: { color: '#fff', fontWeight: '700', fontSize: 14, padding: 10, paddingBottom: 2 }, albumDesc: { color: '#8888aa', fontSize: 12, paddingHorizontal: 10, paddingBottom: 10 }, modalOverlay: { flex: 1, backgroundColor: 'rgba(0,0,0,0.7)', justifyContent: 'flex-end' }, modalCard: { backgroundColor: '#1a1a2e', borderTopLeftRadius: 24, borderTopRightRadius: 24, padding: 24, paddingBottom: 40 }, modalTitle: { color: '#fff', fontSize: 20, fontWeight: '700', marginBottom: 20 }, input: { backgroundColor: 'rgba(255,255,255,0.06)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.1)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 12, color: '#fff', fontSize: 15, marginBottom: 12 }, inputDesc: { height: 80, textAlignVertical: 'top' }, modalActions: { flexDirection: 'row', gap: 10, marginTop: 8 }, cancelBtn: { flex: 1, paddingVertical: 14, borderRadius: 12, borderWidth: 1, borderColor: 'rgba(255,255,255,0.1)', alignItems: 'center' }, cancelBtnText: { color: '#8888aa', fontWeight: '600' }, createBtn: { flex: 1, borderRadius: 12, overflow: 'hidden' }, createBtnGradient: { paddingVertical: 14, alignItems: 'center' }, createBtnText: { color: '#fff', fontWeight: '700' },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270/** * KeyStone – Gallery Screen * Infinite-scroll photo grid with timeline grouping. * Works on mobile (native FlashList) and web (CSS grid fallback). */
import { View, Text, StyleSheet, TouchableOpacity, FlatList, Dimensions, RefreshControl, Platform, TextInput, ActivityIndicator,} from 'react-native';import { useState, useCallback, useRef } from 'react';import { Image } from 'expo-image';import { SafeAreaView } from 'react-native-safe-area-context';import { Ionicons } from '@expo/vector-icons';import { useInfinitePhotos, useSearchPhotos } from '../../hooks/usePhotos';import { useSyncStore } from '../../store/syncStore';import { runSync } from '../../services/syncEngine';import { Photo } from '../../services/api';
const { width } = Dimensions.get('window');const isWeb = Platform.OS === 'web';
// Responsive column countconst getNumColumns = () => { if (isWeb) { const w = typeof window !== 'undefined' ? window.innerWidth : 1024; if (w > 1200) return 6; if (w > 768) return 4; return 3; } return width > 600 ? 4 : 3;};
const NUM_COLS = getNumColumns();const ITEM_SIZE = Math.floor((width - (NUM_COLS + 1) * 2) / NUM_COLS);
function PhotoItem({ photo, onPress }: { photo: Photo; onPress: () => void }) { return ( <TouchableOpacity onPress={onPress} activeOpacity={0.85} style={[styles.photoItem, { width: isWeb ? undefined : ITEM_SIZE, height: isWeb ? undefined : ITEM_SIZE }]} > <Image source={{ uri: photo.thumbnail_path || photo.bucket_path }} style={styles.photoImage} contentFit="cover" transition={200} cachePolicy="memory-disk" /> {photo.is_favorite && ( <View style={styles.favBadge}> <Ionicons name="heart" size={10} color="#fff" /> </View> )} </TouchableOpacity> );}
function SyncBanner() { const { isRunning, uploaded, totalPhotos } = useSyncStore(); if (!isRunning) return null; return ( <View style={styles.syncBanner}> <ActivityIndicator size="small" color="#7c3aed" /> <Text style={styles.syncText}> Syncing… {uploaded}/{totalPhotos} photos </Text> </View> );}
export default function GalleryScreen() { const [searchQuery, setSearchQuery] = useState(''); const [isSearching, setIsSearching] = useState(false);
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading, refetch, isRefetching, } = useInfinitePhotos();
const { data: searchData, isLoading: isSearchLoading } = useSearchPhotos( isSearching ? searchQuery : '', );
const photos: Photo[] = isSearching ? (searchData?.items || []) : (data?.pages?.flatMap(p => p.items) || []);
const handleSyncNow = useCallback(async () => { runSync(); }, []);
const renderItem = ({ item }: { item: Photo }) => ( <PhotoItem photo={item} onPress={() => {}} /> );
const renderFooter = () => { if (!isFetchingNextPage) return null; return ( <View style={styles.loaderFooter}> <ActivityIndicator color="#7c3aed" /> </View> ); };
return ( <SafeAreaView style={styles.safeArea} edges={['top']}> <View style={styles.container}>
{/* Header */} <View style={styles.header}> <View> <Text style={styles.headerTitle}>KeyStone</Text> <Text style={styles.headerSubtitle}> {photos.length > 0 ? `${data?.pages?.[0]?.total ?? 0} photos` : 'Your private cloud'} </Text> </View> <View style={styles.headerActions}> <TouchableOpacity style={styles.iconBtn} onPress={handleSyncNow}> <Ionicons name="cloud-upload-outline" size={22} color="#c4c4d4" /> </TouchableOpacity> </View> </View>
{/* Search Bar */} <View style={styles.searchRow}> <View style={styles.searchBar}> <Ionicons name="search" size={16} color="#555577" style={{ marginRight: 8 }} /> <TextInput style={styles.searchInput} placeholder="Search photos…" placeholderTextColor="#555577" value={searchQuery} onChangeText={(t) => { setSearchQuery(t); setIsSearching(t.length > 0); }} returnKeyType="search" /> {searchQuery.length > 0 && ( <TouchableOpacity onPress={() => { setSearchQuery(''); setIsSearching(false); }}> <Ionicons name="close-circle" size={16} color="#555577" /> </TouchableOpacity> )} </View> </View>
{/* Sync Banner */} <SyncBanner />
{/* Photo Grid */} {isLoading ? ( <View style={styles.centered}> <ActivityIndicator size="large" color="#7c3aed" /> <Text style={styles.loadingText}>Loading photos…</Text> </View> ) : photos.length === 0 ? ( <View style={styles.centered}> <Text style={styles.emptyEmoji}>📷</Text> <Text style={styles.emptyTitle}>No photos yet</Text> <Text style={styles.emptyText}>Tap the sync button to back up your camera roll.</Text> <TouchableOpacity style={styles.emptyBtn} onPress={handleSyncNow}> <Text style={styles.emptyBtnText}>Start Sync</Text> </TouchableOpacity> </View> ) : ( <FlatList data={photos} renderItem={renderItem} keyExtractor={(item) => item.id} numColumns={NUM_COLS} key={`cols-${NUM_COLS}`} contentContainerStyle={styles.grid} columnWrapperStyle={styles.row} onEndReached={() => { if (hasNextPage && !isFetchingNextPage) fetchNextPage(); }} onEndReachedThreshold={0.5} ListFooterComponent={renderFooter} refreshControl={ <RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#7c3aed" /> } showsVerticalScrollIndicator={false} /> )} </View> </SafeAreaView> );}
const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: '#0f0f23' }, container: { flex: 1, backgroundColor: '#0f0f23' },
header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 12, }, headerTitle: { fontSize: 24, fontWeight: '800', color: '#fff' }, headerSubtitle: { fontSize: 12, color: '#555577', marginTop: 2 }, headerActions: { flexDirection: 'row', gap: 8 }, iconBtn: { width: 36, height: 36, borderRadius: 10, backgroundColor: 'rgba(255,255,255,0.06)', alignItems: 'center', justifyContent: 'center', },
searchRow: { paddingHorizontal: 16, paddingBottom: 12 }, searchBar: { flexDirection: 'row', alignItems: 'center', backgroundColor: 'rgba(255,255,255,0.06)', borderWidth: 1, borderColor: 'rgba(255,255,255,0.08)', borderRadius: 12, paddingHorizontal: 12, paddingVertical: 10, }, searchInput: { flex: 1, color: '#fff', fontSize: 14 },
syncBanner: { flexDirection: 'row', alignItems: 'center', backgroundColor: 'rgba(124,58,237,0.12)', borderBottomWidth: 1, borderBottomColor: 'rgba(124,58,237,0.2)', paddingHorizontal: 16, paddingVertical: 10, gap: 8, }, syncText: { color: '#c4a8ff', fontSize: 13 },
grid: { paddingHorizontal: 2, paddingBottom: 20 }, row: { gap: 2, marginBottom: 2 }, photoItem: { flex: isWeb ? 1 : undefined, aspectRatio: 1, backgroundColor: '#1a1a2e', borderRadius: 4, overflow: 'hidden', }, photoImage: { width: '100%', height: '100%' }, favBadge: { position: 'absolute', top: 4, right: 4, backgroundColor: 'rgba(239,68,68,0.85)', borderRadius: 8, padding: 3, },
centered: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 32 }, loadingText: { color: '#8888aa', marginTop: 12, fontSize: 14 }, emptyEmoji: { fontSize: 64, marginBottom: 16 }, emptyTitle: { fontSize: 22, fontWeight: '700', color: '#fff', marginBottom: 8 }, emptyText: { fontSize: 14, color: '#8888aa', textAlign: 'center', lineHeight: 20, marginBottom: 24 }, emptyBtn: { backgroundColor: '#7c3aed', paddingHorizontal: 28, paddingVertical: 13, borderRadius: 14 }, emptyBtnText: { color: '#fff', fontWeight: '700', fontSize: 15 },
loaderFooter: { paddingVertical: 20, alignItems: 'center' },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258/** * KeyStone – Settings Screen */
import { View, Text, StyleSheet, TouchableOpacity, Switch, ScrollView, Alert, Platform,} from 'react-native';import { SafeAreaView } from 'react-native-safe-area-context';import { Ionicons } from '@expo/vector-icons';import { useAuthStore } from '../../store/authStore';import { useSyncStore } from '../../store/syncStore';import { runSync, pauseSync, resumeSync } from '../../services/syncEngine';import { healthCheck } from '../../services/api';import { useState, useEffect } from 'react';
function SettingRow({ icon, label, sublabel, children, onPress, dangerous,}: { icon: string; label: string; sublabel?: string; children?: React.ReactNode; onPress?: () => void; dangerous?: boolean;}) { return ( <TouchableOpacity style={styles.settingRow} onPress={onPress} disabled={!onPress} activeOpacity={onPress ? 0.7 : 1} > <View style={[styles.settingIcon, dangerous && styles.settingIconDanger]}> <Ionicons name={icon as any} size={18} color={dangerous ? '#ef4444' : '#7c3aed'} /> </View> <View style={styles.settingInfo}> <Text style={[styles.settingLabel, dangerous && { color: '#ef4444' }]}>{label}</Text> {sublabel ? <Text style={styles.settingSubLabel}>{sublabel}</Text> : null} </View> {children} {!children && onPress && ( <Ionicons name="chevron-forward" size={16} color="#555577" /> )} </TouchableOpacity> );}
function Section({ title, children }: { title: string; children: React.ReactNode }) { return ( <View style={styles.section}> <Text style={styles.sectionTitle}>{title}</Text> <View style={styles.sectionCard}>{children}</View> </View> );}
export default function SettingsScreen() { const { user, signOut } = useAuthStore(); const { settings, updateSettings, isRunning, isPaused, uploaded, skipped, failed, totalPhotos } = useSyncStore(); const [apiStatus, setApiStatus] = useState<'checking' | 'ok' | 'error'>('checking');
useEffect(() => { healthCheck() .then(() => setApiStatus('ok')) .catch(() => setApiStatus('error')); }, []);
const handleSignOut = () => { if (Platform.OS === 'web') { signOut(); } else { Alert.alert('Sign Out', 'Are you sure you want to sign out?', [ { text: 'Cancel', style: 'cancel' }, { text: 'Sign Out', style: 'destructive', onPress: signOut }, ]); } };
const handleSyncToggle = () => { if (isRunning) { pauseSync(); } else { runSync(); } };
return ( <SafeAreaView style={styles.safeArea} edges={['top']}> <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
{/* Header */} <View style={styles.header}> <Text style={styles.headerTitle}>Settings</Text> </View>
{/* Profile */} <View style={styles.profileCard}> <View style={styles.avatar}> <Text style={styles.avatarText}> {user?.email?.[0]?.toUpperCase() ?? '?'} </Text> </View> <View style={styles.profileInfo}> <Text style={styles.profileEmail}>{user?.email ?? 'Unknown'}</Text> <View style={styles.statusRow}> <View style={[styles.statusDot, apiStatus === 'ok' && styles.statusDotGreen, apiStatus === 'error' && styles.statusDotRed]} /> <Text style={styles.statusText}> API {apiStatus === 'checking' ? 'connecting…' : apiStatus === 'ok' ? 'connected' : 'unreachable'} </Text> </View> </View> </View>
{/* Sync Stats */} {(uploaded > 0 || skipped > 0 || failed > 0) && ( <View style={styles.statsRow}> <View style={styles.statItem}> <Text style={styles.statNum}>{uploaded}</Text> <Text style={styles.statLabel}>Uploaded</Text> </View> <View style={styles.statDivider} /> <View style={styles.statItem}> <Text style={styles.statNum}>{skipped}</Text> <Text style={styles.statLabel}>Skipped</Text> </View> <View style={styles.statDivider} /> <View style={styles.statItem}> <Text style={[styles.statNum, failed > 0 && { color: '#ef4444' }]}>{failed}</Text> <Text style={styles.statLabel}>Failed</Text> </View> </View> )}
{/* Sync */} <Section title="Sync"> <SettingRow icon="sync-outline" label="Auto Sync" sublabel="Automatically back up new photos"> <Switch value={settings.autoSync} onValueChange={(v) => updateSettings({ autoSync: v })} trackColor={{ false: '#2a2a4a', true: '#7c3aed' }} thumbColor="#fff" /> </SettingRow> <View style={styles.divider} /> <SettingRow icon="wifi-outline" label="Wi-Fi Only" sublabel="Don't sync on cellular data"> <Switch value={settings.wifiOnly} onValueChange={(v) => updateSettings({ wifiOnly: v })} trackColor={{ false: '#2a2a4a', true: '#7c3aed' }} thumbColor="#fff" /> </SettingRow> <View style={styles.divider} /> <SettingRow icon={isRunning ? 'pause-circle-outline' : 'play-circle-outline'} label={isRunning ? (isPaused ? 'Resume Sync' : 'Pause Sync') : 'Sync Now'} sublabel={isRunning ? `${uploaded}/${totalPhotos} photos` : 'Manually start a sync'} onPress={handleSyncToggle} /> </Section>
{/* Quality */} <Section title="Quality"> {(['low', 'medium', 'high'] as const).map((q, i, arr) => ( <View key={q}> <SettingRow icon="image-outline" label={q.charAt(0).toUpperCase() + q.slice(1)} sublabel={q === 'low' ? 'Faster uploads, less storage' : q === 'high' ? 'Best quality, more storage' : 'Balanced'} onPress={() => updateSettings({ thumbnailQuality: q })} > {settings.thumbnailQuality === q && ( <Ionicons name="checkmark-circle" size={20} color="#7c3aed" /> )} </SettingRow> {i < arr.length - 1 && <View style={styles.divider} />} </View> ))} </Section>
{/* About */} <Section title="About"> <SettingRow icon="information-circle-outline" label="Version" sublabel="1.0.0 – KeyStone Photo Cloud" /> <View style={styles.divider} /> <SettingRow icon="code-outline" label="API Endpoint" sublabel="dpv007-keystone.hf.space" /> </Section>
{/* Account */} <Section title="Account"> <SettingRow icon="log-out-outline" label="Sign Out" onPress={handleSignOut} dangerous /> </Section>
<View style={{ height: 40 }} /> </ScrollView> </SafeAreaView> );}
const styles = StyleSheet.create({ safeArea: { flex: 1, backgroundColor: '#0f0f23' }, container: { flex: 1, backgroundColor: '#0f0f23' }, header: { paddingHorizontal: 16, paddingVertical: 14 }, headerTitle: { fontSize: 24, fontWeight: '800', color: '#fff' },
profileCard: { flexDirection: 'row', alignItems: 'center', marginHorizontal: 16, marginBottom: 16, backgroundColor: 'rgba(124,58,237,0.1)', borderWidth: 1, borderColor: 'rgba(124,58,237,0.2)', borderRadius: 16, padding: 16, gap: 14, }, avatar: { width: 48, height: 48, borderRadius: 24, backgroundColor: '#7c3aed', alignItems: 'center', justifyContent: 'center' }, avatarText: { color: '#fff', fontWeight: '800', fontSize: 20 }, profileInfo: { flex: 1 }, profileEmail: { color: '#fff', fontWeight: '600', fontSize: 15 }, statusRow: { flexDirection: 'row', alignItems: 'center', gap: 6, marginTop: 4 }, statusDot: { width: 7, height: 7, borderRadius: 4, backgroundColor: '#555577' }, statusDotGreen: { backgroundColor: '#22c55e' }, statusDotRed: { backgroundColor: '#ef4444' }, statusText: { color: '#8888aa', fontSize: 12 },
statsRow: { flexDirection: 'row', marginHorizontal: 16, marginBottom: 16, backgroundColor: 'rgba(255,255,255,0.04)', borderRadius: 14, borderWidth: 1, borderColor: 'rgba(255,255,255,0.06)', padding: 14, }, statItem: { flex: 1, alignItems: 'center' }, statNum: { color: '#7c3aed', fontSize: 22, fontWeight: '800' }, statLabel: { color: '#8888aa', fontSize: 11, marginTop: 2 }, statDivider: { width: 1, backgroundColor: 'rgba(255,255,255,0.06)' },
section: { marginBottom: 16 }, sectionTitle: { color: '#555577', fontSize: 11, fontWeight: '700', letterSpacing: 1, textTransform: 'uppercase', marginHorizontal: 16, marginBottom: 8 }, sectionCard: { marginHorizontal: 16, backgroundColor: 'rgba(255,255,255,0.04)', borderRadius: 16, borderWidth: 1, borderColor: 'rgba(255,255,255,0.06)', overflow: 'hidden' }, settingRow: { flexDirection: 'row', alignItems: 'center', padding: 14, gap: 12 }, settingIcon: { width: 34, height: 34, borderRadius: 9, backgroundColor: 'rgba(124,58,237,0.15)', alignItems: 'center', justifyContent: 'center' }, settingIconDanger: { backgroundColor: 'rgba(239,68,68,0.12)' }, settingInfo: { flex: 1 }, settingLabel: { color: '#e0e0f0', fontWeight: '600', fontSize: 14 }, settingSubLabel: { color: '#555577', fontSize: 12, marginTop: 2 }, divider: { height: 1, backgroundColor: 'rgba(255,255,255,0.04)', marginLeft: 60 },});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960/** * KeyStone – Root Layout * Sets up QueryClient, auth initialization, and route guarding. */
import { useEffect } from 'react';import { Stack, useRouter, useSegments } from 'expo-router';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { StatusBar } from 'expo-status-bar';import { useAuthStore } from '../store/authStore';import { registerBackgroundSync } from '../services/backgroundSync';import { Platform } from 'react-native';
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 1000 * 60 * 2, // 2 minutes retry: 2, }, },});
function AuthGuard({ children }: { children: React.ReactNode }) { const { session, isInitialized, initialize } = useAuthStore(); const segments = useSegments(); const router = useRouter();
useEffect(() => { initialize(); }, []);
useEffect(() => { if (!isInitialized) return;
const inAuthGroup = segments[0] === '(auth)';
if (!session && !inAuthGroup) { router.replace('/(auth)/login'); } else if (session && inAuthGroup) { router.replace('/(tabs)/gallery'); // Register background sync on native if (Platform.OS !== 'web') { registerBackgroundSync(); } } }, [session, isInitialized, segments]);
return <>{children}</>;}
export default function RootLayout() { return ( <QueryClientProvider client={queryClient}> <AuthGuard> <StatusBar style="light" /> <Stack screenOptions={{ headerShown: false }} /> </AuthGuard> </QueryClientProvider> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849/** * KeyStone – Albums React Query Hooks */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';import { listAlbums, createAlbum, getAlbum, addPhotosToAlbum, Album } from '../services/api';
export const albumKeys = { all: ['albums'] as const, lists: () => [...albumKeys.all, 'list'] as const, detail: (id: string) => [...albumKeys.all, id] as const,};
export function useAlbums() { return useQuery({ queryKey: albumKeys.lists(), queryFn: listAlbums, staleTime: 1000 * 60 * 2, });}
export function useAlbum(id: string) { return useQuery({ queryKey: albumKeys.detail(id), queryFn: () => getAlbum(id), enabled: !!id, });}
export function useCreateAlbum() { const qc = useQueryClient(); return useMutation({ mutationFn: (data: { name: string; description?: string }) => createAlbum(data), onSuccess: () => { qc.invalidateQueries({ queryKey: albumKeys.lists() }); }, });}
export function useAddPhotosToAlbum() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ albumId, photoIds }: { albumId: string; photoIds: string[] }) => addPhotosToAlbum(albumId, photoIds), onSuccess: (_, { albumId }) => { qc.invalidateQueries({ queryKey: albumKeys.detail(albumId) }); }, });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970/** * KeyStone – Photos React Query Hooks */
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { listPhotos, getPhoto, deletePhoto, updatePhoto, searchPhotos, Photo } from '../services/api';
// ── Keys ───────────────────────────────────────────────────────────────────────export const photoKeys = { all: ['photos'] as const, lists: () => [...photoKeys.all, 'list'] as const, list: (filters?: object) => [...photoKeys.lists(), filters] as const, detail: (id: string) => [...photoKeys.all, id] as const, search: (q: string) => [...photoKeys.all, 'search', q] as const,};
// ── Infinite Gallery ───────────────────────────────────────────────────────────export function useInfinitePhotos(favoritesOnly = false) { return useInfiniteQuery({ queryKey: photoKeys.list({ favoritesOnly }), queryFn: ({ pageParam }) => listPhotos({ limit: 60, cursor: pageParam as string | undefined, favorites_only: favoritesOnly }), initialPageParam: undefined as string | undefined, getNextPageParam: (lastPage) => lastPage.has_more ? lastPage.next_cursor ?? undefined : undefined, staleTime: 1000 * 60, });}
// ── Single Photo ───────────────────────────────────────────────────────────────export function usePhoto(id: string) { return useQuery({ queryKey: photoKeys.detail(id), queryFn: () => getPhoto(id), enabled: !!id, });}
// ── Search ─────────────────────────────────────────────────────────────────────export function useSearchPhotos(q: string) { return useQuery({ queryKey: photoKeys.search(q), queryFn: () => searchPhotos(q), enabled: q.length > 0, staleTime: 1000 * 30, });}
// ── Delete Photo ───────────────────────────────────────────────────────────────export function useDeletePhoto() { const qc = useQueryClient(); return useMutation({ mutationFn: (id: string) => deletePhoto(id), onSuccess: () => { qc.invalidateQueries({ queryKey: photoKeys.lists() }); }, });}
// ── Toggle Favorite ────────────────────────────────────────────────────────────export function useToggleFavorite() { const qc = useQueryClient(); return useMutation({ mutationFn: ({ id, is_favorite }: { id: string; is_favorite: boolean }) => updatePhoto(id, { is_favorite }), onSuccess: () => { qc.invalidateQueries({ queryKey: photoKeys.lists() }); }, });}1234567891011121314151617181920212223242526/** * KeyStone – Sync Hook */
import { useMutation } from '@tanstack/react-query';import { runSync, pauseSync, resumeSync } from '../services/syncEngine';import { useSyncStore } from '../store/syncStore';
export function useSync() { const { isRunning, isPaused, uploaded, skipped, failed, totalPhotos } = useSyncStore();
const startMutation = useMutation({ mutationFn: runSync });
return { isRunning, isPaused, uploaded, skipped, failed, totalPhotos, startSync: startMutation.mutate, pauseSync, resumeSync, isStarting: startMutation.isPending, };}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "name": "keystone", "version": "1.0.0", "main": "expo-router/entry", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", "lint": "expo lint" }, "dependencies": { "@expo/vector-icons": "^14.0.2", "@react-native-async-storage/async-storage": "^1.23.1", "@supabase/supabase-js": "^2.47.10", "@tanstack/react-query": "^5.62.3", "expo": "~52.0.20", "expo-asset": "~10.0.0", "expo-background-fetch": "~12.0.1", "expo-battery": "^57.0.1", "expo-blur": "~14.0.1", "expo-constants": "~17.0.3", "expo-crypto": "~14.0.1", "expo-file-system": "~18.0.6", "expo-image": "~2.0.3", "expo-linear-gradient": "~14.0.1", "expo-media-library": "~16.0.5", "expo-network": "~7.0.1", "expo-router": "~4.0.14", "expo-splash-screen": "~0.29.18", "expo-status-bar": "~2.0.0", "expo-task-manager": "~12.0.3", "react": "18.3.1", "react-native": "0.76.5", "react-native-gesture-handler": "~2.20.2", "react-native-reanimated": "~3.16.1", "react-native-safe-area-context": "4.12.0", "react-native-screens": "~4.4.0", "react-native-web": "~0.19.13", "zustand": "^5.0.2" }, "devDependencies": { "@babel/core": "^7.25.2", "@types/react": "~18.3.12", "typescript": "^5.3.3" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164/** * KeyStone – API Client * Thin wrapper around fetch that attaches the Supabase JWT automatically. */
import { supabase, API_URL } from './supabase';
class ApiError extends Error { constructor(public status: number, message: string) { super(message); this.name = 'ApiError'; }}
async function getAuthHeader(): Promise<Record<string, string>> { const { data: { session } } = await supabase.auth.getSession(); if (!session?.access_token) { throw new ApiError(401, 'Not authenticated'); } return { Authorization: `Bearer ${session.access_token}` };}
async function request<T>( path: string, options: RequestInit = {},): Promise<T> { const authHeader = await getAuthHeader(); const url = `${API_URL}${path}`;
const response = await fetch(url, { ...options, headers: { 'Content-Type': 'application/json', ...authHeader, ...options.headers, }, });
if (!response.ok) { const body = await response.json().catch(() => ({})); throw new ApiError(response.status, body.detail || `HTTP ${response.status}`); }
if (response.status === 204) return undefined as T; return response.json();}
// ── Auth ──────────────────────────────────────────────────────────────────────export const verifyToken = () => request('/auth/verify', { method: 'POST' });
// ── Sync ──────────────────────────────────────────────────────────────────────export const syncStart = (data: { device_name: string; platform: string; device_token?: string }) => request('/sync/start', { method: 'POST', body: JSON.stringify(data) });
export const syncCheck = (hashes: string[]) => request<{ missing_hashes: string[]; existing_count: number; missing_count: number }>( '/sync/check', { method: 'POST', body: JSON.stringify({ hashes }) }, );
// ── Photos ────────────────────────────────────────────────────────────────────export const listPhotos = (params?: { limit?: number; cursor?: string; favorites_only?: boolean }) => { const qs = new URLSearchParams(); if (params?.limit) qs.set('limit', String(params.limit)); if (params?.cursor) qs.set('cursor', params.cursor); if (params?.favorites_only) qs.set('favorites_only', 'true'); return request<{ items: Photo[]; total: number; next_cursor: string | null; has_more: boolean }>( `/photos?${qs.toString()}`, );};
export const getPhoto = (id: string) => request<Photo>(`/photos/${id}`);
export const deletePhoto = (id: string) => request(`/photos/${id}`, { method: 'DELETE' });
export const updatePhoto = (id: string, data: Partial<Photo>) => request<Photo>(`/photos/${id}`, { method: 'PATCH', body: JSON.stringify(data) });
// ── Upload ────────────────────────────────────────────────────────────────────export const uploadPhoto = async ( fileUri: string, filename: string, mimeType: string, sha256: string, takenAt?: string,) => { const authHeader = await getAuthHeader(); const formData = new FormData(); formData.append('file', { uri: fileUri, name: filename, type: mimeType } as any); formData.append('sha256', sha256); if (takenAt) formData.append('taken_at', takenAt);
const response = await fetch(`${API_URL}/upload`, { method: 'POST', headers: authHeader, body: formData, });
if (!response.ok) { const body = await response.json().catch(() => ({})); throw new ApiError(response.status, body.detail || 'Upload failed'); } return response.json();};
// ── Albums ────────────────────────────────────────────────────────────────────export const listAlbums = () => request<Album[]>('/albums');
export const createAlbum = (data: { name: string; description?: string }) => request<Album>('/albums', { method: 'POST', body: JSON.stringify(data) });
export const getAlbum = (id: string) => request<Album>(`/albums/${id}`);
export const addPhotosToAlbum = (albumId: string, photoIds: string[]) => request(`/albums/${albumId}/photos`, { method: 'POST', body: JSON.stringify({ photo_ids: photoIds }), });
// ── Search ────────────────────────────────────────────────────────────────────export const searchPhotos = (q: string, limit = 50) => request<{ items: Photo[]; total: number; has_more: boolean }>( `/search?q=${encodeURIComponent(q)}&limit=${limit}`, );
// ── Health ────────────────────────────────────────────────────────────────────export const healthCheck = () => fetch(`${API_URL}/health`).then(r => r.json());
// ── Types ─────────────────────────────────────────────────────────────────────export interface Photo { id: string; user_id: string; sha256: string; filename: string; mime_type: string; bucket_path: string; thumbnail_path: string | null; preview_path: string | null; width: number | null; height: number | null; size: number; taken_at: string | null; created_at: string; uploaded_at: string; deleted: boolean; is_favorite: boolean; ai_description: string | null; ai_tags: string | null;}
export interface Album { id: string; user_id: string; name: string; description: string | null; cover_photo_id: string | null; created_at: string; updated_at: string; photo_count: number;}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273/** * KeyStone – Background Sync * Registers an Expo Background Fetch task that runs the sync engine * periodically even when the app is in the background. */
import * as BackgroundFetch from 'expo-background-fetch';import * as TaskManager from 'expo-task-manager';import * as Battery from 'expo-battery';
import { runSync } from './syncEngine';import { useSyncStore } from '../store/syncStore';
export const BACKGROUND_SYNC_TASK = 'KEYSTONE_BACKGROUND_SYNC';
// ── Task Definition ───────────────────────────────────────────────────────────TaskManager.defineTask(BACKGROUND_SYNC_TASK, async () => { console.log('[BackgroundSync] Task fired'); const { settings } = useSyncStore.getState();
if (!settings.autoSync) { return BackgroundFetch.BackgroundFetchResult.NoData; }
try { // Skip if battery is critically low (< 15%) try { const batteryLevel = await Battery.getBatteryLevelAsync(); const batteryState = await Battery.getBatteryStateAsync(); const isCharging = batteryState === Battery.BatteryState.CHARGING || batteryState === Battery.BatteryState.FULL;
if (batteryLevel < 0.15 && !isCharging) { console.log('[BackgroundSync] Battery too low – skipping'); return BackgroundFetch.BackgroundFetchResult.NoData; } } catch { // expo-battery may not be available on all platforms }
await runSync(); return BackgroundFetch.BackgroundFetchResult.NewData; } catch (err) { console.error('[BackgroundSync] Error:', err); return BackgroundFetch.BackgroundFetchResult.Failed; }});
// ── Registration ──────────────────────────────────────────────────────────────export async function registerBackgroundSync(): Promise<void> { const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_SYNC_TASK); if (isRegistered) return;
try { await BackgroundFetch.registerTaskAsync(BACKGROUND_SYNC_TASK, { minimumInterval: 15 * 60, // 15 minutes minimum (iOS may enforce longer) stopOnTerminate: false, startOnBoot: true, }); console.log('[BackgroundSync] Registered successfully'); } catch (err) { console.warn('[BackgroundSync] Registration failed:', err); }}
export async function unregisterBackgroundSync(): Promise<void> { try { await BackgroundFetch.unregisterTaskAsync(BACKGROUND_SYNC_TASK); console.log('[BackgroundSync] Unregistered'); } catch { // Task may not be registered }}1234567891011121314151617181920212223242526272829303132333435363738/** * KeyStone – Hash Utility * Computes SHA256 of a local file using expo-crypto. */
import * as Crypto from 'expo-crypto';import * as FileSystem from 'expo-file-system';
/** * Compute the SHA256 hash of a file at the given URI. * Reads the file as base64, then hashes it. */export async function computeFileSHA256(uri: string): Promise<string> { // Read file as base64 const base64 = await FileSystem.readAsStringAsync(uri, { encoding: FileSystem.EncodingType.Base64, });
// Convert base64 to binary string and hash const digest = await Crypto.digestStringAsync( Crypto.CryptoDigestAlgorithm.SHA256, base64, { encoding: Crypto.CryptoEncoding.HEX }, );
return digest;}
/** * Compute SHA256 from a base64-encoded string directly. */export async function computeBase64SHA256(base64: string): Promise<string> { return Crypto.digestStringAsync( Crypto.CryptoDigestAlgorithm.SHA256, base64, { encoding: Crypto.CryptoEncoding.HEX }, );}12345678910111213141516import { createClient } from '@supabase/supabase-js';import AsyncStorage from '@react-native-async-storage/async-storage';
const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL!;const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!;
export const supabase = createClient(supabaseUrl, supabaseAnonKey, { auth: { storage: AsyncStorage, autoRefreshToken: true, persistSession: true, detectSessionInUrl: false, },});
export const API_URL = process.env.EXPO_PUBLIC_API_URL || 'https://dpv007-keystone.hf.space';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157/** * KeyStone – Sync Engine * Core upload loop: * 1. Request media library permission * 2. Fetch all photos from camera roll * 3. Compute SHA256 for each * 4. POST /sync/check to get only missing hashes * 5. Upload missing photos one by one */
import * as MediaLibrary from 'expo-media-library';import * as Network from 'expo-network';import { Platform } from 'react-native';
import { syncStart, syncCheck, uploadPhoto } from './api';import { computeFileSHA256 } from './hashUtil';import { useSyncStore } from '../store/syncStore';import { useAuthStore } from '../store/authStore';
const BATCH_SIZE = 50; // hashes sent per /sync/check call
/** * Request media library permissions. * Returns true if granted. */export async function requestMediaPermission(): Promise<boolean> { const { status } = await MediaLibrary.requestPermissionsAsync(); return status === 'granted';}
/** * Main sync function. Call this to start a full sync session. */export async function runSync(): Promise<void> { const syncStore = useSyncStore.getState(); const { settings } = syncStore;
// Guard: already running if (syncStore.isRunning) return;
// Guard: Wi-Fi only check if (settings.wifiOnly) { const netState = await Network.getNetworkStateAsync(); if (netState.type !== Network.NetworkStateType.WIFI) { console.log('[Sync] Wi-Fi only mode – skipping sync (not on Wi-Fi)'); return; } }
// Guard: permissions const hasPermission = await requestMediaPermission(); if (!hasPermission) { console.warn('[Sync] Media library permission not granted'); return; }
syncStore.setRunning(true); syncStore.resetStats();
try { // 1. Register device const deviceName = `${Platform.OS}-device`; const platform = Platform.OS; // android | ios | web const { device_id } = await syncStart({ device_name: deviceName, platform }); syncStore.setDeviceId(device_id);
// 2. Fetch all media assets let after: string | undefined; let hasNextPage = true; const allAssets: MediaLibrary.Asset[] = [];
while (hasNextPage) { const page = await MediaLibrary.getAssetsAsync({ mediaType: [MediaLibrary.MediaType.photo], first: 100, after, sortBy: MediaLibrary.SortBy.creationTime, }); allAssets.push(...page.assets); hasNextPage = page.hasNextPage; after = page.endCursor; }
syncStore.setTotalPhotos(allAssets.length); console.log(`[Sync] Found ${allAssets.length} photos in camera roll`);
// 3. Process in batches for hash check for (let i = 0; i < allAssets.length; i += BATCH_SIZE) { if (syncStore.isPaused) { console.log('[Sync] Paused – waiting...'); await new Promise(resolve => setTimeout(resolve, 2000)); i -= BATCH_SIZE; // retry this batch continue; }
const batch = allAssets.slice(i, i + BATCH_SIZE);
// Compute SHA256 for each asset in batch const hashMap: Record<string, MediaLibrary.Asset> = {}; for (const asset of batch) { try { const info = await MediaLibrary.getAssetInfoAsync(asset); const uri = info.localUri || asset.uri; const hash = await computeFileSHA256(uri); hashMap[hash] = asset; } catch (err) { console.warn('[Sync] Failed to hash asset:', asset.filename, err); } }
const batchHashes = Object.keys(hashMap); if (batchHashes.length === 0) continue;
// 4. Check which are missing on server const { missing_hashes, existing_count } = await syncCheck(batchHashes); syncStore.incrementSkipped(); // approximate
console.log(`[Sync] Batch: ${existing_count} existing, ${missing_hashes.length} to upload`);
// 5. Upload missing for (const hash of missing_hashes) { if (syncStore.isPaused) break;
const asset = hashMap[hash]; if (!asset) continue;
try { const info = await MediaLibrary.getAssetInfoAsync(asset); const uri = info.localUri || asset.uri; const mimeType = asset.mediaType === 'photo' ? 'image/jpeg' : 'image/jpeg'; const takenAt = new Date(asset.creationTime).toISOString();
await uploadPhoto(uri, asset.filename, mimeType, hash, takenAt); syncStore.incrementUploaded(); console.log(`[Sync] Uploaded: ${asset.filename}`); } catch (err: any) { syncStore.incrementFailed(); console.error(`[Sync] Upload failed for ${asset.filename}:`, err.message); } } }
console.log('[Sync] Complete ✓'); } catch (err) { console.error('[Sync] Fatal error:', err); } finally { syncStore.setRunning(false); }}
export function pauseSync() { useSyncStore.getState().setPaused(true);}
export function resumeSync() { useSyncStore.getState().setPaused(false);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384/** * KeyStone – Auth Store (Zustand) * Manages Supabase session, user profile, and auth state machine. */
import { create } from 'zustand';import { Session, User } from '@supabase/supabase-js';import { supabase } from '../services/supabase';
interface AuthState { session: Session | null; user: User | null; isLoading: boolean; isInitialized: boolean;
// Actions initialize: () => Promise<void>; signIn: (email: string, password: string) => Promise<void>; signUp: (email: string, password: string) => Promise<void>; signOut: () => Promise<void>; resetPassword: (email: string) => Promise<void>;}
export const useAuthStore = create<AuthState>((set) => ({ session: null, user: null, isLoading: false, isInitialized: false,
initialize: async () => { // Restore session from AsyncStorage const { data: { session } } = await supabase.auth.getSession(); set({ session, user: session?.user ?? null, isInitialized: true });
// Listen for auth state changes supabase.auth.onAuthStateChange((_event, session) => { set({ session, user: session?.user ?? null }); }); },
signIn: async (email, password) => { set({ isLoading: true }); try { const { data, error } = await supabase.auth.signInWithPassword({ email, password }); if (error) throw error; set({ session: data.session, user: data.user }); } finally { set({ isLoading: false }); } },
signUp: async (email, password) => { set({ isLoading: true }); try { const { data, error } = await supabase.auth.signUp({ email, password }); if (error) throw error; set({ session: data.session, user: data.user ?? null }); } finally { set({ isLoading: false }); } },
signOut: async () => { set({ isLoading: true }); try { await supabase.auth.signOut(); set({ session: null, user: null }); } finally { set({ isLoading: false }); } },
resetPassword: async (email) => { set({ isLoading: true }); try { const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo: 'keystone://reset-password', }); if (error) throw error; } finally { set({ isLoading: false }); } },}));1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192/** * KeyStone – Sync Store (Zustand) * Tracks upload queue, progress, and sync settings. */
import { create } from 'zustand';
export type UploadItem = { id: string; // local asset ID uri: string; filename: string; sha256: string; status: 'pending' | 'uploading' | 'done' | 'failed' | 'duplicate'; progress: number; // 0-100 error?: string;};
interface SyncSettings { autoSync: boolean; wifiOnly: boolean; thumbnailQuality: 'low' | 'medium' | 'high';}
interface SyncState { // Queue queue: UploadItem[]; isRunning: boolean; isPaused: boolean; deviceId: string | null;
// Stats uploaded: number; skipped: number; failed: number; totalPhotos: number;
// Settings settings: SyncSettings;
// Actions setQueue: (items: UploadItem[]) => void; updateItem: (id: string, updates: Partial<UploadItem>) => void; setRunning: (running: boolean) => void; setPaused: (paused: boolean) => void; setDeviceId: (id: string) => void; incrementUploaded: () => void; incrementSkipped: () => void; incrementFailed: () => void; setTotalPhotos: (count: number) => void; updateSettings: (settings: Partial<SyncSettings>) => void; resetStats: () => void;}
export const useSyncStore = create<SyncState>((set) => ({ queue: [], isRunning: false, isPaused: false, deviceId: null, uploaded: 0, skipped: 0, failed: 0, totalPhotos: 0,
settings: { autoSync: true, wifiOnly: true, thumbnailQuality: 'medium', },
setQueue: (items) => set({ queue: items }),
updateItem: (id, updates) => set((state) => ({ queue: state.queue.map((item) => item.id === id ? { ...item, ...updates } : item, ), })),
setRunning: (running) => set({ isRunning: running }), setPaused: (paused) => set({ isPaused: paused }), setDeviceId: (id) => set({ deviceId: id }),
incrementUploaded: () => set((s) => ({ uploaded: s.uploaded + 1 })), incrementSkipped: () => set((s) => ({ skipped: s.skipped + 1 })), incrementFailed: () => set((s) => ({ failed: s.failed + 1 })), setTotalPhotos: (count) => set({ totalPhotos: count }),
updateSettings: (settings) => set((state) => ({ settings: { ...state.settings, ...settings } })),
resetStats: () => set({ uploaded: 0, skipped: 0, failed: 0, totalPhotos: 0 }),}));123456789{ "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, "paths": { "@/*": ["./*"] } }}mobile/.env.exampleDeleted-10
mobile/app.jsonDeleted-60
mobile/app/(auth)/_layout.tsxDeleted-12
mobile/app/(auth)/forgot-password.tsxDeleted-94
mobile/app/(auth)/login.tsxDeleted-207
mobile/app/(auth)/register.tsxDeleted-176
mobile/app/(tabs)/_layout.tsxDeleted-60
mobile/app/(tabs)/albums.tsxDeleted-182
mobile/app/(tabs)/gallery.tsxDeleted-270
mobile/app/(tabs)/settings.tsxDeleted-258
mobile/app/_layout.tsxDeleted-60
mobile/hooks/useAlbums.tsDeleted-49
mobile/hooks/usePhotos.tsDeleted-70
mobile/hooks/useSync.tsDeleted-26
mobile/package.jsonDeleted-47
mobile/services/api.tsDeleted-164
mobile/services/backgroundSync.tsDeleted-73
mobile/services/hashUtil.tsDeleted-38
mobile/services/supabase.tsDeleted-16
mobile/services/syncEngine.tsDeleted-157
mobile/store/authStore.tsDeleted-84
mobile/store/syncStore.tsDeleted-92
mobile/tsconfig.jsonDeleted-9