forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
734 lines (622 loc) · 17.3 KB
/
content.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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import Fragment from '../utils/fragment'
import Key from '../utils/key'
import OffsetKey from '../utils/offset-key'
import Raw from '../serializers/raw'
import React from 'react'
import Selection from '../models/selection'
import Text from './text'
import includes from 'lodash/includes'
import keycode from 'keycode'
import { IS_FIREFOX } from '../utils/environment'
/**
* Noop.
*
* @type {Function}
*/
function noop() {}
/**
* Content types.
*
* @type {Object}
*/
const TYPES = {
HTML: 'text/html',
SLATE: 'application/x-slate',
TEXT: 'text/plain'
}
/**
* Content.
*
* @type {Component}
*/
class Content extends React.Component {
/**
* Property types.
*
* @type {Object}
*/
static propTypes = {
className: React.PropTypes.string,
editor: React.PropTypes.object.isRequired,
onBeforeInput: React.PropTypes.func,
onChange: React.PropTypes.func,
onKeyDown: React.PropTypes.func,
onPaste: React.PropTypes.func,
onSelect: React.PropTypes.func,
readOnly: React.PropTypes.bool,
renderMark: React.PropTypes.func.isRequired,
renderNode: React.PropTypes.func.isRequired,
spellCheck: React.PropTypes.bool,
state: React.PropTypes.object.isRequired,
style: React.PropTypes.object
};
/**
* Default properties.
*
* @type {Object}
*/
static defaultProps = {
readOnly: false,
spellCheck: true,
style: {}
};
/**
* Constructor.
*
* @param {Object} props
*/
constructor(props) {
super(props)
this.tmp = {}
this.tmp.compositions = 0
this.forces = 0
}
/**
* Should the component update?
*
* @param {Object} props
* @param {Object} state
* @return {Boolean} shouldUpdate
*/
shouldComponentUpdate = (props, state) => {
return props.state.isNative
? false
: true
}
/**
* While rendering, set the `isRendering` flag.
*
* @param {Object} props
* @param {Object} state]
*/
componentWillUpdate = (props, state) => {
this.tmp.isRendering = true
}
/**
* When finished rendering, move the `isRendering` flag on next tick.
*
* @param {Object} props
* @param {Object} state]
*/
componentDidUpdate = (props, state) => {
setTimeout(() => {
this.tmp.isRendering = false
})
}
/**
* On before input, bubble up.
*
* @param {Event} e
*/
onBeforeInput = (e) => {
if (this.props.readOnly) return
this.props.onBeforeInput(e)
}
/**
* On blur, update the selection to be not focused.
*
* @param {Event} e
*/
onBlur = (e) => {
if (this.props.readOnly) return
if (this.tmp.isCopying) return
let { state } = this.props
state = state
.transform()
.blur()
.apply({ isNative: true })
this.onChange(state)
}
/**
* On change, bubble up.
*
* @param {State} state
*/
onChange = (state) => {
this.props.onChange(state)
}
/**
* On composition start, set the `isComposing` flag.
*
* @param {Event} e
*/
onCompositionStart = (e) => {
this.tmp.isComposing = true
this.tmp.compositions++
}
/**
* On composition end, remove the `isComposing` flag on the next tick. Also
* increment the `forces` key, which will force the contenteditable element
* to completely re-render, since IME puts React in an unreconcilable state.
*
* @param {Event} e
*/
onCompositionEnd = (e) => {
this.forces++
const count = this.tmp.compositions
// The `count` check here ensures that if another composition starts
// before the timeout has closed out this one, we will abort unsetting the
// `isComposing` flag, since a composition in still in affect.
setTimeout(() => {
if (this.tmp.compositions > count) return
this.tmp.isComposing = false
})
}
/**
* On copy, defer to `onCutCopy`, then bubble up.
*
* @param {Event} e
*/
onCopy = (e) => {
this.onCutCopy(e)
}
/**
* On cut, defer to `onCutCopy`, then bubble up.
*
* @param {Event} e
*/
onCut = (e) => {
if (this.props.readOnly) return
this.onCutCopy(e)
// Once the cut has successfully executed, delete the current selection.
window.requestAnimationFrame(() => {
const state = this.props.state.transform().delete().apply()
this.onChange(state)
})
}
/**
* On cut and copy, add the currently selected fragment to the currently
* selected DOM, so that it will show up when pasted.
*
* @param {Event} e
*/
onCutCopy = (e) => {
const native = window.getSelection()
if (!native.rangeCount) return
const { state } = this.props
const { fragment } = state
const encoded = Fragment.serialize(fragment)
// Wrap the first character of the selection in a span that has the encoded
// fragment attached as an attribute, so it will show up in the copied HTML.
const range = native.getRangeAt(0)
const contents = range.cloneContents()
const wrapper = window.document.createElement('span')
const text = contents.childNodes[0]
const char = text.textContent.slice(0, 1)
const first = window.document.createTextNode(char)
const rest = text.textContent.slice(1)
text.textContent = rest
wrapper.appendChild(first)
wrapper.setAttribute('data-fragment', encoded)
contents.insertBefore(wrapper, text)
// Add the phony content to the DOM, and select it, so it will be copied.
const body = window.document.querySelector('body')
const div = window.document.createElement('div')
div.setAttribute('contenteditable', true)
div.style.position = 'absolute'
div.style.left = '-9999px'
div.appendChild(contents)
body.appendChild(div)
// Set the `isCopying` flag, so our `onSelect` logic doesn't fire.
this.tmp.isCopying = true
const r = window.document.createRange()
// COMPAT: In Firefox, trying to use the terser `native.selectAllChildren`
// throws an error, so we use the older `range` equivalent. (2016/06/21)
r.selectNodeContents(div)
native.removeAllRanges()
native.addRange(r)
// Revert to the previous selection right after copying.
window.requestAnimationFrame(() => {
body.removeChild(div)
native.removeAllRanges()
native.addRange(range)
this.tmp.isCopying = false
})
}
/**
* On drag end, unset the `isDragging` flag.
*
* @param {Event} e
*/
onDragEnd = (e) => {
this.tmp.isDragging = false
}
/**
* On drag over, set the `isDragging` flag and the `isInternalDrag` flag.
*
* @param {Event} e
*/
onDragOver = (e) => {
if (this.tmp.isDragging) return
this.tmp.isDragging = true
this.tmp.isInternalDrag = false
}
/**
* On drag start, set the `isDragging` flag and the `isInternalDrag` flag.
*
* @param {Event} e
*/
onDragStart = (e) => {
this.tmp.isDragging = true
this.tmp.isInternalDrag = true
const { state } = this.props
const { fragment } = state
const encoded = Fragment.serialize(fragment)
const data = e.nativeEvent.dataTransfer
data.setData(TYPES.SLATE, encoded)
}
/**
* On drop.
*
* @param {Event} e
*/
onDrop = (e) => {
if (this.props.readOnly) return
e.preventDefault()
const { state } = this.props
const { selection } = state
const data = e.nativeEvent.dataTransfer
const drop = {}
// Resolve the point where the drop occured.
const { x, y } = e.nativeEvent
const range = window.document.caretRangeFromPoint(x, y)
const startNode = range.startContainer
const startOffset = range.startOffset
const point = OffsetKey.findPoint(startNode, startOffset, state)
let target = Selection.create({
anchorKey: point.key,
anchorOffset: point.offset,
focusKey: point.key,
focusOffset: point.offset,
isFocused: true
})
// If the target is inside a void node, abort.
if (state.document.hasVoidParent(point.key)) return
// If the drag is internal, handle it now. And it the target is after the
// selection, it needs to account for the selection's content being deleted.
if (this.tmp.isInternalDrag) {
if (
selection.endKey == target.endKey &&
selection.endOffset < target.endOffset
) {
const width = selection.startKey == selection.endKey
? selection.endOffset - selection.startOffset
: selection.endOffset
target = target.moveBackward(width)
}
const fragment = state.fragment
const next = state
.transform()
.delete()
.moveTo(target)
.insertFragment(fragment)
.apply()
this.onChange(next)
return
}
// COMPAT: In Firefox, `types` is array-like. (2016/06/21)
const types = Array.from(data.types)
// Handle external Slate drags.
if (includes(types, TYPES.SLATE)) {
const encoded = data.getData(TYPES.SLATE)
const fragment = Fragment.deserialize(encoded)
drop.type = 'fragment'
drop.fragment = fragment
}
// Handle files.
else if (data.files.length) {
drop.type = 'files'
drop.files = data.files
}
// Handle HTML.
else if (includes(types, TYPES.HTML)) {
drop.type = 'html'
drop.text = data.getData(TYPES.TEXT)
drop.html = data.getData(TYPES.HTML)
}
// Handle plain text.
else {
drop.type = 'text'
drop.text = data.getData(TYPES.TEXT)
}
drop.data = data
drop.target = target
this.props.onDrop(e, drop)
}
/**
* On input, handle spellcheck and other similar edits that don't go trigger
* the `onBeforeInput` and instead update the DOM directly.
*
* @param {Event} e
*/
onInput = (e) => {
let { state } = this.props
const { selection } = state
const native = window.getSelection()
const { anchorNode, anchorOffset, focusOffset } = native
const { textContent } = anchorNode
const offsetKey = OffsetKey.findKey(anchorNode)
const { key, index } = OffsetKey.parse(offsetKey)
const { start, end } = OffsetKey.findBounds(key, index, state)
const range = OffsetKey.findRange(anchorNode, state)
const { text, marks } = range
// If the text is no different, abort.
if (textContent == text) return
// Determine what the selection should be after changing the text.
const delta = textContent.length - text.length
const after = selection.collapseToEnd().moveForward(delta)
// Create an updated state with the text replaced.
state = state
.transform()
.moveTo({
anchorKey: key,
anchorOffset: start,
focusKey: key,
focusOffset: end
})
.delete()
.insertText(textContent, marks)
.moveTo(after)
.apply()
// Change the current state.
this.onChange(state)
}
/**
* On key down, prevent the default behavior of certain commands that will
* leave the editor in an out-of-sync state, then bubble up.
*
* @param {Event} e
*/
onKeyDown = (e) => {
if (this.props.readOnly) return
const key = keycode(e.which)
if (
this.tmp.isComposing &&
(key == 'left' || key == 'right' || key == 'up' || key == 'down')
) {
e.preventDefault()
return
}
if (
(key == 'enter') ||
(key == 'backspace') ||
(key == 'delete') ||
(key == 'b' && Key.isCommand(e)) ||
(key == 'i' && Key.isCommand(e)) ||
(key == 'y' && Key.isWindowsCommand(e)) ||
(key == 'z' && Key.isCommand(e))
) {
e.preventDefault()
}
this.props.onKeyDown(e)
}
/**
* On paste, determine the type and bubble up.
*
* @param {Event} e
*/
onPaste = (e) => {
if (this.props.readOnly) return
e.preventDefault()
const data = e.clipboardData
const paste = {}
// COMPAT: In Firefox, `types` is array-like. (2016/06/21)
const types = Array.from(data.types)
// Handle files.
if (data.files.length) {
paste.type = 'files'
paste.files = data.files
}
// Treat it as rich text if there is HTML content.
else if (includes(types, TYPES.HTML)) {
paste.type = 'html'
paste.text = data.getData(TYPES.TEXT)
paste.html = data.getData(TYPES.HTML)
}
// Treat everything else as plain text.
else {
paste.type = 'text'
paste.text = data.getData(TYPES.TEXT)
}
// If html, and the html includes a `data-fragment` attribute, it's actually
// a raw-serialized JSON fragment from a previous cut/copy, so deserialize
// it and insert it normally.
if (paste.type == 'html' && ~paste.html.indexOf('<span data-fragment="')) {
const regexp = /data-fragment="([^\s]+)"/
const matches = regexp.exec(paste.html)
const [ full, encoded ] = matches
const fragment = Fragment.deserialize(encoded)
let { state } = this.props
state = state
.transform()
.insertFragment(fragment)
.apply()
this.onChange(state)
return
}
paste.data = data
this.props.onPaste(e, paste)
}
/**
* On select, update the current state's selection.
*
* @param {Event} e
*/
onSelect = (e) => {
if (this.props.readOnly) return
if (this.tmp.isRendering) return
if (this.tmp.isCopying) return
if (this.tmp.isComposing) return
let { state } = this.props
let { document, selection } = state
const native = window.getSelection()
if (!native.rangeCount) {
selection = selection.merge({ isFocused: false })
state = state.merge({ selection })
this.onChange(state)
return
}
// Calculate the Slate-specific selection based on the native one.
const { anchorNode, anchorOffset, focusNode, focusOffset } = native
const anchor = OffsetKey.findPoint(anchorNode, anchorOffset, state)
const focus = OffsetKey.findPoint(focusNode, focusOffset, state)
// If the native selection is inside text nodes, we can trust the native
// state and not need to re-render.
const isNative = (
anchorNode.nodeType == 3 &&
focusNode.nodeType == 3
)
state = state
.transform()
.focus()
.moveTo({
anchorKey: anchor.key,
anchorOffset: anchor.offset,
focusKey: focus.key,
focusOffset: focus.offset
})
.apply({ isNative })
this.onChange(state)
}
/**
* Render the editor content.
*
* @return {Element} element
*/
render = () => {
const { className, readOnly, state } = this.props
const { document } = state
const children = document.nodes
.map(node => this.renderNode(node))
.toArray()
let style = {
// Prevent the default outline styles.
outline: 'none',
// Preserve adjacent whitespace and new lines.
whiteSpace: 'pre-wrap',
// Allow words to break if they are too long.
wordWrap: 'break-word',
// COMPAT: In iOS, a formatting menu with bold, italic and underline
// buttons is shown which causes our internal state to get out of sync in
// weird ways. This hides that. (2016/06/21)
...(readOnly ? {} : { WebkitUserModify: 'read-write-plaintext-only' }),
// Allow for passed-in styles to override anything.
...this.props.style,
}
// COMPAT: In Firefox, spellchecking can remove entire wrapping elements
// including inline ones like `<a>`, which is jarring for the user but also
// causes the DOM to get into an irreconilable state.
const spellCheck = IS_FIREFOX ? false : this.props.spellCheck
return (
<div
key={`slate-content-${this.forces}`}
contentEditable={!readOnly}
suppressContentEditableWarning
className={className}
onBeforeInput={this.onBeforeInput}
onBlur={this.onBlur}
onCompositionEnd={this.onCompositionEnd}
onCompositionStart={this.onCompositionStart}
onCopy={this.onCopy}
onCut={this.onCut}
onDragEnd={this.onDragEnd}
onDragOver={this.onDragOver}
onDragStart={this.onDragStart}
onDrop={this.onDrop}
onInput={this.onInput}
onKeyDown={this.onKeyDown}
onKeyUp={noop}
onPaste={this.onPaste}
onSelect={this.onSelect}
spellCheck={spellCheck}
style={style}
>
{children}
</div>
)
}
/**
* Render a `node`.
*
* @param {Node} node
* @return {Element} element
*/
renderNode = (node) => {
switch (node.kind) {
case 'block':
case 'inline':
return this.renderElement(node)
case 'text':
return this.renderText(node)
}
}
/**
* Render an element `node`.
*
* @param {Node} node
* @return {Element} element
*/
renderElement = (node) => {
const { editor, renderNode, state } = this.props
const Component = renderNode(node)
const children = node.nodes
.map(child => this.renderNode(child))
.toArray()
const attributes = {
'data-key': node.key
}
return (
<Component
attributes={attributes}
key={node.key}
editor={editor}
node={node}
state={state}
>
{children}
</Component>
)
}
/**
* Render a text `node`.
*
* @param {Node} node
* @return {Element} element
*/
renderText = (node) => {
const { editor, renderMark, state } = this.props
return (
<Text
key={node.key}
editor={editor}
node={node}
renderMark={renderMark}
state={state}
/>
)
}
}
/**
* Export.
*/
export default Content