From d67b665f31bee292cae532ea84c73b5044844abf Mon Sep 17 00:00:00 2001 From: noreplydev Date: Wed, 14 Feb 2024 16:58:06 +0100 Subject: [PATCH] feat: add context prop to the editor component --- packages/core/src/editor/Editor.tsx | 76 ++++++++++++++------------ packages/core/src/editor/store.tsx | 1 + packages/core/src/interfaces/editor.ts | 1 + 3 files changed, 44 insertions(+), 34 deletions(-) diff --git a/packages/core/src/editor/Editor.tsx b/packages/core/src/editor/Editor.tsx index 721bcb576..08ef10239 100644 --- a/packages/core/src/editor/Editor.tsx +++ b/packages/core/src/editor/Editor.tsx @@ -25,6 +25,47 @@ export const Editor: React.FC>> = ({ ); } + // use props provided context or internal one + const internalContext = useEditorContext(options); + const context = options.context ?? internalContext; + + // sync enabled prop with editor store options + useEffect(() => { + if (!context) { + return; + } + + if ( + options.enabled === undefined || + context.query.getOptions().enabled === options.enabled + ) { + return; + } + + context.actions.setOptions((editorOptions) => { + editorOptions.enabled = options.enabled; + }); + }, [context, options.enabled]); + + useEffect(() => { + context.subscribe( + (_) => ({ + json: context.query.serialize(), + }), + () => { + context.query.getOptions().onNodesChange(context.query); + } + ); + }, [context]); + + return context ? ( + + {children} + + ) : null; +}; + +export const useEditorContext = (options) => { const optionsRef = useRef(options); const context = useEditorStore( @@ -72,38 +113,5 @@ export const Editor: React.FC>> = ({ } ); - // sync enabled prop with editor store options - useEffect(() => { - if (!context) { - return; - } - - if ( - options.enabled === undefined || - context.query.getOptions().enabled === options.enabled - ) { - return; - } - - context.actions.setOptions((editorOptions) => { - editorOptions.enabled = options.enabled; - }); - }, [context, options.enabled]); - - useEffect(() => { - context.subscribe( - (_) => ({ - json: context.query.serialize(), - }), - () => { - context.query.getOptions().onNodesChange(context.query); - } - ); - }, [context]); - - return context ? ( - - {children} - - ) : null; + return context; }; diff --git a/packages/core/src/editor/store.tsx b/packages/core/src/editor/store.tsx index d851e3b19..29dfdd4d4 100644 --- a/packages/core/src/editor/store.tsx +++ b/packages/core/src/editor/store.tsx @@ -35,6 +35,7 @@ export const editorInitialState: EditorState = { isMultiSelectEnabled: (e: MouseEvent) => !!e.metaKey, }), normalizeNodes: () => {}, + context: null, }, }; diff --git a/packages/core/src/interfaces/editor.ts b/packages/core/src/interfaces/editor.ts index 114069c4e..b27ed4b01 100644 --- a/packages/core/src/interfaces/editor.ts +++ b/packages/core/src/interfaces/editor.ts @@ -34,6 +34,7 @@ export type Options = { >, query: QueryCallbacksFor ) => void; + context: EditorStore; }; export type Resolver = Record;