-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolymer-expressions.js
599 lines (495 loc) · 16.5 KB
/
polymer-expressions.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
// Copyright 2013 Google Inc.
//
// 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.
(function (global) {
'use strict';
// JScript does not have __proto__. We wrap all object literals with
// createObject which uses Object.create, Object.defineProperty and
// Object.getOwnPropertyDescriptor to create a new object that does the exact
// same thing. The main downside to this solution is that we have to extract
// all those property descriptors for IE.
var createObject = ('__proto__' in {}) ?
function(obj) { return obj; } :
function(obj) {
var proto = obj.__proto__;
if (!proto)
return obj;
var newObject = Object.create(proto);
Object.getOwnPropertyNames(obj).forEach(function(name) {
Object.defineProperty(newObject, name,
Object.getOwnPropertyDescriptor(obj, name));
});
return newObject;
};
function prepareBinding(expressionText, name, node, filterRegistry) {
var expression;
try {
expression = getExpression(expressionText);
if (expression.scopeIdent &&
(node.nodeType !== Node.ELEMENT_NODE ||
node.tagName !== 'TEMPLATE' ||
(name !== 'bind' && name !== 'repeat'))) {
throw Error('as and in can only be used within <template bind/repeat>');
}
} catch (ex) {
console.error('Invalid expression syntax: ' + expressionText, ex);
return;
}
return function(model, node, oneTime) {
var binding = expression.getBinding(model, filterRegistry, oneTime);
if (expression.scopeIdent && binding) {
node.polymerExpressionScopeIdent_ = expression.scopeIdent;
if (expression.indexIdent)
node.polymerExpressionIndexIdent_ = expression.indexIdent;
}
return binding;
}
}
// TODO(rafaelw): Implement simple LRU.
var expressionParseCache = Object.create(null);
function getExpression(expressionText) {
var expression = expressionParseCache[expressionText];
if (!expression) {
var delegate = new ASTDelegate();
esprima.parse(expressionText, delegate);
expression = new Expression(delegate);
expressionParseCache[expressionText] = expression;
}
return expression;
}
function Literal(value) {
this.value = value;
this.valueFn_ = undefined;
}
Literal.prototype = {
valueFn: function() {
if (!this.valueFn_) {
var value = this.value;
this.valueFn_ = function() {
return value;
}
}
return this.valueFn_;
}
}
function IdentPath(name) {
this.name = name;
this.path = Path.get(name);
}
IdentPath.prototype = {
valueFn: function() {
if (!this.valueFn_) {
var name = this.name;
var path = this.path;
this.valueFn_ = function(model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
}
}
return this.valueFn_;
},
setValue: function(model, newValue) {
return this.path.setValueFrom(model, newValue);
}
};
function MemberExpression(object, property, accessor) {
// convert literal computed property access where literal value is a value
// path to ident dot-access.
if (accessor == '[' &&
property instanceof Literal &&
Path.get(property.value).valid) {
accessor = '.';
property = new IdentPath(property.value);
}
this.dynamicDeps = typeof object == 'function' || object.dynamic;
this.dynamic = typeof property == 'function' ||
property.dynamic ||
accessor == '[';
this.simplePath =
!this.dynamic &&
!this.dynamicDeps &&
property instanceof IdentPath &&
(object instanceof MemberExpression || object instanceof IdentPath);
this.object = this.simplePath ? object : getFn(object);
this.property = accessor == '.' ? property : getFn(property);
}
MemberExpression.prototype = {
get fullPath() {
if (!this.fullPath_) {
var last = this.object instanceof IdentPath ?
this.object.name : this.object.fullPath;
this.fullPath_ = Path.get(last + '.' + this.property.name);
}
return this.fullPath_;
},
valueFn: function() {
if (!this.valueFn_) {
var object = this.object;
if (this.simplePath) {
var path = this.fullPath;
this.valueFn_ = function(model, observer) {
if (observer)
observer.addPath(model, path);
return path.getValueFrom(model);
};
} else if (this.property instanceof IdentPath) {
var path = Path.get(this.property.name);
this.valueFn_ = function(model, observer) {
var context = object(model, observer);
if (observer)
observer.addPath(context, path);
return path.getValueFrom(context);
}
} else {
// Computed property.
var property = this.property;
this.valueFn_ = function(model, observer) {
var context = object(model, observer);
var propName = property(model, observer);
if (observer)
observer.addPath(context, propName);
return context ? context[propName] : undefined;
};
}
}
return this.valueFn_;
},
setValue: function(model, newValue) {
if (this.simplePath) {
this.fullPath.setValueFrom(model, newValue);
return newValue;
}
var object = this.object(model);
var propName = this.property instanceof IdentPath ? this.property.name :
this.property(model);
return object[propName] = newValue;
}
};
function Filter(name, args) {
this.name = name;
this.args = [];
for (var i = 0; i < args.length; i++) {
this.args[i] = getFn(args[i]);
}
}
Filter.prototype = {
transform: function(value, toModelDirection, filterRegistry, model,
observer) {
var fn = filterRegistry[this.name];
var context = model;
if (fn) {
context = undefined;
} else {
fn = context[this.name];
if (!fn) {
console.error('Cannot find filter: ' + this.name);
return;
}
}
// If toModelDirection is falsey, then the "normal" (dom-bound) direction
// is used. Otherwise, it looks for a 'toModel' property function on the
// object.
if (toModelDirection) {
fn = fn.toModel;
} else if (typeof fn.toDOM == 'function') {
fn = fn.toDOM;
}
if (typeof fn != 'function') {
console.error('No ' + (toModelDirection ? 'toModel' : 'toDOM') +
' found on' + this.name);
return;
}
var args = [value];
for (var i = 0; i < this.args.length; i++) {
args[i + 1] = getFn(this.args[i])(model, observer);
}
return fn.apply(context, args);
}
};
function notImplemented() { throw Error('Not Implemented'); }
var unaryOperators = {
'+': function(v) { return +v; },
'-': function(v) { return -v; },
'!': function(v) { return !v; }
};
var binaryOperators = {
'+': function(l, r) { return l+r; },
'-': function(l, r) { return l-r; },
'*': function(l, r) { return l*r; },
'/': function(l, r) { return l/r; },
'%': function(l, r) { return l%r; },
'<': function(l, r) { return l<r; },
'>': function(l, r) { return l>r; },
'<=': function(l, r) { return l<=r; },
'>=': function(l, r) { return l>=r; },
'==': function(l, r) { return l==r; },
'!=': function(l, r) { return l!=r; },
'===': function(l, r) { return l===r; },
'!==': function(l, r) { return l!==r; },
'&&': function(l, r) { return l&&r; },
'||': function(l, r) { return l||r; },
};
function getFn(arg) {
return typeof arg == 'function' ? arg : arg.valueFn();
}
function ASTDelegate() {
this.expression = null;
this.filters = [];
this.deps = {};
this.currentPath = undefined;
this.scopeIdent = undefined;
this.indexIdent = undefined;
this.dynamicDeps = false;
}
ASTDelegate.prototype = {
createUnaryExpression: function(op, argument) {
if (!unaryOperators[op])
throw Error('Disallowed operator: ' + op);
argument = getFn(argument);
return function(model, observer) {
return unaryOperators[op](argument(model, observer));
};
},
createBinaryExpression: function(op, left, right) {
if (!binaryOperators[op])
throw Error('Disallowed operator: ' + op);
left = getFn(left);
right = getFn(right);
return function(model, observer) {
return binaryOperators[op](left(model, observer),
right(model, observer));
};
},
createConditionalExpression: function(test, consequent, alternate) {
test = getFn(test);
consequent = getFn(consequent);
alternate = getFn(alternate);
return function(model, observer) {
return test(model, observer) ?
consequent(model, observer) : alternate(model, observer);
}
},
createIdentifier: function(name) {
var ident = new IdentPath(name);
ident.type = 'Identifier';
return ident;
},
createMemberExpression: function(accessor, object, property) {
var ex = new MemberExpression(object, property, accessor);
if (ex.dynamicDeps)
this.dynamicDeps = true;
return ex;
},
createLiteral: function(token) {
return new Literal(token.value);
},
createArrayExpression: function(elements) {
for (var i = 0; i < elements.length; i++)
elements[i] = getFn(elements[i]);
return function(model, observer) {
var arr = []
for (var i = 0; i < elements.length; i++)
arr.push(elements[i](model, observer));
return arr;
}
},
createProperty: function(kind, key, value) {
return {
key: key instanceof IdentPath ? key.name : key.value,
value: value
};
},
createObjectExpression: function(properties) {
for (var i = 0; i < properties.length; i++)
properties[i].value = getFn(properties[i].value);
return function(model, observer) {
var obj = {};
for (var i = 0; i < properties.length; i++)
obj[properties[i].key] = properties[i].value(model, observer);
return obj;
}
},
createFilter: function(name, args) {
this.filters.push(new Filter(name, args));
},
createAsExpression: function(expression, scopeIdent) {
this.expression = expression;
this.scopeIdent = scopeIdent;
},
createInExpression: function(scopeIdent, indexIdent, expression) {
this.expression = expression;
this.scopeIdent = scopeIdent;
this.indexIdent = indexIdent;
},
createTopLevel: function(expression) {
this.expression = expression;
},
createThisExpression: notImplemented
}
function ConstantObservable(value) {
this.value_ = value;
}
ConstantObservable.prototype = {
open: function() { return this.value_; },
discardChanges: function() { return this.value_; },
deliver: function() {},
close: function() {},
}
function Expression(delegate) {
this.scopeIdent = delegate.scopeIdent;
this.indexIdent = delegate.indexIdent;
if (!delegate.expression)
throw Error('No expression found.');
this.expression = delegate.expression;
getFn(this.expression); // forces enumeration of path dependencies
this.filters = delegate.filters;
this.dynamicDeps = delegate.dynamicDeps;
}
Expression.prototype = {
getBinding: function(model, filterRegistry, oneTime) {
if (oneTime)
return this.getValue(model, undefined, filterRegistry);
var observer = new CompoundObserver();
this.getValue(model, observer, filterRegistry); // captures deps.
var self = this;
function valueFn() {
if (self.dynamicDeps)
observer.startReset();
var value = self.getValue(model,
self.dynamicDeps ? observer : undefined,
filterRegistry);
if (self.dynamicDeps)
observer.finishReset();
return value;
}
function setValueFn(newValue) {
self.setValue(model, newValue, filterRegistry);
return newValue;
}
return new ObserverTransform(observer, valueFn, setValueFn, true);
},
getValue: function(model, observer, filterRegistry) {
var value = getFn(this.expression)(model, observer);
for (var i = 0; i < this.filters.length; i++) {
value = this.filters[i].transform(value, false, filterRegistry, model,
observer);
}
return value;
},
setValue: function(model, newValue, filterRegistry) {
var count = this.filters ? this.filters.length : 0;
while (count-- > 0) {
newValue = this.filters[count].transform(newValue, true, filterRegistry,
model);
}
if (this.expression.setValue)
return this.expression.setValue(model, newValue);
}
}
/**
* Converts a style property name to a css property name. For example:
* "WebkitUserSelect" to "-webkit-user-select"
*/
function convertStylePropertyName(name) {
return String(name).replace(/[A-Z]/g, function(c) {
return '-' + c.toLowerCase();
});
}
function isEventHandler(name) {
return name[0] === 'o' &&
name[1] === 'n' &&
name[2] === '-';
}
function prepareEventBinding(path, name) {
var eventType = name.substring(3);
return function(model, node, oneTime) {
var fn = path.getValueFrom(model);
function handler() {
if (!oneTime)
fn = path.getValueFrom(model);
fn.apply(model, arguments);
}
node.addEventListener(eventType, handler);
if (oneTime)
return;
function bindingValue() {
return '{{ ' + path + ' }}';
}
return {
open: bindingValue,
discardChanges: bindingValue,
close: function() {
node.removeEventListener(eventType, handler);
}
};
}
}
function PolymerExpressions() {}
PolymerExpressions.prototype = {
// "built-in" filters
styleObject: function(value) {
var parts = [];
for (var key in value) {
parts.push(convertStylePropertyName(key) + ': ' + value[key]);
}
return parts.join('; ');
},
tokenList: function(value) {
var tokens = [];
for (var key in value) {
if (value[key])
tokens.push(key);
}
return tokens.join(' ');
},
// binding delegate API
prepareInstancePositionChanged: function(template) {
var indexIdent = template.polymerExpressionIndexIdent_;
if (!indexIdent)
return;
return function(templateInstance, index) {
templateInstance.model[indexIdent] = index;
};
},
prepareBinding: function(pathString, name, node) {
if (isEventHandler(name)) {
var path = Path.get(pathString);
if (!path.valid) {
console.error('on-* bindings must be simple path expressions');
return;
}
return prepareEventBinding(path, name);
}
if (Path.get(pathString).valid)
return; // bail out early if pathString is simple path.
return prepareBinding(pathString, name, node, this);
},
prepareInstanceModel: function(template) {
var scopeName = template.polymerExpressionScopeIdent_;
if (!scopeName)
return;
var parentScope = template.templateInstance ?
template.templateInstance.model :
template.model;
return function(model) {
var scope = Object.create(parentScope);
scope[scopeName] = model;
return scope;
};
}
};
global.PolymerExpressions = PolymerExpressions;
if (global.exposeGetExpression)
global.getExpression_ = getExpression
})(this);