forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontent.js
More file actions
727 lines (603 loc) · 18.1 KB
/
content.js
File metadata and controls
727 lines (603 loc) · 18.1 KB
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
import Base64 from '../serializers/base-64'
import Debug from 'debug'
import Node from './node'
import OffsetKey from '../utils/offset-key'
import React from 'react'
import ReactDOM from 'react-dom'
import Selection from '../models/selection'
import Transfer from '../utils/transfer'
import TYPES from '../constants/types'
import getWindow from 'get-window'
import keycode from 'keycode'
import noop from '../utils/noop'
import { IS_FIREFOX, IS_MAC } from '../constants/environment'
/**
* Debug.
*
* @type {Function}
*/
const debug = Debug('slate:content')
/**
* 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.isRequired,
onBlur: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
onCopy: React.PropTypes.func.isRequired,
onCut: React.PropTypes.func.isRequired,
onDrop: React.PropTypes.func.isRequired,
onKeyDown: React.PropTypes.func.isRequired,
onPaste: React.PropTypes.func.isRequired,
onSelect: React.PropTypes.func.isRequired,
readOnly: React.PropTypes.bool.isRequired,
schema: React.PropTypes.object,
spellCheck: React.PropTypes.bool.isRequired,
state: React.PropTypes.object.isRequired,
style: React.PropTypes.object
};
/**
* Default properties.
*
* @type {Object}
*/
static defaultProps = {
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) => {
// If the readOnly state has changed, we need to re-render so that
// the cursor will be added or removed again.
if (props.readOnly != this.props.readOnly) return true
// If the state has been transformed natively, never re-render, or else we
// will end up duplicating content.
if (props.state.isNative) return false
return (
props.className != this.props.className ||
props.schema != this.props.schema ||
props.spellCheck != this.props.spellCheck ||
props.state != this.props.state ||
props.style != this.props.style
)
}
/**
* 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 and
* clean up the DOM's activeElement if neccessary.
*
* @param {Object} prevProps
* @param {Object} prevState
*/
componentDidUpdate = (prevProps, prevState) => {
setTimeout(() => {
this.tmp.isRendering = false
}, 1)
// If the state is blurred now, but was focused before, and the DOM still
// has a node inside the editor selected, we need to blur it.
if (this.props.state.isBlurred && prevProps.state.isFocused) {
const el = ReactDOM.findDOMNode(this)
const window = getWindow(el)
const native = window.getSelection()
if (!el.contains(native.anchorNode)) return
native.removeAllRanges()
el.blur()
}
}
/**
* Get a point from a native selection's DOM `element` and `offset`.
*
* @param {Element} element
* @param {Number} offset
* @return {Object}
*/
getPoint(element, offset) {
const { state, editor } = this.props
const { document } = state
const schema = editor.getSchema()
const offsetKey = OffsetKey.findKey(element, offset)
const { key } = offsetKey
const node = document.getDescendant(key)
const decorators = document.getDescendantDecorators(key, schema)
const ranges = node.getRanges(decorators)
const point = OffsetKey.findPoint(offsetKey, ranges)
return point
}
/**
* On before input, bubble up.
*
* @param {Event} e
*/
onBeforeInput = (e) => {
if (this.props.readOnly) return
if (isNonEditable(e)) return
const data = {}
debug('onBeforeInput', data)
this.props.onBeforeInput(e, data)
}
/**
* On blur, update the selection to be not focused.
*
* @param {Event} e
*/
onBlur = (e) => {
if (this.props.readOnly) return
if (this.tmp.isCopying) return
if (isNonEditable(e)) return
const data = {}
debug('onBlur', data)
this.props.onBlur(e, data)
}
/**
* On change, bubble up.
*
* @param {State} state
*/
onChange = (state) => {
debug('onChange', state)
this.props.onChange(state)
}
/**
* On composition start, set the `isComposing` flag.
*
* @param {Event} e
*/
onCompositionStart = (e) => {
if (isNonEditable(e)) return
this.tmp.isComposing = true
this.tmp.compositions++
debug('onCompositionStart')
}
/**
* 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) => {
if (isNonEditable(e)) return
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
})
debug('onCompositionEnd')
}
/**
* On copy, defer to `onCutCopy`, then bubble up.
*
* @param {Event} e
*/
onCopy = (e) => {
if (isNonEditable(e)) return
const window = getWindow(e.target)
this.tmp.isCopying = true
window.requestAnimationFrame(() => {
this.tmp.isCopying = false
})
const { state } = this.props
const data = {}
data.type = 'fragment'
data.fragment = state.fragment
debug('onCopy', data)
this.props.onCopy(e, data)
}
/**
* On cut, defer to `onCutCopy`, then bubble up.
*
* @param {Event} e
*/
onCut = (e) => {
if (this.props.readOnly) return
if (isNonEditable(e)) return
const window = getWindow(e.target)
this.tmp.isCopying = true
window.requestAnimationFrame(() => {
this.tmp.isCopying = false
})
const { state } = this.props
const data = {}
data.type = 'fragment'
data.fragment = state.fragment
debug('onCut', data)
this.props.onCut(e, data)
}
/**
* On drag end, unset the `isDragging` flag.
*
* @param {Event} e
*/
onDragEnd = (e) => {
if (isNonEditable(e)) return
this.tmp.isDragging = false
this.tmp.isInternalDrag = null
debug('onDragEnd')
}
/**
* On drag over, set the `isDragging` flag and the `isInternalDrag` flag.
*
* @param {Event} e
*/
onDragOver = (e) => {
if (isNonEditable(e)) return
const { dataTransfer } = e.nativeEvent
const transfer = new Transfer(dataTransfer)
// Prevent default when nodes are dragged to allow dropping.
if (transfer.getType() == 'node') {
e.preventDefault()
}
if (this.tmp.isDragging) return
this.tmp.isDragging = true
this.tmp.isInternalDrag = false
debug('onDragOver')
}
/**
* On drag start, set the `isDragging` flag and the `isInternalDrag` flag.
*
* @param {Event} e
*/
onDragStart = (e) => {
if (isNonEditable(e)) return
this.tmp.isDragging = true
this.tmp.isInternalDrag = true
const { dataTransfer } = e.nativeEvent
const transfer = new Transfer(dataTransfer)
// If it's a node being dragged, the data type is already set.
if (transfer.getType() == 'node') return
const { state } = this.props
const { fragment } = state
const encoded = Base64.serializeNode(fragment)
dataTransfer.setData(TYPES.FRAGMENT, encoded)
debug('onDragStart')
}
/**
* On drop.
*
* @param {Event} e
*/
onDrop = (e) => {
if (this.props.readOnly) return
if (isNonEditable(e)) return
e.preventDefault()
const window = getWindow(e.target)
const { state } = this.props
const { dataTransfer, x, y } = e.nativeEvent
const transfer = new Transfer(dataTransfer)
const data = transfer.getData()
// Resolve the point where the drop occured.
let range
// COMPAT: In Firefox, `caretRangeFromPoint` doesn't exist. (2016/07/25)
if (window.document.caretRangeFromPoint) {
range = window.document.caretRangeFromPoint(x, y)
} else {
range = window.document.createRange()
range.setStart(e.nativeEvent.rangeParent, e.nativeEvent.rangeOffset)
}
const startNode = range.startContainer
const startOffset = range.startOffset
const point = this.getPoint(startNode, startOffset)
const 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
// Add drop-specific information to the data.
data.target = target
data.effect = dataTransfer.dropEffect
if (data.type == 'fragment' || data.type == 'node') {
data.isInternal = this.tmp.isInternalDrag
}
debug('onDrop', data)
this.props.onDrop(e, data)
}
/**
* 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) => {
if (this.tmp.isRendering) return
if (this.tmp.isComposing) return
if (this.props.state.isBlurred) return
if (isNonEditable(e)) return
debug('onInput')
const window = getWindow(e.target)
// Get the selection point.
const native = window.getSelection()
const { anchorNode, anchorOffset } = native
const point = this.getPoint(anchorNode, anchorOffset)
const { key, index, start, end } = point
// Get the range in question.
const { state, editor } = this.props
const { document, selection } = state
const schema = editor.getSchema()
const decorators = document.getDescendantDecorators(key, schema)
const node = document.getDescendant(key)
const ranges = node.getRanges(decorators)
const range = ranges.get(index)
// Get the text information.
const isLast = index == ranges.size - 1
const { text, marks } = range
let { textContent } = anchorNode
const lastChar = textContent.charAt(textContent.length - 1)
// If we're dealing with the last leaf, and the DOM text ends in a new line,
// we will have added another new line in <Leaf>'s render method to account
// for browsers collapsing a single trailing new lines, so remove it.
if (isLast && lastChar == '\n') {
textContent = textContent.slice(0, -1)
}
// 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.
const next = state
.transform()
.moveTo({
anchorKey: key,
anchorOffset: start,
focusKey: key,
focusOffset: end
})
.delete()
.insertText(textContent, marks)
.moveTo(after)
.apply()
// Change the current state.
this.onChange(next)
}
/**
* 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
if (isNonEditable(e)) return
const key = keycode(e.which)
const data = {}
// When composing, these characters commit the composition but also move the
// selection before we're able to handle it, so prevent their default,
// selection-moving behavior.
if (
this.tmp.isComposing &&
(key == 'left' || key == 'right' || key == 'up' || key == 'down')
) {
e.preventDefault()
return
}
// Add helpful properties for handling hotkeys to the data object.
data.code = e.which
data.key = key
data.isAlt = e.altKey
data.isCmd = IS_MAC ? e.metaKey && !e.altKey : false
data.isCtrl = e.ctrlKey && !e.altKey
data.isLine = IS_MAC ? e.metaKey : false
data.isMeta = e.metaKey
data.isMod = IS_MAC ? e.metaKey && !e.altKey : e.ctrlKey && !e.altKey
data.isModAlt = IS_MAC ? e.metaKey && e.altKey : e.ctrlKey && e.altKey
data.isShift = e.shiftKey
data.isWord = IS_MAC ? e.altKey : e.ctrlKey
// These key commands have native behavior in contenteditable elements which
// will cause our state to be out of sync, so prevent them.
if (
(key == 'enter') ||
(key == 'backspace') ||
(key == 'delete') ||
(key == 'b' && data.isMod) ||
(key == 'i' && data.isMod) ||
(key == 'y' && data.isMod) ||
(key == 'z' && data.isMod)
) {
e.preventDefault()
}
debug('onKeyDown', data)
this.props.onKeyDown(e, data)
}
/**
* On paste, determine the type and bubble up.
*
* @param {Event} e
*/
onPaste = (e) => {
if (this.props.readOnly) return
if (isNonEditable(e)) return
e.preventDefault()
const transfer = new Transfer(e.clipboardData)
const data = transfer.getData()
debug('onPaste', data)
this.props.onPaste(e, data)
}
/**
* 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
if (isNonEditable(e)) return
const window = getWindow(e.target)
const { state } = this.props
let { document, selection } = state
const native = window.getSelection()
const data = {}
// If there are no ranges, the editor was blurred natively.
if (!native.rangeCount) {
data.selection = selection.merge({ isFocused: false })
data.isNative = true
}
// Otherwise, determine the Slate selection from the native one.
else {
const { anchorNode, anchorOffset, focusNode, focusOffset } = native
const anchor = this.getPoint(anchorNode, anchorOffset)
const focus = this.getPoint(focusNode, focusOffset)
// There are valid situations where a select event will fire when we're
// already at that position (for example when entering a character), since
// our `insertText` transform already updates the selection. In those
// cases we can safely ignore the event.
if (
anchor.key == selection.anchorKey &&
anchor.offset == selection.anchorOffset &&
focus.key == selection.focusKey &&
focus.offset == selection.focusOffset &&
selection.isFocused
) {
return
}
const properties = {
anchorKey: anchor.key,
anchorOffset: anchor.offset,
focusKey: focus.key,
focusOffset: focus.offset,
isFocused: true,
isBackward: null
}
data.selection = selection
.merge(properties)
.normalize(document)
}
debug('onSelect', { data, selection: data.selection.toJS() })
this.props.onSelect(e, data)
}
/**
* Render the editor content.
*
* @return {Element} element
*/
render = () => {
debug('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={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) => {
const { editor, schema, state } = this.props
return (
<Node
key={node.key}
node={node}
parent={state.document}
schema={schema}
state={state}
editor={editor}
/>
)
}
}
/**
* Check if an `event` is being fired from inside a non-contentediable child
* element, in which case we'll want to ignore it.
*
* @param {Event} event
* @return {Boolean}
*/
function isNonEditable(event) {
const { target } = event
return !target.isContentEditable
}
/**
* Export.
*/
export default Content