forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
editable.tsx
1949 lines (1715 loc) · 71 KB
/
editable.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
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import getDirection from 'direction'
import debounce from 'lodash/debounce'
import throttle from 'lodash/throttle'
import React, {
useCallback,
useEffect,
useMemo,
useReducer,
useRef,
useState,
forwardRef,
ForwardedRef,
} from 'react'
import { JSX } from 'react'
import scrollIntoView from 'scroll-into-view-if-needed'
import {
Editor,
Element,
Node,
NodeEntry,
Path,
Range,
Text,
Transforms,
} from 'slate'
import { useAndroidInputManager } from '../hooks/android-input-manager/use-android-input-manager'
import useChildren from '../hooks/use-children'
import { DecorateContext } from '../hooks/use-decorate'
import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'
import { ReadOnlyContext } from '../hooks/use-read-only'
import { useSlate } from '../hooks/use-slate'
import { useTrackUserInput } from '../hooks/use-track-user-input'
import { ReactEditor } from '../plugin/react-editor'
import { TRIPLE_CLICK } from '../utils/constants'
import {
DOMElement,
DOMRange,
DOMText,
getActiveElement,
getDefaultView,
getSelection,
isDOMElement,
isDOMNode,
isPlainTextOnlyPaste,
} from '../utils/dom'
import {
CAN_USE_DOM,
HAS_BEFORE_INPUT_SUPPORT,
IS_ANDROID,
IS_CHROME,
IS_FIREFOX,
IS_FIREFOX_LEGACY,
IS_IOS,
IS_WEBKIT,
IS_UC_MOBILE,
IS_WECHATBROWSER,
} from '../utils/environment'
import Hotkeys from '../utils/hotkeys'
import {
EDITOR_TO_ELEMENT,
EDITOR_TO_FORCE_RENDER,
EDITOR_TO_PENDING_INSERTION_MARKS,
EDITOR_TO_USER_MARKS,
EDITOR_TO_USER_SELECTION,
EDITOR_TO_WINDOW,
ELEMENT_TO_NODE,
IS_COMPOSING,
IS_FOCUSED,
IS_READ_ONLY,
MARK_PLACEHOLDER_SYMBOL,
NODE_TO_ELEMENT,
PLACEHOLDER_SYMBOL,
} from '../utils/weak-maps'
import { RestoreDOM } from './restore-dom/restore-dom'
import { AndroidInputManager } from '../hooks/android-input-manager/android-input-manager'
import { ComposingContext } from '../hooks/use-composing'
type DeferredOperation = () => void
const Children = (props: Parameters<typeof useChildren>[0]) => (
<React.Fragment>{useChildren(props)}</React.Fragment>
)
/**
* `RenderElementProps` are passed to the `renderElement` handler.
*/
export interface RenderElementProps {
children: any
element: Element
attributes: {
'data-slate-node': 'element'
'data-slate-inline'?: true
'data-slate-void'?: true
dir?: 'rtl'
ref: any
}
}
/**
* `RenderLeafProps` are passed to the `renderLeaf` handler.
*/
export interface RenderLeafProps {
children: any
leaf: Text
text: Text
attributes: {
'data-slate-leaf': true
}
}
/**
* `EditableProps` are passed to the `<Editable>` component.
*/
export type EditableProps = {
decorate?: (entry: NodeEntry) => Range[]
onDOMBeforeInput?: (event: InputEvent) => void
placeholder?: string
readOnly?: boolean
role?: string
style?: React.CSSProperties
renderElement?: (props: RenderElementProps) => JSX.Element
renderLeaf?: (props: RenderLeafProps) => JSX.Element
renderPlaceholder?: (props: RenderPlaceholderProps) => JSX.Element
scrollSelectionIntoView?: (editor: ReactEditor, domRange: DOMRange) => void
as?: React.ElementType
disableDefaultStyles?: boolean
} & React.TextareaHTMLAttributes<HTMLDivElement>
/**
* Editable.
*/
export const Editable = forwardRef(
(props: EditableProps, forwardedRef: ForwardedRef<HTMLDivElement>) => {
const defaultRenderPlaceholder = useCallback(
(props: RenderPlaceholderProps) => <DefaultPlaceholder {...props} />,
[]
)
const {
autoFocus,
decorate = defaultDecorate,
onDOMBeforeInput: propsOnDOMBeforeInput,
placeholder,
readOnly = false,
renderElement,
renderLeaf,
renderPlaceholder = defaultRenderPlaceholder,
scrollSelectionIntoView = defaultScrollSelectionIntoView,
style: userStyle = {},
as: Component = 'div',
disableDefaultStyles = false,
...attributes
} = props
const editor = useSlate()
// Rerender editor when composition status changed
const [isComposing, setIsComposing] = useState(false)
const ref = useRef<HTMLDivElement | null>(null)
const deferredOperations = useRef<DeferredOperation[]>([])
const [placeholderHeight, setPlaceholderHeight] = useState<
number | undefined
>()
const processing = useRef(false)
const { onUserInput, receivedUserInput } = useTrackUserInput()
const [, forceRender] = useReducer(s => s + 1, 0)
EDITOR_TO_FORCE_RENDER.set(editor, forceRender)
// Update internal state on each render.
IS_READ_ONLY.set(editor, readOnly)
// Keep track of some state for the event handler logic.
const state = useMemo(
() => ({
isDraggingInternally: false,
isUpdatingSelection: false,
latestElement: null as DOMElement | null,
hasMarkPlaceholder: false,
}),
[]
)
// The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it
// needs to be manually focused.
useEffect(() => {
if (ref.current && autoFocus) {
ref.current.focus()
}
}, [autoFocus])
/**
* The AndroidInputManager object has a cyclical dependency on onDOMSelectionChange
*
* It is defined as a reference to simplify hook dependencies and clarify that
* it needs to be initialized.
*/
const androidInputManagerRef = useRef<
AndroidInputManager | null | undefined
>()
// Listen on the native `selectionchange` event to be able to update any time
// the selection changes. This is required because React's `onSelect` is leaky
// and non-standard so it doesn't fire until after a selection has been
// released. This causes issues in situations where another change happens
// while a selection is being dragged.
const onDOMSelectionChange = useMemo(
() =>
throttle(() => {
const el = ReactEditor.toDOMNode(editor, editor)
const root = el.getRootNode()
if (!processing.current && IS_WEBKIT && root instanceof ShadowRoot) {
processing.current = true
const active = getActiveElement()
if (active) {
document.execCommand('indent')
} else {
Transforms.deselect(editor)
}
processing.current = false
return
}
const androidInputManager = androidInputManagerRef.current
if (
(IS_ANDROID || !ReactEditor.isComposing(editor)) &&
(!state.isUpdatingSelection || androidInputManager?.isFlushing()) &&
!state.isDraggingInternally
) {
const root = ReactEditor.findDocumentOrShadowRoot(editor)
const { activeElement } = root
const el = ReactEditor.toDOMNode(editor, editor)
const domSelection = getSelection(root)
if (activeElement === el) {
state.latestElement = activeElement
IS_FOCUSED.set(editor, true)
} else {
IS_FOCUSED.delete(editor)
}
if (!domSelection) {
return Transforms.deselect(editor)
}
const { anchorNode, focusNode } = domSelection
const anchorNodeSelectable =
ReactEditor.hasEditableTarget(editor, anchorNode) ||
ReactEditor.isTargetInsideNonReadonlyVoid(editor, anchorNode)
const focusNodeInEditor = ReactEditor.hasTarget(editor, focusNode)
if (anchorNodeSelectable && focusNodeInEditor) {
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true,
})
if (range) {
if (
!ReactEditor.isComposing(editor) &&
!androidInputManager?.hasPendingChanges() &&
!androidInputManager?.isFlushing()
) {
Transforms.select(editor, range)
} else {
androidInputManager?.handleUserSelect(range)
}
}
}
// Deselect the editor if the dom selection is not selectable in readonly mode
if (readOnly && (!anchorNodeSelectable || !focusNodeInEditor)) {
Transforms.deselect(editor)
}
}
}, 100),
[editor, readOnly, state]
)
const scheduleOnDOMSelectionChange = useMemo(
() => debounce(onDOMSelectionChange, 0),
[onDOMSelectionChange]
)
androidInputManagerRef.current = useAndroidInputManager({
node: ref,
onDOMSelectionChange,
scheduleOnDOMSelectionChange,
})
useIsomorphicLayoutEffect(() => {
// Update element-related weak maps with the DOM element ref.
let window
if (ref.current && (window = getDefaultView(ref.current))) {
EDITOR_TO_WINDOW.set(editor, window)
EDITOR_TO_ELEMENT.set(editor, ref.current)
NODE_TO_ELEMENT.set(editor, ref.current)
ELEMENT_TO_NODE.set(ref.current, editor)
} else {
NODE_TO_ELEMENT.delete(editor)
}
// Make sure the DOM selection state is in sync.
const { selection } = editor
const root = ReactEditor.findDocumentOrShadowRoot(editor)
const domSelection = getSelection(root)
if (
!domSelection ||
!ReactEditor.isFocused(editor) ||
androidInputManagerRef.current?.hasPendingAction()
) {
return
}
const setDomSelection = (forceChange?: boolean) => {
const hasDomSelection = domSelection.type !== 'None'
// If the DOM selection is properly unset, we're done.
if (!selection && !hasDomSelection) {
return
}
// Get anchorNode and focusNode
const focusNode = domSelection.focusNode
let anchorNode
// COMPAT: In firefox the normal seletion way does not work
// (https://github.com/ianstormtaylor/slate/pull/5486#issue-1820720223)
if (IS_FIREFOX && domSelection.rangeCount > 1) {
const firstRange = domSelection.getRangeAt(0)
const lastRange = domSelection.getRangeAt(domSelection.rangeCount - 1)
// Right to left
if (firstRange.startContainer === focusNode) {
anchorNode = lastRange.endContainer
} else {
// Left to right
anchorNode = firstRange.startContainer
}
} else {
anchorNode = domSelection.anchorNode
}
// verify that the dom selection is in the editor
const editorElement = EDITOR_TO_ELEMENT.get(editor)!
let hasDomSelectionInEditor = false
if (
editorElement.contains(anchorNode) &&
editorElement.contains(focusNode)
) {
hasDomSelectionInEditor = true
}
// If the DOM selection is in the editor and the editor selection is already correct, we're done.
if (
hasDomSelection &&
hasDomSelectionInEditor &&
selection &&
!forceChange
) {
const slateRange = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: true,
// domSelection is not necessarily a valid Slate range
// (e.g. when clicking on contentEditable:false element)
suppressThrow: true,
})
if (slateRange && Range.equals(slateRange, selection)) {
if (!state.hasMarkPlaceholder) {
return
}
// Ensure selection is inside the mark placeholder
if (
anchorNode?.parentElement?.hasAttribute(
'data-slate-mark-placeholder'
)
) {
return
}
}
}
// when <Editable/> is being controlled through external value
// then its children might just change - DOM responds to it on its own
// but Slate's value is not being updated through any operation
// and thus it doesn't transform selection on its own
if (selection && !ReactEditor.hasRange(editor, selection)) {
editor.selection = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true,
})
return
}
// Otherwise the DOM selection is out of sync, so update it.
state.isUpdatingSelection = true
const newDomRange: DOMRange | null =
selection && ReactEditor.toDOMRange(editor, selection)
if (newDomRange) {
if (ReactEditor.isComposing(editor) && !IS_ANDROID) {
domSelection.collapseToEnd()
} else if (Range.isBackward(selection!)) {
domSelection.setBaseAndExtent(
newDomRange.endContainer,
newDomRange.endOffset,
newDomRange.startContainer,
newDomRange.startOffset
)
} else {
domSelection.setBaseAndExtent(
newDomRange.startContainer,
newDomRange.startOffset,
newDomRange.endContainer,
newDomRange.endOffset
)
}
scrollSelectionIntoView(editor, newDomRange)
} else {
domSelection.removeAllRanges()
}
return newDomRange
}
// In firefox if there is more then 1 range and we call setDomSelection we remove the ability to select more cells in a table
if (domSelection.rangeCount <= 1) {
setDomSelection()
}
const ensureSelection =
androidInputManagerRef.current?.isFlushing() === 'action'
if (!IS_ANDROID || !ensureSelection) {
setTimeout(() => {
state.isUpdatingSelection = false
})
return
}
let timeoutId: ReturnType<typeof setTimeout> | null = null
const animationFrameId = requestAnimationFrame(() => {
if (ensureSelection) {
const ensureDomSelection = (forceChange?: boolean) => {
try {
const el = ReactEditor.toDOMNode(editor, editor)
el.focus()
setDomSelection(forceChange)
} catch (e) {
// Ignore, dom and state might be out of sync
}
}
// Compat: Android IMEs try to force their selection by manually re-applying it even after we set it.
// This essentially would make setting the slate selection during an update meaningless, so we force it
// again here. We can't only do it in the setTimeout after the animation frame since that would cause a
// visible flicker.
ensureDomSelection()
timeoutId = setTimeout(() => {
// COMPAT: While setting the selection in an animation frame visually correctly sets the selection,
// it doesn't update GBoards spellchecker state. We have to manually trigger a selection change after
// the animation frame to ensure it displays the correct state.
ensureDomSelection(true)
state.isUpdatingSelection = false
})
}
})
return () => {
cancelAnimationFrame(animationFrameId)
if (timeoutId) {
clearTimeout(timeoutId)
}
}
})
// Listen on the native `beforeinput` event to get real "Level 2" events. This
// is required because React's `beforeinput` is fake and never really attaches
// to the real event sadly. (2019/11/01)
// https://github.com/facebook/react/issues/11211
const onDOMBeforeInput = useCallback(
(event: InputEvent) => {
const el = ReactEditor.toDOMNode(editor, editor)
const root = el.getRootNode()
if (processing?.current && IS_WEBKIT && root instanceof ShadowRoot) {
const ranges = event.getTargetRanges()
const range = ranges[0]
const newRange = new window.Range()
newRange.setStart(range.startContainer, range.startOffset)
newRange.setEnd(range.endContainer, range.endOffset)
// Translate the DOM Range into a Slate Range
const slateRange = ReactEditor.toSlateRange(editor, newRange, {
exactMatch: false,
suppressThrow: false,
})
Transforms.select(editor, slateRange)
event.preventDefault()
event.stopImmediatePropagation()
return
}
onUserInput()
if (
!readOnly &&
ReactEditor.hasEditableTarget(editor, event.target) &&
!isDOMEventHandled(event, propsOnDOMBeforeInput)
) {
// COMPAT: BeforeInput events aren't cancelable on android, so we have to handle them differently using the android input manager.
if (androidInputManagerRef.current) {
return androidInputManagerRef.current.handleDOMBeforeInput(event)
}
// Some IMEs/Chrome extensions like e.g. Grammarly set the selection immediately before
// triggering a `beforeinput` expecting the change to be applied to the immediately before
// set selection.
scheduleOnDOMSelectionChange.flush()
onDOMSelectionChange.flush()
const { selection } = editor
const { inputType: type } = event
const data = (event as any).dataTransfer || event.data || undefined
const isCompositionChange =
type === 'insertCompositionText' || type === 'deleteCompositionText'
// COMPAT: use composition change events as a hint to where we should insert
// composition text if we aren't composing to work around https://github.com/ianstormtaylor/slate/issues/5038
if (isCompositionChange && ReactEditor.isComposing(editor)) {
return
}
let native = false
if (
type === 'insertText' &&
selection &&
Range.isCollapsed(selection) &&
// Only use native character insertion for single characters a-z or space for now.
// Long-press events (hold a + press 4 = ä) to choose a special character otherwise
// causes duplicate inserts.
event.data &&
event.data.length === 1 &&
/[a-z ]/i.test(event.data) &&
// Chrome has issues correctly editing the start of nodes: https://bugs.chromium.org/p/chromium/issues/detail?id=1249405
// When there is an inline element, e.g. a link, and you select
// right after it (the start of the next node).
selection.anchor.offset !== 0
) {
native = true
// Skip native if there are marks, as
// `insertText` will insert a node, not just text.
if (editor.marks) {
native = false
}
// Chrome also has issues correctly editing the end of anchor elements: https://bugs.chromium.org/p/chromium/issues/detail?id=1259100
// Therefore we don't allow native events to insert text at the end of anchor nodes.
const { anchor } = selection
const [node, offset] = ReactEditor.toDOMPoint(editor, anchor)
const anchorNode = node.parentElement?.closest('a')
const window = ReactEditor.getWindow(editor)
if (
native &&
anchorNode &&
ReactEditor.hasDOMNode(editor, anchorNode)
) {
// Find the last text node inside the anchor.
const lastText = window?.document
.createTreeWalker(anchorNode, NodeFilter.SHOW_TEXT)
.lastChild() as DOMText | null
if (
lastText === node &&
lastText.textContent?.length === offset
) {
native = false
}
}
// Chrome has issues with the presence of tab characters inside elements with whiteSpace = 'pre'
// causing abnormal insert behavior: https://bugs.chromium.org/p/chromium/issues/detail?id=1219139
if (
native &&
node.parentElement &&
window?.getComputedStyle(node.parentElement)?.whiteSpace === 'pre'
) {
const block = Editor.above(editor, {
at: anchor.path,
match: n => Element.isElement(n) && Editor.isBlock(editor, n),
})
if (block && Node.string(block[0]).includes('\t')) {
native = false
}
}
}
// COMPAT: For the deleting forward/backward input types we don't want
// to change the selection because it is the range that will be deleted,
// and those commands determine that for themselves.
if (!type.startsWith('delete') || type.startsWith('deleteBy')) {
const [targetRange] = (event as any).getTargetRanges()
if (targetRange) {
const range = ReactEditor.toSlateRange(editor, targetRange, {
exactMatch: false,
suppressThrow: false,
})
if (!selection || !Range.equals(selection, range)) {
native = false
const selectionRef =
!isCompositionChange &&
editor.selection &&
Editor.rangeRef(editor, editor.selection)
Transforms.select(editor, range)
if (selectionRef) {
EDITOR_TO_USER_SELECTION.set(editor, selectionRef)
}
}
}
}
// Composition change types occur while a user is composing text and can't be
// cancelled. Let them through and wait for the composition to end.
if (isCompositionChange) {
return
}
if (!native) {
event.preventDefault()
}
// COMPAT: If the selection is expanded, even if the command seems like
// a delete forward/backward command it should delete the selection.
if (
selection &&
Range.isExpanded(selection) &&
type.startsWith('delete')
) {
const direction = type.endsWith('Backward') ? 'backward' : 'forward'
Editor.deleteFragment(editor, { direction })
return
}
switch (type) {
case 'deleteByComposition':
case 'deleteByCut':
case 'deleteByDrag': {
Editor.deleteFragment(editor)
break
}
case 'deleteContent':
case 'deleteContentForward': {
Editor.deleteForward(editor)
break
}
case 'deleteContentBackward': {
Editor.deleteBackward(editor)
break
}
case 'deleteEntireSoftLine': {
Editor.deleteBackward(editor, { unit: 'line' })
Editor.deleteForward(editor, { unit: 'line' })
break
}
case 'deleteHardLineBackward': {
Editor.deleteBackward(editor, { unit: 'block' })
break
}
case 'deleteSoftLineBackward': {
Editor.deleteBackward(editor, { unit: 'line' })
break
}
case 'deleteHardLineForward': {
Editor.deleteForward(editor, { unit: 'block' })
break
}
case 'deleteSoftLineForward': {
Editor.deleteForward(editor, { unit: 'line' })
break
}
case 'deleteWordBackward': {
Editor.deleteBackward(editor, { unit: 'word' })
break
}
case 'deleteWordForward': {
Editor.deleteForward(editor, { unit: 'word' })
break
}
case 'insertLineBreak':
Editor.insertSoftBreak(editor)
break
case 'insertParagraph': {
Editor.insertBreak(editor)
break
}
case 'insertFromComposition':
case 'insertFromDrop':
case 'insertFromPaste':
case 'insertFromYank':
case 'insertReplacementText':
case 'insertText': {
if (type === 'insertFromComposition') {
// COMPAT: in Safari, `compositionend` is dispatched after the
// `beforeinput` for "insertFromComposition". But if we wait for it
// then we will abort because we're still composing and the selection
// won't be updated properly.
// https://www.w3.org/TR/input-events-2/
if (ReactEditor.isComposing(editor)) {
setIsComposing(false)
IS_COMPOSING.set(editor, false)
}
}
// use a weak comparison instead of 'instanceof' to allow
// programmatic access of paste events coming from external windows
// like cypress where cy.window does not work realibly
if (data?.constructor.name === 'DataTransfer') {
ReactEditor.insertData(editor, data)
} else if (typeof data === 'string') {
// Only insertText operations use the native functionality, for now.
// Potentially expand to single character deletes, as well.
if (native) {
deferredOperations.current.push(() =>
Editor.insertText(editor, data)
)
} else {
Editor.insertText(editor, data)
}
}
break
}
}
// Restore the actual user section if nothing manually set it.
const toRestore = EDITOR_TO_USER_SELECTION.get(editor)?.unref()
EDITOR_TO_USER_SELECTION.delete(editor)
if (
toRestore &&
(!editor.selection || !Range.equals(editor.selection, toRestore))
) {
Transforms.select(editor, toRestore)
}
}
},
[
editor,
onDOMSelectionChange,
onUserInput,
propsOnDOMBeforeInput,
readOnly,
scheduleOnDOMSelectionChange,
]
)
const callbackRef = useCallback(
(node: HTMLDivElement | null) => {
if (node == null) {
onDOMSelectionChange.cancel()
scheduleOnDOMSelectionChange.cancel()
EDITOR_TO_ELEMENT.delete(editor)
NODE_TO_ELEMENT.delete(editor)
if (ref.current && HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
ref.current.removeEventListener('beforeinput', onDOMBeforeInput)
}
} else {
// Attach a native DOM event handler for `beforeinput` events, because React's
// built-in `onBeforeInput` is actually a leaky polyfill that doesn't expose
// real `beforeinput` events sadly... (2019/11/04)
// https://github.com/facebook/react/issues/11211
if (HAS_BEFORE_INPUT_SUPPORT) {
// @ts-ignore The `beforeinput` event isn't recognized.
node.addEventListener('beforeinput', onDOMBeforeInput)
}
}
ref.current = node
if (typeof forwardedRef === 'function') {
forwardedRef(node)
} else if (forwardedRef) {
forwardedRef.current = node
}
},
[
onDOMSelectionChange,
scheduleOnDOMSelectionChange,
editor,
onDOMBeforeInput,
forwardedRef,
]
)
useIsomorphicLayoutEffect(() => {
const window = ReactEditor.getWindow(editor)
// Attach a native DOM event handler for `selectionchange`, because React's
// built-in `onSelect` handler doesn't fire for all selection changes. It's
// a leaky polyfill that only fires on keypresses or clicks. Instead, we
// want to fire for any change to the selection inside the editor.
// (2019/11/04) https://github.com/facebook/react/issues/5785
window.document.addEventListener(
'selectionchange',
scheduleOnDOMSelectionChange
)
// Listen for dragend and drop globally. In Firefox, if a drop handler
// initiates an operation that causes the originally dragged element to
// unmount, that element will not emit a dragend event. (2024/06/21)
const stoppedDragging = () => {
state.isDraggingInternally = false
}
window.document.addEventListener('dragend', stoppedDragging)
window.document.addEventListener('drop', stoppedDragging)
return () => {
window.document.removeEventListener(
'selectionchange',
scheduleOnDOMSelectionChange
)
window.document.removeEventListener('dragend', stoppedDragging)
window.document.removeEventListener('drop', stoppedDragging)
}
}, [scheduleOnDOMSelectionChange, state])
const decorations = decorate([editor, []])
const showPlaceholder =
placeholder &&
editor.children.length === 1 &&
Array.from(Node.texts(editor)).length === 1 &&
Node.string(editor) === '' &&
!isComposing
const placeHolderResizeHandler = useCallback(
(placeholderEl: HTMLElement | null) => {
if (placeholderEl && showPlaceholder) {
setPlaceholderHeight(placeholderEl.getBoundingClientRect()?.height)
} else {
setPlaceholderHeight(undefined)
}
},
[showPlaceholder]
)
if (showPlaceholder) {
const start = Editor.start(editor, [])
decorations.push({
[PLACEHOLDER_SYMBOL]: true,
placeholder,
onPlaceholderResize: placeHolderResizeHandler,
anchor: start,
focus: start,
})
}
const { marks } = editor
state.hasMarkPlaceholder = false
if (editor.selection && Range.isCollapsed(editor.selection) && marks) {
const { anchor } = editor.selection
const leaf = Node.leaf(editor, anchor.path)
const { text, ...rest } = leaf
// While marks isn't a 'complete' text, we can still use loose Text.equals
// here which only compares marks anyway.
if (!Text.equals(leaf, marks as Text, { loose: true })) {
state.hasMarkPlaceholder = true
const unset = Object.fromEntries(
Object.keys(rest).map(mark => [mark, null])
)
decorations.push({
[MARK_PLACEHOLDER_SYMBOL]: true,
...unset,
...marks,
anchor,
focus: anchor,
})
}
}
// Update EDITOR_TO_MARK_PLACEHOLDER_MARKS in setTimeout useEffect to ensure we don't set it
// before we receive the composition end event.
useEffect(() => {
setTimeout(() => {
const { selection } = editor
if (selection) {
const { anchor } = selection
const text = Node.leaf(editor, anchor.path)
// While marks isn't a 'complete' text, we can still use loose Text.equals
// here which only compares marks anyway.
if (marks && !Text.equals(text, marks as Text, { loose: true })) {
EDITOR_TO_PENDING_INSERTION_MARKS.set(editor, marks)
return
}
}
EDITOR_TO_PENDING_INSERTION_MARKS.delete(editor)
})
})
return (
<ReadOnlyContext.Provider value={readOnly}>
<ComposingContext.Provider value={isComposing}>
<DecorateContext.Provider value={decorate}>
<RestoreDOM node={ref} receivedUserInput={receivedUserInput}>
<Component
role={readOnly ? undefined : 'textbox'}
aria-multiline={readOnly ? undefined : true}
{...attributes}
// COMPAT: Certain browsers don't support the `beforeinput` event, so we'd
// have to use hacks to make these replacement-based features work.
// For SSR situations HAS_BEFORE_INPUT_SUPPORT is false and results in prop
// mismatch warning app moves to browser. Pass-through consumer props when
// not CAN_USE_DOM (SSR) and default to falsy value
spellCheck={
HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM
? attributes.spellCheck
: false
}
autoCorrect={
HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM
? attributes.autoCorrect
: 'false'
}
autoCapitalize={
HAS_BEFORE_INPUT_SUPPORT || !CAN_USE_DOM
? attributes.autoCapitalize
: 'false'
}
data-slate-editor
data-slate-node="value"
// explicitly set this
contentEditable={!readOnly}
// in some cases, a decoration needs access to the range / selection to decorate a text node,
// then you will select the whole text node when you select part the of text
// this magic zIndex="-1" will fix it
zindex={-1}
suppressContentEditableWarning
ref={callbackRef}
style={{
...(disableDefaultStyles
? {}
: {
// Allow positioning relative to the editable element.
position: 'relative',
// Preserve adjacent whitespace and new lines.
whiteSpace: 'pre-wrap',
// Allow words to break if they are too long.
wordWrap: 'break-word',
// Make the minimum height that of the placeholder.
...(placeholderHeight
? { minHeight: placeholderHeight }