-
Notifications
You must be signed in to change notification settings - Fork 15
/
templates.js
590 lines (556 loc) · 20.9 KB
/
templates.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
var saddle = require('saddle');
var serializeObject = require('serialize-object');
(function() {
for (var key in saddle) {
exports[key] = saddle[key];
}
})();
exports.Marker = Marker;
exports.View = View;
exports.ViewInstance = ViewInstance;
exports.DynamicViewInstance = DynamicViewInstance;
exports.ParentWrapper = ParentWrapper;
exports.Views = Views;
exports.MarkupHook = MarkupHook;
exports.ElementOn = ElementOn;
exports.ComponentOn = ComponentOn;
exports.AsProperty = AsProperty;
exports.AsObject = AsObject;
exports.AsObjectComponent = AsObjectComponent;
exports.AsArray = AsArray;
exports.AsArrayComponent = AsArrayComponent;
exports.emptyTemplate = new saddle.Template([]);
// Add ::isUnbound to Template && Binding
saddle.Template.prototype.isUnbound = function(context) {
return context.unbound;
};
saddle.Binding.prototype.isUnbound = function() {
return this.template.expression.isUnbound(this.context);
};
// Add Template::resolve
saddle.Template.prototype.resolve = function() {};
// The Template::dependencies method is specific to how Derby bindings work,
// so extend all of the Saddle Template types here
saddle.Template.prototype.dependencies = function(context) {
return getArrayDependencies(this.content, context);
};
saddle.Doctype.prototype.dependencies = function() {};
saddle.Text.prototype.dependencies = function() {};
saddle.DynamicText.prototype.dependencies = function(context) {
return getDependencies(this.expression, context);
};
saddle.Comment.prototype.dependencies = function() {};
saddle.DynamicComment.prototype.dependencies = function(context) {
return getDependencies(this.expression, context);
};
saddle.Element.prototype.dependencies = function(context) {
var items = getMapDependencies(this.attributes, context);
return getArrayDependencies(this.content, context, items);
};
saddle.Block.prototype.dependencies = function(context) {
var items = getDependencies(this.expression, context);
return getArrayDependencies(this.content, context, items);
};
saddle.ConditionalBlock.prototype.dependencies = function(context) {
var items = getArrayDependencies(this.expressions, context);
return getArrayOfArrayDependencies(this.contents, context, items);
};
saddle.EachBlock.prototype.dependencies = function(context) {
var items = getDependencies(this.expression, context);
items = getArrayDependencies(this.content, context, items);
return getArrayDependencies(this.elseContent, context, items);
};
saddle.Attribute.prototype.dependencies = function() {};
saddle.DynamicAttribute.prototype.dependencies = function(context) {
return getDependencies(this.expression, context);
};
function getArrayOfArrayDependencies(expressions, context, items) {
if (!expressions) return items;
for (var i = 0, len = expressions.length; i < len; i++) {
items = getArrayDependencies(expressions[i], context, items);
}
return items;
}
function getArrayDependencies(expressions, context, items) {
if (!expressions) return items;
for (var i = 0, len = expressions.length; i < len; i++) {
items = getDependencies(expressions[i], context, items);
}
return items;
}
function getMapDependencies(expressions, context, items) {
if (!expressions) return items;
for (var key in expressions) {
items = getDependencies(expressions[key], context, items);
}
return items;
}
function getDependencies(expression, context, items) {
var dependencies = expression && expression.dependencies(context);
if (!dependencies) return items;
for (var i = 0, len = dependencies.length; i < len; i++) {
items || (items = []);
items.push(dependencies[i]);
}
return items;
}
var markerHooks = [{
emit: function(context, node) {
node.$component = context.controller;
context.controller.markerNode = node;
}
}];
function Marker(data) {
saddle.Comment.call(this, data, markerHooks);
}
Marker.prototype = Object.create(saddle.Comment.prototype);
Marker.prototype.type = 'Marker';
Marker.prototype.serialize = function() {
return serializeObject.instance(this, this.data);
};
Marker.prototype.get = function() {
return '';
};
function ViewAttributesMap(source) {
var items = source.split(/\s+/);
for (var i = 0, len = items.length; i < len; i++) {
this[items[i]] = true;
}
}
function ViewArraysMap(source) {
var items = source.split(/\s+/);
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i].split('/');
this[item[0]] = item[1] || item[0];
}
}
function View(views, name, source, options) {
this.views = views;
this.name = name;
this.source = source;
this.options = options;
var nameSegments = (this.name || '').split(':');
var lastSegment = nameSegments.pop();
this.namespace = nameSegments.join(':');
this.registeredName = (lastSegment === 'index') ? this.namespace : this.name;
this.attributesMap = options && options.attributes &&
new ViewAttributesMap(options.attributes);
this.arraysMap = options && options.arrays &&
new ViewArraysMap(options.arrays);
// The empty string is considered true for easier HTML attribute parsing
this.unminified = options && (options.unminified || options.unminified === '');
this.string = options && (options.string || options.string === '');
this.literal = options && (options.literal || options.literal === '');
this.template = null;
this.componentFactory = null;
}
View.prototype = Object.create(saddle.Template.prototype);
View.prototype.type = 'View';
View.prototype.serialize = function() {
return null;
};
View.prototype._isComponent = function(context) {
if (!this.componentFactory) return false;
if (context.attributes && context.attributes.extend) return false;
return true;
};
View.prototype._initComponent = function(context) {
return (this._isComponent(context)) ?
this.componentFactory.init(context) : context;
};
View.prototype._queueCreate = function(context, viewContext) {
if (this._isComponent(context)) {
var componentFactory = this.componentFactory;
context.queue(function queuedCreate() {
componentFactory.create(viewContext);
});
if (!context.hooks) return;
context.queue(function queuedComponentHooks() {
// Kick off hooks if view instance specified `on` or `as` attributes
for (var i = 0, len = context.hooks.length; i < len; i++) {
context.hooks[i].emit(context, viewContext.controller);
}
});
}
};
View.prototype.get = function(context, unescaped) {
var viewContext = this._initComponent(context);
var template = this.template || this.parse();
return template.get(viewContext, unescaped);
};
View.prototype.getFragment = function(context, binding) {
var viewContext = this._initComponent(context);
var template = this.template || this.parse();
var fragment = template.getFragment(viewContext, binding);
this._queueCreate(context, viewContext);
return fragment;
};
View.prototype.appendTo = function(parent, context) {
var viewContext = this._initComponent(context);
var template = this.template || this.parse();
template.appendTo(parent, viewContext);
this._queueCreate(context, viewContext);
};
View.prototype.attachTo = function(parent, node, context) {
var viewContext = this._initComponent(context);
var template = this.template || this.parse();
var node = template.attachTo(parent, node, viewContext);
this._queueCreate(context, viewContext);
return node;
};
View.prototype.dependencies = function(context) {
var template = this.template || this.parse();
return template.dependencies(context);
};
View.prototype.parse = function() {
this._parse();
if (this.componentFactory) {
var marker = new Marker(this.name);
this.template.content.unshift(marker);
}
return this.template;
};
// View.prototype._parse is defined in parsing.js, so that it doesn't have to
// be included in the client if templates are all parsed server-side
View.prototype._parse = function() {
throw new Error('View parsing not available');
};
function ViewInstance(name, attributes, hooks, initHooks) {
this.name = name;
this.attributes = attributes;
this.hooks = hooks;
this.initHooks = initHooks;
this.view = null;
}
ViewInstance.prototype = Object.create(saddle.Template.prototype);
ViewInstance.prototype.type = 'ViewInstance';
ViewInstance.prototype.serialize = function() {
return serializeObject.instance(this, this.name, this.attributes, this.hooks, this.initHooks);
};
ViewInstance.prototype.get = function(context, unescaped) {
var view = this._find(context);
var viewContext = context.viewChild(view, this.attributes, this.hooks, this.initHooks);
return view.get(viewContext, unescaped);
};
ViewInstance.prototype.getFragment = function(context, binding) {
var view = this._find(context);
var viewContext = context.viewChild(view, this.attributes, this.hooks, this.initHooks);
return view.getFragment(viewContext, binding);
};
ViewInstance.prototype.appendTo = function(parent, context) {
var view = this._find(context);
var viewContext = context.viewChild(view, this.attributes, this.hooks, this.initHooks);
view.appendTo(parent, viewContext);
};
ViewInstance.prototype.attachTo = function(parent, node, context) {
var view = this._find(context);
var viewContext = context.viewChild(view, this.attributes, this.hooks, this.initHooks);
return view.attachTo(parent, node, viewContext);
};
ViewInstance.prototype.dependencies = function(context) {
var view = this._find(context);
var viewContext = context.viewChild(view, this.attributes, this.hooks, this.initHooks);
return view.dependencies(viewContext);
};
ViewInstance.prototype._find = function(context) {
if (this.view) return this.view;
var contextView = context.getView();
var namespace = contextView && contextView.namespace;
this.view = context.meta.views.find(this.name, namespace);
if (!this.view) {
var message = context.meta.views.findErrorMessage(this.name, contextView);
throw new Error(message);
}
return this.view;
};
function DynamicViewInstance(nameExpression, attributes, hooks, initHooks) {
this.nameExpression = nameExpression;
this.attributes = attributes;
this.hooks = hooks;
this.initHooks = initHooks;
}
DynamicViewInstance.prototype = Object.create(ViewInstance.prototype);
DynamicViewInstance.prototype.type = 'DynamicViewInstance';
DynamicViewInstance.prototype.serialize = function() {
return serializeObject.instance(this, this.nameExpression, this.attributes, this.hooks, this.initHooks);
};
DynamicViewInstance.prototype._find = function(context) {
var name = this.nameExpression.get(context);
var contextView = context.getView();
var namespace = contextView && contextView.namespace;
var view = name && context.meta.views.find(name, namespace);
return view || exports.emptyTemplate;
};
function ParentWrapper(template, expression) {
this.template = template;
this.expression = expression;
}
ParentWrapper.prototype = Object.create(saddle.Template.prototype);
ParentWrapper.prototype.type = 'ParentWrapper';
ParentWrapper.prototype.serialize = function() {
return serializeObject.instance(this, this.template, this.expression);
};
ParentWrapper.prototype.get = function(context, unescaped) {
return (this.expression || this.template).get(context.forViewParent(), unescaped);
};
ParentWrapper.prototype.getFragment = function(context, binding) {
return this.template.getFragment(context.forViewParent(), binding);
};
ParentWrapper.prototype.appendTo = function(parent, context) {
this.template.appendTo(parent, context.forViewParent());
};
ParentWrapper.prototype.attachTo = function(parent, node, context) {
return this.template.attachTo(parent, node, context.forViewParent());
};
ParentWrapper.prototype.resolve = function(context) {
return this.expression && this.expression.resolve(context.forViewParent());
};
ParentWrapper.prototype.dependencies = function(context, forInnerPath) {
return (this.expression || this.template).dependencies(context.forViewParent(), forInnerPath);
};
function ViewsMap() {}
function Views() {
this.nameMap = new ViewsMap();
this.tagMap = new ViewsMap();
// TODO: elementMap is deprecated and should be removed with Derby 0.6.0
this.elementMap = this.tagMap;
}
Views.prototype.find = function(name, namespace) {
var map = this.nameMap;
// Exact match lookup
var exactName = (namespace) ? namespace + ':' + name : name;
var match = map[exactName];
if (match) return match;
// Relative lookup
var segments = name.split(':');
var segmentsDepth = segments.length;
if (namespace) segments = namespace.split(':').concat(segments);
// Iterate through segments, leaving the `segmentsDepth` segments and
// removing the second to `segmentsDepth` segment to traverse up the
// namespaces. Decrease `segmentsDepth` if not found and repeat again.
while (segmentsDepth > 0) {
var testSegments = segments.slice();
while (testSegments.length > segmentsDepth) {
testSegments.splice(-1 - segmentsDepth, 1);
var testName = testSegments.join(':');
var match = map[testName];
if (match) return match;
}
segmentsDepth--;
}
};
Views.prototype.register = function(name, source, options) {
var mapName = name.replace(/:index$/, '');
var view = this.nameMap[mapName];
if (view) {
// Recreate the view if it already exists. We re-apply the constructor
// instead of creating a new view object so that references to object
// can be cached after finding the first time
var componentFactory = view.componentFactory;
View.call(view, this, name, source, options);
view.componentFactory = componentFactory;
} else {
view = new View(this, name, source, options);
}
this.nameMap[mapName] = view;
// TODO: element is deprecated and should be removed with Derby 0.6.0
var tagName = options && (options.tag || options.element);
if (tagName) this.tagMap[tagName] = view;
return view;
};
Views.prototype.serialize = function(options) {
var out = 'function(derbyTemplates, views) {' +
'var expressions = derbyTemplates.expressions;' +
'var templates = derbyTemplates.templates;';
var forServer = options && options.server;
var minify = options && options.minify;
for (var name in this.nameMap) {
var view = this.nameMap[name];
var template = view.template || view.parse();
if (!forServer && view.options) {
// Do not serialize views with the `serverOnly` option, except when
// serializing for a server script
if (view.options.serverOnly) continue;
// For views with the `server` option, serialize them with a blank
// template body. This allows them to be used from other views on the
// browser, but they will output nothing on the browser
if (view.options.server) template = exports.emptyTemplate;
}
out += 'views.register(' + serializeObject.args([
view.name
, (minify) ? null : view.source
, (hasKeys(view.options)) ? view.options : null
]) + ').parse = function() {return this.template = ' + template.serialize() + '};';
}
return out + '}';
};
Views.prototype.findErrorMessage = function(name, contextView) {
var names = Object.keys(this.nameMap);
var message = 'Cannot find view "' + name + '" in' +
[''].concat(names).join('\n ') + '\n';
if (contextView) {
message += '\nWithin template "' + contextView.name + '":\n' + contextView.source;
}
return message;
};
function MarkupHook() {}
MarkupHook.prototype.module = saddle.Template.prototype.module;
function ElementOn(name, expression) {
this.name = name;
this.expression = expression;
}
ElementOn.prototype = Object.create(MarkupHook.prototype);
ElementOn.prototype.type = 'ElementOn';
ElementOn.prototype.serialize = function() {
return serializeObject.instance(this, this.name, this.expression);
};
ElementOn.prototype.emit = function(context, element) {
var elementOn = this;
if (this.name === 'create') {
this.apply(context, element);
} else if (this.name === 'destroy') {
var destroyListeners = element.$destroyListeners || (element.$destroyListeners = []);
destroyListeners.push(function elementOnDestroy() {
elementOn.apply(context, element);
});
} else {
element.addEventListener(this.name, function elementOnListener(event) {
return elementOn.apply(context, element, event);
}, false);
}
};
ElementOn.prototype.apply = function(context, element, event) {
var modelData = context.controller.model.data;
modelData.$event = event;
modelData.$element = element;
var out = this.expression.apply(context);
delete modelData.$event;
delete modelData.$element;
return out;
};
function ComponentOn(name, expression) {
this.name = name;
this.expression = expression;
}
ComponentOn.prototype = Object.create(MarkupHook.prototype);
ComponentOn.prototype.type = 'ComponentOn';
ComponentOn.prototype.serialize = function() {
return serializeObject.instance(this, this.name, this.expression);
};
ComponentOn.prototype.emit = function(context, component) {
var expression = this.expression;
component.on(this.name, function componentOnListener() {
var args = arguments.length && Array.prototype.slice.call(arguments);
return expression.apply(context, args);
});
};
function AsProperty(segments) {
this.segments = segments;
this.lastSegment = segments.pop();
}
AsProperty.prototype = Object.create(MarkupHook.prototype);
AsProperty.prototype.type = 'AsProperty';
AsProperty.prototype.serialize = function() {
var segments = this.segments.concat(this.lastSegment);
return serializeObject.instance(this, segments);
};
AsProperty.prototype.emit = function(context, target) {
var node = traverseAndCreate(context.controller, this.segments);
node[this.lastSegment] = target;
};
function AsObject(segments, keyExpression) {
AsProperty.call(this, segments);
this.keyExpression = keyExpression;
}
AsObject.prototype = Object.create(AsProperty.prototype);
AsObject.prototype.type = 'AsObject';
AsObject.prototype.serialize = function() {
var segments = this.segments.concat(this.lastSegment);
return serializeObject.instance(this, segments, this.keyExpression);
};
AsObject.prototype.emit = function(context, target) {
var node = traverseAndCreate(context.controller, this.segments);
var object = node[this.lastSegment] || (node[this.lastSegment] = {});
var key = this.keyExpression.get(context);
object[key] = target;
this.addListeners(target, object, key);
};
AsObject.prototype.addListeners = function(target, object, key) {
this.addDestroyListener(target, function asObjectDestroy() {
delete object[key];
});
};
AsObject.prototype.addDestroyListener = function(target, listener) {
var listeners = target.$destroyListeners || (target.$destroyListeners = []);
listeners.push(listener);
};
function AsObjectComponent(segments, keyExpression) {
AsObject.call(this, segments, keyExpression);
}
AsObjectComponent.prototype = Object.create(AsObject.prototype);
AsObjectComponent.prototype.type = 'AsObjectComponent';
AsObjectComponent.prototype.addDestroyListener = function(target, listener) {
target.on('destroy', listener);
};
function AsArray(segments) {
AsProperty.call(this, segments);
}
AsArray.prototype = Object.create(AsProperty.prototype);
AsArray.prototype.type = 'AsArray';
AsArray.prototype.emit = function(context, target) {
var node = traverseAndCreate(context.controller, this.segments);
var array = node[this.lastSegment] || (node[this.lastSegment] = []);
// Iterate backwards, since rendering will usually append
for (var i = array.length; i--;) {
var item = array[i];
// Don't add an item if already in the array
if (item === target) return;
var mask = this.comparePosition(target, item);
// If the emitted target is after the current item in the document,
// insert it next in the array
// Node.DOCUMENT_POSITION_FOLLOWING = 4
if (mask & 4) {
array.splice(i + 1, 0, target);
this.addListeners(target, array);
return;
}
}
// Add to the beginning if before all items
array.unshift(target);
this.addListeners(target, array);
};
AsArray.prototype.addListeners = function(target, array) {
this.addDestroyListener(target, function asArrayDestroy() {
var index = array.indexOf(target);
if (index !== -1) array.splice(index, 1);
});
};
AsArray.prototype.comparePosition = function(target, item) {
return item.compareDocumentPosition(target);
};
AsArray.prototype.addDestroyListener = AsObject.prototype.addDestroyListener;
function AsArrayComponent(segments) {
AsArray.call(this, segments);
}
AsArrayComponent.prototype = Object.create(AsArray.prototype);
AsArrayComponent.prototype.type = 'AsArrayComponent';
AsArrayComponent.prototype.comparePosition = function(target, item) {
return item.markerNode.compareDocumentPosition(target.markerNode);
};
AsArrayComponent.prototype.addDestroyListener = AsObjectComponent.prototype.addDestroyListener;
function traverseAndCreate(node, segments) {
var len = segments.length;
if (!len) return node;
for (var i = 0; i < len; i++) {
var segment = segments[i];
node = node[segment] || (node[segment] = {});
}
return node;
}
function hasKeys(value) {
if (!value) return false;
for (var key in value) {
return true;
}
return false;
}