-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathinput.ts
896 lines (802 loc) · 33.3 KB
/
input.ts
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
import {EditorSelection, EditorState, SelectionRange, RangeSet, Annotation, Text} from "@codemirror/state"
import {EditorView} from "./editorview"
import {ContentView} from "./contentview"
import {LineView} from "./blockview"
import {ViewUpdate, PluginValue, clickAddsSelectionRange, dragMovesSelection as dragBehavior, atomicRanges,
logException, mouseSelectionStyle, PluginInstance, focusChangeEffect, getScrollMargins} from "./extension"
import browser from "./browser"
import {groupAt, skipAtomicRanges} from "./cursor"
import {getSelection, focusPreventScroll, Rect, dispatchKey, scrollableParent} from "./dom"
// This will also be where dragging info and such goes
export class InputState {
lastKeyCode: number = 0
lastKeyTime: number = 0
lastTouchTime = 0
lastFocusTime = 0
lastScrollTop = 0
lastScrollLeft = 0
// On iOS, some keys need to have their default behavior happen
// (after which we retroactively handle them and reset the DOM) to
// avoid messing up the virtual keyboard state.
pendingIOSKey: undefined | {key: string, keyCode: number} | KeyboardEvent = undefined
lastSelectionOrigin: string | null = null
lastSelectionTime: number = 0
lastEscPress: number = 0
lastContextMenu: number = 0
scrollHandlers: ((event: Event) => boolean | void)[] = []
handlers: {[event: string]: {
observers: readonly HandlerFunction[],
handlers: readonly HandlerFunction[]
}} = Object.create(null)
// -1 means not in a composition. Otherwise, this counts the number
// of changes made during the composition. The count is used to
// avoid treating the start state of the composition, before any
// changes have been made, as part of the composition.
composing = -1
// Tracks whether the next change should be marked as starting the
// composition (null means no composition, true means next is the
// first, false means first has already been marked for this
// composition)
compositionFirstChange: boolean | null = null
// End time of the previous composition
compositionEndedAt = 0
// Used in a kludge to detect when an Enter keypress should be
// considered part of the composition on Safari, which fires events
// in the wrong order
compositionPendingKey = false
// Used to categorize changes as part of a composition, even when
// the mutation events fire shortly after the compositionend event
compositionPendingChange = false
mouseSelection: MouseSelection | null = null
// When a drag from the editor is active, this points at the range
// being dragged.
draggedContent: SelectionRange | null = null
notifiedFocused: boolean
setSelectionOrigin(origin: string) {
this.lastSelectionOrigin = origin
this.lastSelectionTime = Date.now()
}
constructor(readonly view: EditorView) {
this.handleEvent = this.handleEvent.bind(this)
this.notifiedFocused = view.hasFocus
// On Safari adding an input event handler somehow prevents an
// issue where the composition vanishes when you press enter.
if (browser.safari) view.contentDOM.addEventListener("input", () => null)
if (browser.gecko) firefoxCopyCutHack(view.contentDOM.ownerDocument)
}
handleEvent(event: Event) {
if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event)) return
if (event.type == "keydown" && this.keydown(event as KeyboardEvent)) return
this.runHandlers(event.type, event)
}
runHandlers(type: string, event: Event) {
let handlers = this.handlers[type]
if (handlers) {
for (let observer of handlers.observers) observer(this.view, event)
for (let handler of handlers.handlers) {
if (event.defaultPrevented) break
if (handler(this.view, event)) { event.preventDefault(); break }
}
}
}
ensureHandlers(plugins: readonly PluginInstance[]) {
let handlers = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM
for (let type in handlers) if (type != "scroll") {
let passive = !handlers[type].handlers.length
let exists: (typeof prev)["type"] | null = prev[type]
if (exists && passive != !exists.handlers.length) {
dom.removeEventListener(type, this.handleEvent)
exists = null
}
if (!exists) dom.addEventListener(type, this.handleEvent, {passive})
}
for (let type in prev) if (type != "scroll" && !handlers[type])
dom.removeEventListener(type, this.handleEvent)
this.handlers = handlers
}
keydown(event: KeyboardEvent) {
// Must always run, even if a custom handler handled the event
this.lastKeyCode = event.keyCode
this.lastKeyTime = Date.now()
if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2000) return true
if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0) this.view.inputState.lastEscPress = 0
// Chrome for Android usually doesn't fire proper key events, but
// occasionally does, usually surrounded by a bunch of complicated
// composition changes. When an enter or backspace key event is
// seen, hold off on handling DOM events for a bit, and then
// dispatch it.
if (browser.android && browser.chrome && !(event as any).synthetic &&
(event.keyCode == 13 || event.keyCode == 8)) {
this.view.observer.delayAndroidKey(event.key, event.keyCode)
return true
}
// Preventing the default behavior of Enter on iOS makes the
// virtual keyboard get stuck in the wrong (lowercase)
// state. So we let it go through, and then, in
// applyDOMChange, notify key handlers of it and reset to
// the state they produce.
let pending
if (browser.ios && !(event as any).synthetic && !event.altKey && !event.metaKey &&
((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey ||
EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
this.pendingIOSKey = pending || event
setTimeout(() => this.flushIOSKey(), 250)
return true
}
if (event.keyCode != 229) this.view.observer.forceFlush()
return false
}
flushIOSKey(change?: {from: number, to: number, insert: Text}) {
let key = this.pendingIOSKey
if (!key) return false
// This looks like an autocorrection before Enter
if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString())) return false
this.pendingIOSKey = undefined
return dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : undefined)
}
ignoreDuringComposition(event: Event): boolean {
if (!/^key/.test(event.type)) return false
if (this.composing > 0) return true
// See https://www.stum.de/2016/06/24/handling-ime-events-in-javascript/.
// On some input method editors (IMEs), the Enter key is used to
// confirm character selection. On Safari, when Enter is pressed,
// compositionend and keydown events are sometimes emitted in the
// wrong order. The key event should still be ignored, even when
// it happens after the compositionend event.
if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
this.compositionPendingKey = false
return true
}
return false
}
startMouseSelection(mouseSelection: MouseSelection) {
if (this.mouseSelection) this.mouseSelection.destroy()
this.mouseSelection = mouseSelection
}
update(update: ViewUpdate) {
if (this.mouseSelection) this.mouseSelection.update(update)
if (this.draggedContent && update.docChanged) this.draggedContent = this.draggedContent.map(update.changes)
if (update.transactions.length) this.lastKeyCode = this.lastSelectionTime = 0
}
destroy() {
if (this.mouseSelection) this.mouseSelection.destroy()
}
}
type HandlerFunction = (view: EditorView, event: Event) => boolean | void
function bindHandler(
plugin: PluginValue,
handler: (this: PluginValue, event: Event, view: EditorView) => boolean | void
): HandlerFunction {
return (view, event) => {
try {
return handler.call(plugin, event, view)
} catch (e) {
logException(view.state, e)
}
}
}
function computeHandlers(plugins: readonly PluginInstance[]) {
let result: {[event: string]: {
observers: HandlerFunction[],
handlers: HandlerFunction[]
}} = Object.create(null)
function record(type: string) {
return result[type] || (result[type] = {observers: [], handlers: []})
}
for (let plugin of plugins) {
let spec = plugin.spec
if (spec && spec.domEventHandlers) for (let type in spec.domEventHandlers) {
let f = spec.domEventHandlers[type]
if (f) record(type).handlers.push(bindHandler(plugin.value!, f))
}
if (spec && spec.domEventObservers) for (let type in spec.domEventObservers) {
let f = spec.domEventObservers[type]
if (f) record(type).observers.push(bindHandler(plugin.value!, f))
}
}
for (let type in handlers) record(type).handlers.push(handlers[type])
for (let type in observers) record(type).observers.push(observers[type])
return result
}
const PendingKeys = [
{key: "Backspace", keyCode: 8, inputType: "deleteContentBackward"},
{key: "Enter", keyCode: 13, inputType: "insertParagraph"},
{key: "Enter", keyCode: 13, inputType: "insertLineBreak"},
{key: "Delete", keyCode: 46, inputType: "deleteContentForward"}
]
const EmacsyPendingKeys = "dthko"
// Key codes for modifier keys
export const modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225]
const dragScrollMargin = 6
/// Interface that objects registered with
/// [`EditorView.mouseSelectionStyle`](#view.EditorView^mouseSelectionStyle)
/// must conform to.
export interface MouseSelectionStyle {
/// Return a new selection for the mouse gesture that starts with
/// the event that was originally given to the constructor, and ends
/// with the event passed here. In case of a plain click, those may
/// both be the `mousedown` event, in case of a drag gesture, the
/// latest `mousemove` event will be passed.
///
/// When `extend` is true, that means the new selection should, if
/// possible, extend the start selection. If `multiple` is true, the
/// new selection should be added to the original selection.
get: (curEvent: MouseEvent, extend: boolean, multiple: boolean) => EditorSelection
/// Called when the view is updated while the gesture is in
/// progress. When the document changes, it may be necessary to map
/// some data (like the original selection or start position)
/// through the changes.
///
/// This may return `true` to indicate that the `get` method should
/// get queried again after the update, because something in the
/// update could change its result. Be wary of infinite loops when
/// using this (where `get` returns a new selection, which will
/// trigger `update`, which schedules another `get` in response).
update: (update: ViewUpdate) => boolean | void
}
export type MakeSelectionStyle = (view: EditorView, event: MouseEvent) => MouseSelectionStyle | null
function dragScrollSpeed(dist: number) {
return Math.max(0, dist) * 0.7 + 8
}
function dist(a: MouseEvent, b: MouseEvent) {
return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY))
}
class MouseSelection {
dragging: null | boolean
extend: boolean
multiple: boolean
lastEvent: MouseEvent
scrollParent: HTMLElement | null
scrollSpeed = {x: 0, y: 0}
scrolling = -1
atoms: readonly RangeSet<any>[]
constructor(private view: EditorView,
private startEvent: MouseEvent,
private style: MouseSelectionStyle,
private mustSelect: boolean) {
this.lastEvent = startEvent
this.scrollParent = scrollableParent(view.contentDOM)
this.atoms = view.state.facet(atomicRanges).map(f => f(view))
let doc = view.contentDOM.ownerDocument!
doc.addEventListener("mousemove", this.move = this.move.bind(this))
doc.addEventListener("mouseup", this.up = this.up.bind(this))
this.extend = startEvent.shiftKey
this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent)
this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false
}
start(event: MouseEvent) {
// When clicking outside of the selection, immediately apply the
// effect of starting the selection
if (this.dragging === false) this.select(event)
}
move(event: MouseEvent) {
if (event.buttons == 0) return this.destroy()
if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) return
this.select(this.lastEvent = event)
let sx = 0, sy = 0
let rect = this.scrollParent?.getBoundingClientRect()
|| {left: 0, top: 0, right: this.view.win.innerWidth, bottom: this.view.win.innerHeight}
let margins = getScrollMargins(this.view)
if (event.clientX - margins.left <= rect.left + dragScrollMargin)
sx = -dragScrollSpeed(rect.left - event.clientX)
else if (event.clientX + margins.right >= rect.right - dragScrollMargin)
sx = dragScrollSpeed(event.clientX - rect.right)
if (event.clientY - margins.top <= rect.top + dragScrollMargin)
sy = -dragScrollSpeed(rect.top - event.clientY)
else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin)
sy = dragScrollSpeed(event.clientY - rect.bottom)
this.setScrollSpeed(sx, sy)
}
up(event: MouseEvent) {
if (this.dragging == null) this.select(this.lastEvent)
if (!this.dragging) event.preventDefault()
this.destroy()
}
destroy() {
this.setScrollSpeed(0, 0)
let doc = this.view.contentDOM.ownerDocument!
doc.removeEventListener("mousemove", this.move)
doc.removeEventListener("mouseup", this.up)
this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null
}
setScrollSpeed(sx: number, sy: number) {
this.scrollSpeed = {x: sx, y: sy}
if (sx || sy) {
if (this.scrolling < 0) this.scrolling = setInterval(() => this.scroll(), 50)
} else if (this.scrolling > -1) {
clearInterval(this.scrolling)
this.scrolling = -1
}
}
scroll() {
if (this.scrollParent) {
this.scrollParent.scrollLeft += this.scrollSpeed.x
this.scrollParent.scrollTop += this.scrollSpeed.y
} else {
this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y)
}
if (this.dragging === false) this.select(this.lastEvent)
}
skipAtoms(sel: EditorSelection) {
let ranges = null
for (let i = 0; i < sel.ranges.length; i++) {
let range = sel.ranges[i], updated = null
if (range.empty) {
let pos = skipAtomicRanges(this.atoms, range.from, 0)
if (pos != range.from) updated = EditorSelection.cursor(pos, -1)
} else {
let from = skipAtomicRanges(this.atoms, range.from, -1)
let to = skipAtomicRanges(this.atoms, range.to, 1)
if (from != range.from || to != range.to)
updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to)
}
if (updated) {
if (!ranges) ranges = sel.ranges.slice()
ranges[i] = updated
}
}
return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel
}
select(event: MouseEvent) {
let {view} = this, selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple))
if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false))
this.view.dispatch({
selection,
userEvent: "select.pointer"
})
this.mustSelect = false
}
update(update: ViewUpdate) {
if (this.style.update(update)) setTimeout(() => this.select(this.lastEvent), 20)
}
}
function addsSelectionRange(view: EditorView, event: MouseEvent) {
let facet = view.state.facet(clickAddsSelectionRange)
return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey
}
function dragMovesSelection(view: EditorView, event: MouseEvent) {
let facet = view.state.facet(dragBehavior)
return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey
}
function isInPrimarySelection(view: EditorView, event: MouseEvent) {
let {main} = view.state.selection
if (main.empty) return false
// On boundary clicks, check whether the coordinates are inside the
// selection's client rectangles
let sel = getSelection(view.root)
if (!sel || sel.rangeCount == 0) return true
let rects = sel.getRangeAt(0).getClientRects()
for (let i = 0; i < rects.length; i++) {
let rect = rects[i]
if (rect.left <= event.clientX && rect.right >= event.clientX &&
rect.top <= event.clientY && rect.bottom >= event.clientY) return true
}
return false
}
function eventBelongsToEditor(view: EditorView, event: Event): boolean {
if (!event.bubbles) return true
if (event.defaultPrevented) return false
for (let node: Node | null = event.target as Node, cView; node != view.contentDOM; node = node.parentNode)
if (!node || node.nodeType == 11 || ((cView = ContentView.get(node)) && cView.ignoreEvent(event)))
return false
return true
}
const handlers: {[key: string]: (view: EditorView, event: any) => boolean} = Object.create(null)
const observers: {[key: string]: (view: EditorView, event: any) => undefined} = Object.create(null)
// This is very crude, but unfortunately both these browsers _pretend_
// that they have a clipboard API—all the objects and methods are
// there, they just don't work, and they are hard to test.
const brokenClipboardAPI = (browser.ie && browser.ie_version < 15) ||
(browser.ios && browser.webkit_version < 604)
function capturePaste(view: EditorView) {
let parent = view.dom.parentNode
if (!parent) return
let target = parent.appendChild(document.createElement("textarea"))
target.style.cssText = "position: fixed; left: -10000px; top: 10px"
target.focus()
setTimeout(() => {
view.focus()
target.remove()
doPaste(view, target.value)
}, 50)
}
function doPaste(view: EditorView, input: string) {
let {state} = view, changes, i = 1, text = state.toText(input)
let byLine = text.lines == state.selection.ranges.length
let linewise = lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString()
if (linewise) {
let lastLine = -1
changes = state.changeByRange(range => {
let line = state.doc.lineAt(range.from)
if (line.from == lastLine) return {range}
lastLine = line.from
let insert = state.toText((byLine ? text.line(i++).text : input) + state.lineBreak)
return {changes: {from: line.from, insert},
range: EditorSelection.cursor(range.from + insert.length)}
})
} else if (byLine) {
changes = state.changeByRange(range => {
let line = text.line(i++)
return {changes: {from: range.from, to: range.to, insert: line.text},
range: EditorSelection.cursor(range.from + line.length)}
})
} else {
changes = state.replaceSelection(text)
}
view.dispatch(changes, {
userEvent: "input.paste",
scrollIntoView: true
})
}
observers.scroll = view => {
view.inputState.lastScrollTop = view.scrollDOM.scrollTop
view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft
}
handlers.keydown = (view, event: KeyboardEvent) => {
view.inputState.setSelectionOrigin("select")
if (event.keyCode == 27) view.inputState.lastEscPress = Date.now()
return false
}
observers.touchstart = (view, e) => {
view.inputState.lastTouchTime = Date.now()
view.inputState.setSelectionOrigin("select.pointer")
}
observers.touchmove = view => {
view.inputState.setSelectionOrigin("select.pointer")
}
handlers.mousedown = (view, event: MouseEvent) => {
view.observer.flush()
if (view.inputState.lastTouchTime > Date.now() - 2000) return false // Ignore touch interaction
let style: MouseSelectionStyle | null = null
for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
style = makeStyle(view, event)
if (style) break
}
if (!style && event.button == 0) style = basicMouseSelection(view, event)
if (style) {
let mustFocus = !view.hasFocus
view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus))
if (mustFocus) view.observer.ignore(() => focusPreventScroll(view.contentDOM))
let mouseSel = view.inputState.mouseSelection
if (mouseSel) {
mouseSel.start(event)
return mouseSel.dragging === false
}
}
return false
}
function rangeForClick(view: EditorView, pos: number, bias: -1 | 1, type: number): SelectionRange {
if (type == 1) { // Single click
return EditorSelection.cursor(pos, bias)
} else if (type == 2) { // Double click
return groupAt(view.state, pos, bias)
} else { // Triple click
let visual = LineView.find(view.docView, pos), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos)
let from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to
if (to < view.state.doc.length && to == line.to) to++
return EditorSelection.range(from, to)
}
}
let insideY = (y: number, rect: Rect) => y >= rect.top && y <= rect.bottom
let inside = (x: number, y: number, rect: Rect) => insideY(y, rect) && x >= rect.left && x <= rect.right
// Try to determine, for the given coordinates, associated with the
// given position, whether they are related to the element before or
// the element after the position.
function findPositionSide(view: EditorView, pos: number, x: number, y: number) {
let line = LineView.find(view.docView, pos)
if (!line) return 1
let off = pos - line.posAtStart
// Line boundaries point into the line
if (off == 0) return 1
if (off == line.length) return -1
// Positions on top of an element point at that element
let before = line.coordsAt(off, -1)
if (before && inside(x, y, before)) return -1
let after = line.coordsAt(off, 1)
if (after && inside(x, y, after)) return 1
// This is probably a line wrap point. Pick before if the point is
// beside it.
return before && insideY(y, before) ? -1 : 1
}
function queryPos(view: EditorView, event: MouseEvent): {pos: number, bias: 1 | -1} {
let pos = view.posAtCoords({x: event.clientX, y: event.clientY}, false)
return {pos, bias: findPositionSide(view, pos, event.clientX, event.clientY)}
}
const BadMouseDetail = browser.ie && browser.ie_version <= 11
let lastMouseDown: MouseEvent | null = null, lastMouseDownCount = 0, lastMouseDownTime = 0
function getClickType(event: MouseEvent) {
if (!BadMouseDetail) return event.detail
let last = lastMouseDown, lastTime = lastMouseDownTime
lastMouseDown = event
lastMouseDownTime = Date.now()
return lastMouseDownCount = !last || (lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 &&
Math.abs(last.clientY - event.clientY) < 2) ? (lastMouseDownCount + 1) % 3 : 1
}
function basicMouseSelection(view: EditorView, event: MouseEvent) {
let start = queryPos(view, event), type = getClickType(event)
let startSel = view.state.selection
return {
update(update) {
if (update.docChanged) {
start.pos = update.changes.mapPos(start.pos)
startSel = startSel.map(update.changes)
}
},
get(event, extend, multiple) {
let cur = queryPos(view, event), removed
let range = rangeForClick(view, cur.pos, cur.bias, type)
if (start.pos != cur.pos && !extend) {
let startRange = rangeForClick(view, start.pos, start.bias, type)
let from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to)
range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from)
}
if (extend)
return startSel.replaceRange(startSel.main.extend(range.from, range.to))
else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)))
return removed
else if (multiple)
return startSel.addRange(range)
else
return EditorSelection.create([range])
}
} as MouseSelectionStyle
}
function removeRangeAround(sel: EditorSelection, pos: number) {
for (let i = 0; i < sel.ranges.length; i++) {
let {from, to} = sel.ranges[i]
if (from <= pos && to >= pos)
return EditorSelection.create(sel.ranges.slice(0, i).concat(sel.ranges.slice(i + 1)),
sel.mainIndex == i ? 0 : sel.mainIndex - (sel.mainIndex > i ? 1 : 0))
}
return null
}
handlers.dragstart = (view, event: DragEvent) => {
let {selection: {main: range}} = view.state
if ((event.target as HTMLElement).draggable) {
let cView = view.docView.nearest(event.target as HTMLElement)
if (cView && cView.isWidget) {
let from = cView.posAtStart, to = from + cView.length
if (from >= range.to || to <= range.from) range = EditorSelection.range(from, to)
}
}
let {inputState} = view
if (inputState.mouseSelection) inputState.mouseSelection.dragging = true
inputState.draggedContent = range
if (event.dataTransfer) {
event.dataTransfer.setData("Text", view.state.sliceDoc(range.from, range.to))
event.dataTransfer.effectAllowed = "copyMove"
}
return false
}
handlers.dragend = view => {
view.inputState.draggedContent = null
return false
}
function dropText(view: EditorView, event: DragEvent, text: string, direct: boolean) {
if (!text) return
let dropPos = view.posAtCoords({x: event.clientX, y: event.clientY}, false)
let {draggedContent} = view.inputState
let del = direct && draggedContent && dragMovesSelection(view, event)
? {from: draggedContent.from, to: draggedContent.to} : null
let ins = {from: dropPos, insert: text}
let changes = view.state.changes(del ? [del, ins] : ins)
view.focus()
view.dispatch({
changes,
selection: {anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1)},
userEvent: del ? "move.drop" : "input.drop"
})
view.inputState.draggedContent = null
}
handlers.drop = (view, event: DragEvent) => {
if (!event.dataTransfer) return false
if (view.state.readOnly) return true
let files = event.dataTransfer.files
if (files && files.length) { // For a file drop, read the file's text.
let text = Array(files.length), read = 0
let finishFile = () => {
if (++read == files.length)
dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false)
}
for (let i = 0; i < files.length; i++) {
let reader = new FileReader
reader.onerror = finishFile
reader.onload = () => {
if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result as string)) text[i] = reader.result
finishFile()
}
reader.readAsText(files[i])
}
return true
} else {
let text = event.dataTransfer.getData("Text")
if (text) {
dropText(view, event, text, true)
return true
}
}
return false
}
handlers.paste = (view: EditorView, event: ClipboardEvent) => {
if (view.state.readOnly) return true
view.observer.flush()
let data = brokenClipboardAPI ? null : event.clipboardData
if (data) {
doPaste(view, data.getData("text/plain") || data.getData("text/uri-list"))
return true
} else {
capturePaste(view)
return false
}
}
function captureCopy(view: EditorView, text: string) {
// The extra wrapper is somehow necessary on IE/Edge to prevent the
// content from being mangled when it is put onto the clipboard
let parent = view.dom.parentNode
if (!parent) return
let target = parent.appendChild(document.createElement("textarea"))
target.style.cssText = "position: fixed; left: -10000px; top: 10px"
target.value = text
target.focus()
target.selectionEnd = text.length
target.selectionStart = 0
setTimeout(() => {
target.remove()
view.focus()
}, 50)
}
function copiedRange(state: EditorState) {
let content = [], ranges: {from: number, to: number}[] = [], linewise = false
for (let range of state.selection.ranges) if (!range.empty) {
content.push(state.sliceDoc(range.from, range.to))
ranges.push(range)
}
if (!content.length) {
// Nothing selected, do a line-wise copy
let upto = -1
for (let {from} of state.selection.ranges) {
let line = state.doc.lineAt(from)
if (line.number > upto) {
content.push(line.text)
ranges.push({from: line.from, to: Math.min(state.doc.length, line.to + 1)})
}
upto = line.number
}
linewise = true
}
return {text: content.join(state.lineBreak), ranges, linewise}
}
let lastLinewiseCopy: string | null = null
handlers.copy = handlers.cut = (view, event: ClipboardEvent) => {
let {text, ranges, linewise} = copiedRange(view.state)
if (!text && !linewise) return false
lastLinewiseCopy = linewise ? text : null
if (event.type == "cut" && !view.state.readOnly)
view.dispatch({
changes: ranges,
scrollIntoView: true,
userEvent: "delete.cut"
})
let data = brokenClipboardAPI ? null : event.clipboardData
if (data) {
data.clearData()
data.setData("text/plain", text)
return true
} else {
captureCopy(view, text)
return false
}
}
export const isFocusChange = Annotation.define<boolean>()
export function focusChangeTransaction(state: EditorState, focus: boolean) {
let effects = []
for (let getEffect of state.facet(focusChangeEffect)) {
let effect = getEffect(state, focus)
if (effect) effects.push(effect)
}
return effects ? state.update({effects, annotations: isFocusChange.of(true)}) : null
}
function updateForFocusChange(view: EditorView) {
setTimeout(() => {
let focus = view.hasFocus
if (focus != view.inputState.notifiedFocused) {
let tr = focusChangeTransaction(view.state, focus)
if (tr) view.dispatch(tr)
else view.update([])
}
}, 10)
}
observers.focus = view => {
view.inputState.lastFocusTime = Date.now()
// When focusing reset the scroll position, move it back to where it was
if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
view.scrollDOM.scrollTop = view.inputState.lastScrollTop
view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft
}
updateForFocusChange(view)
}
observers.blur = view => {
view.observer.clearSelectionRange()
updateForFocusChange(view)
}
observers.compositionstart = observers.compositionupdate = view => {
if (view.inputState.compositionFirstChange == null)
view.inputState.compositionFirstChange = true
if (view.inputState.composing < 0) {
// FIXME possibly set a timeout to clear it again on Android
view.inputState.composing = 0
}
}
observers.compositionend = view => {
view.inputState.composing = -1
view.inputState.compositionEndedAt = Date.now()
view.inputState.compositionPendingKey = true
view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0
view.inputState.compositionFirstChange = null
if (browser.chrome && browser.android) {
// Delay flushing for a bit on Android because it'll often fire a
// bunch of contradictory changes in a row at end of compositon
view.observer.flushSoon()
} else if (view.inputState.compositionPendingChange) {
// If we found pending records, schedule a flush.
Promise.resolve().then(() => view.observer.flush())
} else {
// Otherwise, make sure that, if no changes come in soon, the
// composition view is cleared.
setTimeout(() => {
if (view.inputState.composing < 0 && view.docView.hasComposition)
view.update([])
}, 50)
}
}
observers.contextmenu = view => {
view.inputState.lastContextMenu = Date.now()
}
handlers.beforeinput = (view, event) => {
// Because Chrome Android doesn't fire useful key events, use
// beforeinput to detect backspace (and possibly enter and delete,
// but those usually don't even seem to fire beforeinput events at
// the moment) and fake a key event for it.
//
// (preventDefault on beforeinput, though supported in the spec,
// seems to do nothing at all on Chrome).
let pending
if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
view.observer.delayAndroidKey(pending.key, pending.keyCode)
if (pending.key == "Backspace" || pending.key == "Delete") {
let startViewHeight = window.visualViewport?.height || 0
setTimeout(() => {
// Backspacing near uneditable nodes on Chrome Android sometimes
// closes the virtual keyboard. This tries to crudely detect
// that and refocus to get it back.
if ((window.visualViewport?.height || 0) > startViewHeight + 10 && view.hasFocus) {
view.contentDOM.blur()
view.focus()
}
}, 100)
}
}
if (browser.ios && event.inputType == "deleteContentForward") {
// For some reason, DOM changes (and beforeinput) happen _before_
// the key event for ctrl-d on iOS when using an external
// keyboard.
view.observer.flushSoon()
}
// Safari will occasionally forget to fire compositionend at the end of a dead-key composition
if (browser.safari && event.inputType == "insertText" && view.inputState.composing >= 0) {
setTimeout(() => observers.compositionend(view, event), 20)
}
return false
}
const appliedFirefoxHack: Set<Document> = new Set
// In Firefox, when cut/copy handlers are added to the document, that
// somehow avoids a bug where those events aren't fired when the
// selection is empty. See https://github.com/codemirror/dev/issues/1082
// and https://bugzilla.mozilla.org/show_bug.cgi?id=995961
function firefoxCopyCutHack(doc: Document) {
if (!appliedFirefoxHack.has(doc)) {
appliedFirefoxHack.add(doc)
doc.addEventListener("copy", () => {})
doc.addEventListener("cut", () => {})
}
}