freshyo/apps/web-ui/src/components/RegionGate.tsx
2026-10-20 17:31:30 +05:30

134 lines
4.5 KiB
TypeScript

import React, { useEffect, useState } from 'react'
import { useLocation } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { trpc } from '../lib/trpc-client'
import { useAuth } from '../lib/auth-context'
import { useRegionStore } from '../lib/stores/region-store'
import { useAddressStore } from '../lib/stores/address-store'
import { RegionSelector } from './RegionSelector'
/**
* Blocks the app until a valid browsing region exists. On first launch (or
* when the saved region no longer exists) it shows the full-screen
* RegionSelector. Once a region is saved, children render untouched.
*
* SSR note: until the persisted region hydrates on the client, children
* render as-is so the server markup matches the first client render (no
* hydration mismatch). The gate overlay only appears after hydration when
* there is genuinely no valid region.
*/
export function RegionGate({ children }: { children: React.ReactNode }) {
const selectedRegionId = useRegionStore((state) => state.selectedRegionId)
const selectedRegion = useRegionStore((state) => state.selectedRegion)
const setRegion = useRegionStore((state) => state.setRegion)
const clearRegion = useRegionStore((state) => state.clearRegion)
const setSelectedAddressId = useAddressStore((state) => state.setSelectedAddressId)
const { isAuthenticated, isLoading: isAuthLoading } = useAuth()
const location = useLocation()
const [hasHydrated, setHasHydrated] = useState<boolean>(() =>
useRegionStore.persist.hasHydrated()
)
const { data: regions } = trpc.common.listRegions.useQuery()
// A sole saved address is the only delivery option, so it opens directly
// instead of showing a one-item region/address chooser.
const { data: addressesData, isLoading: addressesLoading } = trpc.user.address.getUserAddresses.useQuery(
undefined,
{ enabled: hasHydrated && isAuthenticated }
)
const soleAddress =
isAuthenticated && addressesData?.data?.length === 1 ? addressesData.data[0] : null
// Wait for the persisted region to load before deciding whether to prompt.
useEffect(() => {
if (useRegionStore.persist.hasHydrated()) {
setHasHydrated(true)
return
}
const unsubscribe = useRegionStore.persist.onFinishHydration(() => setHasHydrated(true))
return unsubscribe
}, [])
// Validate the saved region against the live list. A stale/unknown id must
// lead to selection, never a silent checkout fallback.
useEffect(() => {
if (!hasHydrated || !regions || selectedRegionId == null) return
const match = regions.find((region) => region.id === selectedRegionId)
if (!match) {
clearRegion()
return
}
if (
selectedRegion?.id !== match.id ||
selectedRegion?.name !== match.name ||
selectedRegion?.description !== match.description
) {
setRegion(match)
}
}, [hasHydrated, regions, selectedRegionId, selectedRegion, setRegion, clearRegion])
// No saved region + exactly one address -> adopt that address's region.
useEffect(() => {
if (!hasHydrated || selectedRegionId != null || isAuthLoading) return
if (!soleAddress || soleAddress.regionId == null || !regions) return
const match = regions.find((region) => region.id === soleAddress.regionId)
if (!match) return
setRegion(match)
setSelectedAddressId(soleAddress.id)
}, [
hasHydrated,
selectedRegionId,
isAuthLoading,
soleAddress,
regions,
setRegion,
setSelectedAddressId,
])
// Standalone full-screen routes opt out of the region gate overlay.
if (location.pathname === '/location-selector') {
return <>{children}</>
}
if (!hasHydrated) {
return <>{children}</>
}
// Wait for auth/addresses before deciding whether the sole-address shortcut
// applies; otherwise the chooser would flash before it is dismissed.
if (
selectedRegionId == null &&
(isAuthLoading || (isAuthenticated && addressesLoading))
) {
return (
<>
{children}
<div className="fixed inset-0 z-[90] flex items-center justify-center bg-white">
<Loader2 className="h-8 w-8 animate-spin text-brand-500" />
</div>
</>
)
}
if (selectedRegionId == null) {
return (
<>
{children}
<div className="fixed inset-0 z-[90] overflow-y-auto bg-white">
<div className="mx-auto w-full max-w-2xl">
<RegionSelector mode="gate" />
</div>
</div>
</>
)
}
return <>{children}</>
}
export default RegionGate