-
Notifications
You must be signed in to change notification settings - Fork 2k
/
property-effects.html
2204 lines (2103 loc) · 79.2 KB
/
property-effects.html
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
<!--
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../utils/boot.html">
<link rel="import" href="../utils/mixin.html">
<link rel="import" href="../utils/path.html">
<!-- for notify, reflect -->
<link rel="import" href="../utils/case-map.html">
<link rel="import" href="property-accessors.html">
<!-- for annotated effects -->
<link rel="import" href="template-stamp.html">
<script>
(function() {
'use strict';
const CaseMap = Polymer.CaseMap;
// Monotonically increasing unique ID used for de-duping effects triggered
// from multiple properties in the same turn
let dedupeId = 0;
// Property effect types; effects are stored on the prototype using these keys
const TYPES = {
ANY: '__propertyEffects',
COMPUTE: '__computeEffects',
REFLECT: '__reflectEffects',
NOTIFY: '__notifyEffects',
PROPAGATE: '__propagateEffects',
OBSERVE: '__observeEffects',
READ_ONLY: '__readOnly'
}
/**
* Ensures that the model has an own-property map of effects for the given type.
* The model may be a prototype or an instance.
*
* Property effects are stored as arrays of effects by property in a map,
* by named type on the model. e.g.
*
* __computeEffects: {
* foo: [ ... ],
* bar: [ ... ]
* }
*
* If the model does not yet have an effect map for the type, one is created
* and returned. If it does, but it is not an own property (i.e. the
* prototype had effects), the the map is deeply cloned and the copy is
* set on the model and returned, ready for new effects to be added.
*
* @param {Object} model Prototype or instance
* @param {string} type Property effect type
* @return {Object} The own-property map of effects for the given type
* @private
*/
function ensureOwnEffectMap(model, type) {
let effects = model[type];
if (!effects) {
effects = model[type] = {};
} else if (!model.hasOwnProperty(type)) {
effects = model[type] = Object.create(model[type]);
for (let p in effects) {
let protoFx = effects[p];
let instFx = effects[p] = Array(protoFx.length);
for (let i=0; i<protoFx.length; i++) {
instFx[i] = protoFx[i];
}
}
}
return effects;
}
// -- effects ----------------------------------------------
/**
* Runs all effects of a given type for the given set of property changes
* on an instance.
*
* @param {Object} inst The instance with effects to run
* @param {string} type Type of effect to run
* @param {Object} props Bag of current property changes
* @param {Object=} oldProps Bag of previous values for changed properties
* @private
*/
function runEffects(inst, effects, props, oldProps, hasPaths) {
if (effects) {
let ran;
let id = dedupeId++;
for (let prop in props) {
if (runEffectsForProperty(inst, effects, id, prop, props, oldProps, hasPaths)) {
ran = true;
}
}
return ran;
}
}
/**
* Runs a list of effects for a given property.
*
* @param {Object} inst The instance with effects to run
* @param {Array} effects Array of effects
* @param {number} id Effect run id used for de-duping effects
* @param {string} prop Name of changed property
* @param {*} value Value of changed property
* @param {*} old Previous value of changed property
* @private
*/
function runEffectsForProperty(inst, effects, dedupeId, prop, props, oldProps, hasPaths) {
let ran;
let rootProperty = hasPaths ? Polymer.Path.root(prop) : prop;
let fxs = effects[rootProperty];
if (fxs) {
for (let i=0, l=fxs.length, fx; (i<l) && (fx=fxs[i]); i++) {
if ((!fx.info || fx.info.lastRun !== dedupeId) &&
(!hasPaths || pathMatchesTrigger(prop, fx.trigger))) {
fx.fn(inst, prop, props, oldProps, fx.info, hasPaths);
if (fx.info) {
fx.info.lastRun = dedupeId;
}
ran = true;
}
}
}
return ran;
}
/**
* Determines whether a property/path that has changed matches the trigger
* criteria for an effect. A trigger is a descriptor with the following
* structure, which matches the descriptors returned from `parseArg`.
* e.g. for `foo.bar.*`:
* ```
* trigger: {
* name: 'a.b',
* structured: true,
* wildcard: true
* }
* ```
* If no trigger is given, the path is deemed to match.
*
* @param {string} path Path or property that changed
* @param {Object} trigger Descriptor
* @return {boolean} Whether the path matched the trigger
*/
function pathMatchesTrigger(path, trigger) {
if (trigger) {
let triggerPath = trigger.name;
return (triggerPath == path) ||
(trigger.structured && Polymer.Path.isAncestor(triggerPath, path)) ||
(trigger.wildcard && Polymer.Path.isDescendant(triggerPath, path));
} else {
return true;
}
}
/**
* Implements the "observer" effect.
*
* Calls the method with `info.methodName` on the instance, passing the
* new and old values.
*
* @param {Object} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runObserverEffect(inst, property, props, oldProps, info) {
let fn = inst[info.methodName];
let changedProp = info.property;
if (fn) {
fn.call(inst, inst.__data[changedProp], oldProps[changedProp]);
} else {
console.warn('observer method `' + info.methodName + '` not defined');
}
}
/**
* Runs "notify" effects for a set of changed properties.
*
* This method differs from the generic `runEffects` method in that it
* will dispatch path notification events in the case that the property
* changed was a path and the root property for that path didn't have a
* "notify" effect. This is to maintain 1.0 behavior that did not require
* `notify: true` to ensure object sub-property notifications were
* sent.
*
* @param {Element} inst The instance with effects to run
* @param {Object} props Bag of current property changes
* @param {Object} oldProps Bag of previous values for changed properties
* @private
*/
function runNotifyEffects(inst, notifyProps, props, oldProps, hasPaths) {
// Notify
let fxs = inst.__notifyEffects;
let notified;
let id = dedupeId++;
// Try normal notify effects; if none, fall back to try path notification
for (let prop in notifyProps) {
if (notifyProps[prop]) {
if (fxs && runEffectsForProperty(inst, fxs, id, prop, props, oldProps, hasPaths)) {
notified = true;
} else if (hasPaths && notifyPath(inst, prop, props)) {
notified = true;
}
}
}
// Flush host if we actually notified and host was batching
let host;
if (notified && (host = inst.__dataHost) && host._flushProperties) {
host._flushProperties();
}
}
/**
* Dispatches {property}-changed events with path information in the detail
* object to indicate a sub-path of the property was changed.
*
* @param {Element} inst The element from which to fire the event
* @param {string} path The path that was changed
* @param {*} value
* @private
*/
function notifyPath(inst, path, props) {
let rootProperty = Polymer.Path.root(path);
if (rootProperty !== path) {
let eventName = Polymer.CaseMap.camelToDashCase(rootProperty) + '-changed';
dispatchNotifyEvent(inst, eventName, props[path], path);
return true;
}
}
/**
* Dispatches {property}-changed events to indicate a property (or path)
* changed.
*
* @param {Element} inst The element from which to fire the event
* @param {string} eventName The name of the event to send ('{property}-changed')
* @param {*} value The value of the changed property
* @param {string | null | undefined} path If a sub-path of this property changed, the path
* that changed (optional).
* @private
*/
function dispatchNotifyEvent(inst, eventName, value, path) {
let detail = {
value: value,
queueProperty: true
};
if (path) {
detail.path = path;
}
inst.dispatchEvent(new CustomEvent(eventName, { detail }));
}
/**
* Implements the "notify" effect.
*
* Dispatches a non-bubbling event named `info.eventName` on the instance
* with a detail object containing the new `value`.
*
* @param {Element} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runNotifyEffect(inst, property, props, oldProps, info, hasPaths) {
let rootProperty = hasPaths ? Polymer.Path.root(property) : property;
let path = rootProperty != property ? property : null;
let value = path ? Polymer.Path.get(inst, path) : inst.__data[property];
if (path && value === undefined) {
value = props[property]; // specifically for .splices
}
dispatchNotifyEvent(inst, info.eventName, value, path);
}
/**
* Adds a 2-way binding notification event listener to the node specified
*
* @param {Object} node Child element to add listener to
* @param {Object} inst Host element instance to handle notification event
* @param {Object} info Listener metadata stored via addAnnotatedListener
* @private
*/
function addNotifyListener(node, inst, info) {
node.addEventListener(info.event, function(e) {
handleNotification(e, inst, info.property, info.path, info.negate);
});
}
/**
* Handler function for 2-way notification events. Receives context
* information captured in the `addNotifyListener` closure from the
* `__notifyListeners` metadata.
*
* Sets the value of the notified property to the host property or path. If
* the event contained path information, translate that path to the host
* scope's name for that path first.
*
* @param {Event} e Notification event (e.g. '<property>-changed')
* @param {Object} inst Host element instance handling the notification event
* @param {string} property Child element property that was bound
* @param {string} path Host property/path that was bound
* @param {boolean} negate Whether the binding was negated
* @private
*/
function handleNotification(e, inst, property, path, negate) {
let value;
let targetPath = e.detail && e.detail.path;
if (targetPath) {
path = Polymer.Path.translate(property, path, targetPath);
value = e.detail && e.detail.value;
} else {
value = e.target[property];
}
value = negate ? !value : value;
setPropertyFromNotification(inst, path, value, e);
}
/**
* Called by 2-way binding notification event listeners to set a property
* or path to the host based on a notification from a bound child.
*
* @param {string} path Path on this instance to set
* @param {*} value Value to set to given path
* @protected
*/
function setPropertyFromNotification(inst, path, value, event) {
let detail = event.detail;
if (detail && detail.queueProperty) {
if (!inst.__readOnly || !inst.__readOnly[path]) {
inst._setPendingPropertyOrPath(path, value, true, Boolean(detail.path));
}
} else {
inst.set(path, value);
}
}
/**
* Implements the "reflect" effect.
*
* Sets the attribute named `info.attrName` to the given property value.
*
* @param {Object} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runReflectEffect(inst, property, props, oldProps, info) {
let value = inst.__data[property];
if (Polymer.sanitizeDOMValue) {
value = Polymer.sanitizeDOMValue(value, info.attrName, 'attribute', inst);
}
inst._propertyToAttribute(property, info.attrName, value);
}
/**
* Runs "computed" effects for a set of changed properties.
*
* This method differs from the generic `runEffects` method in that it
* continues to run computed effects based on the output of each pass until
* there are no more newly computed properties. This ensures that all
* properties that will be computed by the initial set of changes are
* computed before other effects (binding propagation, observers, and notify)
* run.
*
* @param {Element} inst The instance the effect will be run on
* @param {Object} changedProps Bag of changed properties
* @param {Object} oldProps Bag of previous values for changed properties
* @private
*/
function runComputedEffects(inst, changedProps, oldProps, hasPaths) {
let computeEffects = inst.__computeEffects;
if (computeEffects) {
let inputProps = changedProps;
while (runEffects(inst, computeEffects, inputProps, oldProps, hasPaths)) {
Object.assign(oldProps, inst.__dataOld);
Object.assign(changedProps, inst.__dataPending);
inputProps = inst.__dataPending;
inst.__dataPending = null;
}
}
}
/**
* Implements the "computed property" effect by running the method with the
* values of the arguments specified in the `info` object and setting the
* return value to the computed property specified.
*
* @param {Object} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runComputedEffect(inst, property, props, oldProps, info) {
let result = runMethodEffect(inst, property, props, oldProps, info);
let computedProp = info.methodInfo;
if (inst.__propertyEffects && inst.__propertyEffects[computedProp]) {
inst._setPendingProperty(computedProp, result, true);
} else {
inst[computedProp] = result;
}
}
/**
* Computes path changes based on path links set up using the `linkPaths`
* API.
*
* @param {Element} inst The instance whose props are changing
* @param {Object} changedProps Bag of changed properties
* @private
*/
function computeLinkedPaths(inst, changedProps, hasPaths) {
let links;
if (hasPaths && (links = inst.__dataLinkedPaths)) {
const cache = inst.__dataTemp;
let link;
for (let a in links) {
let b = links[a];
for (let path in changedProps) {
if (Polymer.Path.isDescendant(a, path)) {
link = Polymer.Path.translate(a, b, path);
cache[link] = changedProps[link] = changedProps[path];
let notifyProps = inst.__dataToNotify || (inst.__dataToNotify = {});
notifyProps[link] = true;
} else if (Polymer.Path.isDescendant(b, path)) {
link = Polymer.Path.translate(b, a, path);
cache[link] = changedProps[link] = changedProps[path];
let notifyProps = inst.__dataToNotify || (inst.__dataToNotify = {});
notifyProps[link] = true;
}
}
}
}
}
// -- bindings ----------------------------------------------
/**
* Adds "binding" property effects for the template annotation
* ("note" for short) and node index specified. These may either be normal
* "binding" effects (property/path bindings) or "method binding"
* effects, aka inline computing functions, depending on the type of binding
* detailed in the note.
*
* @param {Object} model Prototype or instance
* @param {Object} note Annotation note returned from Annotator
* @param {number} index Index into `__templateNodes` list of annotated nodes that the
* note applies to
* @param {Object=} dynamicFns Map indicating whether method names should
* be included as a dependency to the effect.
* @private
*/
function addBindingEffect(model, note, index, dynamicFns) {
for (let i=0; i<note.parts.length; i++) {
let part = note.parts[i];
if (part.signature) {
addMethodBindingEffect(model, note, part, index, dynamicFns);
} else if (!part.literal) {
if (note.kind === 'attribute' && note.name[0] === '-') {
console.warn('Cannot set attribute ' + note.name +
' because "-" is not a valid attribute starting character');
} else {
model._addPropertyEffect(Polymer.Path.root(part.value), TYPES.PROPAGATE, {
fn: runBindingEffect,
info: {
kind: note.kind,
index: index,
name: note.name,
propertyName: note.propertyName,
value: part.value,
isCompound: note.isCompound,
compoundIndex: part.compoundIndex,
event: part.event,
customEvent: part.customEvent,
negate: part.negate
}
});
}
}
}
}
/**
* Implements the "binding" (property/path binding) effect.
*
* @param {Element} inst The instance the effect will be run on
* @param {string} path Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runBindingEffect(inst, path, props, oldProps, info, hasPaths) {
let value;
let node = inst.__templateNodes[info.index];
// Subpath notification: transform path and set to client
// e.g.: foo="{{obj.sub}}", path: 'obj.sub.prop', set 'foo.prop'=obj.sub.prop
if (hasPaths && (path.length > info.value.length) &&
(info.kind == 'property') && !info.isCompound &&
node.__propertyEffects && node.__propertyEffects[info.name]) {
let value = props[path];
path = Polymer.Path.translate(info.value, info.name, path);
if (node._setPendingPropertyOrPath(path, value, false, true)) {
inst._enqueueClient(node);
}
} else {
// Root or deeper path was set; extract bound path value
// e.g.: foo="{{obj.sub}}", path: 'obj', set 'foo'=obj.sub
// or: foo="{{obj.sub}}", path: 'obj.sub.prop', set 'foo'=obj.sub
if (path != info.value) {
value = Polymer.Path.get(inst, info.value);
} else {
if (hasPaths && Polymer.Path.isPath(path)) {
value = Polymer.Path.get(inst, path);
} else {
value = inst.__data[path];
}
}
// Propagate value to child
applyBindingValue(inst, info, value);
}
}
/**
* Sets the value for an "binding" (binding) effect to a node,
* either as a property or attribute.
*
* @param {Object} inst The instance owning the binding effect
* @param {Object} info Effect metadata
* @param {*} value Value to set
* @private
*/
function applyBindingValue(inst, info, value) {
let node = inst.__templateNodes[info.index];
value = computeBindingValue(node, value, info);
if (Polymer.sanitizeDOMValue) {
value = Polymer.sanitizeDOMValue(value, info.name, info.kind, node);
}
if (info.kind == 'attribute') {
// Attribute binding
inst._valueToNodeAttribute(node, value, info.name);
} else {
// Property binding
let prop = info.name;
if (node.__propertyEffects && node.__propertyEffects[prop]) {
if (!node.__readOnly || !node.__readOnly[prop]) {
if (node._setPendingProperty(prop, value)) {
inst._enqueueClient(node);
}
}
} else {
inst._setUnmanagedPropertyToNode(node, prop, value);
}
}
}
/**
* Transforms an "binding" effect value based on compound & negation
* effect metadata, as well as handling for special-case properties
*
* @param {Node} node Node the value will be set to
* @param {*} value Value to set
* @param {Object} info Effect metadata
* @return {*} Transformed value to set
* @private
*/
function computeBindingValue(node, value, info) {
if (info.negate) {
value = !value;
}
if (info.isCompound) {
let storage = node.__dataCompoundStorage[info.name];
storage[info.compoundIndex] = value;
value = storage.join('');
}
if (info.kind !== 'attribute') {
// Some browsers serialize `undefined` to `"undefined"`
if (info.name === 'textContent' ||
(node.localName == 'input' && info.name == 'value')) {
value = value == undefined ? '' : value;
}
}
return value;
}
/**
* Adds "binding method" property effects for the template binding
* ("note" for short), part metadata, and node index specified.
*
* @param {Object} model Prototype or instance
* @param {Object} note Binding note returned from Annotator
* @param {Object} part The compound part metadata
* @param {number} index Index into `__templateNodes` list of annotated nodes that the
* note applies to
* @param {Object=} dynamicFns Map indicating whether method names should
* be included as a dependency to the effect.
* @private
*/
function addMethodBindingEffect(model, note, part, index, dynamicFns) {
createMethodEffect(model, part.signature, TYPES.PROPAGATE,
runMethodBindingEffect, {
index: index,
isCompound: note.isCompound,
compoundIndex: part.compoundIndex,
kind: note.kind,
name: note.name,
negate: part.negate,
part: part
}, dynamicFns
);
}
/**
* Implements the "binding method" (inline computed function) effect.
*
* Runs the method with the values of the arguments specified in the `info`
* object and setting the return value to the node property/attribute.
*
* @param {Object} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runMethodBindingEffect(inst, property, props, oldProps, info) {
let val = runMethodEffect(inst, property, props, oldProps, info);
applyBindingValue(inst, info.methodInfo, val);
}
/**
* Post-processes template bindings (notes for short) provided by the
* Bindings library for use by the effects system:
* - Parses bindings for methods into method `signature` objects
* - Memoizes the root property for path bindings
* - Recurses into nested templates and processes those templates and
* extracts any host properties, which are set to the template's
* `_content._hostProps`
* - Adds bindings from the host to <template> elements for any nested
* template's lexically bound "host properties"; template handling
* elements can then add accessors to the template for these properties
* to forward host properties into template instances accordingly.
*
* @param {Array<Object>} notes List of notes to process; the notes are
* modified in place.
* @private
*/
function processAnnotations(notes) {
if (!notes._processed) {
for (let i=0; i<notes.length; i++) {
let note = notes[i];
// Parse bindings for methods & path roots (models)
for (let j=0; j<note.bindings.length; j++) {
let b = note.bindings[j];
for (let k=0; k<b.parts.length; k++) {
let p = b.parts[k];
if (!p.literal) {
p.signature = parseMethod(p.value);
if (!p.signature) {
p.rootProperty = Polymer.Path.root(p.value);
}
}
}
}
// Recurse into nested templates & bind host props
if (note.templateContent) {
processAnnotations(note.templateContent._notes);
let hostProps = note.templateContent._hostProps =
discoverTemplateHostProps(note.templateContent._notes);
let bindings = [];
for (let prop in hostProps) {
bindings.push({
index: note.index,
kind: 'property',
name: '_host_' + prop,
parts: [{
mode: '{',
value: prop
}]
});
}
note.bindings = note.bindings.concat(bindings);
}
}
notes._processed = true;
}
}
/**
* Finds all property usage in templates (property/path bindings and function
* arguments) and returns the path roots as keys in a map. Each outer template
* merges inner _hostProps to propagate inner host property needs to outer
* templates.
*
* @param {Array<Object>} notes List of notes to process for a given template
* @return {Object<string,boolean>} Map of host properties that the template
* (or any nested templates) uses
* @private
*/
function discoverTemplateHostProps(notes) {
let hostProps = {};
for (let i=0, n; (i<notes.length) && (n=notes[i]); i++) {
// Find all bindings to parent.* and spread them into _parentPropChain
for (let j=0, b$=n.bindings, b; (j<b$.length) && (b=b$[j]); j++) {
for (let k=0, p$=b.parts, p; (k<p$.length) && (p=p$[k]); k++) {
if (p.signature) {
let args = p.signature.args;
for (let kk=0; kk<args.length; kk++) {
let rootProperty = args[kk].rootProperty;
if (rootProperty) {
hostProps[rootProperty] = true;
}
}
hostProps[p.signature.methodName] = true;
} else {
if (p.rootProperty) {
hostProps[p.rootProperty] = true;
}
}
}
}
// Merge child _hostProps into this _hostProps
if (n.templateContent) {
let templateHostProps = n.templateContent._hostProps;
Object.assign(hostProps, templateHostProps);
}
}
return hostProps;
}
/**
* Returns true if a binding's metadata meets all the requirements to allow
* 2-way binding, and therefore a <property>-changed event listener should be
* added:
* - used curly braces
* - is a property (not attribute) binding
* - is not a textContent binding
* - is not compound
*
* @param {Object} binding Binding metadata
* @return {boolean} True if 2-way listener should be added
* @private
*/
function shouldAddListener(binding) {
return binding.name &&
binding.kind != 'attribute' &&
binding.kind != 'text' &&
!binding.isCompound &&
binding.parts[0].mode === '{';
}
/**
* Sets up a prototypical `__notifyListeners` metadata array to be used at
* instance time to add event listeners for 2-way bindings.
*
* @param {Object} model Prototype (instances not currently supported)
* @param {number} index Index into `__templateNodes` list of annotated nodes that the
* event should be added to
* @param {string} property Property of target node to listen for changes
* @param {string} path Host path that the change should be propagated to
* @param {string=} event A custom event name to listen for (e.g. via the
* `{{prop::eventName}}` syntax)
* @param {boolean=} negate Whether the notified value should be negated before
* setting to host path
* @private
*/
function addAnnotatedListener(model, index, property, path, event, negate) {
let eventName = event ||
(CaseMap.camelToDashCase(property) + '-changed');
model.__notifyListeners = model.__notifyListeners || [];
model.__notifyListeners.push({
index: index,
property: property,
path: path,
event: eventName,
negate: negate
});
}
/**
* Adds all 2-way binding notification listeners to a host based on
* `__notifyListeners` metadata recorded by prior calls to`addAnnotatedListener`
*
* @param {Object} inst Host element instance
* @private
*/
function setupNotifyListeners(inst) {
let b$ = inst.__notifyListeners;
for (let i=0, l=b$.length, info; (i<l) && (info=b$[i]); i++) {
let node = inst.__templateNodes[info.index];
addNotifyListener(node, inst, info);
}
}
/**
* On the `inst` element that was previously bound, uses `inst.__templateNotes`
* to setup compound binding storage structures onto the bound
* nodes (`inst.__templateNodes`).
* (`inst._, and 2-way binding event listeners are also added.)
*
* @param {Object} inst Instance that bas been previously bound
* @private
*/
function setupBindings(inst) {
let notes = inst.__templateNotes;
if (notes.length) {
for (let i=0; i < notes.length; i++) {
let note = notes[i];
let node = inst.__templateNodes[i];
node.__dataHost = inst;
if (note.bindings) {
setupCompoundBinding(note, node);
}
}
}
if (inst.__notifyListeners) {
setupNotifyListeners(inst);
}
}
// -- for method-based effects (complexObserver & computed) --------------
/**
* Adds property effects for each argument in the method signature (and
* optionally, for the method name if `dynamic` is true) that calls the
* provided effect function.
*
* @param {Element | Object} model Prototype or instance
* @param {Object} sig Method signature metadata
* @param {string} type
* @param {Function} effectFn Function to run when arguments change
* @param {*=} methodInfo
* @param {Object=} dynamicFns Map indicating whether method names should
* be included as a dependency to the effect. Note, defaults to true
* if the signature is statci (sig.static is true).
* @private
*/
function createMethodEffect(model, sig, type, effectFn, methodInfo, dynamicFns) {
let dynamicFn = sig.static || dynamicFns && dynamicFns[sig.methodName];
let info = {
methodName: sig.methodName,
args: sig.args,
methodInfo,
dynamicFn
};
for (let i=0, arg; (i<sig.args.length) && (arg=sig.args[i]); i++) {
if (!arg.literal) {
model._addPropertyEffect(arg.rootProperty, type, {
fn: effectFn, info: info, trigger: arg
});
}
}
if (dynamicFn) {
model._addPropertyEffect(sig.methodName, type, {
fn: effectFn, info: info
});
}
}
/**
* Calls a method with arguments marshaled from properties on the instance
* based on the method signature contained in the effect metadata.
*
* Multi-property observers, computed properties, and inline computing
* functions call this function to invoke the method, then use the return
* value accordingly.
*
* @param {Object} inst The instance the effect will be run on
* @param {string} property Name of property
* @param {*} value Current value of property
* @param {*} old Previous value of property
* @param {Object} info Effect metadata
* @private
*/
function runMethodEffect(inst, property, props, oldProps, info) {
// Instances can optionally have a _methodHost which allows redirecting where
// to find methods. Currently used by `templatize`.
let context = inst._methodHost || inst;
let fn = context[info.methodName];
if (fn) {
let args = marshalArgs(inst.__data, info.args, property, props);
return fn.apply(context, args);
} else if (!info.dynamicFn) {
console.warn('method `' + info.methodName + '` not defined');
}
}
const emptyArray = [];
/**
* Parses an expression string for a method signature, and returns a metadata
* describing the method in terms of `methodName`, `static` (whether all the
* arguments are literals), and an array of `args`
*
* @param {string} expression The expression to parse
* @return {?Object} The method metadata object if a method expression was
* found, otherwise `undefined`
* @private
*/
function parseMethod(expression) {
// tries to match valid javascript property names
let m = expression.match(/([^\s]+?)\(([\s\S]*)\)/);
if (m) {
let sig = { methodName: m[1], static: true };
if (m[2].trim()) {
// replace escaped commas with comma entity, split on un-escaped commas
let args = m[2].replace(/\\,/g, ',').split(',');
return parseArgs(args, sig);
} else {
sig.args = emptyArray;
return sig;
}
}
return null;
}
/**
* Parses an array of arguments and sets the `args` property of the supplied
* signature metadata object. Sets the `static` property to false if any
* argument is a non-literal.
*
* @param {Array<string>} argList Array of argument names
* @param {Object} sig Method signature metadata object
* @return {Object} The updated signature metadata object
* @private
*/
function parseArgs(argList, sig) {
sig.args = argList.map(function(rawArg) {
let arg = parseArg(rawArg);
if (!arg.literal) {
sig.static = false;
}
return arg;
}, this);
return sig;
}
/**
* Parses an individual argument, and returns an argument metadata object
* with the following fields:
*
* {
* value: 'prop', // property/path or literal value
* literal: false, // whether argument is a literal
* structured: false, // whether the property is a path
* rootProperty: 'prop', // the root property of the path
* wildcard: false // whether the argument was a wildcard '.*' path
* }
*
* @param {string} rawArg The string value of the argument
* @return {Object} Argument metadata object
* @private
*/
function parseArg(rawArg) {
// clean up whitespace
let arg = rawArg.trim()
// replace comma entity with comma
.replace(/,/g, ',')
// repair extra escape sequences; note only commas strictly need
// escaping, but we allow any other char to be escaped since its
// likely users will do this
.replace(/\\(.)/g, '\$1')
;
// basic argument descriptor
let a = {
name: arg
};
// detect literal value (must be String or Number)
let fc = arg[0];
if (fc === '-') {
fc = arg[1];
}
if (fc >= '0' && fc <= '9') {
fc = '#';
}
switch(fc) {
case "'":
case '"':
a.value = arg.slice(1, -1);
a.literal = true;
break;
case '#':