freshyo/apps/user-ui/src/contexts/RegionContext.tsx
2026-10-07 00:27:11 +05:30

135 lines
4.5 KiB
TypeScript

import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
import { StorageServiceCasual } from 'common-ui';
import type { ReactParentComponent } from '@packages/shared';
import { trpc } from '../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;
}
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(() => {
StorageServiceCasual.getItem(ACTIVE_REGION_KEY).then((raw) => {
if (raw) {
try {
const parsed = JSON.parse(raw);
if (typeof parsed?.regionId === 'number') {
setStored({
loaded: true,
value: {
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,
},
});
return;
}
} catch {
// ignore corrupt cache
}
}
setStored({ loaded: true, value: null });
});
}, []);
// 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 match = stored.value != null
? regionsData.regions.find((r) => r.id === stored.value!.regionId)
: undefined;
if (match && stored.value != null) {
// Resolve names from the server list by id: the persisted strings may
// be stale after a region rename, and must never render verbatim.
setState({
regionId: stored.value.regionId,
regionName: match.name ?? stored.value.regionName,
boundId: stored.value.boundId,
boundName: stored.value.boundName,
isLoading: false,
});
} else {
if (stored.value != null) {
void StorageServiceCasual.removeItem(ACTIVE_REGION_KEY);
}
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) => {
await StorageServiceCasual.setItem(
ACTIVE_REGION_KEY,
JSON.stringify({ regionId, regionName, boundId: boundId ?? null, boundName: boundName ?? null })
);
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]
);
};