-
Notifications
You must be signed in to change notification settings - Fork 319
/
index.js
134 lines (121 loc) · 2.74 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/** @jsx jsx */
import { jsx } from '@emotion/core'
import { useContext } from 'react'
import { Data } from 'slate'
import { Context } from '../../components/context'
import Form from './Form'
import Overlay from './Overlay'
const hasJSXBlock = (editor, type) => {
if (!editor.hasBlock('jsx-void') && !editor.hasBlock('jsx')) return false
return editor.value.blocks.some(
node => node.data && node.data.get('type') === type
)
}
const setJSXProps = (editor, dataObject) => {
const {
value: { startBlock, document }
} = editor
const data = Data.create(dataObject)
if (startBlock.data.get('type') !== dataObject.type) {
const parent = document.getParent(startBlock.key)
if (parent) {
editor.setNodeByKey(parent.key, { type: 'jsx', data })
}
} else {
editor.setBlocks({ data })
}
}
const insertJSXBlock = (editor, type, props, component) => {
const { isVoid } = component.propertyControls
if (isVoid) {
editor.insertBlock({
type: 'jsx-void',
data: {
type,
props: Data.create(props)
}
})
} else {
editor.wrapBlock({
type: 'jsx',
data: {
type,
props: Data.create(props)
}
})
}
}
const getProps = node => {
const map = node.data.get('props')
if (typeof map.toJS !== 'function') return map
return map.toJS()
}
const Wrapper = ({
editor,
attributes,
isSelected,
component,
Component,
props,
children,
fields = {}
}) => {
return (
<div style={{ position: 'relative' }}>
<Component {...attributes} {...props}>
{children || null}
</Component>
{!isSelected && Component.propertyControls.isVoid && <Overlay />}
{isSelected && (
<Form
fields={fields}
value={props}
onSubmit={next => {
editor.setJSXProps({
type: component,
props: next
})
}}
/>
)}
</div>
)
}
const Node = ({ type, next, ...props }) => {
const { components } = useContext(Context)
const Component = components[type]
if (!Component) return next()
return (
<Wrapper
{...props}
Component={Component}
component={type}
fields={Component.propertyControls}
/>
)
}
export default (opts = {}) => ({
queries: {
hasJSXBlock
},
commands: {
insertJSXBlock,
setJSXProps
},
renderNode: (props, editor, next) => {
const { node } = props
const isJSXNode = node.type === 'jsx' || node.type === 'jsx-void'
if (!isJSXNode) return next()
const type = node.data.get('type')
if (!type) return next()
return (
<Node
{...props}
next={next}
editor={editor}
type={type}
props={getProps(node)}
/>
)
}
})