37 lines
1.4 KiB
TypeScript
37 lines
1.4 KiB
TypeScript
import { createPersistReduxStore } from '@3rapp/store';
|
|
import { produce } from 'immer';
|
|
|
|
import { Reducer } from 'react';
|
|
|
|
import { ThemeActions, defaultThemeOptions } from './constants';
|
|
import { ThemeDispatchs, ThemeOptions } from './types';
|
|
// 生成dispatch的reducer 没有类型会在使用的时候报错
|
|
const ThemeReducer: Reducer<ThemeOptions, ThemeDispatchs> = produce((draft, action) => {
|
|
switch (action.type) {
|
|
case ThemeActions.CHANGE_MODE:
|
|
draft.mode = action.value;
|
|
break;
|
|
case ThemeActions.TOOGLE_MODE:
|
|
draft.mode = draft.mode === 'light' ? 'dark' : 'light';
|
|
break;
|
|
case ThemeActions.CHANGE_COMPACT:
|
|
draft.compact = action.value;
|
|
break;
|
|
case ThemeActions.TOOGLE_COMPACT:
|
|
draft.compact = !draft.compact;
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
});
|
|
export const createThemeStore = (initialState: Partial<ThemeOptions> = {}) =>
|
|
createPersistReduxStore(
|
|
ThemeReducer,
|
|
{ ...initialState, ...defaultThemeOptions },
|
|
// partialize 用于过滤需要存储的数据
|
|
{ name: 'theme', partialize: (state) => ({ mode: state.mode, compact: state.compact }) },
|
|
{ name: 'theme' },
|
|
);
|
|
// 使用useref持久化储存store 以便在组件生命周期内共享
|
|
export type ThemeStoreType = ReturnType<typeof createThemeStore>;
|