crush-level-web/src/context/mainLayout/index.tsx

65 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-11-28 06:31:36 +00:00
'use client'
import { createContext, useReducer, useEffect, useState } from 'react'
2025-11-13 08:38:25 +00:00
2025-11-28 06:31:36 +00:00
export * from './useMainLayout'
2025-11-13 08:38:25 +00:00
const MainLayoutContext = createContext<{
2025-11-28 06:31:36 +00:00
isSidebarExpanded: boolean
dispatch: (action: { type: 'updateState'; payload: Partial<typeof initialState> }) => void
2025-11-13 08:38:25 +00:00
}>({
isSidebarExpanded: false,
dispatch: () => {},
2025-11-28 06:31:36 +00:00
})
2025-11-13 08:38:25 +00:00
const initialState = {
isSidebarExpanded: false,
2025-11-28 06:31:36 +00:00
}
2025-11-13 08:38:25 +00:00
2025-11-28 06:31:36 +00:00
const reducer = (
state: typeof initialState,
action: { type: 'updateState'; payload: Partial<typeof initialState> }
) => {
2025-11-13 08:38:25 +00:00
switch (action.type) {
2025-11-28 06:31:36 +00:00
case 'updateState':
2025-11-13 08:38:25 +00:00
return {
...state,
...action.payload,
2025-11-28 06:31:36 +00:00
}
2025-11-13 08:38:25 +00:00
}
2025-11-28 06:31:36 +00:00
return state
2025-11-13 08:38:25 +00:00
}
export const MainLayoutProvider = ({ children }: { children: React.ReactNode }) => {
2025-11-28 06:31:36 +00:00
const [state, dispatch] = useReducer(reducer, initialState)
const [isHydrated, setIsHydrated] = useState(false)
2025-11-13 08:38:25 +00:00
// 客户端 hydration 后从 localStorage 恢复状态
useEffect(() => {
2025-11-28 06:31:36 +00:00
setIsHydrated(true)
const saved = localStorage.getItem('sidebarExpanded')
2025-11-13 08:38:25 +00:00
if (saved !== null) {
dispatch({
2025-11-28 06:31:36 +00:00
type: 'updateState',
2025-11-13 08:38:25 +00:00
payload: {
2025-11-28 06:31:36 +00:00
isSidebarExpanded: JSON.parse(saved),
},
})
2025-11-13 08:38:25 +00:00
}
2025-11-28 06:31:36 +00:00
}, [])
2025-11-13 08:38:25 +00:00
// 当状态改变时保存到 localStorage
useEffect(() => {
if (isHydrated) {
2025-11-28 06:31:36 +00:00
localStorage.setItem('sidebarExpanded', JSON.stringify(state.isSidebarExpanded))
2025-11-13 08:38:25 +00:00
}
2025-11-28 06:31:36 +00:00
}, [state.isSidebarExpanded, isHydrated])
2025-11-13 08:38:25 +00:00
return (
<MainLayoutContext.Provider value={{ isSidebarExpanded: state.isSidebarExpanded, dispatch }}>
{children}
</MainLayoutContext.Provider>
2025-11-28 06:31:36 +00:00
)
2025-11-13 08:38:25 +00:00
}
2025-11-28 06:31:36 +00:00
export default MainLayoutContext