Compare commits

...

2 Commits

Author SHA1 Message Date
48c266c252 Remove CameraPreviewManager and CameraPreviewView classes to streamline camera functionality integration. 2025-12-23 23:44:55 +05:30
b6040d6042 Refactor App component and add Map screen with location permissions handling
- Updated App component to improve structure and readability.
- Replaced ICameraSDK with MyNativeModule for native interactions.
- Enhanced error handling during app initialization and QR code generation.
- Introduced a new Map screen that requests location permissions and handles user alerts for permission status.
- Added new dependencies for location permissions management.
2025-12-23 23:44:43 +05:30
6 changed files with 6913 additions and 231 deletions

332
App.tsx
View File

@@ -1,4 +1,3 @@
import React, { useEffect, useState } from 'react';
import {
StatusBar,
useColorScheme,
@@ -12,6 +11,7 @@ import {
ScrollView,
} from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { useState, useEffect } from 'react';
import Login from './src/components/Login';
import Register from './src/components/Register';
@@ -21,10 +21,9 @@ import { ScannerScreen } from './src/screens/ScannerScreen';
type Screen = 'login' | 'register' | 'home' | 'scanner';
// ✅ Correct native module
const { ICameraSDK } = NativeModules;
const { MyNativeModule } = NativeModules;
function App(): JSX.Element {
function App() {
const isDarkMode = useColorScheme() === 'dark';
const [currentScreen, setCurrentScreen] = useState<Screen>('login');
@@ -37,206 +36,223 @@ function App(): JSX.Element {
/* -------------------- INIT -------------------- */
useEffect(() => {
initializeApp();
initializeApp();
console.log('ICameraSDK:', ICameraSDK);
ICameraSDK?.greet?.('John')
.then((msg: string) => console.log(msg))
.catch(console.error);
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 loggedIn = await authAPI.isLoggedIn();
if (loggedIn) {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setCurrentScreen('home');
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);
}
} catch (e) {
console.error(e);
} finally {
setIsInitialized(true);
}
};
/* -------------------- NAVIGATION -------------------- */
const navigateToLogin = () => {
setCurrentUser(null);
setQrCode(null);
setCurrentScreen('login');
setCurrentUser(null);
setQrCode(null);
setCurrentScreen('login');
};
const navigateToRegister = () => {
setCurrentScreen('register');
setCurrentScreen('register');
};
const navigateToHome = async () => {
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setQrCode(null);
setCurrentScreen('home');
const user = await authAPI.getCurrentUser();
setCurrentUser(user);
setQrCode(null);
setCurrentScreen('home');
};
const openScanner = () => {
setCurrentScreen('scanner');
setCurrentScreen('scanner');
};
/* -------------------- ACTIONS -------------------- */
const handleLogout = async () => {
try {
await authAPI.logout();
navigateToLogin();
Alert.alert('Success', 'Logged out successfully');
} catch {
Alert.alert('Error', 'Failed to logout');
}
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');
}
};
const generateQRCode = async () => {
if (!currentUser?.email || !ICameraSDK) {
Alert.alert('Error', 'Native QR module not available');
return;
}
if (!currentUser?.email) {
Alert.alert('Error', 'No user email available');
return;
}
setIsGeneratingQR(true);
try {
const qrData = `User: ${currentUser.fullName}\nEmail: ${currentUser.email}`;
const base64 = await ICameraSDK.generateQRCode(qrData, 300, 300);
setQrCode(base64);
} catch (e) {
console.error(e);
Alert.alert('Error', 'QR generation failed');
} 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,
]);
setScannedCodes(prev => [
{
code: result.code,
format: result.format,
timestamp: new Date().toLocaleTimeString(),
},
...prev,
]);
Alert.alert(
'Scanned',
`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}
/>
);
case 'register':
return (
<Register
onNavigateToLogin={navigateToLogin}
onRegisterSuccess={navigateToHome}
/>
);
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>
{qrCode && <Image source={{ uri: qrCode }} style={styles.qrImage} />}
<TouchableOpacity style={styles.button} onPress={openScanner}>
<Text style={styles.buttonText}>Scan QR / Barcode</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.qrButton]}
onPress={generateQRCode}
disabled={isGeneratingQR}
>
<Text style={styles.buttonText}>
{isGeneratingQR ? 'Generating...' : 'Generate QR'}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.logoutButton]}
onPress={handleLogout}
>
<Text style={styles.buttonText}>Logout</Text>
</TouchableOpacity>
</ScrollView>
);
}
};
if (!isInitialized) {
return (
<SafeAreaProvider>
<View style={styles.loading}>
<Text>Initializing...</Text>
</View>
</SafeAreaProvider>
);
}
switch (currentScreen) {
case 'login':
return (
<Login
onNavigateToRegister= { navigateToRegister }
onLoginSuccess = { navigateToHome }
/>
);
case 'register':
return (
<SafeAreaProvider>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
{renderScreen()}
</SafeAreaProvider>
<Register
onNavigateToLogin= { navigateToLogin }
onRegisterSuccess = { navigateToHome }
/>
);
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>
{
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.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.logoutButton } onPress = { handleLogout } >
<Text style={ styles.buttonText }> Logout </Text>
</TouchableOpacity>
</ScrollView>
);
default:
return null;
}
};
/* -------------------- LOADING -------------------- */
if (!isInitialized) {
return (
<SafeAreaProvider>
<View style= { styles.loadingContainer } >
<Text style={ styles.loadingText }> Initializing...</Text>
</View>
</SafeAreaProvider>
);
}
export default App;
/* -------------------- STYLES -------------------- */
return (
<SafeAreaProvider>
<StatusBar barStyle= { isDarkMode? 'light-content': 'dark-content' } />
{ renderScreen() }
</SafeAreaProvider>
);
}
const styles = StyleSheet.create({
loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
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 },
button: {
backgroundColor: '#6366f1',
padding: 14,
borderRadius: 18,
marginBottom: 12,
minWidth: 220,
alignItems: 'center',
},
qrButton: { backgroundColor: '#10b981' },
logoutButton: { backgroundColor: '#ef4444' },
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' },
});
export default App;

View File

@@ -1,39 +0,0 @@
package com.lynkeduppro.camera
import com.facebook.react.uimanager.SimpleViewManager
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
import com.facebook.react.bridge.LifecycleEventListener
class CameraPreviewManager :
SimpleViewManager<CameraPreviewView>(),
LifecycleEventListener {
private var previewView: CameraPreviewView? = null
override fun getName(): String = "CameraPreviewView"
override fun createViewInstance(reactContext: ThemedReactContext): CameraPreviewView {
previewView = CameraPreviewView(reactContext)
reactContext.addLifecycleEventListener(this)
return previewView!!
}
@ReactProp(name = "active")
fun setActive(view: CameraPreviewView, active: Boolean) {
if (active && reactContext is androidx.lifecycle.LifecycleOwner) {
view.startCamera(reactContext as androidx.lifecycle.LifecycleOwner)
}
}
override fun onHostResume() {
previewView?.let {
if (reactContext is androidx.lifecycle.LifecycleOwner) {
it.startCamera(reactContext as androidx.lifecycle.LifecycleOwner)
}
}
}
override fun onHostPause() {}
override fun onHostDestroy() {}
}

View File

@@ -1,33 +0,0 @@
package com.lynkeduppro.camera
import android.content.Context
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
class CameraPreviewView(context: Context) : PreviewView(context) {
fun startCamera(lifecycleOwner: LifecycleOwner) {
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(surfaceProvider)
}
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
preview
)
}, ContextCompat.getMainExecutor(context))
}
}

View File

@@ -10,12 +10,16 @@
"test": "jest"
},
"dependencies": {
"@mapbox/polyline": "^1.2.1",
"@react-native-async-storage/async-storage": "^1.24.0",
"@react-native-community/geolocation": "^3.4.0",
"@react-native-community/netinfo": "^11.3.1",
"@react-native/new-app-screen": "0.82.1",
"lynkeduppro-login-sdk": "^0.1.9",
"react": "19.1.1",
"react-native": "0.82.1",
"react-native-maps": "^1.26.20",
"react-native-permissions": "^5.4.4",
"react-native-safe-area-context": "^5.5.2"
},
"devDependencies": {
@@ -41,4 +45,4 @@
"engines": {
"node": ">=20"
}
}
}

72
src/screens/Map.tsx Normal file
View File

@@ -0,0 +1,72 @@
import React, { useEffect } from 'react';
import { View, Text, Platform, Alert, Linking } from 'react-native';
import { check, PERMISSIONS, request, RESULTS } from 'react-native-permissions';
export default function Map() {
useEffect(() => {
const init = async () => {
const hasPermission = await requestLocationPermission();
if (hasPermission) {
console.log('Permission granted');
} else {
console.log('Permission denied');
}
};
init();
}, []);
async function requestLocationPermission(): Promise<boolean> {
try {
const permission = Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
default: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
});
const status = await check(permission);
if (status === RESULTS.GRANTED) {
console.log('Location permission already granted');
return true;
}
if (status === RESULTS.UNAVAILABLE) {
console.log('Location permission not available on this device');
return false;
}
const result = await request(permission);
if (result === RESULTS.GRANTED) {
console.log('Location permission granted');
return true;
} else if (result === RESULTS.DENIED) {
console.log('Location permission denied');
return false;
} else if (result === RESULTS.BLOCKED) {
console.log('Location permission permanently denied');
Alert.alert(
'Location Permission Blocked',
'Location permission is required to use this feature.',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Open Settings', onPress: () => Linking.openSettings() },
],
{ cancelable: true },
);
return false;
}
return false;
} catch (error) {
console.error('Location permission error:', error);
return false;
}
}
return (
<View>
<Text>Map</Text>
</View>
);
}

6662
yarn.lock Normal file

File diff suppressed because it is too large Load Diff