You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.1 KiB
77 lines
2.1 KiB
import {
|
|
createContext,
|
|
useContext,
|
|
useEffect,
|
|
useState,
|
|
type ReactNode,
|
|
} from 'react';
|
|
|
|
/* ===================== 角色(端)上下文 =====================
|
|
* 区分「求职端 candidate」与「企业端 enterprise」两套管路。
|
|
* - 进入 (tabs) 视为求职端,进入 (enterprise) 视为企业端;
|
|
* - identity-select 选定身份时写入 role,两端布局挂载时也会兜底校正。
|
|
*
|
|
* 持久化:当前为会话内(内存)实现,App 重启后回到 null(重新选择身份)。
|
|
* 若已安装 @react-native-async-storage/async-storage,可将文件底部
|
|
* persistRole / loadRole 替换为真实读写,即可跨重启记住当前端。
|
|
*/
|
|
|
|
export type AppRole = 'candidate' | 'enterprise';
|
|
|
|
interface RoleContextValue {
|
|
role: AppRole | null;
|
|
setRole: (role: AppRole) => void;
|
|
clearRole: () => void;
|
|
}
|
|
|
|
const RoleContext = createContext<RoleContextValue | undefined>(undefined);
|
|
|
|
let memoryRole: AppRole | null = null;
|
|
|
|
function persistRole(role: AppRole | null): void {
|
|
memoryRole = role;
|
|
// TODO(持久化): 安装 async-storage 后改为 AsyncStorage.setItem('app_role', role ?? '')
|
|
}
|
|
|
|
function loadRole(): Promise<AppRole | null> {
|
|
return Promise.resolve(memoryRole);
|
|
// TODO(持久化): 安装 async-storage 后改为 AsyncStorage.getItem('app_role')
|
|
}
|
|
|
|
export function RoleProvider({ children }: { children: ReactNode }) {
|
|
const [role, setRoleState] = useState<AppRole | null>(null);
|
|
|
|
useEffect(() => {
|
|
let active = true;
|
|
loadRole().then((stored) => {
|
|
if (active && stored) setRoleState(stored);
|
|
});
|
|
return () => {
|
|
active = false;
|
|
};
|
|
}, []);
|
|
|
|
const setRole = (next: AppRole) => {
|
|
setRoleState(next);
|
|
persistRole(next);
|
|
};
|
|
|
|
const clearRole = () => {
|
|
setRoleState(null);
|
|
persistRole(null);
|
|
};
|
|
|
|
return (
|
|
<RoleContext.Provider value={{ role, setRole, clearRole }}>
|
|
{children}
|
|
</RoleContext.Provider>
|
|
);
|
|
}
|
|
|
|
export function useRole(): RoleContextValue {
|
|
const ctx = useContext(RoleContext);
|
|
if (!ctx) {
|
|
throw new Error('useRole 必须在 RoleProvider 内部使用');
|
|
}
|
|
return ctx;
|
|
}
|
|
|