This repository was archived by the owner on Feb 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy patheditor-context.js
97 lines (90 loc) · 2.09 KB
/
editor-context.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* External dependencies
*/
import {
createContext,
useContext,
useCallback,
useState,
} from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { useEffect } from 'react';
/**
* @typedef {import('@woocommerce/type-defs/contexts').EditorDataContext} EditorDataContext
* @typedef {import('@woocommerce/type-defs/cart').CartData} CartData
*/
const EditorContext = createContext( {
isEditor: false,
currentPostId: 0,
currentView: '',
previewData: {},
getPreviewData: () => void null,
setCurrentView: () => void null,
} );
/**
* @return {EditorDataContext} Returns the editor data context value
*/
export const useEditorContext = () => {
return useContext( EditorContext );
};
/**
* Editor provider
*
* @param {Object} props Incoming props for the provider.
* @param {*} props.children The children being wrapped.
* @param {Object} [props.previewData] The preview data for editor.
* @param {number} [props.currentPostId] The post being edited.
* @param {string} [props.currentView] Current view, if using a view switcher.
*/
export const EditorProvider = ( {
children,
currentPostId = 0,
currentView: initialView = null,
previewData = {},
} ) => {
/**
* @type {number} editingPostId
*/
const editingPostId = useSelect(
( select ) => {
if ( ! currentPostId ) {
const store = select( 'core/editor' );
return store.getCurrentPostId();
}
return currentPostId;
},
[ currentPostId ]
);
const getPreviewData = useCallback(
( name ) => {
if ( name in previewData ) {
return previewData[ name ];
}
return {};
},
[ previewData ]
);
const setCurrentView = ( view ) => {
setView( view );
};
const [ currentView, setView ] = useState( initialView );
useEffect( () => {
setView( initialView );
}, [ initialView ] );
/**
* @type {EditorDataContext}
*/
const editorData = {
isEditor: true,
currentPostId: editingPostId,
currentView,
previewData,
getPreviewData,
setCurrentView,
};
return (
<EditorContext.Provider value={ editorData }>
{ children }
</EditorContext.Provider>
);
};