-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
executable file
·575 lines (494 loc) · 15.8 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
import Debug from 'debug'
import React from 'react'
import Types from 'prop-types'
import getWindow from 'get-window'
import logger from 'slate-dev-logger'
import throttle from 'lodash/throttle'
import EVENT_HANDLERS from '../constants/event-handlers'
import Node from './node'
import findDOMRange from '../utils/find-dom-range'
import findRange from '../utils/find-range'
import scrollToSelection from '../utils/scroll-to-selection'
import {
IS_FIREFOX,
IS_IOS,
IS_ANDROID,
SUPPORTED_EVENTS,
} 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 = {
autoCorrect: Types.bool.isRequired,
children: Types.any.isRequired,
className: Types.string,
editor: Types.object.isRequired,
readOnly: Types.bool.isRequired,
role: Types.string,
spellCheck: Types.bool.isRequired,
style: Types.object,
tabIndex: Types.number,
tagName: Types.string,
}
/**
* Default properties.
*
* @type {Object}
*/
static defaultProps = {
style: {},
tagName: 'div',
}
/**
* Constructor.
*
* @param {Object} props
*/
constructor(props) {
super(props)
this.tmp = {}
this.tmp.key = 0
this.tmp.isUpdatingSelection = false
EVENT_HANDLERS.forEach(handler => {
this[handler] = event => {
this.onEvent(handler, event)
}
})
}
/**
* When the editor first mounts in the DOM we need to:
*
* - Add native DOM event listeners.
* - Update the selection, in case it starts focused.
*/
componentDidMount = () => {
const window = getWindow(this.element)
window.document.addEventListener(
'selectionchange',
this.onNativeSelectionChange
)
// COMPAT: Restrict scope of `beforeinput` to mobile.
if ((IS_IOS || IS_ANDROID) && SUPPORTED_EVENTS.beforeinput) {
this.element.addEventListener('beforeinput', this.onNativeBeforeInput)
}
this.updateSelection()
}
/**
* When unmounting, remove DOM event listeners.
*/
componentWillUnmount() {
const window = getWindow(this.element)
if (window) {
window.document.removeEventListener(
'selectionchange',
this.onNativeSelectionChange
)
}
// COMPAT: Restrict scope of `beforeinput` to mobile.
if ((IS_IOS || IS_ANDROID) && SUPPORTED_EVENTS.beforeinput) {
this.element.removeEventListener('beforeinput', this.onNativeBeforeInput)
}
}
/**
* On update, update the selection.
*/
componentDidUpdate = () => {
this.updateSelection()
}
/**
* Update the native DOM selection to reflect the internal model.
*/
updateSelection = () => {
const { editor } = this.props
const { value } = editor
const { selection } = value
const { isBackward } = selection
const window = getWindow(this.element)
const native = window.getSelection()
const { rangeCount, anchorNode } = native
// If both selections are blurred, do nothing.
if (!rangeCount && selection.isBlurred) return
// If the selection has been blurred, but is still inside the editor in the
// DOM, blur it manually.
if (selection.isBlurred) {
if (!this.isInEditor(anchorNode)) return
native.removeAllRanges()
this.element.blur()
debug('updateSelection', { selection, native })
return
}
// If the selection isn't set, do nothing.
if (selection.isUnset) return
// Otherwise, figure out which DOM nodes should be selected...
const current = !!rangeCount && native.getRangeAt(0)
const range = findDOMRange(selection, window)
if (!range) {
logger.error(
'Unable to find a native DOM range from the current selection.',
{ selection }
)
return
}
const { startContainer, startOffset, endContainer, endOffset } = range
// If the new range matches the current selection, there is nothing to fix.
// COMPAT: The native `Range` object always has it's "start" first and "end"
// last in the DOM. It has no concept of "backwards/forwards", so we have
// to check both orientations here. (2017/10/31)
if (current) {
if (
(startContainer == current.startContainer &&
startOffset == current.startOffset &&
endContainer == current.endContainer &&
endOffset == current.endOffset) ||
(startContainer == current.endContainer &&
startOffset == current.endOffset &&
endContainer == current.startContainer &&
endOffset == current.startOffset)
) {
return
}
}
// Otherwise, set the `isUpdatingSelection` flag and update the selection.
this.tmp.isUpdatingSelection = true
native.removeAllRanges()
// COMPAT: IE 11 does not support Selection.setBaseAndExtent
if (native.setBaseAndExtent) {
// COMPAT: Since the DOM range has no concept of backwards/forwards
// we need to check and do the right thing here.
if (isBackward) {
native.setBaseAndExtent(
range.endContainer,
range.endOffset,
range.startContainer,
range.startOffset
)
} else {
native.setBaseAndExtent(
range.startContainer,
range.startOffset,
range.endContainer,
range.endOffset
)
}
} else {
// COMPAT: IE 11 does not support Selection.extend, fallback to addRange
native.addRange(range)
}
// Scroll to the selection, in case it's out of view.
scrollToSelection(native)
// Then unset the `isUpdatingSelection` flag after a delay.
setTimeout(() => {
// COMPAT: In Firefox, it's not enough to create a range, you also need to
// focus the contenteditable element too. (2016/11/16)
if (IS_FIREFOX && this.element) this.element.focus()
this.tmp.isUpdatingSelection = false
})
debug('updateSelection', { selection, native })
}
/**
* The React ref method to set the root content element locally.
*
* @param {Element} element
*/
ref = element => {
this.element = element
}
/**
* Check if an event `target` is fired from within the contenteditable
* element. This should be false for edits happening in non-contenteditable
* children, such as void nodes and other nested Slate editors.
*
* @param {Element} target
* @return {Boolean}
*/
isInEditor = target => {
const { element } = this
// COMPAT: Text nodes don't have `isContentEditable` property. So, when
// `target` is a text node use its parent node for check.
const el = target.nodeType === 3 ? target.parentNode : target
return (
el.isContentEditable &&
(el === element || el.closest('[data-slate-editor]') === element)
)
}
/**
* On `event` with `handler`.
*
* @param {String} handler
* @param {Event} event
*/
onEvent(handler, event) {
debug('onEvent', handler)
// COMPAT: Composition events can change the DOM out of under React, so we
// increment this key to ensure that a full re-render happens. (2017/10/16)
if (handler == 'onCompositionEnd') {
this.tmp.key++
}
// Ignore `onBlur`, `onFocus` and `onSelect` events generated
// programmatically while updating selection.
if (
this.tmp.isUpdatingSelection &&
(handler == 'onSelect' || handler == 'onBlur' || handler == 'onFocus')
) {
return
}
// COMPAT: There are situations where a select event will fire with a new
// native selection that resolves to the same internal position. In those
// cases we don't need to trigger any changes, since our internal model is
// already up to date, but we do want to update the native selection again
// to make sure it is in sync. (2017/10/16)
if (handler == 'onSelect') {
const { editor } = this.props
const { value } = editor
const { selection } = value
const window = getWindow(event.target)
const native = window.getSelection()
const range = findRange(native, value)
if (range && range.equals(selection)) {
this.updateSelection()
return
}
}
// Don't handle drag and drop events coming from embedded editors.
if (
handler == 'onDragEnd' ||
handler == 'onDragEnter' ||
handler == 'onDragExit' ||
handler == 'onDragLeave' ||
handler == 'onDragOver' ||
handler == 'onDragStart' ||
handler == 'onDrop'
) {
const { target } = event
const targetEditorNode = target.closest('[data-slate-editor]')
if (targetEditorNode !== this.element) return
}
// Some events require being in editable in the editor, so if the event
// target isn't, ignore them.
if (
handler == 'onBeforeInput' ||
handler == 'onBlur' ||
handler == 'onCompositionEnd' ||
handler == 'onCompositionStart' ||
handler == 'onCopy' ||
handler == 'onCut' ||
handler == 'onFocus' ||
handler == 'onInput' ||
handler == 'onKeyDown' ||
handler == 'onKeyUp' ||
handler == 'onPaste' ||
handler == 'onSelect'
) {
if (!this.isInEditor(event.target)) return
}
this.props[handler](event)
}
/**
* On a native `beforeinput` event, use the additional range information
* provided by the event to manipulate text exactly as the browser would.
*
* This is currently only used on iOS and Android.
*
* @param {InputEvent} event
*/
onNativeBeforeInput = event => {
if (this.props.readOnly) return
if (!this.isInEditor(event.target)) return
const [targetRange] = event.getTargetRanges()
if (!targetRange) return
const { editor } = this.props
switch (event.inputType) {
case 'deleteContentBackward': {
event.preventDefault()
const range = findRange(targetRange, editor.value)
editor.change(change => change.deleteAtRange(range))
break
}
case 'insertLineBreak': // intentional fallthru
case 'insertParagraph': {
event.preventDefault()
const range = findRange(targetRange, editor.value)
editor.change(change => {
if (change.value.isInVoid) {
change.collapseToStartOfNextText()
} else {
change.splitBlockAtRange(range)
}
})
break
}
case 'insertReplacementText': // intentional fallthru
case 'insertText': {
// `data` should have the text for the `insertText` input type and
// `dataTransfer` should have the text for the `insertReplacementText`
// input type, but Safari uses `insertText` for spell check replacements
// and sets `data` to `null`.
const text =
event.data == null
? event.dataTransfer.getData('text/plain')
: event.data
if (text == null) return
event.preventDefault()
const { value } = editor
const { selection } = value
const range = findRange(targetRange, value)
editor.change(change => {
change.insertTextAtRange(range, text, selection.marks)
// If the text was successfully inserted, and the selection had marks
// on it, unset the selection's marks.
if (selection.marks && value.document != change.value.document) {
change.select({ marks: null })
}
})
break
}
}
}
/**
* On native `selectionchange` event, trigger the `onSelect` handler. This is
* needed to account for React's `onSelect` being non-standard and not firing
* until after a selection has been released. This causes issues in situations
* where another change happens while a selection is being made.
*
* @param {Event} event
*/
onNativeSelectionChange = throttle(event => {
if (this.props.readOnly) return
const window = getWindow(event.target)
const { activeElement } = window.document
if (activeElement !== this.element) return
this.props.onSelect(event)
}, 100)
/**
* Render the editor content.
*
* @return {Element}
*/
render() {
const { props } = this
const { className, readOnly, editor, tabIndex, role, tagName } = props
const { value } = editor
const Container = tagName
const { document, selection } = value
const indexes = document.getSelectionIndexes(selection, selection.isFocused)
const children = document.nodes.toArray().map((child, i) => {
const isSelected = !!indexes && indexes.start <= i && i < indexes.end
return this.renderNode(child, isSelected)
})
const handlers = EVENT_HANDLERS.reduce((obj, handler) => {
obj[handler] = this[handler]
return obj
}, {})
const 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 value 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.
...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 irreconcilable value. (2016/09/01)
const spellCheck = IS_FIREFOX ? false : props.spellCheck
debug('render', { props })
return (
<Container
{...handlers}
data-slate-editor
key={this.tmp.key}
ref={this.ref}
data-key={document.key}
contentEditable={readOnly ? null : true}
suppressContentEditableWarning
className={className}
onBlur={this.onBlur}
onFocus={this.onFocus}
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={this.onKeyUp}
onPaste={this.onPaste}
onSelect={this.onSelect}
autoCorrect={props.autoCorrect ? 'on' : 'off'}
spellCheck={spellCheck}
style={style}
role={readOnly ? null : role || 'textbox'}
tabIndex={tabIndex}
// COMPAT: The Grammarly Chrome extension works by changing the DOM out
// from under `contenteditable` elements, which leads to weird behaviors
// so we have to disable it like this. (2017/04/24)
data-gramm={false}
>
{children}
{this.props.children}
</Container>
)
}
/**
* Render a `child` node of the document.
*
* @param {Node} child
* @param {Boolean} isSelected
* @return {Element}
*/
renderNode = (child, isSelected) => {
const { editor, readOnly } = this.props
const { value } = editor
const { document, decorations } = value
const { stack } = editor
let decs = document.getDecorations(stack)
if (decorations) decs = decorations.concat(decs)
return (
<Node
block={null}
editor={editor}
decorations={decs}
isSelected={isSelected}
key={child.key}
node={child}
parent={document}
readOnly={readOnly}
/>
)
}
}
/**
* Mix in handler prop types.
*/
EVENT_HANDLERS.forEach(handler => {
Content.propTypes[handler] = Types.func.isRequired
})
/**
* Export.
*
* @type {Component}
*/
export default Content