2022-10-13 18:04:06 +08:00
|
|
|
import type { EditorContainer } from '@blocksuite/editor';
|
|
|
|
|
|
|
|
import { createContext, useContext, useEffect, useState } from 'react';
|
|
|
|
import type { PropsWithChildren } from 'react';
|
|
|
|
|
|
|
|
type EditorContextValue = {
|
|
|
|
editor: EditorContainer | null;
|
2022-10-18 00:28:39 +08:00
|
|
|
mode: EditorContainer['mode'];
|
2022-10-13 18:04:06 +08:00
|
|
|
setEditor: (editor: EditorContainer) => void;
|
2022-10-18 00:28:39 +08:00
|
|
|
setMode: (mode: EditorContainer['mode']) => void;
|
2022-10-13 18:04:06 +08:00
|
|
|
};
|
2022-10-24 11:42:11 +08:00
|
|
|
|
2022-10-13 18:04:06 +08:00
|
|
|
type EditorContextProps = PropsWithChildren<{}>;
|
|
|
|
|
|
|
|
export const EditorContext = createContext<EditorContextValue>({
|
|
|
|
editor: null,
|
2022-10-18 00:28:39 +08:00
|
|
|
mode: 'page',
|
2022-10-13 18:04:06 +08:00
|
|
|
setEditor: () => {},
|
2022-10-18 00:28:39 +08:00
|
|
|
setMode: () => {},
|
2022-10-13 18:04:06 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
export const useEditor = () => useContext(EditorContext);
|
|
|
|
|
|
|
|
export const EditorProvider = ({
|
|
|
|
children,
|
|
|
|
}: PropsWithChildren<EditorContextProps>) => {
|
|
|
|
const [editor, setEditor] = useState<EditorContainer | null>(null);
|
2022-10-18 00:28:39 +08:00
|
|
|
const [mode, setMode] = useState<EditorContainer['mode']>('page');
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const event = new CustomEvent('affine.switch-mode', { detail: mode });
|
|
|
|
window.dispatchEvent(event);
|
|
|
|
}, [mode]);
|
2022-10-13 18:04:06 +08:00
|
|
|
|
|
|
|
return (
|
2022-10-18 00:28:39 +08:00
|
|
|
<EditorContext.Provider value={{ editor, setEditor, mode, setMode }}>
|
2022-10-13 18:04:06 +08:00
|
|
|
{children}
|
|
|
|
</EditorContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default EditorProvider;
|