Add Map screen with location permissions handling and integrate current location feature

This commit is contained in:
2025-12-24 23:49:57 +05:30
parent 48c266c252
commit 741ab60fce
4 changed files with 365 additions and 271 deletions

427
App.tsx
View File

@@ -1,14 +1,14 @@
import {
StatusBar,
useColorScheme,
View,
StyleSheet,
Text,
TouchableOpacity,
Alert,
NativeModules,
Image,
ScrollView,
StatusBar,
useColorScheme,
View,
StyleSheet,
Text,
TouchableOpacity,
Alert,
NativeModules,
Image,
ScrollView,
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { useState, useEffect } from 'react';
@@ -18,241 +18,258 @@ import Register from './src/components/Register';
import { authAPI } from './src/services/authAPI';
import { networkService } from './src/services/networkService';
import { ScannerScreen } from './src/screens/ScannerScreen';
import Map from './src/screens/Map';
type Screen = 'login' | 'register' | 'home' | 'scanner';
type Screen = 'login' | 'register' | 'home' | 'scanner' | 'map';
const { MyNativeModule } = NativeModules;
function App() {
const isDarkMode = useColorScheme() === 'dark';
const isDarkMode = useColorScheme() === 'dark';
const [currentScreen, setCurrentScreen] = useState<Screen>('login');
const [isInitialized, setIsInitialized] = useState(false);
const [isOnline, setIsOnline] = useState(true);
const [currentUser, setCurrentUser] = useState<any>(null);
const [qrCode, setQrCode] = useState<string | null>(null);
const [isGeneratingQR, setIsGeneratingQR] = useState(false);
const [scannedCodes, setScannedCodes] = useState<any[]>([]);
const [currentScreen, setCurrentScreen] = useState<Screen>('login');
const [isInitialized, setIsInitialized] = useState(false);
const [isOnline, setIsOnline] = useState(true);
const [currentUser, setCurrentUser] = useState<any>(null);
const [qrCode, setQrCode] = useState<string | null>(null);
const [isGeneratingQR, setIsGeneratingQR] = useState(false);
const [scannedCodes, setScannedCodes] = useState<any[]>([]);
/* -------------------- INIT -------------------- */
useEffect(() => {
initializeApp();
/* -------------------- INIT -------------------- */
useEffect(() => {
initializeApp();
console.log('MyNativeModule:', MyNativeModule);
MyNativeModule?.greet?.('John').then((msg: any) => {
console.log(msg);
});
console.log('MyNativeModule:', MyNativeModule);
MyNativeModule?.greet?.('John').then((msg: any) => {
console.log(msg);
});
const unsubscribe = networkService.addListener(networkState => {
setIsOnline(networkState.isConnected);
});
const unsubscribe = networkService.addListener(networkState => {
setIsOnline(networkState.isConnected);
});
return unsubscribe;
}, []);
return unsubscribe;
}, []);
const initializeApp = async () => {
try {
await authAPI.initialize();
const initializeApp = async () => {
try {
await authAPI.initialize();
const isLoggedIn = await authAPI.isLoggedIn();
if (isLoggedIn) {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setCurrentScreen('home');
}
} catch (error) {
console.error('Initialization error:', error);
} finally {
setIsInitialized(true);
}
};
const isLoggedIn = await authAPI.isLoggedIn();
if (isLoggedIn) {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setCurrentScreen('home');
}
} catch (error) {
console.error('Initialization error:', error);
} finally {
setIsInitialized(true);
}
};
/* -------------------- NAVIGATION -------------------- */
const navigateToLogin = () => {
setCurrentUser(null);
setQrCode(null);
setCurrentScreen('login');
};
/* -------------------- NAVIGATION -------------------- */
const navigateToLogin = () => {
setCurrentUser(null);
setQrCode(null);
setCurrentScreen('login');
};
const navigateToRegister = () => {
setCurrentScreen('register');
};
const navigateToRegister = () => {
setCurrentScreen('register');
};
const navigateToHome = async () => {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setQrCode(null);
setCurrentScreen('home');
};
const navigateToHome = async () => {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setQrCode(null);
setCurrentScreen('home');
};
const openScanner = () => {
setCurrentScreen('scanner');
};
const openScanner = () => {
setCurrentScreen('scanner');
};
/* -------------------- ACTIONS -------------------- */
const handleLogout = async () => {
try {
await authAPI.logout();
setQrCode(null);
navigateToLogin();
Alert.alert('Success', 'Logged out successfully');
} catch {
Alert.alert('Error', 'Failed to logout');
}
};
const openMap = () => {
setCurrentScreen('map');
};
const showAppStatus = async () => {
try {
const status = await authAPI.getAppStatus();
Alert.alert(
'App Status',
`Network: ${status.network.isOnline ? 'Online' : 'Offline'}
/* -------------------- ACTIONS -------------------- */
const handleLogout = async () => {
try {
await authAPI.logout();
setQrCode(null);
navigateToLogin();
Alert.alert('Success', 'Logged out successfully');
} catch {
Alert.alert('Error', 'Failed to logout');
}
};
const showAppStatus = async () => {
try {
const status = await authAPI.getAppStatus();
Alert.alert(
'App Status',
`Network: ${status.network.isOnline ? 'Online' : 'Offline'}
Users: ${status.storage.totalUsers}
Current User: ${status.authentication.currentUser || 'None'}
Logged In: ${status.authentication.isLoggedIn ? 'Yes' : 'No'}`
);
} catch {
Alert.alert('Error', 'Failed to get app status');
}
};
);
} catch {
Alert.alert('Error', 'Failed to get app status');
}
};
const generateQRCode = async () => {
if (!currentUser?.email) {
Alert.alert('Error', 'No user email available');
return;
}
const generateQRCode = async () => {
if (!currentUser?.email) {
Alert.alert('Error', 'No user email available');
return;
}
setIsGeneratingQR(true);
try {
const qrData = `User: ${currentUser.fullName}\nEmail: ${currentUser.email}`;
const base64Image = await MyNativeModule.generateQRCode(qrData, 300, 300);
setQrCode(base64Image);
} catch (error) {
console.error(error);
Alert.alert('Error', 'Failed to generate QR code');
} finally {
setIsGeneratingQR(false);
}
};
setIsGeneratingQR(true);
try {
const qrData = `User: ${currentUser.fullName}\nEmail: ${currentUser.email}`;
const base64Image = await MyNativeModule.generateQRCode(qrData, 300, 300);
setQrCode(base64Image);
} catch (error) {
console.error(error);
Alert.alert('Error', 'Failed to generate QR code');
} finally {
setIsGeneratingQR(false);
}
};
const handleScanResult = (result: any) => {
setScannedCodes(prev => [
{
code: result.code,
format: result.format,
timestamp: new Date().toLocaleTimeString(),
},
...prev,
]);
const handleScanResult = (result: any) => {
setScannedCodes(prev => [
{
code: result.code,
format: result.format,
timestamp: new Date().toLocaleTimeString(),
},
...prev,
]);
Alert.alert(
'Scanned Successfully',
`Code: ${result.code}\nFormat: ${result.format}`,
[{ text: 'OK', onPress: () => setCurrentScreen('home') }]
);
};
Alert.alert(
'Scanned Successfully',
`Code: ${result.code}\nFormat: ${result.format}`,
[{ text: 'OK', onPress: () => setCurrentScreen('home') }]
);
};
/* -------------------- RENDER -------------------- */
const renderScreen = () => {
switch (currentScreen) {
case 'login':
return (
<Login
onNavigateToRegister= { navigateToRegister }
onLoginSuccess = { navigateToHome }
/>
);
/* -------------------- RENDER -------------------- */
const renderScreen = () => {
switch (currentScreen) {
case 'login':
return (
<Login
onNavigateToRegister={navigateToRegister}
onLoginSuccess={navigateToHome}
/>
);
case 'register':
return (
<Register
onNavigateToLogin= { navigateToLogin }
onRegisterSuccess = { navigateToHome }
/>
);
case 'register':
return (
<Register
onNavigateToLogin={navigateToLogin}
onRegisterSuccess={navigateToHome}
/>
);
case 'scanner':
return (
<ScannerScreen
presignedUrl= "https://your-backend-presigned-url.com"
onScan = { handleScanResult }
/>
);
case 'scanner':
return (
<ScannerScreen
presignedUrl="https://your-backend-presigned-url.com"
onScan={handleScanResult}
/>
);
case 'home':
return (
<ScrollView style= { styles.homeContainer } contentContainerStyle = { styles.scrollContent } >
<Text style={ styles.welcomeText }>
Welcome, { currentUser?.fullName || 'User'
}
</Text>
case 'home':
return (
<ScrollView style={styles.homeContainer} contentContainerStyle={styles.scrollContent} >
<Text style={styles.welcomeText}>
Welcome, {currentUser?.fullName || 'User'
}
</Text>
{
qrCode && (
<Image source={ { uri: qrCode } } style = { styles.qrImage } />
)
}
{
qrCode && (
<Image source={{ uri: qrCode }} style={styles.qrImage} />
)
}
<TouchableOpacity style={ styles.scannerButton } onPress = { openScanner } >
<Text style={ styles.buttonText }> Scan QR / Barcode </Text>
</TouchableOpacity>
<TouchableOpacity style={styles.scannerButton} onPress={openScanner} >
<Text style={styles.buttonText}> Scan QR / Barcode </Text>
</TouchableOpacity>
< TouchableOpacity
style = { styles.qrButton }
onPress = { generateQRCode }
disabled = { isGeneratingQR }
>
<Text style={ styles.buttonText }>
{ isGeneratingQR? 'Generating...': 'Generate QR Code' }
</Text>
</TouchableOpacity>
< TouchableOpacity
style={styles.qrButton}
onPress={generateQRCode}
disabled={isGeneratingQR}
>
<Text style={styles.buttonText}>
{isGeneratingQR ? 'Generating...' : 'Generate QR Code'}
</Text>
</TouchableOpacity>
< TouchableOpacity style = { styles.statusButton } onPress = { showAppStatus } >
<Text style={ styles.buttonText }> App Status </Text>
</TouchableOpacity>
< TouchableOpacity style={styles.statusButton} onPress={showAppStatus} >
<Text style={styles.buttonText}> App Status </Text>
</TouchableOpacity>
< TouchableOpacity style = { styles.logoutButton } onPress = { handleLogout } >
<Text style={ styles.buttonText }> Logout </Text>
</TouchableOpacity>
</ScrollView>
);
< TouchableOpacity style={styles.mapButton} onPress={openMap} >
<Text style={styles.buttonText}> Open Map </Text>
</TouchableOpacity>
default:
return null;
}
};
< TouchableOpacity style={styles.logoutButton} onPress={handleLogout} >
<Text style={styles.buttonText}> Logout </Text>
</TouchableOpacity>
</ScrollView>
);
/* -------------------- LOADING -------------------- */
if (!isInitialized) {
return (
<SafeAreaProvider>
<View style= { styles.loadingContainer } >
<Text style={ styles.loadingText }> Initializing...</Text>
</View>
</SafeAreaProvider>
);
}
case 'map':
return (
<View style={{ flex: 1 }}>
<Map onClose={() => setCurrentScreen('home')} />
</View>
);
return (
<SafeAreaProvider>
<StatusBar barStyle= { isDarkMode? 'light-content': 'dark-content' } />
{ renderScreen() }
</SafeAreaProvider>
);
default:
return null;
}
};
/* -------------------- LOADING -------------------- */
if (!isInitialized) {
return (
<SafeAreaProvider>
<View style={styles.loadingContainer} >
<Text style={styles.loadingText}> Initializing...</Text>
</View>
</SafeAreaProvider>
);
}
return (
<SafeAreaProvider>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
{renderScreen()}
</SafeAreaProvider>
);
}
const styles = StyleSheet.create({
loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
loadingText: { fontSize: 18, fontWeight: '600' },
homeContainer: { flex: 1 },
scrollContent: { alignItems: 'center', padding: 20 },
welcomeText: { fontSize: 24, fontWeight: '700', marginBottom: 20 },
qrImage: { width: 300, height: 300, marginBottom: 20 },
scannerButton: { backgroundColor: '#9333ea', padding: 14, borderRadius: 20, marginBottom: 10 },
qrButton: { backgroundColor: '#10b981', padding: 14, borderRadius: 20, marginBottom: 10 },
statusButton: { backgroundColor: '#3bb6d8', padding: 14, borderRadius: 20, marginBottom: 10 },
logoutButton: { backgroundColor: '#ff6b6b', padding: 14, borderRadius: 20 },
buttonText: { color: '#fff', fontWeight: '600' },
loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
loadingText: { fontSize: 18, fontWeight: '600' },
homeContainer: { flex: 1 },
scrollContent: { alignItems: 'center', padding: 20 },
welcomeText: { fontSize: 24, fontWeight: '700', marginBottom: 20 },
qrImage: { width: 300, height: 300, marginBottom: 20 },
scannerButton: { backgroundColor: '#9333ea', padding: 14, borderRadius: 20, marginBottom: 10 },
qrButton: { backgroundColor: '#10b981', padding: 14, borderRadius: 20, marginBottom: 10 },
statusButton: { backgroundColor: '#3bb6d8', padding: 14, borderRadius: 20, marginBottom: 10 },
mapButton: { backgroundColor: '#2563eb', padding: 14, borderRadius: 20, marginBottom: 10 },
logoutButton: { backgroundColor: '#ff6b6b', padding: 14, borderRadius: 20 },
buttonText: { color: '#fff', fontWeight: '600' },
});
export default App;