-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathEditorProvider.tsx
78 lines (65 loc) · 1.89 KB
/
EditorProvider.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
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
import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'
import { EditorState, Plugin } from 'prosemirror-state'
import { EditorProps, EditorView } from 'prosemirror-view'
import React, { createContext, useContext, useState } from 'react'
const EditorStateContext = createContext<EditorState | null>(null)
const EditorViewContext = createContext<EditorView | null>(null)
export const useEditorState = (): EditorState => {
const context = useContext(EditorStateContext)
if (!context) {
throw new Error(`useEditorState is only available inside EditorProvider`)
}
return context
}
export const useEditorView = (): EditorView => {
const context = useContext(EditorViewContext)
if (!context) {
throw new Error(`useEditorView is only available inside EditorProvider`)
}
return context
}
export const EditorProvider: React.FC<{
// schema or doc
doc?: ProsemirrorNode
schema?: Schema
plugins?: Plugin[]
editorProps?: EditorProps
// handleDocChange?: (doc: ProsemirrorNode) => void
}> = ({
doc,
schema,
plugins = [],
editorProps,
// handleDocChange,
children,
}) => {
const [state, setState] = useState(() => {
return EditorState.create({ doc, schema, plugins })
})
const [view] = useState(
() =>
new EditorView(undefined, {
...editorProps,
state,
dispatchTransaction: function (tr) {
// const doc = this.state.doc
const state = this.state.apply(tr)
view.updateState(state)
setState(state)
// if (handleDocChange && state.doc !== doc) {
// handleDocChange(state.doc)
// }
},
})
)
// useEffect(() => {
// return () => view.destroy()
// })
return (
<EditorStateContext.Provider value={state}>
<EditorViewContext.Provider value={view}>
{children}
</EditorViewContext.Provider>
</EditorStateContext.Provider>
)
}