forked from steemit/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
782 lines (654 loc) · 17.8 KB
/
core.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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
import Base64 from '../serializers/base-64'
import Character from '../models/character'
import Debug from 'debug'
import Placeholder from '../components/placeholder'
import React from 'react'
import String from '../utils/string'
import getWindow from 'get-window'
import { IS_MAC } from '../constants/environment'
/**
* Debug.
*
* @type {Function}
*/
const debug = Debug('slate:core')
/**
* The default plugin.
*
* @param {Object} options
* @property {Element} placeholder
* @property {String} placeholderClassName
* @property {Object} placeholderStyle
* @return {Object}
*/
function Plugin(options = {}) {
const {
placeholder,
placeholderClassName,
placeholderStyle,
} = options
/**
* On before change, enforce the editor's schema.
*
* @param {State} state
* @param {Editor} schema
* @return {State}
*/
function onBeforeChange(state, editor) {
// Don't normalize with plugins schema when typing text in native mode
if (state.isNative) return state
const schema = editor.getSchema()
const { state: prevState } = editor.state
// Since schema can only normalize the document, we avoid creating
// a transform and normalize the selection if the document is the same
if (prevState && state.document == prevState.document) return state
const newState = state.transform()
.normalizeWith(schema)
.apply({ save: false })
return newState
}
/**
* On before input, see if we can let the browser continue with it's native
* input behavior, to avoid a re-render for performance.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @param {Editor} editor
* @return {State}
*/
function onBeforeInput(e, data, state, editor) {
const { document, startKey, startOffset, startInline, startText } = state
// Determine what the characters would be if natively inserted.
const schema = editor.getSchema()
const decorators = document.getDescendantDecorators(startKey, schema)
const initialChars = startText.getDecorations(decorators)
const prevChar = startOffset === 0 ? null : initialChars.get(startOffset - 1)
const nextChar = startOffset === initialChars.size ? null : initialChars.get(startOffset)
const char = Character.create({
text: e.data,
marks: (prevChar && prevChar.marks)
// When cursor is at start of a range of marks, without
// preceding text, the native behavior is to insert inside the
// range of marks.
|| (!prevChar && nextChar && nextChar.marks)
})
const chars = initialChars.insert(startOffset, char)
// Determine what the characters should be, if not natively inserted.
let next = state
.transform()
.insertText(e.data)
.apply()
const nextText = next.startText
const nextChars = nextText.getDecorations(decorators)
// We do not have to re-render if the current selection is collapsed, the
// current node is not empty, there are no marks on the cursor, the cursor
// is not at the edge of an inline node, and the natively inserted
// characters would be the same as the non-native.
const isNative = (
(state.isCollapsed) &&
(state.startText.text != '') &&
(state.selection.marks == null) &&
// Must not be, for example, at edge of an inline link
(!startInline || !state.selection.isAtStartOf(startInline)) &&
(!startInline || !state.selection.isAtEndOf(startInline)) &&
(chars.equals(nextChars))
)
// Add the `isNative` flag directly, so we don't have to re-transform.
if (isNative) {
next = next.merge({ isNative })
}
// If not native, prevent default so that the DOM remains untouched.
if (!isNative) e.preventDefault()
debug('onBeforeInput', { data, isNative })
return next
}
/**
* On blur.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onBlur(e, data, state) {
const isNative = true
debug('onBlur', { data, isNative })
return state
.transform()
.blur()
.apply({ isNative })
}
/**
* On copy.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onCopy(e, data, state) {
debug('onCopy', data)
onCutOrCopy(e, data, state)
}
/**
* On cut.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @param {Editor} editor
* @return {State}
*/
function onCut(e, data, state, editor) {
debug('onCut', data)
onCutOrCopy(e, data, state)
const window = getWindow(e.target)
// Once the fake cut content has successfully been added to the clipboard,
// delete the content in the current selection.
window.requestAnimationFrame(() => {
const next = editor
.getState()
.transform()
.delete()
.apply()
editor.onChange(next)
})
}
/**
* On cut or copy, create a fake selection so that we can add a Base 64
* encoded copy of the fragment to the HTML, to decode on future pastes.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onCutOrCopy(e, data, state) {
const window = getWindow(e.target)
const native = window.getSelection()
if (!native.rangeCount) return
const { fragment } = data
const encoded = Base64.serializeNode(fragment)
const range = native.getRangeAt(0)
const contents = range.cloneContents()
// Remove any zero-width space spans from the cloned DOM so that they don't
// show up elsewhere when copied.
const zws = [].slice.call(contents.querySelectorAll('.slate-zero-width-space'))
zws.forEach(zw => zw.parentNode.removeChild(zw))
// 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 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-slate-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)
// COMPAT: In Firefox, trying to use the terser `native.selectAllChildren`
// throws an error, so we use the older `range` equivalent. (2016/06/21)
const r = window.document.createRange()
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)
})
}
/**
* On drop.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onDrop(e, data, state) {
debug('onDrop', { data })
switch (data.type) {
case 'text':
case 'html':
return onDropText(e, data, state)
case 'fragment':
return onDropFragment(e, data, state)
}
}
/**
* On drop fragment.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onDropFragment(e, data, state) {
debug('onDropFragment', { data })
const { selection } = state
let { fragment, target, isInternal } = data
// If the drag is internal and the target is after the selection, it
// needs to account for the selection's content being deleted.
if (
isInternal &&
selection.endKey == target.endKey &&
selection.endOffset < target.endOffset
) {
target = target.moveBackward(selection.startKey == selection.endKey
? selection.endOffset - selection.startOffset
: selection.endOffset)
}
let transform = state.transform()
if (isInternal) transform.delete()
return transform
.moveTo(target)
.insertFragment(fragment)
.apply()
}
/**
* On drop text, split the blocks at new lines.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onDropText(e, data, state) {
debug('onDropText', { data })
const { text, target } = data
let transform = state
.transform()
.moveTo(target)
text
.split('\n')
.forEach((line, i) => {
if (i > 0) transform.splitBlock()
transform.insertText(line)
})
return transform.apply()
}
/**
* On key down.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDown(e, data, state) {
debug('onKeyDown', { data })
switch (data.key) {
case 'enter': return onKeyDownEnter(e, data, state)
case 'backspace': return onKeyDownBackspace(e, data, state)
case 'delete': return onKeyDownDelete(e, data, state)
case 'left': return onKeyDownLeft(e, data, state)
case 'right': return onKeyDownRight(e, data, state)
case 'y': return onKeyDownY(e, data, state)
case 'z': return onKeyDownZ(e, data, state)
case 'k': return onKeyDownK(e, data, state)
}
}
/**
* On `enter` key down, split the current block in half.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownEnter(e, data, state) {
debug('onKeyDownEnter', { data })
const { document, startKey, startBlock } = state
// For void blocks, we don't want to split. Instead we just move to the
// start of the next text node if one exists.
if (startBlock && startBlock.isVoid) {
const text = document.getNextText(startKey)
if (!text) return
return state
.transform()
.collapseToStartOf(text)
.apply()
}
return state
.transform()
.splitBlock()
.apply()
}
/**
* On `backspace` key down, delete backwards.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownBackspace(e, data, state) {
debug('onKeyDownBackspace', { data })
// If expanded, delete regularly.
if (state.isExpanded) {
return state
.transform()
.delete()
.apply()
}
const { startOffset, startBlock } = state
const text = startBlock.text
let n
// Determine how far backwards to delete.
if (data.isWord) {
n = String.getWordOffsetBackward(text, startOffset)
}
else if (data.isLine) {
n = startOffset
}
else {
n = String.getCharOffsetBackward(text, startOffset)
}
return state
.transform()
.deleteBackward(n)
.apply()
}
/**
* On `delete` key down, delete forwards.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownDelete(e, data, state) {
debug('onKeyDownDelete', { data })
// If expanded, delete regularly.
if (state.isExpanded) {
return state
.transform()
.delete()
.apply()
}
const { startOffset, startBlock } = state
const text = startBlock.text
let n
// Determine how far forwards to delete.
if (data.isWord) {
n = String.getWordOffsetForward(text, startOffset)
}
else if (data.isLine) {
n = text.length - startOffset
}
else {
n = String.getCharOffsetForward(text, startOffset)
}
return state
.transform()
.deleteForward(n)
.apply()
}
/**
* On `left` key down, move backward.
*
* COMPAT: This is required to solve for the case where an inline void node is
* surrounded by empty text nodes with zero-width spaces in them. Without this
* the zero-width spaces will cause two arrow keys to jump to the next text.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownLeft(e, data, state) {
if (data.isCtrl) return
if (data.isOpt) return
if (state.isExpanded) return
const { document, startText } = state
const hasVoidParent = document.hasVoidParent(startText.key)
if (
startText.text == '' ||
hasVoidParent
) {
const previousText = document.getPreviousText(startText.key)
if (!previousText) return
debug('onKeyDownLeft', { data })
e.preventDefault()
return state
.transform()
.collapseToEndOf(previousText)
.apply()
}
}
/**
* On `right` key down, move forward.
*
* COMPAT: This is required to solve for the case where an inline void node is
* surrounded by empty text nodes with zero-width spaces in them. Without this
* the zero-width spaces will cause two arrow keys to jump to the next text.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownRight(e, data, state) {
if (data.isCtrl) return
if (data.isOpt) return
if (state.isExpanded) return
const { document, startText } = state
const hasVoidParent = document.hasVoidParent(startText)
if (
startText.text == '' ||
hasVoidParent
) {
const nextText = document.getNextText(startText)
if (!nextText) return state
debug('onKeyDownRight', { data })
e.preventDefault()
return state
.transform()
.collapseToStartOf(nextText)
.apply()
}
}
/**
* On `y` key down, redo.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownY(e, data, state) {
if (!data.isMod) return
debug('onKeyDownY', { data })
return state
.transform()
.redo()
.apply({ save: false })
}
/**
* On `z` key down, undo or redo.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownZ(e, data, state) {
if (!data.isMod) return
debug('onKeyDownZ', { data })
return state
.transform()
[data.isShift ? 'redo' : 'undo']()
.apply({ save: false })
}
/**
* On `k` key down, delete untill the end of the line (mac only)
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onKeyDownK(e, data, state) {
if (!IS_MAC || !data.isCtrl) return
debug('onKeyDownK', { data })
const { startOffset, startBlock } = state
return state
.transform()
.deleteForward(startBlock.text.length - startOffset)
.apply()
}
/**
* On paste.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onPaste(e, data, state) {
debug('onPaste', { data })
switch (data.type) {
case 'fragment':
return onPasteFragment(e, data, state)
case 'text':
case 'html':
return onPasteText(e, data, state)
}
}
/**
* On paste fragment.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onPasteFragment(e, data, state) {
debug('onPasteFragment', { data })
return state
.transform()
.insertFragment(data.fragment)
.apply()
}
/**
* On paste text, split blocks at new lines.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onPasteText(e, data, state) {
debug('onPasteText', { data })
let transform = state.transform()
data.text
.split('\n')
.forEach((line, i) => {
if (i > 0) transform.splitBlock()
transform.insertText(line)
})
return transform.apply()
}
/**
* On select.
*
* @param {Event} e
* @param {Object} data
* @param {State} state
* @return {State}
*/
function onSelect(e, data, state) {
const { selection } = data
debug('onSelect', { data, selection: selection.toJS() })
return state
.transform()
.moveTo(selection)
// Since the document has not changed, We only normalize the selection
// This is done in transform.apply
.apply()
}
/**
* Extend core schema with rendering
*/
/**
* A default schema rule to render block nodes.
*
* @type {Object}
*/
const BLOCK_RENDER_RULE = {
match: (node) => {
return node.kind == 'block'
},
render: (props) => {
return (
<div {...props.attributes} style={{ position: 'relative' }}>
{props.children}
{placeholder
? <Placeholder
className={placeholderClassName}
node={props.node}
parent={props.state.document}
state={props.state}
style={placeholderStyle}
>
{placeholder}
</Placeholder>
: null}
</div>
)
}
}
/**
* A default schema rule to render inline nodes.
*
* @type {Object}
*/
const INLINE_RENDER_RULE = {
match: (node) => {
return node.kind == 'inline'
},
render: (props) => {
return (
<span {...props.attributes} style={{ position: 'relative' }}>
{props.children}
</span>
)
}
}
const schema = {
rules: [
BLOCK_RENDER_RULE,
INLINE_RENDER_RULE
]
}
/**
* Return the core plugin.
*/
return {
onBeforeChange,
onBeforeInput,
onBlur,
onCopy,
onCut,
onDrop,
onKeyDown,
onPaste,
onSelect,
schema,
}
}
/**
* Export.
*/
export default Plugin