forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind-impl.js
1549 lines (1434 loc) · 51.2 KB
/
bind-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
/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {AmpEvents} from '../../../src/amp-events';
import {BindEvents} from './bind-events';
import {BindValidator} from './bind-validator';
import {ChunkPriority, chunk} from '../../../src/chunk';
import {RAW_OBJECT_ARGS_KEY} from '../../../src/action-constants';
import {Services} from '../../../src/services';
import {Signals} from '../../../src/utils/signals';
import {
closestAncestorElementBySelector,
iterateCursor,
} from '../../../src/dom';
import {debounce} from '../../../src/utils/rate-limit';
import {deepEquals, getValueForExpr, parseJson} from '../../../src/json';
import {deepMerge, dict, map} from '../../../src/utils/object';
import {dev, devAssert, user} from '../../../src/log';
import {findIndex, remove} from '../../../src/utils/array';
import {getDetail} from '../../../src/event-helper';
import {getMode} from '../../../src/mode';
import {installServiceInEmbedScope} from '../../../src/service';
import {invokeWebWorker} from '../../../src/web-worker/amp-worker';
import {isArray, isFiniteNumber, isObject, toArray} from '../../../src/types';
import {reportError} from '../../../src/error';
import {rewriteAttributesForElement} from '../../../src/url-rewrite';
import {startsWith} from '../../../src/string';
import {whenDocumentReady} from '../../../src/document-ready';
const TAG = 'amp-bind';
/**
* Regular expression that identifies AMP CSS classes.
* Includes 'i-amphtml-', '-amp-', and 'amp-' prefixes.
* @type {!RegExp}
*/
const AMP_CSS_RE = /^(i?-)?amp(html)?-/;
/**
* Maximum depth for state merge.
* @type {number}
*/
const MAX_MERGE_DEPTH = 10;
/**
* A bound property, e.g. [property]="expression".
* `previousResult` is the result of this expression during the last evaluation.
* @typedef {{property: string, expressionString: string, previousResult: (BindExpressionResultDef|undefined)}}
*/
let BoundPropertyDef;
/**
* A tuple containing a single element and all of its bound properties.
* @typedef {{boundProperties: !Array<BoundPropertyDef>, element: !Element}}
*/
let BoundElementDef;
/**
* A map of tag names to arrays of attributes that do not have non-bind
* counterparts. For instance, amp-carousel allows a `[slide]` attribute,
* but does not support a `slide` attribute.
* @const {!Object<string, !Array<string>>}
*/
const BIND_ONLY_ATTRIBUTES = map({
'AMP-CAROUSEL': ['slide'],
// TODO (#18875): add is-layout-container to validator file for amp-list
'AMP-LIST': ['state', 'is-layout-container'],
'AMP-SELECTOR': ['selected'],
});
/**
* Bind is an ampdoc-scoped service that handles the Bind lifecycle, from
* scanning for bindings to evaluating expressions to mutating elements.
* @implements {../../../src/service.EmbeddableService}
*/
export class Bind {
/**
* If `opt_win` is provided, scans its document for bindings instead.
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Window=} opt_win
*/
constructor(ampdoc, opt_win) {
/** @const {!../../../src/service/ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @const @private {!Window} */
this.win_ = ampdoc.win;
/**
* The window containing the document to scan.
* May differ from the `ampdoc`'s window e.g. in FIE.
* @const @private {!Window}
*/
this.localWin_ = opt_win || ampdoc.win;
/**
* Array of ActionInvocation.sequenceId values that have been invoked.
* Used to ensure that only one "AMP.setState" or "AMP.pushState" action
* may be triggered per event. Periodically cleared.
* @const @private {!Array<number>}
*/
this.actionSequenceIds_ = [];
/** @const @private {!Function} */
this.eventuallyClearActionSequenceIds_ = debounce(this.win_,
() => {
this.actionSequenceIds_.length = 0;
}, 5000);
/** @private {!Array<BoundElementDef>} */
this.boundElements_ = [];
/**
* Maps expression string to the element(s) that contain it.
* @private @const {!Object<string, !Array<!Element>>}
*/
this.expressionToElements_ = map();
/** @private {!../../../src/service/history-impl.History} */
this.history_ = Services.historyForDoc(ampdoc);
/** @private {!Array<string>} */
this.overridableKeys_ = [];
/**
* Upper limit on total number of bindings.
*
* The initial value is set to 1000 which, based on ~2ms expression parse
* time, caps "time to interactive" at ~2s after page load.
*
* User interactions can add new bindings (e.g. infinite scroll), so this
* can increase over time to a final limit of 2000 bindings.
*
* @private {number}
*/
this.maxNumberOfBindings_ = 1000;
/** @const @private {!../../../src/service/resources-impl.Resources} */
this.resources_ = Services.resourcesForDoc(ampdoc);
/**
* The current values of all bound expressions on the page.
* @const @private {!JsonObject}
*/
this.state_ = /** @type {!JsonObject} */ (map());
/** @const {!../../../src/service/timer-impl.Timer} */
this.timer_ = Services.timerFor(this.win_);
/** @private {?./bind-validator.BindValidator} */
this.validator_ = null;
/** @const @private {!../../../src/service/viewer-impl.Viewer} */
this.viewer_ = Services.viewerForDoc(this.ampdoc);
this.viewer_.onMessageRespond('premutate', this.premutate_.bind(this));
/**
* Resolved when the service finishes scanning the document for bindings.
* @const @private {Promise}
*/
this.initializePromise_ = this.viewer_.whenFirstVisible()
.then(() => {
if (opt_win) {
// In FIE, scan the document node of the iframe window.
const {document} = opt_win;
return whenDocumentReady(document).then(() => document);
} else {
// Otherwise, scan the root node of the ampdoc.
return ampdoc.whenReady().then(() => ampdoc.getRootNode());
}
})
.then(root => {
return this.initialize_(root);
});
/** @private {Promise} */
this.setStatePromise_ = null;
/** @private @const {!../../../src/utils/signals.Signals} */
this.signals_ = new Signals();
// Install debug tools.
const g = self.AMP;
g.printState = g.printState || this.debugPrintState_.bind(this);
g.setState = g.setState || (state => this.setState(state));
g.eval = g.eval || this.debugEvaluate_.bind(this);
}
/** @override @nocollapse */
static installInEmbedWindow(embedWin, ampdoc) {
installServiceInEmbedScope(
embedWin, 'bind', new Bind(ampdoc, embedWin));
}
/**
* @return {!../../../src/utils/signals.Signals}
*/
signals() {
return this.signals_;
}
/**
* Merges `state` into the current state and immediately triggers an
* evaluation unless `opt_skipEval` is false.
* @param {!JsonObject} state
* @param {boolean=} opt_skipEval
* @param {boolean=} opt_skipAmpState
* @return {!Promise}
*/
setState(state, opt_skipEval, opt_skipAmpState) {
try {
deepMerge(this.state_, state, MAX_MERGE_DEPTH);
} catch (e) {
user().error(TAG, 'Failed to merge result from AMP.setState().', e);
}
dev().info(TAG, 'state:', this.state_);
if (opt_skipEval) {
return Promise.resolve();
}
const promise = this.initializePromise_
.then(() => this.evaluate_())
.then(results => this.apply_(results, opt_skipAmpState));
if (getMode().test) {
promise.then(() => {
this.dispatchEventForTesting_(BindEvents.SET_STATE);
});
}
return this.setStatePromise_ = promise;
}
/**
* Executes an `AMP.setState()` or `AMP.pushState()` action.
* @param {!../../../src/service/action-impl.ActionInvocation} invocation
* @return {!Promise}
*/
invoke(invocation) {
const {args, event, method, sequenceId, tagOrTarget} = invocation;
// Store the sequenceId values of action invocations and only allow one
// setState() or pushState() event per sequence.
if (this.actionSequenceIds_.includes(sequenceId)) {
user().error(TAG, 'One state action allowed per event.');
return Promise.resolve();
}
this.actionSequenceIds_.push(sequenceId);
// Flush stored sequence IDs five seconds after the last invoked action.
this.eventuallyClearActionSequenceIds_();
const expression = args[RAW_OBJECT_ARGS_KEY];
if (expression) {
// Increment bindings limit by 500 on each invocation to a max of 2000.
this.maxNumberOfBindings_ = Math.min(2000,
Math.max(1000, this.maxNumberOfBindings_ + 500));
this.signals_.signal('FIRST_MUTATE');
const scope = dict();
if (event && getDetail(/** @type {!Event} */ (event))) {
scope['event'] = getDetail(/** @type {!Event} */ (event));
}
switch (method) {
case 'setState':
return this.setStateWithExpression(expression, scope);
case 'pushState':
return this.pushStateWithExpression(expression, scope);
default:
return Promise.reject(dev().createError('Unrecognized method: %s.%s',
tagOrTarget, method));
}
} else {
user().error('AMP-BIND', 'Please use the object-literal syntax, '
+ 'e.g. "AMP.setState({foo: \'bar\'})" instead of '
+ '"AMP.setState(foo=\'bar\')".');
}
return Promise.resolve();
}
/**
* Parses and evaluates an expression with a given scope and merges the
* resulting object into current state.
* @param {string} expression
* @param {!JsonObject} scope
* @return {!Promise}
*/
setStateWithExpression(expression, scope) {
dev().info(TAG, 'setState:', `"${expression}"`);
this.setStatePromise_ = this.evaluateExpression_(expression, scope)
.then(result => this.setState(result))
.then(() => this.getDataForHistory_())
.then(data => {
// Don't bother calling History.replace with empty data.
if (data) {
this.history_.replace(data);
}
});
return this.setStatePromise_;
}
/**
* Same as setStateWithExpression() except also pushes new history.
* Popping the new history stack entry will restore the values of variables
* in `expression`.
* @param {string} expression
* @param {!JsonObject} scope
* @return {!Promise}
*/
pushStateWithExpression(expression, scope) {
dev().info(TAG, 'pushState:', expression);
return this.evaluateExpression_(expression, scope).then(result => {
// Store the current values of each referenced variable in `expression`
// so that we can restore them on history-pop.
const oldState = map();
Object.keys(result).forEach(variable => {
const value = this.state_[variable];
// Store a deep copy of `value` to make sure `oldState` isn't
// modified by subsequent setState() actions.
oldState[variable] = this.copyJsonObject_(value);
});
const onPop = () => this.setState(oldState);
return this.setState(result)
.then(() => this.getDataForHistory_())
.then(data => {
this.history_.push(onPop, data);
});
});
}
/**
* Returns data that should be saved in browser history on AMP.setState() or
* AMP.pushState(). This enables features like restoring browser tabs.
* @return {!Promise<?JsonObject>}
*/
getDataForHistory_() {
const data = dict({
'data': dict({'amp-bind': this.state_}),
'title': this.localWin_.document.title,
});
if (!this.viewer_.isEmbedded()) {
// CC doesn't recognize !JsonObject as a subtype of (JsonObject|null).
return /** @type {!Promise<?JsonObject>} */ (Promise.resolve(data));
}
// Only pass state for history updates to trusted viewers, since they
// may contain user data e.g. form input.
return this.viewer_.isTrustedViewer().then(trusted => {
return (trusted) ? data : null;
});
}
/**
* Removes bindings from `removed` elements and scans `added` for bindings.
* Then, evaluates all expressions and applies results to `added` elements.
* Does _not_ mutate any other elements.
*
* Returned promise is resolved when all operations complete.
* If they don't complete within `timeout` ms, the promise is rejected.
*
* Note that elements with bindings must have attribute `i-amphtml-binding`.
*
* @param {!Array<!Element>} addedElements
* @param {!Array<!Element>} removedElements
* @param {number} timeout Timeout in milliseconds.
* @return {!Promise}
*/
scanAndApply(addedElements, removedElements, timeout = 2000) {
dev().info(TAG, 'rescan:', addedElements, removedElements);
/**
* Helper function for cleaning up bindings in removed elements.
* @param {number} added
* @return {!Promise}
*/
const cleanup = added => {
this.removeBindingsForNodes_(removedElements).then(removed => {
dev().info(TAG,
'⤷', 'Δ:', (added - removed), ', ∑:', this.numberOfBindings());
});
return Promise.resolve();
};
// Early-out if max number of bindings has already been exceeded.
// This can happen since we purge old bindings in `removedElements`
// _after_ adding new ones (rather than before) as an optimization.
if (this.numberOfBindings() > this.maxNumberOfBindings_) {
this.emitMaxBindingsExceededError_();
return cleanup(0);
}
const bindings = [];
// Scan `addedElements` and their children for elements with bindings.
const elementsToScan = addedElements.slice();
addedElements.forEach(el => {
const children = el.querySelectorAll('[i-amphtml-binding]');
Array.prototype.push.apply(elementsToScan, children);
});
elementsToScan.forEach(el => {
this.scanElement_(el, Number.POSITIVE_INFINITY, bindings);
});
const added = bindings.length;
// Early-out if there are no elements to add -- just clean up `removed`.
if (added === 0) {
return cleanup(0);
}
const promise = this.sendBindingsToWorker_(bindings).then(() => {
return this.evaluate_().then(results =>
this.applyElements_(results, addedElements));
}).then(() => {
// Remove bindings at the end to reduce evaluation/apply latency.
cleanup(added);
});
return this.timer_.timeoutPromise(timeout, promise,
'Timed out waiting for amp-bind to process rendered template.');
}
/**
* Returns the stringified value of the global state for a given field-based
* expression, e.g. "foo.bar.baz".
* @param {string} expr
* @return {string}
*/
getStateValue(expr) {
const value = getValueForExpr(this.state_, expr);
if (isObject(value) || isArray(value)) {
return JSON.stringify(/** @type {JsonObject} */(value));
} else {
return String(value);
}
}
/**
* Scans the root node (and array of optional nodes) for bindings.
* @param {!Node} root
* @return {!Promise}
* @private
*/
initialize_(root) {
// Disallow URL property bindings in AMP4EMAIL.
const allowUrlProperties = !this.isAmp4Email_();
this.validator_ = new BindValidator(allowUrlProperties);
// The web worker's evaluator also has an instance of BindValidator
// that should be initialized with the same `allowUrlProperties` value.
return this.ww_('bind.init', [allowUrlProperties]).then(() => {
return Promise.all([
this.addMacros_(),
this.addBindingsForNodes_([root]),
]);
}).then(results => {
dev().info(TAG, '⤷', 'Δ:', results);
// Listen for DOM updates (e.g. template render) to rescan for bindings.
root.addEventListener(AmpEvents.DOM_UPDATE, e => this.onDomUpdate_(e));
// In dev mode, check default values against initial expression results.
if (getMode().development) {
return this.evaluate_().then(results => this.verify_(results));
}
}).then(() => this.checkReadiness_(root));
}
/**
* Bind is "ready" when its initialization completes _and_ all <amp-state>
* elements' local data is parsed and processed (not remote data).
* @param {!Node} root
* @private
*/
checkReadiness_(root) {
const ampStates = root.querySelectorAll('AMP-STATE');
if (ampStates.length > 0) {
const whenBuilt = toArray(ampStates).map(el => el.whenBuilt());
Promise.all(whenBuilt).then(() => this.onReady_());
} else {
this.onReady_();
}
}
/**
* @private
*/
onReady_() {
this.viewer_.sendMessage('bindReady', undefined);
this.dispatchEventForTesting_(BindEvents.INITIALIZE);
}
/**
* @return {boolean}
* @private
*/
isAmp4Email_() {
const html = this.localWin_.document.documentElement;
const amp4email = html.hasAttribute('amp4email')
|| html.hasAttribute('⚡4email');
return amp4email;
}
/**
* The current number of bindings.
* @return {number}
* @visibleForTesting
*/
numberOfBindings() {
return this.boundElements_.reduce((number, boundElement) => {
return number + boundElement.boundProperties.length;
}, 0);
}
/**
* @param {number} value
* @visibleForTesting
*/
setMaxNumberOfBindingsForTesting(value) {
this.maxNumberOfBindings_ = value;
}
/** @return {!../../../src/service/history-impl.History} */
historyForTesting() {
return this.history_;
}
/**
* Calls setState(s), where s is data.state with the non-overridable keys
* removed.
* @param {!JsonObject} data
* @return {!Promise}
* @private
*/
premutate_(data) {
const ignoredKeys = [];
return this.initializePromise_.then(() => {
Object.keys(data['state']).forEach(key => {
if (!this.overridableKeys_.includes(key)) {
delete data['state'][key];
ignoredKeys.push(key);
}
});
if (ignoredKeys.length > 0) {
user().warn(TAG, 'Some state keys could not be premutated ' +
'because they are missing the overridable attribute: ' +
ignoredKeys.join(', '));
}
return this.setState(data['state']);
});
}
/**
* Marks the given key as overridable so that it can be overriden by
* a premutate message from the viewer.
* @param {string} key
*/
addOverridableKey(key) {
this.overridableKeys_.push(key);
}
/**
* Scans the document for <amp-bind-macro> elements, and adds them to the
* bind-evaluator.
*
* Returns a promise that resolves after macros have been added.
*
* @return {!Promise<number>}
* @private
*/
addMacros_() {
// TODO(choumx, #17194): Query selector can miss elements when the body
// is streamed. This should be done at the custom element level.
const elements = this.ampdoc.getBody().querySelectorAll('AMP-BIND-MACRO');
const macros = /** @type {!Array<!BindMacroDef>} */ ([]);
iterateCursor(elements, element => {
const argumentNames = (element.getAttribute('arguments') || '')
.split(',')
.map(s => s.trim());
macros.push({
id: element.getAttribute('id'),
argumentNames,
expressionString: element.getAttribute('expression'),
});
});
if (macros.length == 0) {
return Promise.resolve(0);
} else {
return this.ww_('bind.addMacros', [macros]).then(errors => {
// Report macros that failed to parse (e.g. expression size exceeded).
errors.forEach((e, i) => {
this.reportWorkerError_(
e, `${TAG}: Parsing amp-bind-macro failed.`, elements[i]);
});
return macros.length;
});
}
}
/**
* For each node in an array, scans it and its descendants for bindings.
* This function is not idempotent.
*
* Returns a promise that resolves with the number of bindings added upon
* completion.
*
* @param {!Array<!Node>} nodes
* @return {!Promise<number>}
* @private
*/
addBindingsForNodes_(nodes) {
// For each node, scan it for bindings and store them.
const scanPromises = nodes.map(node => {
// Limit number of total bindings (unless in local manual testing).
const limit = (getMode().localDev && !getMode().test)
? Number.POSITIVE_INFINITY
: this.maxNumberOfBindings_ - this.numberOfBindings();
return this.scanNode_(node, limit).then(results => {
const {bindings, limitExceeded} = results;
if (limitExceeded) {
this.emitMaxBindingsExceededError_();
}
return bindings;
});
});
// Once all scans are complete, combine the bindings and ask web-worker to
// evaluate expressions in a single RPC.
return Promise.all(scanPromises).then(results => {
// `results` is a 2D array where results[i] is an array of bindings.
// Flatten this into a 1D array of bindings via concat.
const bindings = Array.prototype.concat.apply([], results);
return (bindings.length > 0) ? this.sendBindingsToWorker_(bindings) : 0;
});
}
/** Emits console error stating that the binding limit was exceeded. */
emitMaxBindingsExceededError_() {
dev().expectedError(TAG, 'Maximum number of bindings reached ' +
'(%s). Additional elements with bindings will be ignored.',
this.maxNumberOfBindings_);
}
/**
* Sends new bindings to the web worker for parsing.
* @param {!Array<!BindBindingDef>} bindings
* @return {!Promise<number>}
*/
sendBindingsToWorker_(bindings) {
return this.ww_('bind.addBindings', [bindings]).then(parseErrors => {
// Report each parse error.
Object.keys(parseErrors).forEach(expressionString => {
const elements = this.expressionToElements_[expressionString];
if (elements.length > 0) {
this.reportWorkerError_(parseErrors[expressionString],
`${TAG}: Expression compile error in "${expressionString}".`,
elements[0]);
}
});
return bindings.length;
});
}
/**
* For each node in an array, removes all bindings for it and its descendants.
*
* Returns a promise that resolves with the number of removed bindings upon
* completion.
*
* @param {!Array<!Node>} nodes
* @return {!Promise<number>}
* @private
*/
removeBindingsForNodes_(nodes) {
// Eliminate bound elements that are descendants of `nodes`.
remove(this.boundElements_, boundElement => {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].contains(boundElement.element)) {
return true;
}
}
return false;
});
// Eliminate elements from the expression to elements map that
// have node as an ancestor. Delete expressions that are no longer
// bound to elements.
const deletedExpressions = /** @type {!Array<string>} */ ([]);
for (const expression in this.expressionToElements_) {
const elements = this.expressionToElements_[expression];
remove(elements, element => {
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].contains(element)) {
return true;
}
}
return false;
});
if (elements.length == 0) {
deletedExpressions.push(expression);
delete this.expressionToElements_[expression];
}
}
// Remove the bindings from the evaluator.
const removed = deletedExpressions.length;
if (removed > 0) {
return this.ww_('bind.removeBindingsWithExpressionStrings',
[deletedExpressions]).then(() => removed);
} else {
return Promise.resolve(0);
}
}
/**
* Scans `node` for attributes that conform to bind syntax and returns
* a tuple containing bound elements and binding data for the evaluator.
* @param {!Node} node
* @param {number} limit
* @return {!Promise<{bindings: !Array<!BindBindingDef>, limitExceeded: boolean}>}
* @private
*/
scanNode_(node, limit) {
/** @type {!Array<!BindBindingDef>} */
const bindings = [];
const doc = devAssert(node.nodeType == Node.DOCUMENT_NODE
? node : node.ownerDocument, 'ownerDocument is null.');
// Third and fourth params of `createTreeWalker` are not optional on IE11.
const walker = doc.createTreeWalker(node, NodeFilter.SHOW_ELEMENT, null,
/* entityReferenceExpansion */ false);
// Set to true if number of bindings in `node` exceeds `limit`.
let limitExceeded = false;
// Helper function for scanning the tree walker's next node.
// Returns true if the walker has no more nodes.
const scanNextNode_ = () => {
const node = walker.currentNode;
if (!node) {
return true;
}
// If `node` is a Document, it will be scanned first (despite
// NodeFilter.SHOW_ELEMENT). Skip it.
if (node.nodeType !== Node.ELEMENT_NODE) {
return !walker.nextNode();
}
const element = dev().assertElement(node);
const remainingQuota = limit - bindings.length;
if (this.scanElement_(element, remainingQuota, bindings)) {
limitExceeded = true;
}
return !walker.nextNode() || limitExceeded;
};
return new Promise(resolve => {
const chunktion = idleDeadline => {
let completed = false;
// If `requestIdleCallback` is available, scan elements until
// idle time runs out.
if (idleDeadline && !idleDeadline.didTimeout) {
while (idleDeadline.timeRemaining() > 1 && !completed) {
completed = scanNextNode_();
}
} else {
// If `requestIdleCallback` isn't available, scan elements in buckets.
// Bucket size is a magic number that fits within a single frame.
const bucketSize = 250;
for (let i = 0; i < bucketSize && !completed; i++) {
completed = scanNextNode_();
}
}
// If we scanned all elements, resolve. Otherwise, continue chunking.
if (completed) {
resolve({bindings, limitExceeded});
} else {
chunk(this.ampdoc, chunktion, ChunkPriority.LOW);
}
};
chunk(this.ampdoc, chunktion, ChunkPriority.LOW);
});
}
/**
* Scans the element for bindings and adds up to |quota| to `outBindings`.
* Also updates ivars `boundElements_` and `expressionToElements_`.
* @param {!Element} element
* @param {number} quota
* @param {!Array<!BindBindingDef>} outBindings
* @return {boolean} Returns true if `element` contains more than `quota`
* bindings. Otherwise, returns false.
*/
scanElement_(element, quota, outBindings) {
let quotaExceeded = false;
const boundProperties = this.boundPropertiesInElement_(element);
if (boundProperties.length > quota) {
boundProperties.length = quota;
quotaExceeded = true;
}
if (boundProperties.length > 0) {
this.boundElements_.push({element, boundProperties});
}
const {tagName} = element;
boundProperties.forEach(boundProperty => {
const {property, expressionString} = boundProperty;
outBindings.push({tagName, property, expressionString});
if (!this.expressionToElements_[expressionString]) {
this.expressionToElements_[expressionString] = [];
}
this.expressionToElements_[expressionString].push(element);
});
return quotaExceeded;
}
/**
* Returns bound properties for an element.
* @param {!Element} element
* @return {!Array<{property: string, expressionString: string}>}
* @private
*/
boundPropertiesInElement_(element) {
const boundProperties = [];
const attrs = element.attributes;
for (let i = 0, numberOfAttrs = attrs.length; i < numberOfAttrs; i++) {
const attr = attrs[i];
const boundProperty = this.boundPropertyInAttribute_(attr, element);
if (boundProperty) {
boundProperties.push(boundProperty);
}
}
return boundProperties;
}
/**
* Returns the bound property and expression string within a given attribute,
* if it exists. Otherwise, returns null.
* @param {!Attr} attribute
* @param {!Element} element
* @return {?{property: string, expressionString: string}}
* @private
*/
boundPropertyInAttribute_(attribute, element) {
const tag = element.tagName;
const attr = attribute.name;
let property;
if (attr.length > 2 && attr[0] === '[' && attr[attr.length - 1] === ']') {
property = attr.substr(1, attr.length - 2);
} else if (startsWith(attr, 'data-amp-bind-')) {
property = attr.substr(14);
// Ignore `data-amp-bind-foo` if `[foo]` already exists.
if (element.hasAttribute(`[${property}]`)) {
return null;
}
}
if (property) {
if (this.validator_.canBind(tag, property)) {
return {property, expressionString: attribute.value};
} else {
const err = user().createError(
'%s: Binding to [%s] on <%s> is not allowed.', TAG, property, tag);
this.reportError_(err, element);
}
}
return null;
}
/**
* Evaluates a single expression and returns its result.
* @param {string} expression
* @param {!JsonObject} scope
* @return {!Promise<!JsonObject>}
*/
evaluateExpression_(expression, scope) {
return this.initializePromise_.then(() => {
// Allow expression to reference current state in addition to event state.
Object.assign(scope, this.state_);
return this.ww_('bind.evaluateExpression', [expression, scope]);
}).then(returnValue => {
const {result, error} = returnValue;
if (error) {
// Throw to reject promise.
throw this.reportWorkerError_(error, `${TAG}: Expression eval failed.`);
} else {
dev().info(TAG, '⤷', result);
return result;
}
});
}
/**
* Reevaluates all expressions and returns a map of expressions to results.
* @return {!Promise<!Object<string, BindExpressionResultDef>>}
* @private
*/
evaluate_() {
const evaluatePromise = this.ww_('bind.evaluateBindings', [this.state_]);
return evaluatePromise.then(returnValue => {
const {results, errors} = returnValue;
// Report evaluation errors.
Object.keys(errors).forEach(expressionString => {
const elements = this.expressionToElements_[expressionString];
if (elements.length > 0) {
const evalError = errors[expressionString];
const userError = user().createError(
'%s: Expression evaluation error in "%s". %s', TAG,
expressionString, evalError.message);
userError.stack = evalError.stack;
this.reportError_(userError, elements[0]);
}
});
dev().info(TAG, 'bindings:', results);
return results;
});
}
/**
* Verifies expression results vs. current DOM state and returns an
* array of bindings with mismatches (if any).
* @param {Object<string, BindExpressionResultDef>} results
* @param {?Array<!Element>=} elements If provided, only verifies bindings
* contained within the given elements. Otherwise, verifies all bindings.
* @param {boolean=} warn If true, emits a user warning for verification
* mismatches. Otherwise, does not emit a warning.
* @return {!Array<string>}
* @private
*/
verify_(results, elements = null, warn = true) {
// Collate strings containing details of verification mismatches to return.
const mismatches = {};
this.boundElements_.forEach(boundElement => {
const {element, boundProperties} = boundElement;
// If provided, filter elements that are _not_ children of `opt_elements`.
if (elements && !this.elementsContains_(elements, element)) {
return;
}
boundProperties.forEach(boundProperty => {
const newValue = results[boundProperty.expressionString];
if (newValue === undefined) {
return;
}
const mismatch = this.verifyBinding_(boundProperty, element, newValue);
if (!mismatch) {
return;
}
const {tagName} = element;
const {property, expressionString} = boundProperty;
const {expected, actual} = mismatch;
// Only store unique mismatches (dupes possible when rendering an array
// of data to a template).
mismatches[`${tagName}[${property}]${expected}:${actual}`] = true;
if (warn) {
user().warn(TAG, `Default value (${actual}) does not match first `
+ `result (${expected}) for <${tagName} [${property}]="`
+ `${expressionString}">. We recommend writing expressions with `
+ 'matching default values, but this can be safely ignored if '
+ 'intentional.');
}
});
});
return Object.keys(mismatches);
}
/**
* Returns true if `el` is contained within any element in `elements`.
* @param {!Array<!Element>} elements
* @param {!Element} el
* @return {boolean}
* @private
*/
elementsContains_(elements, el) {
for (let i = 0; i < elements.length; i++) {
if (elements[i].contains(el)) {
return true;
}
}
return false;
}
/**
* Determines which properties to update based on results of evaluation
* of all bound expression strings with the current state. This method
* will only return properties that need to be updated along with their
* new value.
* @param {!Array<!BoundPropertyDef>} boundProperties
* @param {Object<string, BindExpressionResultDef>} results
* @return {!Array<{boundProperty: !BoundPropertyDef, newValue: BindExpressionResultDef}>}
* @private
*/
calculateUpdates_(boundProperties, results) {
const updates = [];
boundProperties.forEach(boundProperty => {