freshyo/apps/user-ui/components/RegionGate.tsx
2026-10-05 11:46:47 +05:30

212 lines
7.8 KiB
TypeScript

import React, { useState, useEffect, useRef } from 'react';
import * as Location from 'expo-location';
import * as Linking from 'expo-linking';
import { View, ActivityIndicator, AppState, Platform } from 'react-native';
import { MyText, MyTouchableOpacity, tw } from 'common-ui';
import type { ReactParentComponent } from '@packages/shared';
import { trpc } from '../src/trpc-client';
import { useRegion } from '../src/contexts/RegionContext';
type GateReason = 'denied' | 'servicesOff' | 'unserved' | 'error';
const RegionGate: React.FC<ReactParentComponent> = ({ children }) => {
const { regionId, regionName, isLoading: regionLoading, setRegion } = useRegion();
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(null);
const [denied, setDenied] = useState(false);
const [servicesOff, setServicesOff] = useState(false);
const [detectError, setDetectError] = useState(false);
const [detecting, setDetecting] = useState(true);
const [showPicker, setShowPicker] = useState(false);
const [picked, setPicked] = useState(false);
const [attempt, setAttempt] = useState(0);
const passedRef = useRef(false);
const appState = useRef(AppState.currentState);
const runDetection = async () => {
if (passedRef.current) return;
setDetecting(true);
setDenied(false);
setServicesOff(false);
setDetectError(false);
setCoords(null);
try {
const { status } = await Location.requestForegroundPermissionsAsync();
if (passedRef.current) return;
if (status !== 'granted') {
setDenied(true);
return;
}
const servicesEnabled = await Location.hasServicesEnabledAsync();
if (passedRef.current) return;
if (!servicesEnabled) {
setServicesOff(true);
return;
}
const location = await Location.getCurrentPositionAsync({});
if (passedRef.current) return;
setCoords({ lat: location.coords.latitude, lng: location.coords.longitude });
} catch (error) {
if (!passedRef.current) setDetectError(true);
} finally {
if (!passedRef.current) setDetecting(false);
}
};
useEffect(() => {
void runDetection();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [attempt]);
// Re-check when returning from OS/app Settings.
useEffect(() => {
const sub = AppState.addEventListener('change', (next) => {
if (appState.current.match(/inactive|background/) && next === 'active') {
setAttempt((a) => a + 1);
}
appState.current = next;
});
return () => sub.remove();
}, []);
const resolveQuery = trpc.common.resolveRegionForLocation.useQuery(
{ lat: coords?.lat ?? 0, lng: coords?.lng ?? 0 },
{ enabled: !!coords, retry: false, refetchOnWindowFocus: false, staleTime: Infinity }
);
const resolved = resolveQuery.data;
const resolveFailed = resolveQuery.isError;
useEffect(() => {
if (resolved?.regionId != null) {
passedRef.current = true;
void setRegion(resolved.regionId, resolved.regionName ?? '', resolved.boundId, resolved.boundName);
}
}, [resolved, setRegion]);
const { data: regionsData, isLoading: regionsLoading } = trpc.common.getRegions.useQuery(
undefined,
{ staleTime: Infinity }
);
const handlePick = (id: number, name: string) => {
passedRef.current = true;
setPicked(true);
void setRegion(id, name);
};
const handlePrimaryAction = async () => {
if (servicesOff && Platform.OS === 'android') {
try {
await Location.enableNetworkProviderAsync();
} catch {
// User dismissed the system dialog; fall through to re-check.
}
setAttempt((a) => a + 1);
return;
}
await Linking.openSettings();
};
// GPS resolved to a served region, or the user picked/continued manually.
if (resolved?.regionId != null || picked) {
return <>{children}</>;
}
if (detecting || regionLoading || (!!coords && !resolved && !resolveFailed)) {
return (
<View style={tw`flex-1 items-center justify-center bg-white`} testID="region-gate-loading">
<ActivityIndicator size="large" />
<MyText style={tw`text-gray-500 mt-3`}>Detecting your region…</MyText>
</View>
);
}
const detectionBlocked = denied || servicesOff;
const reason: GateReason = denied
? 'denied'
: servicesOff
? 'servicesOff'
: resolveFailed || detectError
? 'error'
: 'unserved';
// Hard failure (permission or location switch): message + action, picker on demand.
if ((detectionBlocked || showPicker) && reason !== 'unserved') {
if (!showPicker) {
const subheading = denied
? 'We need location permission to auto-detect your region. Grant access in Settings, or choose your region manually.'
: 'Your location is turned off. Turn it on to auto-detect your region, or choose your region manually.';
return (
<View style={tw`flex-1 items-center justify-center bg-white px-8`} testID="region-gate-blocked">
<MyText style={tw`text-2xl font-extrabold text-gray-900 text-center`}>
Unable to obtain location
</MyText>
<MyText style={tw`text-gray-500 mt-3 text-center`}>{subheading}</MyText>
<MyTouchableOpacity
testID="region-gate-action"
style={tw`mt-8 w-full bg-brand500 rounded-xl py-4`}
onPress={handlePrimaryAction}
>
<MyText style={tw`text-white text-center font-bold`}>
{servicesOff && Platform.OS === 'android' ? 'Turn on location' : 'Open Settings'}
</MyText>
</MyTouchableOpacity>
<MyTouchableOpacity
testID="region-gate-manual"
style={tw`mt-3 w-full border border-gray-200 rounded-xl py-4`}
onPress={() => setShowPicker(true)}
>
<MyText style={tw`text-gray-900 text-center font-bold`}>Choose region manually</MyText>
</MyTouchableOpacity>
{regionId != null && (
<MyTouchableOpacity
testID="region-gate-continue-stored"
style={tw`mt-3`}
onPress={() => handlePick(regionId, regionName ?? '')}
>
<MyText style={tw`text-gray-500 text-center text-sm`}>
Continue with {regionName ?? 'saved region'}
</MyText>
</MyTouchableOpacity>
)}
</View>
);
}
}
// Region picker: unserved GPS, resolution failure, or manual choice.
const pickerTitle = reason === 'unserved' ? 'Outside service area' : 'Choose your region';
const pickerMessage =
reason === 'unserved'
? 'Your current location is outside the areas we serve. You can still continue by picking a region below.'
: reason === 'error'
? 'We could not detect your region. Pick one below to continue.'
: 'Pick your region below to continue.';
const regions = regionsData?.regions ?? [];
return (
<View style={tw`flex-1 bg-white px-6 pt-20`} testID="region-gate-picker">
<MyText style={tw`text-2xl font-extrabold text-gray-900`}>{pickerTitle}</MyText>
<MyText style={tw`text-gray-500 mt-2 mb-6`}>{pickerMessage}</MyText>
{regionsLoading ? (
<ActivityIndicator size="large" />
) : (
regions.map((region) => (
<MyTouchableOpacity
key={region.id}
testID={`region-pick-${region.id}`}
style={tw`border border-gray-200 rounded-xl px-4 py-4 mb-3`}
onPress={() => handlePick(region.id, region.name)}
>
<MyText style={tw`text-lg font-bold text-gray-900`}>{region.name}</MyText>
{!!region.description && (
<MyText style={tw`text-gray-500 text-sm mt-1`}>{region.description}</MyText>
)}
</MyTouchableOpacity>
))
)}
</View>
);
};
export default RegionGate;