This repository has been archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy patheventcontract.js
1664 lines (1490 loc) · 59.8 KB
/
eventcontract.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 2005 Google Inc. All Rights Reserved.
/**
*
* @fileoverview Implements the local event handling contract. This
* allows DOM objects in a container that enters into this contract to
* define event handlers which are executed in a local context.
*
* One EventContract instance can manage the contract for multiple
* containers, which are added using the addContainer() method.
*
* Events can be registered using the addEvent() method.
*
* A Dispatcher is added using the dispatchTo() method. Until there is
* a dispatcher, events are queued. The idea is that the EventContract
* class is inlined in the HTML of the top level page and instantiated
* right after the start of <body>. The Dispatcher class is contained
* in the external deferred js, and instantiated and registered with
* EventContract when the external javascript in the page loads. The
* external javascript will also register the jsaction handlers, which
* then pick up the queued events at the time of registration.
*
* Since this class is meant to be inlined in the main page HTML, the
* size of the binary compiled from this file MUST be kept as small as
* possible and thus its dependencies to a minimum.
*/
goog.provide('jsaction.EventContract');
goog.provide('jsaction.EventContractContainer');
goog.require('goog.dom.TagName');
goog.require('jsaction.A11y');
goog.require('jsaction.Attribute');
goog.require('jsaction.Cache');
goog.require('jsaction.Char');
goog.require('jsaction.EventType');
goog.require('jsaction.Property');
goog.require('jsaction.createMouseEvent');
goog.require('jsaction.domGenerator');
goog.require('jsaction.event');
/**
* EventContract intercepts events in the bubbling phase at the
* boundary of a container element, and maps them to generic actions
* which are specified using the custom jsaction attribute in
* HTML. Behavior of the application is then specified in terms of
* handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.
*
* This has several benefits: (1) No DOM event handlers need to be
* registered on the specific elements in the UI. (2) The set of
* events that the application has to handle can be specified in terms
* of the semantics of the application, rather than in terms of DOM
* events. (3) Invocation of handlers can be delayed and handlers can
* be delay loaded in a generic way.
*
* @constructor
*/
jsaction.EventContract = function() {
/**
* A list of functions. Each function will initialize a newly
* registered contract for one event. See addContainer().
*
* @type {!Array.<!jsaction.ContainerInitializerFunction>}
* @private
*/
this.installers_ = [];
/**
* The containers signed up for this event contract. See addContainer().
*
* @type {!Array.<!jsaction.EventContractContainer>}
* @private
*/
this.containers_ = [];
/**
* The list of containers that are children of an existing container. If
* STOP_PROPAGATION is false then we do not install event listeners on these
* (since that would cause the event to be triggered more than once). We do
* want to keep track of these containers such that we properly handle
* additions/removals.
* If STOP_PROPAGATION is true it is safe to add event listeners on all the
* containers.
* @type {!Array.<!jsaction.EventContractContainer>}
* @private
*/
this.nestedContainers_ = [];
/**
* The DOM events which this contract covers. Used to prevent double
* registration of event types. The value of the map is the
* internally created DOM event handler function that handles the
* DOM events. See addEvent().
*
* @type {!Object.<string, !jsaction.EventHandlerFunction>}
* @private
*/
this.events_ = {};
/**
* The dispatcher function. Events are passed to this function for
* handling once it was set using the dispatchTo() method. Usually
* the dispatcher is the bound dispatch() method of a
* jsaction.Dispatcher instance. This is done because the function
* is passed from another jsbinary, so passing the instance and
* invoking the method here would require to leave the method
* unobfuscated.
*
* @type {?function((!jsaction.EventInfo|!Array.<!jsaction.EventInfo>),
* boolean=):(!Event|void)}
* @private
*/
this.dispatcher_ = null;
/**
* The queue of events. Events are queued while there is no
* dispatcher set.
* @type {Array.<!jsaction.EventInfo>}
* @private
*/
this.queue_ = [];
if (jsaction.EventContract.CUSTOM_EVENT_SUPPORT) {
this.addEvent(jsaction.EventType.CUSTOM);
}
};
/**
* @define {boolean} Controls the use of event.path logic for the dom
* walking in createEventInfo_.
*/
jsaction.EventContract.USE_EVENT_PATH =
goog.define('jsaction.EventContract.USE_EVENT_PATH', false);
/**
* Whether the user agent is running on iOS.
* @type {boolean}
* @private
*/
jsaction.EventContract.isIos_ = typeof navigator != 'undefined' &&
/iPhone|iPad|iPod/.test(navigator.userAgent);
/**
* @define {boolean} Support for jsnamespace attribute. This flag can be
* overridden in a build rule to trim down the EventContract's binary size.
*/
jsaction.EventContract.JSNAMESPACE_SUPPORT =
goog.define('jsaction.EventContract.JSNAMESPACE_SUPPORT', true);
/**
* @define {boolean} Handles a11y click casting in the dispatcher rather than
* the event contract. When enabled, it will enable
* jsaction.EventContract.A11Y_CLICK_SUPPORT as well as both are required for
* this functionality.
*/
jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER =
goog.define('jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER', false);
/**
* @define {boolean} Support for accessible click actions. This flag can be
* overridden in a build rule.
* @private
*/
jsaction.EventContract.A11Y_CLICK_SUPPORT_FLAG_ENABLED_ =
goog.define('jsaction.EventContract.A11Y_CLICK_SUPPORT', false);
/**
* Forces A11y click support when the A11Y_SUPPORT_IN_DISPATCHER flag is true.
* @type {boolean}
*/
jsaction.EventContract.A11Y_CLICK_SUPPORT =
jsaction.EventContract.A11Y_CLICK_SUPPORT_FLAG_ENABLED_ ||
jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER;
/**
* @define {boolean} Support for the non-bubbling mouseenter and mouseleave
* events. This flag can be overridden in a build rule.
*/
jsaction.EventContract.MOUSE_SPECIAL_SUPPORT =
goog.define('jsaction.EventContract.MOUSE_SPECIAL_SUPPORT', false);
/**
* @define {boolean} Simulate click events based on touch events for browsers
* that have a 300ms delay before they send the click event. This is
* currently EXPERIMENTAL.
*/
jsaction.EventContract.FAST_CLICK_SUPPORT =
goog.define('jsaction.EventContract.FAST_CLICK_SUPPORT', false);
/**
* @define {boolean} Call stopPropagation on handled events. When integrating
* with non-jsaction event handler based code, you will likely want to turn
* this flag off. While most event handlers will continue to work, jsaction
* binds focus and blur events in the capture phase and thus with
* stopPropagation, none of your non-jsaction-handlers will ever see it.
*/
jsaction.EventContract.STOP_PROPAGATION =
goog.define('jsaction.EventContract.STOP_PROPAGATION', true);
/**
* @define {boolean} Support for custom events, which are type
* jsaction.EventType.CUSTOM. These are native DOM events with an
* additional type field and an optional payload.
*/
jsaction.EventContract.CUSTOM_EVENT_SUPPORT =
goog.define('jsaction.EventContract.CUSTOM_EVENT_SUPPORT', false);
/**
* Specifies a click jsaction event type triggered by an Enter/Space DOM
* keypress.
* @private {string}
* @const
*/
jsaction.EventContract.CLICKKEY_ = 'clickkey';
/**
* Helper function to trim whitespace from the beginning and the end
* of the string. This deliberately doesn't use the closure equivalent
* to keep dependencies small.
*
* @param {string} str Input string.
* @return {string} Trimmed string.
* @private @const
*/
jsaction.EventContract.stringTrim_ = String.prototype.trim ? function(str) {
return str.trim();
} : function(str) {
const trimmedLeft = str.replace(/^\s+/, '');
return trimmedLeft.replace(/\s+$/, '');
};
/**
* This regular expression matches a semicolon.
* @type {RegExp}
* @private
* @const
*/
jsaction.EventContract.REGEXP_SEMICOLON_ = /\s*;\s*/;
/**
* The default event type.
* @type {string}
* @private
*/
jsaction.EventContract.defaultEventType_ = jsaction.EventType.CLICK;
/**
* Information about an element that received a touchstart event
* that we might want to translate into a click event once a touchend
* event arrives.
*
* - node is the target element of the event.
* - x and y are clientX and clientY of the event, respectively.
*
* The fields of this Object are unquoted.
*
* This object is reset when either touchend arrives within a short period of
* time or when "fast click" is canceled due to touchmove or expiration. See
* "resetFastClickNode_" method for more detail.
*
* @private {?{node: !Element, x: number, y: number}}
*/
jsaction.EventContract.fastClickNode_;
/**
* The last emitted touchend event. It's used to ignore subsequent mouse
* events when requested by "_preventMouseEvents".
* @private {?Event}
*/
jsaction.EventContract.preventingMouseEvents_ = null;
/**
* A timer that we schedule after a touchstart. If the timer fires before the
* touchend event, the press is considered a long-press that does not get
* translated into a click.
* @private {number}
*/
jsaction.EventContract.fastClickTimeout_;
/**
* Gets the default event type.
* @return {string} The default event type.
*/
jsaction.EventContract.getDefaultEventType = function() {
return jsaction.EventContract.defaultEventType_;
};
/**
* Sets a new default event type.
* @param {string} eventType The new default event type.
*/
jsaction.EventContract.setDefaultEventType = function(eventType) {
jsaction.EventContract.defaultEventType_ = eventType;
};
/**
* Returns a function that handles events on a container and invokes a local
* event handler (bound using the actions map) on the source node or any of
* its ancestors up to the container to which the returned event handler
* belongs. The local event handler is passed an ActionFlow which allows
* access to the node, event, and values defined on the node. If there are no
* jsaction handlers bound that can handle this event, the flow representing
* the event is stored in a queue for replaying at a later time.
*
* @param {!jsaction.EventContract} eventContract The EventContract
* instance to create this handler for.
* @param {string} eventType The type of the event - e.g. 'click'.
* Note that event.type can differ from eventType. In some browsers (e.g.
* Firefox) the event handling code registers handlers for 'focusin' and
* 'focusout' to handle 'focus' and 'blur' respectively. In those cases,
* event.type might be 'focus', but eventType will be 'focusin'.
* @return {jsaction.EventHandlerFunction} The DOM event handler to
* use for the given event type on all containers.
* @private
*/
jsaction.EventContract.eventHandler_ = function(eventContract, eventType) {
/**
* See description above.
* @param {!Event} e Event.
* @param {boolean=} allowRehandling Used in the case of a11y click casting to
* prevent us from trying to rehandle in an infinite loop.
* @this {!Element}
*/
const handler = function handleEvent(e, allowRehandling = true) {
const container = this;
// Store eventType's value in a local variable so that multiple calls do not
// modify the shared eventType variable.
let eventTypeForDispatch = eventType;
if (jsaction.EventContract.CUSTOM_EVENT_SUPPORT &&
eventTypeForDispatch == jsaction.EventType.CUSTOM) {
const detail = e['detail'];
// For custom events, use a secondary dispatch based on the internal
// custom type of the event.
if (!detail || !detail['_type']) {
// This should never happen.
return;
}
eventTypeForDispatch = detail['_type'];
}
const eventInfo = jsaction.EventContract.createEventInfo_(
eventTypeForDispatch, e, container);
if (eventContract.dispatcher_ &&
!eventInfo['event'][jsaction.A11y.SKIP_GLOBAL_DISPATCH]) {
const globalEventInfo = jsaction.EventContract.createEventInfoInternal_(
eventInfo['eventType'], eventInfo['event'],
eventInfo['targetElement'], eventInfo['action'],
eventInfo['actionElement'], eventInfo['timeStamp']);
// In some cases, createEventInfo_() will rewrite click events to
// clickonly. Revert back to a regular click, otherwise we won't be able
// to execute global event handlers registered on click events.
if (globalEventInfo['eventType'] == jsaction.EventType.CLICKONLY) {
globalEventInfo['eventType'] = jsaction.EventType.CLICK;
}
eventContract.dispatcher_(
globalEventInfo, /* dispatch global event */ true);
}
if (jsaction.EventContract.canSkipDispatch_(eventInfo)) {
return;
}
let stopPropagationAfterDispatch = false;
if (jsaction.EventContract.STOP_PROPAGATION &&
eventInfo['eventType'] !== jsaction.A11y.MAYBE_CLICK_EVENT_TYPE) {
if (jsaction.event.isGecko &&
(eventInfo['targetElement'].tagName == goog.dom.TagName.INPUT ||
eventInfo['targetElement'].tagName == goog.dom.TagName.TEXTAREA) &&
(eventInfo['eventType'] == jsaction.EventType.FOCUS)) {
// Do nothing since stopping propagation a focus event on an input
// element in Firefox makes the text cursor disappear:
// https://bugzilla.mozilla.org/show_bug.cgi?id=509684
} else {
// Since we found a jsaction, prevent other handlers from seeing
// this event.
jsaction.event.stopPropagation(e);
}
} else if (
jsaction.EventContract.STOP_PROPAGATION &&
eventInfo['eventType'] === jsaction.A11y.MAYBE_CLICK_EVENT_TYPE) {
// We first need to let the dispatcher determine whether we can treat this
// event as a click event.
stopPropagationAfterDispatch = true;
}
if (eventContract.dispatcher_) {
if (jsaction.EventContract.shouldPreventDefaultBeforeDispatching(
eventInfo)) {
jsaction.event.preventDefault(e);
}
const eventToRetry = eventContract.dispatcher_(eventInfo);
if (eventToRetry && allowRehandling) {
// The dispatcher only returns an event for MAYBE_CLICK_EVENT_TYPE
// events that can't be casted to a click. We run it through the
// handler again to find keydown actions for it.
handleEvent.call(this, eventToRetry, /* allowRehandling =*/ false);
return;
}
if (stopPropagationAfterDispatch) {
jsaction.event.stopPropagation(eventInfo['event']);
}
} else {
jsaction.EventContract.queueEvent(eventContract, eventInfo, e);
}
jsaction.EventContract.afterEventHandler_(eventInfo);
};
return handler;
};
/**
* Returns true if the default action of this event should be prevented before
* this event is dispatched.
*
* This is primarily for internal use.
*
* @param {!jsaction.EventInfo} eventInfo The event info object.
* @return {boolean}
*/
jsaction.EventContract.shouldPreventDefaultBeforeDispatching = function(
eventInfo) {
// Prevent browser from following <a> node links if a jsaction is present
// and we are dispatching the action now. Note that the targetElement may be a
// child of an anchor that has a jsaction attached. For that reason, we need
// to check the actionElement rather than the targetElement.
return eventInfo['actionElement'] &&
eventInfo['actionElement'].tagName == goog.dom.TagName.A &&
(eventInfo['eventType'] == jsaction.EventType.CLICK ||
eventInfo['eventType'] == jsaction.EventType.CLICKMOD);
};
/**
* Queue an event to be replayed. This is called when an event is handled but no
* dispatcher is registered yet to handle it.
*
* This is primarily for internal use.
*
* @param {!jsaction.EventContract} eventContract The EventContract
* instance to queue the event on.
* @param {!jsaction.EventInfo} eventInfo The event info object.
* @param {!Event} e Event.
*/
jsaction.EventContract.queueEvent = function(eventContract, eventInfo, e) {
const copiedEvent = jsaction.event.maybeCopyEvent(e);
// The event is queued since there is no dispatcher registered
// yet. Potentially make a copy of the event in order to extend its
// life. The copy will later be used when attempting to replay.
eventInfo['event'] = copiedEvent;
eventContract.queue_.push(eventInfo);
};
/**
* Post-processes event. Called after event has been sent to the handler.
* @param {!jsaction.EventInfo} eventInfo
* @private
*/
jsaction.EventContract.afterEventHandler_ = function(eventInfo) {
// Setup sweeper if mouse events have been canceled.
if (eventInfo.event.type == jsaction.EventType.TOUCHEND &&
jsaction.event.isMouseEventsPrevented(eventInfo.event)) {
jsaction.EventContract.preventingMouseEvents_ = /** @type {!Event} */ (
jsaction.event.recreateTouchEventAsClick(eventInfo.event));
}
};
/**
* Searches for a jsaction that the DOM event maps to and creates an
* object containing event information used for dispatching by
* jsaction.Dispatcher. The dispatch information returned consists of
* the event type, target element, action and the Event instance
* supplied by the DOM. The jsaction for the DOM event is the first
* jsaction attribute above the target Node of the event, and below
* the container Node, that specifies a jsaction for the event
* type. If no such jsaction is found, the actionElement properties is null.
*
* @param {string} eventType The type of the event, e.g. 'click', as
* specified by event contract. This may differ from the DOM event
* type, because event contract may use more generic event types.
* @param {!Event} e The Event instance received by the container from
* the DOM.
* @param {!Node} container The container which limits the search for
* jsactions which can handle the event.
* @return {jsaction.EventInfo} The event info object. If its actionElement
* property is null, no jsaction was found above the target Node of the
* event.
* @private
*/
jsaction.EventContract.createEventInfo_ = function(eventType, e, container) {
// We distinguish modified and plain clicks in order to support the
// default browser behavior of modified clicks on links; usually to
// open the URL of the link in new tab or new window on ctrl/cmd
// click. A DOM 'click' event is mapped to the jsaction 'click'
// event iff there is no modifier present on the event. If there is
// a modifier, it's mapped to 'clickmod' instead.
//
// It's allowed to omit the event in the jsaction attribute. In that
// case, 'click' is assumed. Thus the following two are equivalent:
//
// <a href="someurl" jsaction="gna.fu">
// <a href="someurl" jsaction="click:gna.fu">
//
// For unmodified clicks, EventContract invokes the jsaction
// 'gna.fu'. For modified clicks, EventContract won't find a
// suitable action and leave the event to be handled by the
// browser.
//
// In order to also invoke a jsaction handler for a modifier click,
// 'clickmod' needs to be used:
//
// <a href="someurl" jsaction="clickmod:gna.fu">
//
// EventContract invokes the jsaction 'gna.fu' for modified
// clicks. Unmodified clicks are left to the browser.
//
// In order to set up the event contract to handle both clickonly and
// clickmod, only addEvent(jsaction.EventType.CLICK) is necessary.
//
// In order to set up the event contract to handle click,
// addEvent() is necessary for CLICK, KEYDOWN, and KEYPRESS event types. If
// the jsaction.EventContract.A11Y_CLICK_SUPPORT flag is turned on, addEvent()
// will set up the appropriate key event handler automatically.
if (eventType == jsaction.EventType.CLICK &&
jsaction.event.isModifiedClickEvent(e)) {
eventType = jsaction.EventType.CLICKMOD;
} else if (
jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER &&
jsaction.EventContract.A11Y_CLICK_SUPPORT &&
eventType == jsaction.EventType.KEYDOWN &&
!e[jsaction.A11y.SKIP_A11Y_CHECK]) {
// We use a string literal as this value needs to be referenced in the
// dispatcher's binary.
eventType = jsaction.A11y.MAYBE_CLICK_EVENT_TYPE;
} else if (
!jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER &&
jsaction.EventContract.A11Y_CLICK_SUPPORT &&
jsaction.event.isActionKeyEvent(e)) {
eventType = jsaction.EventContract.CLICKKEY_;
}
const target = /** @type {!Element} */ (e.srcElement || e.target);
let eventInfo = jsaction.EventContract.createEventInfoInternal_(
eventType, e, target, '', null);
// NOTE(user): In order to avoid complicating the code that calculates the
// event's path, we need a common interface to iterating over event.path or
// walking the DOM. We use the generator pattern here, as generating the
// path array ahead of time for DOM walks will result in degraded
// performance.
/** @type {jsaction.ActionInfo} */
let actionInfo;
// NOTE(user): This is a work around some issues with custom dispatchers.
let element;
if (jsaction.EventContract.USE_EVENT_PATH) {
const generator = jsaction.domGenerator.getGenerator(
e, target, /** @type {!Element} */ (container));
for (let node; node = generator.next();) {
element = node;
actionInfo =
jsaction.EventContract.getAction_(element, eventType, e, container);
eventInfo = jsaction.EventContract.createEventInfoInternal_(
actionInfo.eventType, actionInfo.event || e, target,
actionInfo.action || '', element, eventInfo['timeStamp']);
// TODO(user): If we can get rid of the break on actionInfo.ignore
// these loops can collapse down to one and the contents can live in
// a function.
// Stop walking the DOM prematurely if we will ignore this event. This is
// used solely for fastbutton's implementation.
if (actionInfo.ignore ||
// An event is handled by at most one jsaction. Thus we stop at
// the first matching jsaction specified in a jsaction attribute
// up the ancestor chain of the event target node.
actionInfo.action) {
break;
}
}
} else {
for (let node = target; node && node != container;
// Walk to the parent node, unless the node has a different owner in
// which case we walk to the owner.
node = node[jsaction.Property.OWNER] || node.parentNode) {
element = node;
actionInfo =
jsaction.EventContract.getAction_(element, eventType, e, container);
// Stop walking the DOM prematurely if we will ignore this event. This is
// used solely for fastbutton's implementation.
if (actionInfo.ignore ||
// An event is handled by at most one jsaction. Thus we stop at
// the first matching jsaction specified in a jsaction attribute
// up the ancestor chain of the event target node.
actionInfo.action) {
break;
}
}
if (actionInfo) {
eventInfo = jsaction.EventContract.createEventInfoInternal_(
actionInfo.eventType, actionInfo.event || e, target,
actionInfo.action || '', element, eventInfo['timeStamp']);
}
}
// A touchend is "enhanced" to support mouse-events canceling.
if (eventInfo && eventInfo['eventType'] == jsaction.EventType.TOUCHEND) {
jsaction.event.addPreventMouseEventsSupport(eventInfo['event']);
}
if (actionInfo && actionInfo.action) {
// Prevent scrolling if the Space key was pressed or prevent the browser's
// default action for native HTML controls.
if (!jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER &&
jsaction.EventContract.A11Y_CLICK_SUPPORT &&
eventType == jsaction.EventContract.CLICKKEY_ &&
(jsaction.event.isSpaceKeyEvent(e) ||
jsaction.event.shouldCallPreventDefaultOnNativeHtmlControl(e))) {
jsaction.event.preventDefault(e);
}
// We attempt to handle the mouseenter/mouseleave events here by
// detecting whether the mouseover/mouseout events correspond to
// entering/leaving an element.
if (jsaction.EventContract.MOUSE_SPECIAL_SUPPORT &&
(eventType == jsaction.EventType.MOUSEENTER ||
eventType == jsaction.EventType.MOUSELEAVE)) {
// We attempt to handle the mouseenter/mouseleave events here by
// detecting whether the mouseover/mouseout events correspond to
// entering/leaving an element.
if (jsaction.event.isMouseSpecialEvent(e, eventType, element)) {
// If both mouseover/mouseout and mouseenter/mouseleave events are
// enabled, two separate handlers for mouseover/mouseout are
// registered. Both handlers will see the same event instance
// so we create a copy to avoid interfering with the dispatching of
// the mouseover/mouseout event.
const copiedEvent = jsaction.event.createMouseSpecialEvent(
e, /** @type {!Element} */ (element));
eventInfo['event'] = /** @type {!Event} */ (copiedEvent);
// Since the mouseenter/mouseleave events do not bubble, the target
// of the event is technically the node on which the jsaction is
// specified (the actionElement).
eventInfo['targetElement'] = element;
} else {
eventInfo['action'] = '';
eventInfo['actionElement'] = null;
}
}
return eventInfo;
}
// Reset action-related properties of the current eventInfo, to ensure we
// won't dispatch a non-existing action.
eventInfo['action'] = '';
eventInfo['actionElement'] = null;
return eventInfo;
};
/**
* @param {string} eventType
* @param {!Event} e
* @param {!Element} targetElement
* @param {string} action
* @param {Element} actionElement
* @param {number=} opt_timeStamp
* @return {jsaction.EventInfo}
* @private
*/
jsaction.EventContract.createEventInfoInternal_ = function(
eventType, e, targetElement, action, actionElement, opt_timeStamp) {
// Event#timeStamp is broken on Firefox for synthetic events. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=238041 for details. Since
// Firefox marks Event#timeStamp as read-only, the only workaround is to
// expose a timestamp directly in eventInfo, to be consistent across all
// browsers.
return /** @type {jsaction.EventInfo} */ ({
'eventType': eventType,
'event': e,
'targetElement': targetElement,
'action': action,
'actionElement': actionElement,
'timeStamp': opt_timeStamp || goog.now()
});
};
/**
* Determines if we can skip triggering the dispatcher based on the eventType
* and action found.
*
* @param {!jsaction.EventInfo} eventInfo
* @return {boolean}
* @private
*/
jsaction.EventContract.canSkipDispatch_ = function(eventInfo) {
// Return early if no action element found while walking up the DOM tree.
if (!jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER &&
!eventInfo['actionElement']) {
return true;
}
// Return early in A11Y_SUPPORT_IN_DISPATCHER mode only if the eventType is
// not MAYBE_CLICK_EVENT_TYPE, because if it is, we want the dispatcher to
// check the key event and retrigger the event if necessary.
if (jsaction.EventContract.A11Y_SUPPORT_IN_DISPATCHER &&
!eventInfo['actionElement'] &&
eventInfo['eventType'] != jsaction.A11y.MAYBE_CLICK_EVENT_TYPE) {
return true;
}
return false;
};
/**
* Accesses the event handler attribute value of a DOM node. It guards
* against weird situations (described in the body) that occur in
* connection with nodes that are removed from their document.
* @param {!Element} node The DOM node.
* @param {string} attribute The name of the attribute to access.
* @return {?string} The attribute value if it was found, null
* otherwise.
* @private
*/
jsaction.EventContract.getAttr_ = function(node, attribute) {
let value = null;
// NOTE(user): Nodes in IE do not always have a getAttribute
// method defined. This is the case where sourceElement has in
// fact been removed from the DOM before eventContract begins
// handling - where a parentNode does not have getAttribute
// defined.
// NOTE(ruilopes): We must use the 'in' operator instead of the regular dot
// notation, since the latter fails in IE8 if the getAttribute method is not
// defined. See b/7139109.
if ('getAttribute' in node) {
value = node.getAttribute(attribute);
}
return value;
};
/**
* Since maps from event to action are immutable we can use a single map
* to represent the empty map.
* @private @const {!Object.<string, string>}
*/
jsaction.EventContract.EMPTY_ACTION_MAP_ = {};
/**
* Parses and caches an element's jsaction element into a map.
*
* This is primarily for internal use.
*
* @param {!Element} node The DOM node to retrieve the jsaction map from.
* @param {!Node} container The node which limits the namespace lookup
* for a jsaction name. The container node itself will not be
* searched.
* @return {!Object.<string, string>} Map from event to qualified name
* of the jsaction bound to it.
*/
jsaction.EventContract.parseActions = function(node, container) {
let actionMap = jsaction.Cache.get(node);
if (!actionMap) {
const attvalue =
jsaction.EventContract.getAttr_(node, jsaction.Attribute.JSACTION);
if (!attvalue) {
actionMap = jsaction.EventContract.EMPTY_ACTION_MAP_;
jsaction.Cache.set(node, actionMap);
} else {
actionMap = jsaction.Cache.getParsed(attvalue);
if (!actionMap) {
actionMap = {};
const values = attvalue.split(jsaction.EventContract.REGEXP_SEMICOLON_);
const I = values ? values.length : 0;
for (let idx = 0; idx < I; idx++) {
const value = values[idx];
if (!value) {
continue;
}
const colon = value.indexOf(jsaction.Char.EVENT_ACTION_SEPARATOR);
const hasColon = colon != -1;
const type = hasColon ?
jsaction.EventContract.stringTrim_(value.substr(0, colon)) :
jsaction.EventContract.defaultEventType_;
const action = hasColon ?
jsaction.EventContract.stringTrim_(value.substr(colon + 1)) :
value;
actionMap[type] = action;
}
jsaction.Cache.setParsed(attvalue, actionMap);
}
// If namespace support is active we need to augment the (potentially
// cached) jsaction mapping with the namespace.
if (jsaction.EventContract.JSNAMESPACE_SUPPORT) {
const noNs = actionMap;
actionMap = {};
for (let type in noNs) {
actionMap[type] = jsaction.EventContract.getQualifiedName_(
noNs[type], node, container);
}
}
jsaction.Cache.set(node, actionMap);
}
}
return actionMap;
};
/**
* Accesses the jsaction map on a node and retrieves the name of the
* action the given event is mapped to, if any. It parses the
* attribute value and stores it in a property on the node for
* subsequent retrieval without re-parsing and re-accessing the
* attribute. In order to fully qualify jsaction names using a
* namespace, the DOM is searched starting at the current node and
* going through ancestor nodes until a jsnamespace attribute is
* found.
*
* @param {!Element} node The DOM node to retrieve the jsaction map
* from.
* @param {string} eventType The type of the event for which to
* retrieve the action.
* @param {!Event} event The current browser event.
* @param {!Node} container The node which limits the namespace lookup
* for a jsaction name. The container node itself will not be
* searched.
* @return {!jsaction.ActionInfo} The action info.
* @private
*/
jsaction.EventContract.getAction_ = function(
node, eventType, event, container) {
const actionMap = jsaction.EventContract.parseActions(node, container);
let originalEventType;
if (jsaction.EventContract.A11Y_CLICK_SUPPORT) {
if (eventType == jsaction.A11y.MAYBE_CLICK_EVENT_TYPE &&
actionMap[jsaction.EventType.CLICK]) {
// We'll take the first CLICK action we find and have the dispatcher check
// if the keydown event can be used as a CLICK. If not, the dispatcher
// will retrigger the event so that we can find a keydown event instead.
originalEventType = eventType;
eventType = jsaction.EventType.CLICK;
} else if (eventType == jsaction.EventContract.CLICKKEY_) {
// A 'click' triggered by a DOM keypress should be mapped to the 'click'
// jsaction.
eventType = jsaction.EventType.CLICK;
} else if (
eventType == jsaction.EventType.CLICK &&
!actionMap[jsaction.EventType.CLICK]) {
// A 'click' triggered by a DOM click should be mapped to the 'click'
// jsaction, if available, or else fallback to the 'clickonly' jsaction.
// If 'click' and 'clickonly' jsactions are used together, 'click' will
// prevail.
eventType = jsaction.EventType.CLICKONLY;
}
}
let overrideEvent = null;
if (jsaction.EventContract.FAST_CLICK_SUPPORT &&
// Don't want fast click behavior? Just bind clickonly instead.
actionMap[jsaction.EventType.CLICK]) {
const fastEvent =
jsaction.EventContract.getFastClickEvent_(node, event, actionMap);
if (!fastEvent) {
// Null means to stop looking for further events, as the logic event
// has already been handled or the event started a sequence that may
// eventually lead to a logic click event.
return {eventType: eventType, action: '', event: null, ignore: true};
} else if (fastEvent != event) {
overrideEvent = fastEvent;
eventType = fastEvent.type;
}
}
// An empty action indicates that no jsaction attribute was found in the given
// DOM node.
const actionName = actionMap[eventType] || '';
// When we get MAYBE_CLICK_EVENT_TYPE as an eventType, we want to retrieve the
// action corresponding to CLICK, but still keep the eventType as
// MAYBE_CLICK_EVENT_TYPE. The dispatcher uses this event type to determine if
// it should get the handler for the action.
return {
eventType: originalEventType ? originalEventType : eventType,
action: actionName,
event: overrideEvent,
ignore: false
};
};
/**
* Returns the qualified jsaction name, i.e. the name of the jsaction
* including the namespace part before the dot. If the given jsaction
* name doesn't already contain the namespace, the function iterates
* over ancestor nodes until a jsnamespace attribute is found, and
* uses the value of that attribute as the namespace.
*
* @param {string} name The jsaction name to resolve the namespace of.
* @param {Element} start The node from which to start searching for a
* jsnamespace attribute.
* @param {Node} container The node which limits the search for a
* jsnamespace attribute. This node will be searched.
* @return {string} The qualified name of the jsaction. If no
* namespace is found, returns the unqualified name in case it
* exists in the global namespace.
* @private
*/
jsaction.EventContract.getQualifiedName_ = function(name, start, container) {
if (jsaction.EventContract.JSNAMESPACE_SUPPORT) {
if (jsaction.EventContract.isQualifiedName_(name)) {
return name;
}
for (let node = start; node; node = node.parentNode) {
const ns = jsaction.EventContract.getNamespace_(
/** @type {!Element} */ (node));
if (ns) {
return ns + jsaction.Char.NAMESPACE_ACTION_SEPARATOR + name;
}
// If this node is the container, stop.
if (node == container) {
break;
}
}
}
return name;
};
/**
* Converts a sequence of touchstart and touchend events into a click event
* and ignores a subsequent click event (within 400ms).
*
* This method returns the original or a synthesized event instance, or null if
* the event should be ignored. The original event indicates that the original
* event should proceed as planned. If the event should be ignored (e.g. to
* issue a new event later), the returned value is null. However, if the
* "fast click" event is determined, a newly synthesized event instance is
* returned. The "click" event has to be synthesized to imitate an actual
* "click" event based on "touchend". This includes filling in type, target,
* clientX/Y, etc, which are expected from a "click" event. The original Event
* instance cannot simply be modified, because the DOM Event Spec defines Event
* properties to be immutable, and some browsers (specifically Safari in iOS/8)
* enforce this.
*
* @param {!Element} node The current node with a jsaction annotation.
* @param {!Event} event The current browser event.
* @param {!Object.<string, string>} actionMap
* @return {Event}
* @private
*/
jsaction.EventContract.getFastClickEvent_ = function(node, event, actionMap) {
if (event.type == jsaction.EventType.CLICK) {
return event;
}
if (event.targetTouches && event.targetTouches.length > 1) {
// Click emulation does not make sense for multi touch.
return event;
}
const fastClickNode = jsaction.EventContract.fastClickNode_;
const target = event.target;
if (target) {
// Don't do anything special for clicks on elements with elaborate built in
// click and focus behavior.
if (jsaction.EventContract.isInput_(target)) {
return event;
}
}
const touch = jsaction.event.getTouchData(event);