/
store.tsx
38 lines (31 loc) · 1.13 KB
/
store.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import React, { PropsWithChildren, createContext, useContext, useReducer } from 'react';
import { EditorStateConfig } from '@codemirror/state';
import { MergeView, MergeConfig } from '@codemirror/merge';
export interface StoreContextValue extends InitialState {
dispatch?: React.Dispatch<InitialState>;
}
export interface InitialState extends MergeConfig {
modified?: EditorStateConfig;
original?: EditorStateConfig;
view?: MergeView;
}
export const initialState: InitialState = {
modified: { doc: '' },
original: { doc: '' },
};
export const Context = createContext<StoreContextValue>(initialState);
export function reducer(state: InitialState, action: InitialState): InitialState {
return {
...state,
...action,
modified: { ...state.modified, ...action.modified },
original: { ...state.original, ...action.original },
};
}
export const useStore = () => {
return useContext(Context);
};
export const Provider: React.FC<PropsWithChildren<any>> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return <Context.Provider value={{ ...state, dispatch }}>{children}</Context.Provider>;
};