124 lines
4.1 KiB
TypeScript
124 lines
4.1 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react'
|
|
import type { ReactParentComponent } from '@packages/shared'
|
|
import { trpc } from '../lib/trpc-client'
|
|
|
|
export const ACTIVE_REGION_KEY = 'active_region'
|
|
|
|
interface RegionState {
|
|
regionId: number | null
|
|
regionName: string | null
|
|
boundId: number | null
|
|
boundName: string | null
|
|
isLoading: boolean
|
|
}
|
|
|
|
interface RegionContextType extends RegionState {
|
|
setRegion: (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => Promise<void>
|
|
}
|
|
|
|
const RegionContext = createContext<RegionContextType | undefined>(undefined)
|
|
|
|
interface StoredRegion {
|
|
regionId: number
|
|
regionName: string | null
|
|
boundId: number | null
|
|
boundName: string | null
|
|
}
|
|
|
|
function readStoredRegion(): StoredRegion | null {
|
|
try {
|
|
const raw = localStorage.getItem(ACTIVE_REGION_KEY)
|
|
if (!raw) return null
|
|
const parsed = JSON.parse(raw)
|
|
if (typeof parsed?.regionId !== 'number') return null
|
|
return {
|
|
regionId: parsed.regionId,
|
|
regionName: typeof parsed.regionName === 'string' ? parsed.regionName : null,
|
|
boundId: typeof parsed?.boundId === 'number' ? parsed.boundId : null,
|
|
boundName: typeof parsed?.boundName === 'string' ? parsed.boundName : null,
|
|
}
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export const RegionProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|
const [state, setState] = useState<RegionState>({
|
|
regionId: null,
|
|
regionName: null,
|
|
boundId: null,
|
|
boundName: null,
|
|
isLoading: true,
|
|
})
|
|
const [stored, setStored] = useState<{ loaded: boolean; value: StoredRegion | null }>({
|
|
loaded: false,
|
|
value: null,
|
|
})
|
|
|
|
useEffect(() => {
|
|
setStored({ loaded: true, value: readStoredRegion() })
|
|
}, [])
|
|
|
|
// Validate the persisted region still exists backend-side. Unknown ids reset
|
|
// so the gate re-prompts instead of serving a ghost region. A stale boundId
|
|
// needs no reset: server merge degrades gracefully to region rows.
|
|
const { data: regionsData } = trpc.common.getRegions.useQuery(undefined, { staleTime: Infinity })
|
|
|
|
useEffect(() => {
|
|
if (!stored.loaded || regionsData === undefined) return
|
|
const valid = stored.value != null && regionsData.regions.some((r) => r.id === stored.value!.regionId)
|
|
if (valid && stored.value != null) {
|
|
setState({ ...stored.value, isLoading: false })
|
|
} else {
|
|
if (stored.value != null) {
|
|
try {
|
|
localStorage.removeItem(ACTIVE_REGION_KEY)
|
|
} catch {
|
|
// ignore storage errors
|
|
}
|
|
}
|
|
setState({ regionId: null, regionName: null, boundId: null, boundName: null, isLoading: false })
|
|
}
|
|
}, [stored, regionsData])
|
|
|
|
const setRegion = useCallback(
|
|
async (regionId: number, regionName: string, boundId?: number | null, boundName?: string | null) => {
|
|
try {
|
|
localStorage.setItem(
|
|
ACTIVE_REGION_KEY,
|
|
JSON.stringify({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null })
|
|
)
|
|
} catch {
|
|
// ignore storage errors (private mode etc.)
|
|
}
|
|
setState({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null, isLoading: false })
|
|
},
|
|
[]
|
|
)
|
|
|
|
const value = useMemo(() => ({ ...state, setRegion }), [state, setRegion])
|
|
|
|
return <RegionContext.Provider value={value}>{children}</RegionContext.Provider>
|
|
}
|
|
|
|
export const useRegion = (): RegionContextType => {
|
|
const context = useContext(RegionContext)
|
|
if (context === undefined) {
|
|
throw new Error('useRegion must be used within a RegionProvider')
|
|
}
|
|
return context
|
|
}
|
|
|
|
/** Spread into user-facing trpc query/mutation inputs so the backend scopes
|
|
* to the active region (and bound, when known). Empty object when no region
|
|
* is set yet (backend keeps its default-region behaviour in that case). */
|
|
export const useRegionParams = (): { regionId?: number; boundId?: number } => {
|
|
const { regionId, boundId } = useRegion()
|
|
return useMemo(
|
|
() => ({
|
|
...(regionId != null ? { regionId } : {}),
|
|
...(boundId != null ? { boundId } : {}),
|
|
}),
|
|
[regionId, boundId]
|
|
)
|
|
}
|