1 | import React from 'react';
|
2 | import PropTypes from 'prop-types';
|
3 | import { defaultEditorState } from '@/utils/default';
|
4 |
|
5 |
|
6 | export const ArchEditorContext = React.createContext({});
|
7 |
|
8 | export class ArchEditorProvider extends React.Component {
|
9 | constructor(props) {
|
10 | super(props);
|
11 | this.setEditorState = this._setEditorState.bind(this);
|
12 | this.state = {
|
13 | editorContext: {
|
14 | contextEditorState: defaultEditorState,
|
15 | setContextEditorState: this.setEditorState,
|
16 | },
|
17 | };
|
18 | }
|
19 |
|
20 | static getDerivedStateFromProps(props, state) {
|
21 | const { value } = props;
|
22 | if (value) {
|
23 | return {
|
24 | editorContext: {
|
25 | ...state.editorContext,
|
26 | contextEditorState: value,
|
27 | },
|
28 | };
|
29 | }
|
30 | return null;
|
31 | }
|
32 |
|
33 | _setEditorState(v) {
|
34 | const { editorContext } = this.state;
|
35 | const { value, onChange } = this.props;
|
36 | if (!value) {
|
37 | this.setState({
|
38 | editorContext: {
|
39 | ...editorContext,
|
40 | contextEditorState: v,
|
41 | },
|
42 | });
|
43 | }
|
44 | if (onChange) onChange(v);
|
45 | }
|
46 |
|
47 | render() {
|
48 | const { children } = this.props;
|
49 | const { editorContext } = this.state;
|
50 | return <ArchEditorContext.Provider value={editorContext}>{children}</ArchEditorContext.Provider>;
|
51 | }
|
52 | }
|
53 |
|
54 | ArchEditorProvider.propTypes = {
|
55 | value: PropTypes.any,
|
56 | onChange: PropTypes.func,
|
57 | children: PropTypes.any,
|
58 | };
|