-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
action-impl.js
1415 lines (1297 loc) · 40.3 KB
/
action-impl.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
import {
ActionTrust_Enum,
DEFAULT_ACTION,
RAW_OBJECT_ARGS_KEY,
actionTrustToString,
} from '#core/constants/action-constants';
import {Keys_Enum} from '#core/constants/key-codes';
import {isAmp4Email} from '#core/document/format';
import {isEnabled} from '#core/dom';
import {isFiniteNumber} from '#core/types';
import {isArray, toArray} from '#core/types/array';
import {debounce, throttle} from '#core/types/function';
import {dict, getValueForExpr, hasOwn, map} from '#core/types/object';
import {getWin} from '#core/window';
import {Services} from '#service';
import {getDetail} from '#utils/event-helper';
import {dev, devAssert, user, userAssert} from '#utils/log';
import {reportError} from '../error-reporting';
import {getMode} from '../mode';
import {registerServiceBuilderForDoc} from '../service-helpers';
/** @const {string} */
const TAG_ = 'Action';
/** @const {string} */
const ACTION_MAP_ = '__AMP_ACTION_MAP__' + Math.random();
/** @const {string} */
const ACTION_QUEUE_ = '__AMP_ACTION_QUEUE__';
/** @const {string} */
const ACTION_HANDLER_ = '__AMP_ACTION_HANDLER__';
/** @const {number} */
const DEFAULT_DEBOUNCE_WAIT = 300; // ms
/** @const {number} */
const DEFAULT_THROTTLE_INTERVAL = 100; // ms
/** @const {!Object<string,!Array<string>>} */
const NON_AMP_ELEMENTS_ACTIONS_ = {
'form': ['submit', 'clear'],
};
const DEFAULT_EMAIL_ALLOWLIST = [
{tagOrTarget: 'AMP', method: 'setState'},
{tagOrTarget: '*', method: 'focus'},
{tagOrTarget: '*', method: 'hide'},
{tagOrTarget: '*', method: 'show'},
{tagOrTarget: '*', method: 'toggleClass'},
{tagOrTarget: '*', method: 'toggleChecked'},
{tagOrTarget: '*', method: 'toggleVisibility'},
];
/**
* Interactable widgets which should trigger tap events when the user clicks
* or activates via the keyboard. Not all are here, e.g. progressbar, tabpanel,
* since they are text inputs, readonly, or composite widgets that shouldn't
* need to trigger tap events from spacebar or enter on their own.
* See https://www.w3.org/TR/wai-aria-1.1/#widget_roles
* @const {!Object<boolean>}
*/
export const TAPPABLE_ARIA_ROLES = {
'button': true,
'checkbox': true,
'link': true,
'listbox': true,
'menuitem': true,
'menuitemcheckbox': true,
'menuitemradio': true,
'option': true,
'radio': true,
'scrollbar': true,
'slider': true,
'spinbutton': true,
'switch': true,
'tab': true,
'treeitem': true,
};
/**
* An expression arg value, e.g. `foo.bar` in `e:t.m(arg=foo.bar)`.
* @typedef {{expression: string}}
*/
let ActionInfoArgExpressionDef;
/**
* An arg value.
* @typedef {(boolean|number|string|ActionInfoArgExpressionDef)}
*/
let ActionInfoArgValueDef;
/**
* Map of arg names to their values, e.g. {arg: 123} in `e:t.m(arg=123)`.
* @typedef {Object<string, ActionInfoArgValueDef>}
*/
let ActionInfoArgsDef;
/**
* @typedef {{
* event: string,
* target: string,
* method: string,
* args: ?ActionInfoArgsDef,
* str: string
* }}
*/
export let ActionInfoDef;
/**
* Function called when an action is invoked.
*
* Optionally, takes this action's position within all actions triggered by
* the same event, as well as said action array, as params.
*
* If the action is chainable, returns a Promise which resolves when the
* action is complete. Otherwise, returns null.
*
* @typedef {function(!ActionInvocation, number=, !Array<!ActionInfoDef>=):?Promise}
*/
let ActionHandlerDef;
/**
* @typedef {Event|DeferredEvent}
*/
export let ActionEventDef;
/**
* The structure that contains all details of the action method invocation.
* @struct @const @package For type.
*/
export class ActionInvocation {
/**
* For example:
*
* <div id="div" on="tap:myForm.submit(foo=bar)">
* <button id="btn">Submit</button>
* </div>
*
* `node` is #myForm.
* `method` is "submit".
* `args` is {'foo': 'bar'}.
* `source` is #btn.
* `caller` is #div.
* `event` is a "click" Event object.
* `actionEventType` is "tap".
* `trust` depends on whether this action was a result of a user gesture.
* `tagOrTarget` is "amp-form".
* `sequenceId` is a pseudo-UUID.
*
* @param {!Node} node Element whose action is being invoked.
* @param {string} method Name of the action being invoked.
* @param {?JsonObject} args Named action arguments.
* @param {?Element} source Element that generated the `event`.
* @param {?Element} caller Element containing the on="..." action handler.
* @param {?ActionEventDef} event The event object that triggered this action.
* @param {!ActionTrust_Enum} trust The trust level of this invocation's trigger.
* @param {?string} actionEventType The AMP event name that triggered this.
* @param {?string} tagOrTarget The global target name or the element tagName.
* @param {number} sequenceId An identifier for this action's sequence (all
* actions triggered by one event e.g. "tap:form1.submit, form2.submit").
*/
constructor(
node,
method,
args,
source,
caller,
event,
trust,
actionEventType = '?',
tagOrTarget = null,
sequenceId = Math.random()
) {
/** @type {!Node} */
this.node = node;
/** @const {string} */
this.method = method;
/** @const {?JsonObject} */
this.args = args;
/** @const {?Element} */
this.source = source;
/** @const {?Element} */
this.caller = caller;
/** @const {?ActionEventDef} */
this.event = event;
/** @const {!ActionTrust_Enum} */
this.trust = trust;
/** @const {?string} */
this.actionEventType = actionEventType;
/** @const {string} */
this.tagOrTarget = tagOrTarget || node.tagName;
/** @const {number} */
this.sequenceId = sequenceId;
}
/**
* Returns true if the trigger event has a trust equal to or greater than
* `minimumTrust`. Otherwise, logs a user error and returns false.
* @param {ActionTrust_Enum} minimumTrust
* @return {boolean}
*/
satisfiesTrust(minimumTrust) {
// Sanity check.
if (!isFiniteNumber(this.trust)) {
dev().error(TAG_, `Invalid trust for '${this.method}': ${this.trust}`);
return false;
}
if (this.trust < minimumTrust) {
const t = actionTrustToString(this.trust);
user().error(
TAG_,
`"${this.actionEventType}" event with "${t}" trust is not allowed to ` +
`invoke "${this.tagOrTarget.toLowerCase()}.${this.method}".`
);
return false;
}
return true;
}
}
/**
* TODO(dvoytenko): consider splitting this class into two:
* 1. A class that has a method "trigger(element, eventType, data)" and
* simply can search target in DOM and trigger methods on it.
* 2. A class that configures event recognizers and rules and then
* simply calls action.trigger.
*/
export class ActionService {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {(!Document|!ShadowRoot)=} opt_root
*/
constructor(ampdoc, opt_root) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @const {!Document|!ShadowRoot} */
this.root_ = opt_root || ampdoc.getRootNode();
/** @const {boolean} */
this.isEmail_ =
this.ampdoc.isSingleDoc() &&
isAmp4Email(/** @type {!Document} */ (this.root_));
/**
* Optional allowlist of actions, e.g.:
*
* [{tagOrTarget: 'AMP', method: 'navigateTo'},
* {tagOrTarget: 'AMP-FORM', method: 'submit'},
* {tagOrTarget: '*', method: 'show'}]
*
* If not null, any actions that are not in the allowlist will be ignored
* and throw a user error at invocation time. Note that `tagOrTarget` is
* always the canonical uppercased form (same as
* `Element.prototype.tagName`). If `tagOrTarget` is the wildcard '*', then
* the allowlisted method is allowed on any tag or target.
*
* For AMP4Email format documents, allowed actions are autogenerated.
* @private {?Array<{tagOrTarget: string, method: string}>}
*/
this.allowlist_ = this.isEmail_ ? DEFAULT_EMAIL_ALLOWLIST : null;
/** @const @private {!Object<string, ActionHandlerDef>} */
this.globalTargets_ = map();
/**
* @const @private {!Object<string, {handler: ActionHandlerDef, minTrust: ActionTrust_Enum}>}
*/
this.globalMethodHandlers_ = map();
// Add core events.
this.addEvent('tap');
this.addEvent('submit');
this.addEvent('change');
this.addEvent('input-debounced');
this.addEvent('input-throttled');
this.addEvent('valid');
this.addEvent('invalid');
}
/**
* @param {string} name
* TODO(dvoytenko): switch to a system where the event recognizers are
* registered with Action instead, e.g. "doubletap", "tap to zoom".
*/
addEvent(name) {
if (name == 'tap') {
// TODO(dvoytenko): if needed, also configure touch-based tap, e.g. for
// fast-click.
this.root_.addEventListener('click', (event) => {
if (!event.defaultPrevented) {
const element = dev().assertElement(event.target);
this.trigger(element, name, event, ActionTrust_Enum.HIGH);
}
});
this.root_.addEventListener('keydown', (event) => {
const {key, target} = event;
const element = dev().assertElement(target);
if (key == Keys_Enum.ENTER || key == Keys_Enum.SPACE) {
const role = element.getAttribute('role');
const isTapEventRole =
role && hasOwn(TAPPABLE_ARIA_ROLES, role.toLowerCase());
if (!event.defaultPrevented && isTapEventRole) {
const hasAction = this.trigger(
element,
name,
event,
ActionTrust_Enum.HIGH
);
// Only if the element has an action do we prevent the default.
// In the absence of an action, e.g. on="[event].method", we do not
// want to stop default behavior.
if (hasAction) {
event.preventDefault();
}
}
}
});
} else if (name == 'submit') {
this.root_.addEventListener(name, (event) => {
const element = dev().assertElement(event.target);
// For get requests, the delegating to the viewer needs to happen
// before this.
this.trigger(element, name, event, ActionTrust_Enum.HIGH);
});
} else if (name == 'change') {
this.root_.addEventListener(name, (event) => {
const element = dev().assertElement(event.target);
this.addTargetPropertiesAsDetail_(event);
this.trigger(element, name, event, ActionTrust_Enum.HIGH);
});
} else if (name == 'input-debounced') {
const debouncedInput = debounce(
this.ampdoc.win,
(event) => {
const target = dev().assertElement(event.target);
this.trigger(
target,
name,
/** @type {!ActionEventDef} */ (event),
ActionTrust_Enum.HIGH
);
},
DEFAULT_DEBOUNCE_WAIT
);
this.root_.addEventListener('input', (event) => {
// Create a DeferredEvent to avoid races where the browser cleans up
// the event object before the async debounced function is called.
const deferredEvent = new DeferredEvent(event);
this.addTargetPropertiesAsDetail_(deferredEvent);
debouncedInput(deferredEvent);
});
} else if (name == 'input-throttled') {
const throttledInput = throttle(
this.ampdoc.win,
(event) => {
const target = dev().assertElement(event.target);
this.trigger(
target,
name,
/** @type {!ActionEventDef} */ (event),
ActionTrust_Enum.HIGH
);
},
DEFAULT_THROTTLE_INTERVAL
);
this.root_.addEventListener('input', (event) => {
const deferredEvent = new DeferredEvent(event);
this.addTargetPropertiesAsDetail_(deferredEvent);
throttledInput(deferredEvent);
});
} else if (name == 'valid' || name == 'invalid') {
this.root_.addEventListener(name, (event) => {
const element = dev().assertElement(event.target);
this.trigger(element, name, event, ActionTrust_Enum.HIGH);
});
}
}
/**
* Registers the action target that will receive all designated actions.
* @param {string} name
* @param {ActionHandlerDef} handler
*/
addGlobalTarget(name, handler) {
this.globalTargets_[name] = handler;
}
/**
* Registers the action handler for a common method.
* @param {string} name
* @param {ActionHandlerDef} handler
* @param {ActionTrust_Enum} minTrust
*/
addGlobalMethodHandler(name, handler, minTrust = ActionTrust_Enum.DEFAULT) {
this.globalMethodHandlers_[name] = {handler, minTrust};
}
/**
* Triggers the specified event on the target element.
* @param {!Element} target
* @param {string} eventType
* @param {?ActionEventDef} event
* @param {!ActionTrust_Enum} trust
* @param {?JsonObject=} opt_args
* @return {boolean} true if the target has an action.
*/
trigger(target, eventType, event, trust, opt_args) {
return this.action_(target, eventType, event, trust, opt_args);
}
/**
* Triggers execution of the method on a target/method.
* @param {!Element} target
* @param {string} method
* @param {?JsonObject} args
* @param {?Element} source
* @param {?Element} caller
* @param {?ActionEventDef} event
* @param {ActionTrust_Enum} trust
*/
execute(target, method, args, source, caller, event, trust) {
const invocation = new ActionInvocation(
target,
method,
args,
source,
caller,
event,
trust
);
this.invoke_(invocation);
}
/**
* Installs action handler for the specified element. The action handler is
* responsible for checking invocation trust.
*
* For AMP elements, use base-element.registerAction() instead.
*
* @param {!Element} target
* @param {ActionHandlerDef} handler
*/
installActionHandler(target, handler) {
// TODO(dvoytenko, #7063): switch back to `target.id` with form proxy.
const targetId = target.getAttribute('id') || '';
devAssert(
isAmpTagName(targetId) ||
target.tagName.toLowerCase() in NON_AMP_ELEMENTS_ACTIONS_,
'AMP or special element expected: %s',
target.tagName + '#' + targetId
);
if (target[ACTION_HANDLER_]) {
dev().error(TAG_, `Action handler already installed for ${target}`);
return;
}
target[ACTION_HANDLER_] = handler;
/** @const {Array<!ActionInvocation>} */
const queuedInvocations = target[ACTION_QUEUE_];
if (isArray(queuedInvocations)) {
// Invoke and clear all queued invocations now handler is installed.
Services.timerFor(getWin(target)).delay(() => {
// TODO(dvoytenko, #1260): dedupe actions.
queuedInvocations.forEach((invocation) => {
try {
handler(invocation);
} catch (e) {
dev().error(TAG_, 'Action execution failed:', invocation, e);
}
});
target[ACTION_QUEUE_].length = 0;
}, 1);
}
}
/**
* Checks if the given element has registered a particular action type.
* @param {!Element} element
* @param {string} actionEventType
* @param {!Element=} opt_stopAt
* @return {boolean}
*/
hasAction(element, actionEventType, opt_stopAt) {
return !!this.findAction_(element, actionEventType, opt_stopAt);
}
/**
* Checks if the given element's registered action resolves to at least one
* existing element by id or a global target (e.g. "AMP").
* @param {!Element} element
* @param {string} actionEventType
* @param {!Element=} opt_stopAt
* @return {boolean}
*/
hasResolvableAction(element, actionEventType, opt_stopAt) {
const action = this.findAction_(element, actionEventType, opt_stopAt);
if (!action) {
return false;
}
return action.actionInfos.some((action) => {
const {target} = action;
return !!this.getActionNode_(target);
});
}
/**
* Checks if the given element's registered action resolves to at least one
* existing element by id or a global target (e.g. "AMP").
* @param {!Element} element
* @param {string} actionEventType
* @param {!Element} targetElement
* @param {!Element=} opt_stopAt
* @return {boolean}
*/
hasResolvableActionForTarget(
element,
actionEventType,
targetElement,
opt_stopAt
) {
const action = this.findAction_(element, actionEventType, opt_stopAt);
if (!action) {
return false;
}
return action.actionInfos.some((actionInfo) => {
const {target} = actionInfo;
return this.getActionNode_(target) == targetElement;
});
}
/**
* For global targets e.g. "AMP", returns the document root. Otherwise,
* `target` is an element id and the corresponding element is returned.
* @param {string} target
* @return {?Document|?Element|?ShadowRoot}
* @private
*/
getActionNode_(target) {
return this.globalTargets_[target]
? this.root_
: this.root_.getElementById(target);
}
/**
* Sets the action allowlist. Can be used to clear it.
* @param {!Array<{tagOrTarget: string, method: string}>} allowlist
*/
setAllowlist(allowlist) {
devAssert(
allowlist.every((v) => v.tagOrTarget && v.method),
'Action allowlist entries should be of shape { tagOrTarget: string, method: string }'
);
this.allowlist_ = allowlist;
}
/**
* Adds an action to the allowlist.
* @param {string} tagOrTarget The tag or target to allowlist, e.g.
* 'AMP-LIST', '*'.
* @param {string|Array<string>} methods The method(s) to allowlist, e.g. 'show', 'hide'.
* @param {Array<string>=} opt_forFormat
*/
addToAllowlist(tagOrTarget, methods, opt_forFormat) {
// TODO(wg-performance): When it becomes possible to getFormat(),
// we can store `format_` instead of `isEmail_` and check
// (opt_forFormat && !opt_forFormat.includes(this.format_))
if (opt_forFormat && opt_forFormat.includes('email') !== this.isEmail_) {
return;
}
if (!this.allowlist_) {
this.allowlist_ = [];
}
if (!isArray(methods)) {
methods = [methods];
}
methods.forEach((method) => {
if (
this.allowlist_.some(
(v) => v.tagOrTarget == tagOrTarget && v.method == method
)
) {
return;
}
this.allowlist_.push({tagOrTarget, method});
});
}
/**
* @param {!Element} source
* @param {string} actionEventType
* @param {?ActionEventDef} event
* @param {!ActionTrust_Enum} trust
* @param {?JsonObject=} opt_args
* @return {boolean} True if the element has an action.
* @private
*/
action_(source, actionEventType, event, trust, opt_args) {
const action = this.findAction_(source, actionEventType);
if (!action) {
return false;
}
// Use a pseudo-UUID to uniquely identify this sequence of actions.
// A sequence is all actions triggered by a single event.
const sequenceId = Math.random();
// Invoke actions serially, where each action waits for its predecessor
// to complete. `currentPromise` is the i'th promise in the chain.
/** @type {?Promise} */
let currentPromise = null;
action.actionInfos.forEach((actionInfo) => {
const {args, method, str, target} = actionInfo;
const dereferencedArgs = dereferenceArgsVariables(args, event, opt_args);
const invokeAction = () => {
const node = this.getActionNode_(target);
if (!node) {
this.error_(`Target "${target}" not found for action [${str}].`);
return;
}
const invocation = new ActionInvocation(
node,
method,
dereferencedArgs,
source,
action.node,
event,
trust,
actionEventType,
node.tagName || target,
sequenceId
);
return this.invoke_(invocation);
};
// Wait for the previous action, if any.
currentPromise = currentPromise
? currentPromise.then(invokeAction)
: invokeAction();
});
return action.actionInfos.length >= 1;
}
/**
* @param {string} message
* @param {?Element=} opt_element
* @private
*/
error_(message, opt_element) {
if (opt_element) {
// reportError() supports displaying the element in dev console.
const e = user().createError(`[${TAG_}] ${message}`);
reportError(e, opt_element);
throw e;
} else {
user().error(TAG_, message);
}
}
/**
* @param {!ActionInvocation} invocation
* @return {?Promise}
* @private
*/
invoke_(invocation) {
const {method, tagOrTarget} = invocation;
// Check that this action is allowlisted (if a allowlist is set).
if (this.allowlist_) {
if (!isActionAllowlisted(invocation, this.allowlist_)) {
this.error_(
`"${tagOrTarget}.${method}" is not allowlisted ${JSON.stringify(
this.allowlist_
)}.`
);
return null;
}
}
// Handle global targets e.g. "AMP".
const globalTarget = this.globalTargets_[tagOrTarget];
if (globalTarget) {
return globalTarget(invocation);
}
// Subsequent handlers assume that invocation target is an Element.
const node = dev().assertElement(invocation.node);
// Handle global actions e.g. "<any-element-id>.toggle".
const globalMethod = this.globalMethodHandlers_[method];
if (globalMethod && invocation.satisfiesTrust(globalMethod.minTrust)) {
return globalMethod.handler(invocation);
}
// Handle element-specific actions.
const lowerTagName = node.tagName.toLowerCase();
if (isAmpTagName(lowerTagName)) {
if (node.enqueAction) {
node.enqueAction(invocation);
} else {
this.error_(`Unrecognized AMP element "${lowerTagName}".`, node);
}
return null;
}
// Special non-AMP elements with AMP ID or known supported actions.
const nonAmpActions = NON_AMP_ELEMENTS_ACTIONS_[lowerTagName];
// TODO(dvoytenko, #7063): switch back to `target.id` with form proxy.
const targetId = node.getAttribute('id') || '';
if (
isAmpTagName(targetId) ||
(nonAmpActions && nonAmpActions.indexOf(method) > -1)
) {
const handler = node[ACTION_HANDLER_];
if (handler) {
handler(invocation);
} else {
node[ACTION_QUEUE_] = node[ACTION_QUEUE_] || [];
node[ACTION_QUEUE_].push(invocation);
}
return null;
}
// Unsupported method.
this.error_(
`Target (${tagOrTarget}) doesn't support "${method}" action.`,
invocation.caller
);
return null;
}
/**
* @param {!Element} target
* @param {string} actionEventType
* @param {!Element=} opt_stopAt
* @return {?{node: !Element, actionInfos: !Array<!ActionInfoDef>}}
*/
findAction_(target, actionEventType, opt_stopAt) {
// Go from target up the DOM tree and find the applicable action.
let n = target;
while (n) {
if (opt_stopAt && n == opt_stopAt) {
return null;
}
const actionInfos = this.matchActionInfos_(n, actionEventType);
if (actionInfos && isEnabled(n)) {
return {node: n, actionInfos: devAssert(actionInfos)};
}
n = n.parentElement;
}
return null;
}
/**
* @param {!Element} node
* @param {string} actionEventType
* @return {?Array<!ActionInfoDef>}
*/
matchActionInfos_(node, actionEventType) {
const actionMap = this.getActionMap_(node, actionEventType);
if (!actionMap) {
return null;
}
return actionMap[actionEventType] || null;
}
/**
* @param {!Element} node
* @param {string} actionEventType
* @return {?Object<string, !Array<!ActionInfoDef>>}
*/
getActionMap_(node, actionEventType) {
let actionMap = node[ACTION_MAP_];
if (actionMap === undefined) {
actionMap = null;
if (node.hasAttribute('on')) {
const action = node.getAttribute('on');
actionMap = parseActionMap(action, node);
node[ACTION_MAP_] = actionMap;
} else if (node.hasAttribute('execute')) {
const action = node.getAttribute('execute');
actionMap = parseActionMap(`${actionEventType}:${action}`, node);
node[ACTION_MAP_] = actionMap;
}
}
return actionMap;
}
/**
* Resets a node's actions with those defined in the given actions string.
* @param {!Element} node
* @param {string} actionsStr
*/
setActions(node, actionsStr) {
node.setAttribute('on', actionsStr);
// Clear cache.
delete node[ACTION_MAP_];
}
/**
* Given a browser 'change' or 'input' event, add `detail` property to it
* containing allowlisted properties of the target element. Noop if `detail`
* is readonly.
* @param {!ActionEventDef} event
* @private
*/
addTargetPropertiesAsDetail_(event) {
const detail = /** @type {!JsonObject} */ (map());
const {target} = event;
if (target.value !== undefined) {
detail['value'] = target.value;
}
// Check tagName instead since `valueAsNumber` isn't supported on IE.
if (target.tagName == 'INPUT') {
// Probably supported natively but convert anyways for consistency.
detail['valueAsNumber'] = Number(target.value);
}
if (target.checked !== undefined) {
detail['checked'] = target.checked;
}
if (target.min !== undefined || target.max !== undefined) {
detail['min'] = target.min;
detail['max'] = target.max;
}
if (target.files) {
detail['files'] = toArray(target.files).map((file) => ({
'name': file.name,
'size': file.size,
'type': file.type,
}));
}
if (Object.keys(detail).length > 0) {
try {
event.detail = detail;
} catch {} // event.detail is readonly
}
}
}
/**
* @param {string} lowercaseTagName
* @return {boolean}
* @private
*/
function isAmpTagName(lowercaseTagName) {
return lowercaseTagName.substring(0, 4) === 'amp-';
}
/**
* Returns `true` if the given action invocation is allowlisted in the given
* allowlist. Default actions' alias, 'activate', are automatically
* allowlisted if their corresponding registered alias is allowlisted.
* @param {!ActionInvocation} invocation
* @param {!Array<{tagOrTarget: string, method: string}>} allowlist
* @return {boolean}
* @private
*/
function isActionAllowlisted(invocation, allowlist) {
let {method} = invocation;
const {node, tagOrTarget} = invocation;
// Use alias if default action is invoked.
if (
method === DEFAULT_ACTION &&
typeof node.getDefaultActionAlias == 'function'
) {
method = node.getDefaultActionAlias();
}
const lcMethod = method.toLowerCase();
const lcTagOrTarget = tagOrTarget.toLowerCase();
return allowlist.some((w) => {
if (
w.tagOrTarget.toLowerCase() === lcTagOrTarget ||
w.tagOrTarget === '*'
) {
if (w.method.toLowerCase() === lcMethod) {
return true;
}
}
return false;
});
}
/**
* A clone of an event object with its function properties replaced.
* This is useful e.g. for event objects that need to be passed to an async
* context, but the browser might have cleaned up the original event object.
* This clone replaces functions with error throws since they won't behave
* normally after the original object has been destroyed.
* @private visible for testing
*/
export class DeferredEvent {
/**
* @param {!Event} event
*/
constructor(event) {
/** @type {?Object} */
this.detail = null;
cloneWithoutFunctions(event, this);
}
}
/**
* Clones an object and replaces its function properties with throws.
* @param {!T} original
* @param {!T=} opt_dest
* @return {!T}
* @template T
* @private
*/
function cloneWithoutFunctions(original, opt_dest) {
const clone = opt_dest || map();
for (const prop in original) {
const value = original[prop];
if (typeof value === 'function') {
clone[prop] = notImplemented;
} else {
clone[prop] = original[prop];
}
}
return clone;
}
/** @private */
function notImplemented() {
devAssert(null, 'Deferred events cannot access native event functions.');
}
/**
* @param {string} action
* @param {!Element} context
* @return {?Object<string, !Array<!ActionInfoDef>>}
* @private Visible for testing only.
*/
export function parseActionMap(action, context) {
const assertAction = assertActionForParser.bind(null, action, context);
const assertToken = assertTokenForParser.bind(null, action, context);
let actionMap = null;
const toks = new ParserTokenizer(action);
let tok;
let peek;
do {
tok = toks.next();
if (
tok.type == TokenType_Enum.EOF ||
(tok.type == TokenType_Enum.SEPARATOR && tok.value == ';')
) {
// Expected, ignore.
} else if (
tok.type == TokenType_Enum.LITERAL ||
tok.type == TokenType_Enum.ID
) {
// Format: event:target.method
// Event: "event:"
const event = tok.value;
// Target: ":target." separator
assertToken(toks.next(), [TokenType_Enum.SEPARATOR], ':');
const actions = [];
// Handlers for event.
do {
const target = assertToken(toks.next(), [
TokenType_Enum.LITERAL,
TokenType_Enum.ID,
]).value;
// Method: ".method". Method is optional.
let method = DEFAULT_ACTION;
let args = null;
peek = toks.peek();
if (peek.type == TokenType_Enum.SEPARATOR && peek.value == '.') {
toks.next(); // Skip '.'
method =
assertToken(toks.next(), [
TokenType_Enum.LITERAL,
TokenType_Enum.ID,
]).value || method;
// Optionally, there may be arguments: "(key = value, key = value)".
peek = toks.peek();