-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathInput.js
2095 lines (1856 loc) · 82.2 KB
/
Input.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
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
// Copyright 2013-2020, University of Colorado Boulder
/**
* Main handler for user-input events in Scenery.
*
* *** Adding input handling to a display
*
* Displays do not have event listeners attached by default. To initialize the event system (that will set up
* listeners), use one of Display's initialize*Events functions.
*
* *** Pointers
*
* A 'pointer' is an abstract way of describing a mouse, a single touch point, or a pen/stylus, similar to in the
* Pointer Events specification (https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html). Touch and pen
* pointers are transient, created when the relevant DOM down event occurs and released when corresponding the DOM up
* or cancel event occurs. However, the mouse pointer is persistent.
*
* Input event listeners can be added to {Node}s directly, or to a pointer. When a DOM event is received, it is first
* broken up into multiple events (if necessary, e.g. multiple touch points), then the dispatch is handled for each
* individual Scenery event. Events are first fired for any listeners attached to the pointer that caused the event,
* then fire on the node directly under the pointer, and if applicable, bubble up the graph to the Scene from which the
* event was triggered. Events are not fired directly on nodes that are not under the pointer at the time of the event.
* To handle many common patterns (like button presses, where mouse-ups could happen when not over the button), it is
* necessary to add those move/up listeners to the pointer itself.
*
* *** Listeners and Events
*
* Event listeners are added with node.addInputListener( listener ), pointer.addInputListener( listener ) and
* display.addInputListener( listener ).
* This listener can be an arbitrary object, and the listener will be triggered by calling listener[eventType]( event ),
* where eventType is one of the event types as described below, and event is a Scenery event with the
* following properties:
* - trail {Trail} - Points to the node under the pointer
* - pointer {Pointer} - The pointer that triggered the event. Additional information about the mouse/touch/pen can be
* obtained from the pointer, for example event.pointer.point.
* - type {string} - The base type of the event (e.g. for touch down events, it will always just be "down").
* - domEvent {UIEvent} - The underlying DOM event that triggered this Scenery event. The DOM event may correspond to
* multiple Scenery events, particularly for touch events. This could be a TouchEvent,
* PointerEvent, MouseEvent, MSPointerEvent, etc.
* - target {Node} - The leaf-most Node in the trail.
* - currentTarget {Node} - The Node to which the listener being fired is attached, or null if the listener is being
* fired directly from a pointer.
*
* Additionally, listeners may support an interrupt() method that detaches it from pointers, or may support being
* "attached" to a pointer (indicating a primary role in controlling the pointer's behavior). See Pointer for more
* information about these interactions.
*
* *** Event Types
*
* Scenery will fire the following base event types:
*
* - down: Triggered when a pointer is pressed down. Touch / pen pointers are created for each down event, and are
* active until an up/cancel event is sent.
* - up: Triggered when a pointer is released normally. Touch / pen pointers will not have any more events associated
* with them after an up event.
* - cancel: Triggered when a pointer is canceled abnormally. Touch / pen pointers will not have any more events
* associated with them after an up event.
* - move: Triggered when a pointer moves.
* - wheel: Triggered when the (mouse) wheel is scrolled. The associated pointer will have wheelDelta information.
* - enter: Triggered when a pointer moves over a Node or one of its children. Does not bubble up. Mirrors behavior from
* the DOM mouseenter (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseenter)
* - exit: Triggered when a pointer moves out from over a Node or one of its children. Does not bubble up. Mirrors
* behavior from the DOM mouseleave (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseleave).
* - over: Triggered when a pointer moves over a Node (not including its children). Mirrors behavior from the DOM
* mouseover (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseover).
* - out: Triggered when a pointer moves out from over a Node (not including its children). Mirrors behavior from the
* DOM mouseout (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseout).
*
* Before firing the base event type (for example, 'move'), Scenery will also fire an event specific to the type of
* pointer. For mice, it will fire 'mousemove', for touch events it will fire 'touchmove', and for pen events it will
* fire 'penmove'. Similarly, for any type of event, it will first fire pointerType+eventType, and then eventType.
*
* **** PDOM Specific Event Types
*
* Some event types can only be triggered from the PDOM. If a SCENERY/Node has accessible content (see
* ParallelDOM.js for more info), then listeners can be added for events fired from the PDOM. The accessibility events
* triggered from a Node are dependent on the `tagName` (ergo the HTMLElement primary sibling) specified by the Node.
*
* Some terminology for understanding:
* - PDOM: parallel DOM, see ParallelDOM.js
* - Primary Sibling: The Node's HTMLElement in the PDOM that is interacted with for accessible interactions and to
* display accessible content. The primary sibling has the tag name specified by the `tagName`
* option, see `ParallelDOM.setTagName`. Primary sibling is further defined in PDOMPeer.js
* - Assistive Technology: aka AT, devices meant to improve the capabilities of an individual with a disability.
*
* The following are the supported accessible events:
*
* - focus: Triggered when navigation focus is set to this Node's primary sibling. This can be triggered with some
* AT too, like screen readers' virtual cursor, but that is not dependable as it can be toggled with a screen
* reader option. Furthermore, this event is not triggered on mobile devices. Does not bubble.
* - focusin: Same as 'focus' event, but bubbles.
* - blur: Triggered when navigation focus leaves this Node's primary sibling. This can be triggered with some
* AT too, like screen readers' virtual cursor, but that is not dependable as it can be toggled with a screen
* reader option. Furthermore, this event is not triggered on mobile devices.
* - focusout: Same as 'blur' event, but bubbles.
* - click: Triggered when this Node's primary sibling is clicked. Note, though this event seems similar to some base
* event types (the event implements `MouseEvent`), it only applies when triggered from the PDOM.
* See https://www.w3.org/TR/DOM-Level-3-Events/#click
* - input: Triggered when the value of an <input>, <select>, or <textarea> element has been changed.
* See https://www.w3.org/TR/DOM-Level-3-Events/#input
* - change: Triggered for <input>, <select>, and <textarea> elements when an alteration to the element's value is
* committed by the user. Unlike the input event, the change event is not necessarily fired for each
* alteration to an element's value. See
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event and
* https://html.spec.whatwg.org/multipage/indices.html#event-change
* - keydown: Triggered for all keys pressed. When a screen reader is active, this event will be omitted
* role="button" is activated.
* See https://www.w3.org/TR/DOM-Level-3-Events/#keydown
* - keyup : Triggered for all keys when released. When a screen reader is active, this event will be omitted
* role="button" is activated.
* See https://www.w3.org/TR/DOM-Level-3-Events/#keyup
*
* *** Event Dispatch
*
* Events have two methods that will cause early termination: event.abort() will cause no more listeners to be notified
* for this event, and event.handle() will allow the current level of listeners to be notified (all pointer listeners,
* or all listeners attached to the current node), but no more listeners after that level will fire. handle and abort
* are like stopPropagation, stopImmediatePropagation for DOM events, except they do not trigger those DOM methods on
* the underlying DOM event.
*
* Up/down/cancel events all happen separately, but for move events, a specific sequence of events occurs if the pointer
* changes the node it is over:
*
* 1. The move event is fired (and bubbles).
* 2. An out event is fired for the old topmost Node (and bubbles).
* 3. exit events are fired for all Nodes in the Trail hierarchy that are now not under the pointer, from the root-most
* to the leaf-most. Does not bubble.
* 4. enter events are fired for all Nodes in the Trail hierarchy that were not under the pointer (but now are), from
* the leaf-most to the root-most. Does not bubble.
* 5. An over event is fired for the new topmost Node (and bubbles).
*
* event.abort() and event.handle() will currently not affect other stages in the 'move' sequence (e.g. event.abort() in
* the 'move' event will not affect the following 'out' event).
*
* For each event type:
*
* 1. Listeners on the pointer will be triggered first (in the order they were added)
* 2. Listeners on the target (top-most) Node will be triggered (in the order they were added to that Node)
* 3. Then if the event bubbles, each Node in the Trail will be triggered, starting from the Node under the top-most
* (that just had listeners triggered) and all the way down to the Scene. Listeners are triggered in the order they
* were added for each Node.
* 4. Listeners on the display will be triggered (in the order they were added)
*
* For each listener being notified, it will fire the more specific pointerType+eventType first (e.g. 'mousemove'),
* then eventType next (e.g. 'move').
*
* Currently, preventDefault() is called on the associated DOM event if the top-most node has the 'interactive' property
* set to a truthy value.
*
* *** Relevant Specifications
*
* DOM Level 3 events spec: http://www.w3.org/TR/DOM-Level-3-Events/
* Touch events spec: http://www.w3.org/TR/touch-events/
* Pointer events spec draft: https://dvcs.w3.org/hg/pointerevents/raw-file/tip/pointerEvents.html
* http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
*
* @author Jonathan Olson <[email protected]>
* @author Sam Reid (PhET Interactive Simulations)
*/
import Action from '../../../axon/js/Action.js';
import TinyEmitter from '../../../axon/js/TinyEmitter.js';
import Vector2 from '../../../dot/js/Vector2.js';
import cleanArray from '../../../phet-core/js/cleanArray.js';
import merge from '../../../phet-core/js/merge.js';
import platform from '../../../phet-core/js/platform.js';
import EventType from '../../../tandem/js/EventType.js';
import Tandem from '../../../tandem/js/Tandem.js';
import NullableIO from '../../../tandem/js/types/NullableIO.js';
import NumberIO from '../../../tandem/js/types/NumberIO.js';
import PDOMUtils from '../accessibility/pdom/PDOMUtils.js';
import Display from '../display/Display.js';
import scenery from '../scenery.js';
import Features from '../util/Features.js';
import Trail from '../util/Trail.js';
import BatchedDOMEvent from './BatchedDOMEvent.js';
import BrowserEvents from './BrowserEvents.js';
import EventIO from './EventIO.js';
import Mouse from './Mouse.js';
import PDOMPointer from './PDOMPointer.js';
import Pen from './Pen.js';
import Pointer from './Pointer.js';
import SceneryEvent from './SceneryEvent.js';
import Touch from './Touch.js';
// Object literal makes it easy to check for the existence of an attribute (compared to [].indexOf()>=0)
const domEventPropertiesToSerialize = {
type: true,
button: true, keyCode: true, key: true,
deltaX: true, deltaY: true, deltaZ: true, deltaMode: true, pointerId: true,
pointerType: true, charCode: true, which: true, clientX: true, clientY: true, pageX: true, pageY: true, changedTouches: true,
scale: true,
target: true, relatedTarget: true,
ctrlKey: true, shiftKey: true, altKey: true, metaKey: true
};
// A list of keys on events that need to be serialized into HTMLElements
const EVENT_KEY_VALUES_AS_ELEMENTS = [ 'target', 'relatedTarget' ];
// A list of events that should still fire, even when the Node is not pickable
const PDOM_UNPICKABLE_EVENTS = [ 'focus', 'blur', 'focusin', 'focusout' ];
const TARGET_SUBSTITUTE_KEY = 'targetSubstitute';
const RELATED_TARGET_SUBSTITUTE_KEY = 'relatedTargetSubstitute';
// A bit more than the maximum amount of time that iOS 14 VoiceOver was observed to delay between
// sending a mouseup event and a click event.
const PDOM_CLICK_DELAY = 80;
class Input {
/**
* @param {Display} display
* @param {boolean} attachToWindow - Whether to add listeners to the window (instead of the Display's domElement).
* @param {boolean} batchDOMEvents - If true, most event types will be batched until otherwise triggered.
* @param {boolean} assumeFullWindow - We can optimize certain things like computing points if we know the display
* fills the entire window.
* @param {boolean|null} passiveEvents - See Display's documentation (controls the presence of the passive flag for
* events, which has some advanced considerations).
*
* @param {Object} [options]
*/
constructor( display, attachToWindow, batchDOMEvents, assumeFullWindow, passiveEvents, options ) {
assert && assert( display instanceof Display );
assert && assert( typeof attachToWindow === 'boolean' );
assert && assert( typeof batchDOMEvents === 'boolean' );
assert && assert( typeof assumeFullWindow === 'boolean' );
options = merge( {
tandem: Tandem.OPTIONAL
}, options );
// @public {Display}
this.display = display;
// @public {Node}
this.rootNode = display.rootNode;
// @public {boolean}
this.attachToWindow = attachToWindow;
this.batchDOMEvents = batchDOMEvents;
this.assumeFullWindow = assumeFullWindow;
// @public {boolean|null}
this.passiveEvents = passiveEvents;
// @private {Array.<BatchedDOMEvent}>
this.batchedEvents = [];
// @public {PDOMPointer|null} - Pointer for accessibility, only created lazily on first pdom event.
this.pdomPointer = null;
// @public {Mouse|null} - Pointer for mouse, only created lazily on first mouse event, so no mouse is allocated on.
// tablets.
this.mouse = null;
// @public {Array.<Pointer>} - All active pointers.
this.pointers = [];
// @public {TinyEmitter.<Pointer>}
this.pointerAddedEmitter = new TinyEmitter();
// @public {boolean} - Whether we are currently firing events. We need to track this to handle re-entrant cases
// like https://github.com/phetsims/balloons-and-static-electricity/issues/406.
this.currentlyFiringEvents = false;
// @private {number} - in miliseconds, the DOMEvent timeStamp when we receive a logical up event.
// We can compare this to the timeStamp on a click vent to filter out the click events
// when some screen readers send both down/up events AND click events to the target
// element, see https://github.com/phetsims/scenery/issues/1094
this.upTimeStamp = 0;
////////////////////////////////////////////////////
// Declare the Actions that send scenery input events to the PhET-iO data stream. Note they use the default value
// of phetioReadOnly false, in case a client wants to synthesize events.
// @private {Action} - Emits pointer validation to the input stream for playback
// This is a high frequency event that is necessary for reproducible playbacks
this.validatePointersAction = new Action( () => {
let i = this.pointers.length;
while ( i-- ) {
const pointer = this.pointers[ i ];
if ( pointer.point && pointer !== this.pdomPointer ) {
this.branchChangeEvents( pointer, pointer.lastDOMEvent, false );
}
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'validatePointersAction' ),
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.mouseUpAction = new Action( ( point, event ) => {
if ( !this.mouse ) { this.initMouse(); }
const pointChanged = this.mouse.up( point, event );
this.mouse.id = null;
this.upEvent( this.mouse, event, pointChanged );
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'mouseUpAction' ),
parameters: [
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a mouse button is released.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.mouseDownAction = new Action( ( id, point, event ) => {
if ( !this.mouse ) { this.initMouse(); }
this.mouse.id = id;
const pointChanged = this.mouse.down( point, event );
this.downEvent( this.mouse, event, pointChanged );
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'mouseDownAction' ),
parameters: [
{ name: 'id', phetioType: NullableIO( NumberIO ) },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a mouse button is pressed.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.mouseMoveAction = new Action( ( point, event ) => {
if ( !this.mouse ) { this.initMouse(); }
this.mouse.move( point, event );
this.moveEvent( this.mouse, event );
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'mouseMoveAction' ),
parameters: [
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the mouse is moved.',
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.mouseOverAction = new Action( ( point, event ) => {
if ( !this.mouse ) { this.initMouse(); }
this.mouse.over( point, event );
// TODO: how to handle mouse-over (and log it)... are we changing the pointer.point without a branch change?
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'mouseOverAction' ),
parameters: [
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the mouse is moved while on the sim.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.mouseOutAction = new Action( ( point, event ) => {
if ( !this.mouse ) { this.initMouse(); }
this.mouse.out( point, event );
// TODO: how to handle mouse-out (and log it)... are we changing the pointer.point without a branch change?
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'mouseOutAction' ),
parameters: [
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the mouse moves out of the display.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.wheelScrollAction = new Action( event => {
if ( !this.mouse ) { this.initMouse(); }
this.mouse.wheel( event );
// don't send mouse-wheel events if we don't yet have a mouse location!
// TODO: Can we set the mouse location based on the wheel event?
if ( this.mouse.point ) {
const trail = this.rootNode.trailUnderPointer( this.mouse ) || new Trail( this.rootNode );
this.dispatchEvent( trail, 'wheel', this.mouse, event, true );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'wheelScrollAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the mouse wheel scrolls.',
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.touchStartAction = new Action( ( id, point, event ) => {
const touch = new Touch( id, point, event );
this.addPointer( touch );
this.downEvent( touch, event, false );
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'touchStartAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a touch begins.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.touchEndAction = new Action( ( id, point, event ) => {
const touch = this.findPointerById( id );
if ( touch ) {
const pointChanged = touch.end( point, event );
this.upEvent( touch, event, pointChanged );
this.removePointer( touch );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'touchEndAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a touch ends.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.touchMoveAction = new Action( ( id, point, event ) => {
const touch = this.findPointerById( id );
if ( touch ) {
touch.move( point, event );
this.moveEvent( touch, event );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'touchMoveAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a touch moves.',
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.touchCancelAction = new Action( ( id, point, event ) => {
const touch = this.findPointerById( id );
if ( touch ) {
const pointChanged = touch.cancel( point, event );
this.cancelEvent( touch, event, pointChanged );
this.removePointer( touch );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'touchCancelAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a touch is canceled.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.penStartAction = new Action( ( id, point, event ) => {
const pen = new Pen( id, point, event );
this.addPointer( pen );
this.downEvent( pen, event, false );
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'penStartAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pen touches the screen.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.penEndAction = new Action( ( id, point, event ) => {
const pen = this.findPointerById( id );
if ( pen ) {
const pointChanged = pen.end( point, event );
this.upEvent( pen, event, pointChanged );
this.removePointer( pen );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'penEndAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pen is lifted.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.penMoveAction = new Action( ( id, point, event ) => {
const pen = this.findPointerById( id );
if ( pen ) {
pen.move( point, event );
this.moveEvent( pen, event );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'penMoveAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pen is moved.',
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.penCancelAction = new Action( ( id, point, event ) => {
const pen = this.findPointerById( id );
if ( pen ) {
const pointChanged = pen.cancel( point, event );
this.cancelEvent( pen, event, pointChanged );
this.removePointer( pen );
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'penCancelAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'point', phetioType: Vector2.Vector2IO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pen is canceled.'
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.gotPointerCaptureAction = new Action( ( id, event ) => {
const pointer = this.findPointerById( id );
if ( pointer ) {
pointer.onGotPointerCapture();
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'gotPointerCaptureAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pointer is captured (normally at the start of an interaction)',
phetioHighFrequency: true
} );
// @private {Action} - Emits to the PhET-iO data stream.
this.lostPointerCaptureAction = new Action( ( id, event ) => {
const pointer = this.findPointerById( id );
if ( pointer ) {
pointer.onLostPointerCapture();
}
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'lostPointerCaptureAction' ),
parameters: [
{ name: 'id', phetioType: NumberIO },
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when a pointer loses its capture (normally at the end of an interaction)',
phetioHighFrequency: true
} );
// wire up accessibility listeners on the display's root accessible DOM element.
if ( this.display._accessible ) {
// @private
this.focusinAction = new Action( event => {
// ignore any focusout callbacks if they are initiated due to implementation details in PDOM manipulation
if ( this.display.blockFocusCallbacks ) {
return;
}
sceneryLog && sceneryLog.Input && sceneryLog.Input( `focusin(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'focus', event, false );
this.dispatchPDOMEvent( trail, 'focusin', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'focusinAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the focusin DOM event.'
} );
// @private
this.focusoutAction = new Action( event => {
// ignore any focusout callbacks if they are initiated due to implementation details in PDOM manipulation
if ( this.display.blockFocusCallbacks ) {
return;
}
sceneryLog && sceneryLog.Input && sceneryLog.Input( `focusOut(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
// recompute the trail on focusout if necessary - since a blur/focusout may have been initiated from a
// focus/focusin listener, it is possible that focusout was called more than once before focusin is called on the
// next active element, see https://github.com/phetsims/scenery/issues/898
if ( !this.pdomPointer ) { this.initPDOMPointer(); }
this.pdomPointer.invalidateTrail( this.getTrailId( event ) );
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'blur', event, false );
this.dispatchPDOMEvent( trail, 'focusout', event, true );
// clear the trail to make sure that our assertions aren't testing a stale trail, do this before
// focusing event.relatedTarget below so that trail isn't cleared after focus
this.pdomPointer.trail = null;
const relatedTarget = event[ RELATED_TARGET_SUBSTITUTE_KEY ] || event.relatedTarget;
// If there exists an event.relatedTarget, user is moving to the next item with "tab" like navigation and
// event.relatedTarget is the element focus is moving to. If the relatedTarget element is removed from the
// document then added back in during focusout callbacks (which is done in AccessibilityTree operations),
// some browsers (IE11 and Safari) will fail to focus the element. So we manually focus the relatedTarget
// so that focus isn't lost. Skipped if focusout callbacks sent focus to an element other than the
// in the PDOM (like on removal), or if callbacks made relatedTarget unfocusable.
//
// Focus is set with DOM API to avoid the performance hit of looking up the Node from trail id.
if ( relatedTarget ) {
const focusMovedInCallbacks = this.isTargetUnderPDOM( document.activeElement );
const targetFocusable = PDOMUtils.isElementFocusable( relatedTarget );
if ( targetFocusable && !focusMovedInCallbacks ) {
relatedTarget.focus();
}
}
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'focusoutAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the focusout DOM event.'
} );
// @private
this.clickAction = new Action( event => {
sceneryLog && sceneryLog.Input && sceneryLog.Input( `click(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'click', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'clickAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the click DOM event.'
} );
// @private
this.inputAction = new Action( event => {
sceneryLog && sceneryLog.Input && sceneryLog.Input( `input(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'input', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'inputAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the input DOM event.'
} );
// @private
this.changeAction = new Action( event => {
sceneryLog && sceneryLog.Input && sceneryLog.Input( `change(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'change', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'changeAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the change DOM event.'
} );
// @private
this.keydownAction = new Action( event => {
sceneryLog && sceneryLog.Input && sceneryLog.Input( `keydown(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'keydown', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'keydownAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the keydown DOM event.'
} );
// @private
this.keyupAction = new Action( event => {
sceneryLog && sceneryLog.Input && sceneryLog.Input( `keyup(${Input.debugText( null, event )});` );
sceneryLog && sceneryLog.Input && sceneryLog.push();
const trail = this.updateTrailForPDOMDispatch( event );
this.dispatchPDOMEvent( trail, 'keyup', event, true );
sceneryLog && sceneryLog.Input && sceneryLog.pop();
}, {
phetioPlayback: true,
tandem: options.tandem.createTandem( 'keyupAction' ),
parameters: [
{ name: 'event', phetioType: EventIO }
],
phetioEventType: EventType.USER,
phetioDocumentation: 'Emits when the PDOM root gets the keyup DOM event.'
} );
// same event options for all DOM listeners
const accessibleEventOptions = Features.passive ? { useCapture: false, passive: false } : false;
// Add a listener to the root accessible DOM element for each event we want to monitor.
PDOMUtils.DOM_EVENTS.forEach( eventName => {
const actionName = `${eventName}Action`;
assert && assert( this[ actionName ], `action not defined on Input: ${actionName}` );
// These exist for the lifetime of the display, and need not be disposed.
this.display.pdomRootElement.addEventListener( eventName, event => {
sceneryLog && sceneryLog.InputEvent && sceneryLog.InputEvent( `Input.${eventName}FromBrowser` );
sceneryLog && sceneryLog.InputEvent && sceneryLog.push();
if ( this.display.interactive ) {
const trailId = this.getTrailId( event );
const trail = trailId ? Trail.fromUniqueId( this.display.rootNode, trailId ) : null;
// Only dispatch the event if the click did not happen rapidly after an up event. It is
// likely that the screen reader dispatched both pointer AND click events in this case, and
// we only want to respond to one or the other. See https://github.com/phetsims/scenery/issues/1094.
// This is outside of the clickAction execution so that blocked clicks are not part of the PhET-iO data
// stream.
if ( trail && !( _.some( trail.nodes, node => node.positionInPDOM ) && eventName === 'click' &&
event.timeStamp - this.upTimeStamp <= PDOM_CLICK_DELAY ) ) {
this[ actionName ].execute( event );
}
}
sceneryLog && sceneryLog.InputEvent && sceneryLog.pop();
}, accessibleEventOptions );
} );
}
}
/**
* Interrupts any input actions that are currently taking place (should stop drags, etc.)
* @public
*/
interruptPointers() {
_.each( this.pointers, pointer => {
pointer.interruptAll();
} );
}
/**
* Called to batch a raw DOM event (which may be immediately fired, depending on the settings).
* @public (scenery-internal)
*
* @param {Event} domEvent
* @param {number} batchType - See BatchedDOMEvent's "enumeration" - TODO: use an actual enumeration
* @param {function} callback - Parameter types defined by the batchType. See BatchedDOMEvent for details
* @param {boolean} triggerImmediate - Certain events can force immediate action, since browsers like Chrome
* only allow certain operations in the callback for a user gesture (e.g. like
* a mouseup to open a window).
*/
batchEvent( domEvent, batchType, callback, triggerImmediate ) {
sceneryLog && sceneryLog.InputEvent && sceneryLog.InputEvent( 'Input.batchEvent' );
sceneryLog && sceneryLog.InputEvent && sceneryLog.push();
// If our display is not interactive, do not respond to any events (but still prevent default)
if ( this.display.interactive ) {
this.batchedEvents.push( BatchedDOMEvent.createFromPool( domEvent, batchType, callback ) );
if ( triggerImmediate || !this.batchDOMEvents ) {
this.fireBatchedEvents();
}
// NOTE: If we ever want to Display.updateDisplay() on events, do so here
}
// Always preventDefault on touch events, since we don't want mouse events triggered afterwards. See
// http://www.html5rocks.com/en/mobile/touchandmouse/ for more information.
// Additionally, IE had some issues with skipping prevent default, see
// https://github.com/phetsims/scenery/issues/464 for mouse handling.
if ( !( this.passiveEvents === true ) && ( callback !== this.mouseDown || platform.edge ) ) {
// We cannot prevent a passive event, so don't try
domEvent.preventDefault();
}
sceneryLog && sceneryLog.InputEvent && sceneryLog.pop();
}
/**
* Fires all of our events that were batched into the batchedEvents array.
* @public (scenery-internal)
*/
fireBatchedEvents() {
sceneryLog && sceneryLog.InputEvent && this.currentlyFiringEvents && sceneryLog.InputEvent(
'REENTRANCE DETECTED' );
// Don't re-entrantly enter our loop, see https://github.com/phetsims/balloons-and-static-electricity/issues/406
if ( !this.currentlyFiringEvents && this.batchedEvents.length ) {
sceneryLog && sceneryLog.InputEvent && sceneryLog.InputEvent( `Input.fireBatchedEvents length:${this.batchedEvents.length}` );
sceneryLog && sceneryLog.InputEvent && sceneryLog.push();
this.currentlyFiringEvents = true;
// needs to be done in order
const batchedEvents = this.batchedEvents;
// IMPORTANT: We need to check the length of the array at every iteration, as it can change due to re-entrant
// event handling, see https://github.com/phetsims/balloons-and-static-electricity/issues/406.
// Events may be appended to this (synchronously) as part of firing initial events, so we want to FULLY run all
// events before clearing our array.
for ( let i = 0; i < batchedEvents.length; i++ ) {
const batchedEvent = batchedEvents[ i ];
batchedEvent.run( this );
batchedEvent.dispose();
}
cleanArray( batchedEvents );
this.currentlyFiringEvents = false;
sceneryLog && sceneryLog.InputEvent && sceneryLog.pop();
}
}
/**
* Clears any batched events that we don't want to process.
* @public (scenery-internal)
*
* NOTE: It is HIGHLY recommended to interrupt pointers and remove non-Mouse pointers before doing this, as
* otherwise it can cause incorrect state in certain types of listeners (e.g. ones that count how many pointers
* are over them).
*/
clearBatchedEvents() {
this.batchedEvents.length = 0;
}
/**
* Checks all pointers to see whether they are still "over" the same nodes (trail). If not, it will fire the usual
* enter/exit events.
* @public (scenery-internal)
*/
validatePointers() {
this.validatePointersAction.execute();
}
/**
* Removes all non-Mouse pointers from internal tracking.
* @public (scenery-internal)
*/
removeTemporaryPointers() {
const fakeDomEvent = {
eek: 'This is a fake DOM event created in removeTemporaryPointers(), called from a Scenery exit event. Our attempt to masquerade seems unsuccessful! :('
};
for ( let i = this.pointers.length - 1; i >= 0; i-- ) {
const pointer = this.pointers[ i ];
if ( !( pointer instanceof Mouse ) ) {
this.pointers.splice( i, 1 );
// Send exit events. As we can't get a DOM event, we'll send a fake object instead.
const exitTrail = pointer.trail || new Trail( this.rootNode );
this.exitEvents( pointer, fakeDomEvent, exitTrail, 0, true );
}
}
}
/**
* Hooks up DOM listeners to whatever type of object we are going to listen to.
* @public (scenery-internal)
*/
connectListeners() {
BrowserEvents.addDisplay( this.display, this.attachToWindow, this.passiveEvents );
}
/**
* Removes DOM listeners from whatever type of object we were listening to.
* @public (scenery-internal)
*/
disconnectListeners() {
BrowserEvents.removeDisplay( this.display, this.attachToWindow, this.passiveEvents );
}
/**
* Extract a {Vector2} global coordinate point from an arbitrary DOM event.
* @public (scenery-internal)
*
* @param {Event} domEvent
* @returns {Vector2}
*/
pointFromEvent( domEvent ) {
const position = Vector2.createFromPool( domEvent.clientX, domEvent.clientY );
if ( !this.assumeFullWindow ) {
const domBounds = this.display.domElement.getBoundingClientRect();
// TODO: consider totally ignoring any with zero width/height, as we aren't attached to the display?
// For now, don't offset.
if ( domBounds.width > 0 && domBounds.height > 0 ) {
position.subtractXY( domBounds.left, domBounds.top );
// Detect a scaling of the display here (the client bounding rect having different dimensions from our
// display), and attempt to compensate.
// NOTE: We can't handle rotation here.
if ( domBounds.width !== this.display.width || domBounds.height !== this.display.height ) {
// TODO: Have code verify the correctness here, and that it's not triggering all the time
position.x *= this.display.width / domBounds.width;
position.y *= this.display.height / domBounds.height;
}
}
}
return position;
}
/**
* Adds a pointer to our list.
* @private
*
* @param {Pointer} pointer
*/
addPointer( pointer ) {
this.pointers.push( pointer );
this.pointerAddedEmitter.emit( pointer );
}
/**
* Removes a pointer from our list. If we get future events for it (based on the ID) it will be ignored.
* @private
*
* @param {Pointer} pointer
*/
removePointer( pointer ) {
// sanity check version, will remove all instances
for ( let i = this.pointers.length - 1; i >= 0; i-- ) {
if ( this.pointers[ i ] === pointer ) {
this.pointers.splice( i, 1 );
}
}
pointer.dispose();
}
/**