@tko/binding.template 4.0.0-alpha8.4 → 4.0.0-beta1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,576 +0,0 @@
1
- /*!
2
- * TKO Template bindings 🥊 @tko/binding.template@4.0.0-alpha8.4
3
- * (c) The Knockout.js Team - https://tko.io
4
- * License: MIT (http://www.opensource.org/licenses/mit-license.php)
5
- */
6
-
7
- import { tagNameLower, setHtml, domData, parseHtmlForTemplateNodes, extend, options, virtualElements, fixUpContinuousNodeArray, replaceDomNodes, memoization, domNodeIsAttachedToDocument, moveCleanedNodesToContainerElement, arrayFilter, ieVersion, makeArray, parseHtmlFragment } from '@tko/utils';
8
- import { applyBindings, setDomNodeChildrenFromArrayMapping, AsyncBindingHandler, bindingEvent, bindingContext } from '@tko/bind';
9
- import { computed } from '@tko/computed';
10
- import { isObservable, dependencyDetection, unwrap, observable, isObservableArray, peek } from '@tko/observable';
11
-
12
- /*! *****************************************************************************
13
- Copyright (c) Microsoft Corporation. All rights reserved.
14
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
15
- this file except in compliance with the License. You may obtain a copy of the
16
- License at http://www.apache.org/licenses/LICENSE-2.0
17
-
18
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
20
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
21
- MERCHANTABLITY OR NON-INFRINGEMENT.
22
-
23
- See the Apache Version 2.0 License for specific language governing permissions
24
- and limitations under the License.
25
- ***************************************************************************** */
26
- /* global Reflect, Promise */
27
-
28
- var extendStatics = Object.setPrototypeOf ||
29
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
31
-
32
- function __extends(d, b) {
33
- extendStatics(d, b);
34
- function __() { this.constructor = d; }
35
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
- }
37
-
38
- // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
39
- // ---- ko.templateSources.domElement -----
40
- // template types
41
- var templateScript = 1, templateTextArea = 2, templateTemplate = 3, templateElement = 4;
42
- function domElement(element) {
43
- this.domElement = element;
44
- if (!element) {
45
- return;
46
- }
47
- var tagNameLower$$1 = tagNameLower(element);
48
- this.templateType =
49
- tagNameLower$$1 === 'script' ? templateScript
50
- : tagNameLower$$1 === 'textarea' ? templateTextArea
51
- // For browsers with proper <template> element support, where the .content property gives a document fragment
52
- : tagNameLower$$1 == 'template' && element.content && element.content.nodeType === 11 ? templateTemplate
53
- : templateElement;
54
- }
55
- domElement.prototype.text = function ( /* valueToWrite */) {
56
- var elemContentsProperty = this.templateType === templateScript ? 'text'
57
- : this.templateType === templateTextArea ? 'value'
58
- : 'innerHTML';
59
- if (arguments.length == 0) {
60
- return this.domElement[elemContentsProperty];
61
- }
62
- else {
63
- var valueToWrite = arguments[0];
64
- if (elemContentsProperty === 'innerHTML') {
65
- setHtml(this.domElement, valueToWrite);
66
- }
67
- else {
68
- this.domElement[elemContentsProperty] = valueToWrite;
69
- }
70
- }
71
- };
72
- var dataDomDataPrefix = domData.nextKey() + '_';
73
- domElement.prototype.data = function (key /*, valueToWrite */) {
74
- if (arguments.length === 1) {
75
- return domData.get(this.domElement, dataDomDataPrefix + key);
76
- }
77
- else {
78
- domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
79
- }
80
- };
81
- var templatesDomDataKey = domData.nextKey();
82
- function getTemplateDomData(element) {
83
- return domData.get(element, templatesDomDataKey) || {};
84
- }
85
- function setTemplateDomData(element, data) {
86
- domData.set(element, templatesDomDataKey, data);
87
- }
88
- domElement.prototype.nodes = function ( /* valueToWrite */) {
89
- var element = this.domElement;
90
- if (arguments.length == 0) {
91
- var templateData = getTemplateDomData(element);
92
- var nodes = templateData.containerData || (this.templateType === templateTemplate ? element.content :
93
- this.templateType === templateElement ? element :
94
- undefined);
95
- if (!nodes || templateData.alwaysCheckText) {
96
- // If the template is associated with an element that stores the template as text,
97
- // parse and cache the nodes whenever there's new text content available. This allows
98
- // the user to update the template content by updating the text of template node.
99
- var text = this['text']();
100
- if (text) {
101
- nodes = parseHtmlForTemplateNodes(text, element.ownerDocument);
102
- this['text'](''); // clear the text from the node
103
- setTemplateDomData(element, { containerData: nodes, alwaysCheckText: true });
104
- }
105
- }
106
- return nodes;
107
- }
108
- else {
109
- var valueToWrite = arguments[0];
110
- setTemplateDomData(element, { containerData: valueToWrite });
111
- }
112
- };
113
- // ---- ko.templateSources.anonymousTemplate -----
114
- // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
115
- // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
116
- // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
117
- function anonymousTemplate(element) {
118
- this.domElement = element;
119
- }
120
- anonymousTemplate.prototype = new domElement();
121
- anonymousTemplate.prototype.constructor = anonymousTemplate;
122
- anonymousTemplate.prototype.text = function ( /* valueToWrite */) {
123
- if (arguments.length == 0) {
124
- var templateData = getTemplateDomData(this.domElement);
125
- if (templateData.textData === undefined && templateData.containerData) {
126
- templateData.textData = templateData.containerData.innerHTML;
127
- }
128
- return templateData.textData;
129
- }
130
- else {
131
- var valueToWrite = arguments[0];
132
- setTemplateDomData(this.domElement, { textData: valueToWrite });
133
- }
134
- };
135
-
136
- // If you want to make a custom template engine,
137
- function templateEngine() { }
138
- extend(templateEngine.prototype, {
139
- renderTemplateSource: function (templateSource, bindingContext$$1, options$$1, templateDocument) {
140
- options$$1.onError('Override renderTemplateSource');
141
- },
142
- createJavaScriptEvaluatorBlock: function (script) {
143
- options.onError('Override createJavaScriptEvaluatorBlock');
144
- },
145
- makeTemplateSource: function (template, templateDocument) {
146
- // Named template
147
- if (typeof template === 'string') {
148
- templateDocument = templateDocument || document;
149
- var elem = templateDocument.getElementById(template);
150
- if (!elem) {
151
- options.onError('Cannot find template with ID ' + template);
152
- }
153
- return new domElement(elem);
154
- }
155
- else if ((template.nodeType == 1) || (template.nodeType == 8)) {
156
- // Anonymous template
157
- return new anonymousTemplate(template);
158
- }
159
- else {
160
- options.onError('Unknown template type: ' + template);
161
- }
162
- },
163
- renderTemplate: function (template, bindingContext$$1, options$$1, templateDocument) {
164
- var templateSource = this['makeTemplateSource'](template, templateDocument);
165
- return this.renderTemplateSource(templateSource, bindingContext$$1, options$$1, templateDocument);
166
- }
167
- });
168
-
169
- var _templateEngine;
170
- var cleanContainerDomDataKey = domData.nextKey();
171
- function setTemplateEngine(tEngine) {
172
- if ((tEngine !== undefined) && !(tEngine instanceof templateEngine)) {
173
- // TODO: ko.templateEngine to appropriate name
174
- throw new Error('templateEngine must inherit from ko.templateEngine');
175
- }
176
- _templateEngine = tEngine;
177
- }
178
- function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
179
- var node;
180
- var nextInQueue = firstNode;
181
- var firstOutOfRangeNode = virtualElements.nextSibling(lastNode);
182
- while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
183
- nextInQueue = virtualElements.nextSibling(node);
184
- action(node, nextInQueue);
185
- }
186
- }
187
- function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext$$1, afterBindingCallback) {
188
- // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
189
- // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
190
- // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
191
- // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
192
- // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
193
- if (continuousNodeArray.length) {
194
- var firstNode = continuousNodeArray[0];
195
- var lastNode = continuousNodeArray[continuousNodeArray.length - 1];
196
- var parentNode = firstNode.parentNode;
197
- var provider = options.bindingProviderInstance;
198
- var preprocessNode = provider.preprocessNode;
199
- if (preprocessNode) {
200
- invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node, nextNodeInRange) {
201
- var nodePreviousSibling = node.previousSibling;
202
- var newNodes = preprocessNode.call(provider, node);
203
- if (newNodes) {
204
- if (node === firstNode) {
205
- firstNode = newNodes[0] || nextNodeInRange;
206
- }
207
- if (node === lastNode) {
208
- lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
209
- }
210
- }
211
- });
212
- // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
213
- // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
214
- // first node needs to be in the array).
215
- continuousNodeArray.length = 0;
216
- if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
217
- return;
218
- }
219
- if (firstNode === lastNode) {
220
- continuousNodeArray.push(firstNode);
221
- }
222
- else {
223
- continuousNodeArray.push(firstNode, lastNode);
224
- fixUpContinuousNodeArray(continuousNodeArray, parentNode);
225
- }
226
- }
227
- // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
228
- // whereas a regular applyBindings won't introduce new memoized nodes
229
- invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) {
230
- if (node.nodeType === 1 || node.nodeType === 8) {
231
- applyBindings(bindingContext$$1, node).then(afterBindingCallback);
232
- }
233
- });
234
- invokeForEachNodeInContinuousRange(firstNode, lastNode, function (node) {
235
- if (node.nodeType === 1 || node.nodeType === 8) {
236
- memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext$$1]);
237
- }
238
- });
239
- // Make sure any changes done by applyBindings or unmemoize are reflected in the array
240
- fixUpContinuousNodeArray(continuousNodeArray, parentNode);
241
- }
242
- }
243
- function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
244
- return nodeOrNodeArray.nodeType ? nodeOrNodeArray
245
- : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
246
- : null;
247
- }
248
- function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext$$1, options$$1, afterBindingCallback) {
249
- options$$1 = options$$1 || {};
250
- var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
251
- var templateDocument = (firstTargetNode || template || {}).ownerDocument;
252
- var templateEngineToUse = (options$$1.templateEngine || _templateEngine);
253
- var renderedNodesArray = templateEngineToUse.renderTemplate(template, bindingContext$$1, options$$1, templateDocument);
254
- // Loosely check result is an array of DOM nodes
255
- if ((typeof renderedNodesArray.length !== 'number') || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType !== 'number')) {
256
- throw new Error('Template engine must return an array of DOM nodes');
257
- }
258
- var haveAddedNodesToParent = false;
259
- switch (renderMode) {
260
- case 'replaceChildren':
261
- virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
262
- haveAddedNodesToParent = true;
263
- break;
264
- case 'replaceNode':
265
- replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
266
- haveAddedNodesToParent = true;
267
- break;
268
- case 'ignoreTargetNode': break;
269
- default:
270
- throw new Error('Unknown renderMode: ' + renderMode);
271
- }
272
- if (haveAddedNodesToParent) {
273
- activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext$$1, afterBindingCallback);
274
- if (options$$1.afterRender) {
275
- dependencyDetection.ignore(options$$1.afterRender, null, [renderedNodesArray, bindingContext$$1['$data']]);
276
- }
277
- if (renderMode === 'replaceChildren') {
278
- bindingEvent.notify(targetNodeOrNodeArray, bindingEvent.childrenComplete);
279
- }
280
- }
281
- return renderedNodesArray;
282
- }
283
- function resolveTemplateName(template, data, context) {
284
- // The template can be specified as:
285
- if (isObservable(template)) {
286
- // 1. An observable, with string value
287
- return template();
288
- }
289
- else if (typeof template === 'function') {
290
- // 2. A function of (data, context) returning a string
291
- return template(data, context);
292
- }
293
- else {
294
- // 3. A string
295
- return template;
296
- }
297
- }
298
- function renderTemplate(template, dataOrBindingContext, options$$1, targetNodeOrNodeArray, renderMode, afterBindingCallback) {
299
- options$$1 = options$$1 || {};
300
- if ((options$$1.templateEngine || _templateEngine) === undefined) {
301
- throw new Error('Set a template engine before calling renderTemplate');
302
- }
303
- renderMode = renderMode || 'replaceChildren';
304
- if (targetNodeOrNodeArray) {
305
- var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
306
- var whenToDispose = function () { return (!firstTargetNode) || !domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
307
- var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode === 'replaceNode') ? firstTargetNode.parentNode : firstTargetNode;
308
- return computed(// So the DOM is automatically updated when any dependency changes
309
- function () {
310
- // Ensure we've got a proper binding context to work with
311
- var bindingContext$$1 = (dataOrBindingContext && (dataOrBindingContext instanceof bindingContext))
312
- ? dataOrBindingContext
313
- : new bindingContext(dataOrBindingContext, null, null, null, { 'exportDependencies': true });
314
- var templateName = resolveTemplateName(template, bindingContext$$1.$data, bindingContext$$1);
315
- var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext$$1, options$$1, afterBindingCallback);
316
- if (renderMode === 'replaceNode') {
317
- targetNodeOrNodeArray = renderedNodesArray;
318
- firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
319
- }
320
- }, null, { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved });
321
- }
322
- else {
323
- // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
324
- return memoization.memoize(function (domNode) {
325
- renderTemplate(template, dataOrBindingContext, options$$1, domNode, 'replaceNode');
326
- });
327
- }
328
- }
329
- function renderTemplateForEach(template, arrayOrObservableArray, options$$1, targetNode, parentBindingContext, afterBindingCallback) {
330
- // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
331
- // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
332
- var arrayItemContext;
333
- // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
334
- function executeTemplateForArrayItem(arrayValue, index) {
335
- var _a;
336
- // Support selecting template as a function of the data being rendered
337
- if (options$$1.as) {
338
- if (options.createChildContextWithAs) {
339
- arrayItemContext = parentBindingContext.createChildContext(arrayValue, options$$1.as, function (context) { context.$index = index; });
340
- }
341
- else {
342
- arrayItemContext = parentBindingContext.extend((_a = {},
343
- _a[options$$1.as] = arrayValue,
344
- _a.$index = index,
345
- _a));
346
- }
347
- }
348
- else {
349
- arrayItemContext = parentBindingContext.createChildContext(arrayValue, options$$1.as, function (context) { context.$index = index; });
350
- }
351
- var templateName = resolveTemplateName(template, arrayValue, arrayItemContext);
352
- return executeTemplate(targetNode, 'ignoreTargetNode', templateName, arrayItemContext, options$$1, afterBindingCallback);
353
- }
354
- // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
355
- var activateBindingsCallback = function (arrayValue, addedNodesArray /*, index */) {
356
- activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext, afterBindingCallback);
357
- if (options$$1.afterRender) {
358
- options$$1.afterRender(addedNodesArray, arrayValue);
359
- }
360
- // release the "cache" variable, so that it can be collected by
361
- // the GC when its value isn't used from within the bindings anymore.
362
- arrayItemContext = null;
363
- };
364
- // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
365
- // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
366
- function localSetDomNodeChildrenFromArrayMapping(newArray, changeList) {
367
- dependencyDetection.ignore(setDomNodeChildrenFromArrayMapping, null, [targetNode, newArray, executeTemplateForArrayItem, options$$1, activateBindingsCallback, changeList]);
368
- bindingEvent.notify(targetNode, bindingEvent.childrenComplete);
369
- }
370
- var shouldHideDestroyed = (options$$1.includeDestroyed === false) || (options.foreachHidesDestroyed && !options$$1.includeDestroyed);
371
- if (!shouldHideDestroyed && !options$$1.beforeRemove && isObservableArray(arrayOrObservableArray)) {
372
- localSetDomNodeChildrenFromArrayMapping(arrayOrObservableArray.peek());
373
- var subscription = arrayOrObservableArray.subscribe(function (changeList) {
374
- localSetDomNodeChildrenFromArrayMapping(arrayOrObservableArray(), changeList);
375
- }, null, 'arrayChange');
376
- subscription.disposeWhenNodeIsRemoved(targetNode);
377
- return subscription;
378
- }
379
- else {
380
- return computed(function () {
381
- var unwrappedArray = unwrap(arrayOrObservableArray) || [];
382
- var unwrappedIsIterable = Symbol.iterator in unwrappedArray;
383
- if (!unwrappedIsIterable) {
384
- unwrappedArray = [unwrappedArray];
385
- }
386
- if (shouldHideDestroyed) {
387
- // Filter out any entries marked as destroyed
388
- unwrappedArray = arrayFilter(unwrappedArray, function (item) {
389
- return item === undefined || item === null || !unwrap(item._destroy);
390
- });
391
- }
392
- localSetDomNodeChildrenFromArrayMapping(unwrappedArray);
393
- }, null, { disposeWhenNodeIsRemoved: targetNode });
394
- }
395
- }
396
- var templateComputedDomDataKey = domData.nextKey();
397
- var TemplateBindingHandler = /** @class */ (function (_super) {
398
- __extends(TemplateBindingHandler, _super);
399
- function TemplateBindingHandler(params) {
400
- var _this = _super.call(this, params) || this;
401
- var element = _this.$element;
402
- var bindingValue = unwrap(_this.value);
403
- // Expose 'conditional' for `else` chaining.
404
- domData.set(element, 'conditional', {
405
- elseChainSatisfied: observable(true)
406
- });
407
- // Support anonymous templates
408
- if (typeof bindingValue === 'string' || bindingValue.name) {
409
- _this.bindNamedTemplate();
410
- }
411
- else if ('nodes' in bindingValue) {
412
- _this.bindNodeTemplate(bindingValue.nodes || []);
413
- }
414
- else {
415
- _this.bindAnonymousTemplate();
416
- }
417
- return _this;
418
- }
419
- TemplateBindingHandler.prototype.bindNamedTemplate = function () {
420
- // It's a named template - clear the element
421
- virtualElements.emptyNode(this.$element);
422
- };
423
- // We've been given an array of DOM nodes. Save them as the template source.
424
- // There is no known use case for the node array being an observable array (if the output
425
- // varies, put that behavior *into* your template - that's what templates are for), and
426
- // the implementation would be a mess, so assert that it's not observable.
427
- TemplateBindingHandler.prototype.bindNodeTemplate = function (nodes) {
428
- if (isObservable(nodes)) {
429
- throw new Error('The "nodes" option must be a plain, non-observable array.');
430
- }
431
- // If the nodes are already attached to a KO-generated container, we reuse that container without moving the
432
- // elements to a new one (we check only the first node, as the nodes are always moved together)
433
- var container = nodes[0] && nodes[0].parentNode;
434
- if (!container || !domData.get(container, cleanContainerDomDataKey)) {
435
- container = moveCleanedNodesToContainerElement(nodes);
436
- domData.set(container, cleanContainerDomDataKey, true);
437
- }
438
- new anonymousTemplate(this.$element).nodes(container);
439
- };
440
- TemplateBindingHandler.prototype.bindAnonymousTemplate = function () {
441
- // It's an anonymous template - store the element contents, then clear the element
442
- var templateNodes = virtualElements.childNodes(this.$element);
443
- if (templateNodes.length === 0) {
444
- throw new Error('Anonymous template defined, but no template content was provided.');
445
- }
446
- var container = moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
447
- new anonymousTemplate(this.$element).nodes(container);
448
- };
449
- TemplateBindingHandler.prototype.onValueChange = function () {
450
- var element = this.$element;
451
- var bindingContext$$1 = this.$context;
452
- var value = this.value;
453
- var options$$1 = unwrap(value);
454
- var shouldDisplay = true;
455
- var templateComputed = null;
456
- var elseChainSatisfied = domData.get(element, 'conditional').elseChainSatisfied;
457
- var templateName;
458
- if (typeof options$$1 === 'string') {
459
- templateName = value;
460
- options$$1 = {};
461
- }
462
- else {
463
- templateName = options$$1.name;
464
- // Support "if"/"ifnot" conditions
465
- if ('if' in options$$1) {
466
- shouldDisplay = unwrap(options$$1["if"]);
467
- }
468
- if (shouldDisplay && 'ifnot' in options$$1) {
469
- shouldDisplay = !unwrap(options$$1.ifnot);
470
- }
471
- }
472
- if ('foreach' in options$$1) {
473
- // Render once for each data point (treating data set as empty if shouldDisplay==false)
474
- var dataArray = (shouldDisplay && options$$1.foreach) || [];
475
- templateComputed = renderTemplateForEach(templateName || element, dataArray, options$$1, element, bindingContext$$1, this.completeBinding);
476
- elseChainSatisfied((unwrap(dataArray) || []).length !== 0);
477
- }
478
- else if (shouldDisplay) {
479
- // Render once for this single data point (or use the viewModel if no data was provided)
480
- var innerBindingContext = ('data' in options$$1)
481
- ? bindingContext$$1.createStaticChildContext(options$$1.data, options$$1.as) // Given an explicit 'data' value, we create a child binding context for it
482
- : bindingContext$$1; // Given no explicit 'data' value, we retain the same binding context
483
- templateComputed = renderTemplate(templateName || element, innerBindingContext, options$$1, element, undefined, this.completeBinding);
484
- elseChainSatisfied(true);
485
- }
486
- else {
487
- virtualElements.emptyNode(element);
488
- elseChainSatisfied(false);
489
- }
490
- // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
491
- this.disposeOldComputedAndStoreNewOne(element, templateComputed);
492
- };
493
- TemplateBindingHandler.prototype.disposeOldComputedAndStoreNewOne = function (element, newComputed) {
494
- var oldComputed = domData.get(element, templateComputedDomDataKey);
495
- if (oldComputed && (typeof oldComputed.dispose === 'function')) {
496
- oldComputed.dispose();
497
- }
498
- domData.set(element, templateComputedDomDataKey, (newComputed && (!newComputed.isActive || newComputed.isActive())) ? newComputed : undefined);
499
- };
500
- Object.defineProperty(TemplateBindingHandler.prototype, "controlsDescendants", {
501
- get: function () { return true; },
502
- enumerable: true,
503
- configurable: true
504
- });
505
- Object.defineProperty(TemplateBindingHandler, "allowVirtualElements", {
506
- get: function () { return true; },
507
- enumerable: true,
508
- configurable: true
509
- });
510
- return TemplateBindingHandler;
511
- }(AsyncBindingHandler));
512
-
513
- function nativeTemplateEngine() {
514
- }
515
- nativeTemplateEngine.prototype = new templateEngine();
516
- nativeTemplateEngine.prototype.constructor = nativeTemplateEngine;
517
- nativeTemplateEngine.prototype.renderTemplateSource = function (templateSource, bindingContext$$1, options$$1, templateDocument) {
518
- var useNodesIfAvailable = !(ieVersion < 9), // IE<9 cloneNode doesn't work properly
519
- templateNodesFunc = useNodesIfAvailable ? templateSource.nodes : null, templateNodes = templateNodesFunc ? templateSource.nodes() : null;
520
- if (templateNodes) {
521
- return makeArray(templateNodes.cloneNode(true).childNodes);
522
- }
523
- else {
524
- var templateText = templateSource.text();
525
- return parseHtmlFragment(templateText, templateDocument);
526
- }
527
- };
528
- nativeTemplateEngine.instance = new nativeTemplateEngine();
529
- setTemplateEngine(nativeTemplateEngine.instance);
530
-
531
- // "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
532
- // "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
533
- var TemplateForEachBindingHandler = /** @class */ (function (_super) {
534
- __extends(TemplateForEachBindingHandler, _super);
535
- function TemplateForEachBindingHandler() {
536
- return _super !== null && _super.apply(this, arguments) || this;
537
- }
538
- Object.defineProperty(TemplateForEachBindingHandler.prototype, "value", {
539
- get: function () {
540
- var modelValue = this.valueAccessor();
541
- var unwrappedValue = peek(modelValue); // Unwrap without setting a dependency here
542
- // If unwrappedValue is the array, pass in the wrapped value on its own
543
- // The value will be unwrapped and tracked within the template binding
544
- // (See https://github.com/SteveSanderson/knockout/issues/523)
545
- if (!unwrappedValue || typeof unwrappedValue.length === 'number') {
546
- return { foreach: modelValue, templateEngine: nativeTemplateEngine.instance };
547
- }
548
- // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
549
- unwrap(modelValue);
550
- return {
551
- foreach: unwrappedValue.data,
552
- as: unwrappedValue.as,
553
- includeDestroyed: unwrappedValue.includeDestroyed,
554
- afterAdd: unwrappedValue.afterAdd,
555
- beforeRemove: unwrappedValue.beforeRemove,
556
- afterRender: unwrappedValue.afterRender,
557
- beforeMove: unwrappedValue.beforeMove,
558
- afterMove: unwrappedValue.afterMove,
559
- templateEngine: nativeTemplateEngine.instance
560
- };
561
- },
562
- enumerable: true,
563
- configurable: true
564
- });
565
- return TemplateForEachBindingHandler;
566
- }(TemplateBindingHandler));
567
-
568
- // 'let': letBinding,
569
- // template: template,
570
- var bindings = {
571
- foreach: TemplateForEachBindingHandler,
572
- template: TemplateBindingHandler
573
- };
574
-
575
- export { bindings, nativeTemplateEngine, templateEngine, setTemplateEngine, renderTemplate, TemplateBindingHandler, domElement, anonymousTemplate };
576
- //# sourceMappingURL=binding.template.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"binding.template.js","sources":["../../../node_modules/tslib/tslib.es6.js"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;AAgBA,IAAI,aAAa,GAAG,MAAM,CAAC,cAAc;KACpC,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,KAAK,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,CAAC;IAC5E,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;;AAE/E,SAAgB,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE;IAC5B,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACpB,SAAS,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC,EAAE;IACvC,CAAC,CAAC,SAAS,GAAG,CAAC,KAAK,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;CACxF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}