/
InlineObject.tsx
299 lines (299 loc) · 9.26 KB
/
InlineObject.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
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import ReactDOM from 'react-dom'
import Base64 from 'slate-base64-serializer'
import React from 'react'
import {isEqual, throttle} from 'lodash'
import classNames from 'classnames'
import {
BlockContentFeatures,
FormBuilderValue,
Marker,
Path,
SlateEditor,
SlateNode,
SlateSelection,
Type
} from '../typeDefs'
import {resolveTypeName} from '../../../utils/resolveTypeName'
import {PatchEvent} from '../../../PatchEvent'
import {FOCUS_TERMINATOR} from '@sanity/util/paths'
import InvalidValue from '../../InvalidValueInput'
import Preview from '../../../Preview'
import styles from './styles/InlineObject.css'
import {Block, Range, Inline} from 'slate'
import {setEventTransfer, getEventRange} from 'slate-react'
type Props = {
attributes: any
blockContentFeatures: BlockContentFeatures
editor: SlateEditor
isSelected?: boolean
markers: Marker[]
node: Block
onFocus: (arg0: Path) => void
onPatch: (event: PatchEvent, value?: FormBuilderValue[]) => void
readOnly?: boolean
type: Type | null
}
type State = {
isDragging: boolean
}
export default class InlineObject extends React.Component<Props, State> {
static defaultProps = {
isSelected: false,
readOnly: false
}
_dropTarget: {
node: SlateNode
selection: SlateSelection
} | null = null
_editorNode: HTMLElement | null = null
_previewContainer: HTMLElement | null = null
state = {
isDragging: false
}
componentDidMount() {
const {editor} = this.props
const elm = ReactDOM.findDOMNode(editor) // eslint-disable-line react/no-find-dom-node
if (elm instanceof HTMLElement) {
this._editorNode = elm
}
}
componentWillUnmount() {
this.removeDragHandlers()
}
addDragHandlers() {
if (this._editorNode) {
this._editorNode.addEventListener('dragover', this.handleDragOverOtherNode)
}
if (this._editorNode) {
this._editorNode.addEventListener('dragleave', this.handleDragLeave)
}
}
removeDragHandlers() {
if (this._editorNode) {
this._editorNode.removeEventListener('dragover', this.handleDragOverOtherNode)
}
if (this._editorNode) {
this._editorNode.removeEventListener('dragleave', this.handleDragLeave)
}
}
handleDragStart = (event: React.DragEvent) => {
const {node} = this.props
this.setState({isDragging: true})
this.addDragHandlers()
const element = ReactDOM.findDOMNode(this._previewContainer) // eslint-disable-line react/no-find-dom-node
if (element && element instanceof HTMLElement) {
const encoded = Base64.serializeNode(node, {preserveKeys: true})
setEventTransfer(event, 'node', encoded)
event.dataTransfer.effectAllowed = 'move'
event.dataTransfer.setDragImage(element, element.clientWidth / 2, -10)
}
this.props.editor.moveToEndOfNode(this.props.node).focus()
}
// Remove the drop target if we leave the editors nodes
handleDragLeave = (event: DragEvent) => {
// must not be .currentTarget!
if (event.target === this._editorNode) {
this.resetDropTarget()
}
}
resetDropTarget() {
this._dropTarget = null
}
restoreSelection() {
const {editor} = this.props
editor.withoutSaving(() => {
editor.moveToEndOfNode(this.props.node).focus()
})
this.resetDropTarget()
}
handleDragOverOtherNode = (event: DragEvent) => {
if (!this.state.isDragging) {
return
}
const targetDOMNode = event.target // Must not be .currentTarget!
// As the event is registered on the editor parent node
// ignore the event if it is coming from from the editor node itself
if (targetDOMNode === this._editorNode) {
this.restoreSelection()
return
}
const {editor} = this.props
const range = getEventRange(event, editor)
if (range === null || (range.focus && range.focus.offset === undefined)) {
this.restoreSelection()
return
}
const targetNode = editor.value.document.getDescendant(range.focus.key)
// If we are dragging over another inline return
if (editor.value.document.getClosestInline(targetNode.key)) {
this.restoreSelection()
return
}
// If we are dragging over a custom type block return
const block = editor.value.document.getClosestBlock(range.focus.key)
if (block && block.type !== 'contentBlock') {
return
}
this.moveCursor(range, targetNode)
}
moveCursor = throttle((range: Range, node: SlateNode) => {
const {editor} = this.props
let theOffset = range.focus.offset
// Check if it is acceptable to move the cursor here
const texts = editor.value.document.getTextsAtRange(
Range.create({
anchor: {
key: node.key,
offset: theOffset - 1
},
focus: {
key: node.key,
offset: theOffset
}
})
)
if (!texts.size) {
theOffset = 0
}
return editor.withoutSaving(() => {
editor
.moveToStartOfNode(node)
.moveForward(theOffset)
.focus()
const selection = editor.value.selection
if (!this._dropTarget || range.focus.offset !== this._dropTarget.selection.focus.offset) {
this._dropTarget = {node: node, selection}
}
return editor
})
}, 30)
handleDragEnd = (event: React.DragEvent) => {
this.setState({isDragging: false})
const {node, editor} = this.props
const target = this._dropTarget
// Return if this is our node
if (!target || target.node === node) {
this.resetDropTarget()
return
}
editor.select(target.selection).removeNodeByKey(node.key)
const {focusBlock, focusText} = editor.value
// Create a new key for the "new" object
let newNode = node.toJSON({preserveKeys: true, perserveData: true})
const newKey = `${focusBlock.key}${focusBlock.nodes.indexOf(focusText) + 1}`
newNode.data.value._key = newKey
newNode.data._key = newKey
newNode.key = newKey
newNode = Inline.create(newNode)
editor.insertInline(newNode)
this.resetDropTarget()
}
handleInvalidValue = (event: PatchEvent) => {
let _event = event
const {editor, onPatch} = this.props
const value = this.getValue()
const parentBlock = editor.value.document.getClosestBlock(value._key)
const path = [{_key: parentBlock.key}, 'children', {_key: value._key}]
path.reverse().forEach(part => {
_event = _event.prefixAll(part)
})
onPatch(_event, value)
}
handleCancelEvent = (event: React.SyntheticEvent) => {
event.stopPropagation()
event.preventDefault()
}
handleEditStart = (event: React.MouseEvent) => {
event.stopPropagation()
const {editor, node, onFocus} = this.props
editor.blur()
editor
.moveToEndOfNode(node)
.focus()
.blur()
const block = editor.value.focusBlock
setTimeout(() => {
onFocus([{_key: block.key}, 'children', {_key: node.key}, FOCUS_TERMINATOR])
}, 100)
}
handleView = () => {
const {editor, node, onFocus} = this.props
onFocus([
{_key: editor.value.document.getParent(node.key).key},
'children',
{_key: node.key},
FOCUS_TERMINATOR
])
}
refPreviewContainer = (elm: HTMLSpanElement | null) => {
this._previewContainer = elm
}
getValue() {
return this.props.node.data.get('value')
}
handleInvalidTypeContainerClick = event => {
event.preventDefault()
event.stopPropagation()
}
// eslint-disable-next-line complexity
render() {
const {
attributes,
blockContentFeatures,
editor,
isSelected,
markers,
node,
readOnly,
type
} = this.props
const value = this.getValue()
const valueType = resolveTypeName(value)
const validTypes = blockContentFeatures.types.inlineObjects.map(objType => objType.name)
if (!validTypes.includes(valueType)) {
return (
<div {...attributes} onClick={this.handleInvalidTypeContainerClick} contentEditable={false}>
<InvalidValue
validTypes={validTypes}
actualType={valueType}
value={value}
onChange={this.handleInvalidValue}
/>
</div>
)
}
const validation = markers.filter(marker => marker.type === 'validation')
const errors = validation.filter(marker => marker.level === 'error')
const classname = classNames([
styles.root,
editor.value.selection.focus.isInNode(node) && styles.focused,
isSelected && styles.selected,
errors.length > 0 && styles.hasErrors
])
const valueKeys = value ? Object.keys(value) : []
const isEmpty = !value || isEqual(valueKeys.sort(), ['_key', '_type'].sort())
return (
<span
{...attributes}
onDragStart={this.handleDragStart}
onDragEnd={this.handleDragEnd}
onDragEnter={this.handleCancelEvent}
onDragLeave={this.handleCancelEvent}
onDrop={this.handleCancelEvent}
draggable={!readOnly}
className={classname}
contentEditable={false}
>
<span
onClick={readOnly ? this.handleView : this.handleEditStart}
ref={this.refPreviewContainer}
className={styles.previewContainer}
style={readOnly ? {cursor: 'default'} : {}}
>
{!isEmpty && <Preview type={type} value={value} layout="inline" />}
{isEmpty && !readOnly && <span>Click to edit</span>}
</span>
</span>
)
}
}