freshyo/apps/user-ui/components/LocationTestWrapper.tsx
2026-10-09 00:58:12 +05:30

69 lines
2.4 KiB
TypeScript

import React, { useEffect } from 'react'
import { ActivityIndicator, View } from 'react-native'
import { MyText, theme, tw } from 'common-ui'
import type { ReactParentComponent } from '@packages/shared'
import { trpc } from '../src/trpc-client'
import { useRegion } from '@/src/hooks/useRegion'
import RegionSelector from '@/src/components/RegionSelector'
const LoadingScreen: React.FC<{ label?: string }> = ({ label }) => (
<View style={tw`flex-1 justify-center items-center bg-white`}>
<ActivityIndicator size="large" color={theme.colors.brand500} />
{label ? <MyText style={tw`text-gray-500 mt-4`}>{label}</MyText> : null}
</View>
)
/**
* Region gate + location fallback.
*
* The browsing region is derived from the device location (see `useRegion`).
* While that is in flight we show a spinner; once a region exists the app
* renders. When the location is unusable — device location switched off,
* permission denied, or coordinates outside every region bound — the user is
* asked to choose a region manually.
*/
const LocationTestWrapper: React.FC<ReactParentComponent> = ({ children }) => {
const {
regionId,
clearRegion,
hydrated,
isResolvingRegion,
} = useRegion()
const { data: regions } = trpc.common.listRegions.useQuery()
// Validate the saved region against the live list. A stale/unknown id must
// lead to selection, never a silent checkout fallback. Membership-only: no
// setRegion here, so this effect can never re-trigger itself.
useEffect(() => {
if (!hydrated || !regions || regionId == null) return
if (!regions.some((region) => region.id === regionId)) {
clearRegion()
}
}, [hydrated, regions, regionId, clearRegion])
// A known region short-circuits every check below.
if (regionId != null) {
return <>{children}</>
}
// Wait for the persisted region to load before deciding: location tracking
// must not start while a stored choice may still appear.
if (!hydrated) {
return <LoadingScreen />
}
// Still deriving the region from device location.
if (isResolvingRegion) {
return <LoadingScreen label="Finding your region..." />
}
// Location unavailable / denied / out of area -> choose a region manually.
return (
<View style={tw`flex-1 bg-white`}>
<RegionSelector mode="gate" selectedRegionId={regionId} />
</View>
)
}
export default LocationTestWrapper