@tko/bind 4.0.0-alpha9.0 → 4.0.0-beta1.0

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.
package/dist/bind.js DELETED
@@ -1,1188 +0,0 @@
1
- /*!
2
- * TKO DOM-Observable Binding 🥊 @tko/bind@4.0.0-alpha9.0
3
- * (c) The Knockout.js Team - https://tko.io
4
- * License: MIT (http://www.opensource.org/licenses/mit-license.php)
5
- */
6
-
7
- import { domData, extend, options, virtualElements, objectMap, tagNameLower, objectForEach, arrayIndexOf, arrayForEach, fixUpContinuousNodeArray, replaceDomNodes, arrayPushAll, anyDomNodeIsAttachedToDocument, arrayMap, cleanNode, removeNode, compareArrays } from '@tko/utils';
8
- import { subscribable, unwrap, isObservable, isWriteableObservable, dependencyDetection, observable } from '@tko/observable';
9
- import { pureComputed, computed } from '@tko/computed';
10
- import { LifeCycle } from '@tko/lifecycle';
11
-
12
- var contextAncestorBindingInfo = Symbol('_ancestorBindingInfo');
13
- var boundElementDomDataKey = domData.nextKey();
14
- var bindingEvent = {
15
- childrenComplete: 'childrenComplete',
16
- descendantsComplete: 'descendantsComplete',
17
- subscribe: function (node, event, callback, context) {
18
- var bindingInfo = domData.getOrSet(node, boundElementDomDataKey, {});
19
- if (!bindingInfo.eventSubscribable) {
20
- bindingInfo.eventSubscribable = new subscribable();
21
- }
22
- return bindingInfo.eventSubscribable.subscribe(callback, context, event);
23
- },
24
- notify: function (node, event) {
25
- var bindingInfo = domData.get(node, boundElementDomDataKey);
26
- if (bindingInfo) {
27
- if (bindingInfo.eventSubscribable) {
28
- bindingInfo.eventSubscribable.notifySubscribers(node, event);
29
- }
30
- }
31
- }
32
- };
33
-
34
- var boundElementDomDataKey$1 = domData.nextKey();
35
- var contextSubscribeSymbol = Symbol('Knockout Context Subscription');
36
- // Unique stub to indicate inheritance.
37
- var inheritParentIndicator = Symbol('Knockout Parent Indicator');
38
- // The bindingContext constructor is only called directly to create the root context. For child
39
- // contexts, use bindingContext.createChildContext or bindingContext.extend.
40
- function bindingContext(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback, settings) {
41
- var self = this;
42
- var shouldInheritData = dataItemOrAccessor === inheritParentIndicator;
43
- var realDataItemOrAccessor = shouldInheritData ? undefined : dataItemOrAccessor;
44
- var isFunc = typeof realDataItemOrAccessor === 'function' && !isObservable(realDataItemOrAccessor);
45
- // Export 'ko' in the binding context so it will be available in bindings and templates
46
- // even if 'ko' isn't exported as a global, such as when using an AMD loader.
47
- // See https://github.com/SteveSanderson/knockout/issues/490
48
- self.ko = options.knockoutInstance;
49
- var subscribable$$1;
50
- // The binding context object includes static properties for the current, parent, and root view models.
51
- // If a view model is actually stored in an observable, the corresponding binding context object, and
52
- // any child contexts, must be updated when the view model is changed.
53
- function updateContext() {
54
- // Most of the time, the context will directly get a view model object, but if a function is given,
55
- // we call the function to retrieve the view model. If the function accesses any observables or returns
56
- // an observable, the dependency is tracked, and those observables can later cause the binding
57
- // context to be updated.
58
- var dataItemOrObservable = isFunc ? realDataItemOrAccessor() : realDataItemOrAccessor;
59
- var dataItem = unwrap(dataItemOrObservable);
60
- if (parentContext) {
61
- // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
62
- // parent context is updated, this context will also be updated.
63
- if (parentContext[contextSubscribeSymbol]) {
64
- parentContext[contextSubscribeSymbol]();
65
- }
66
- // Copy $root and any custom properties from the parent context
67
- extend(self, parentContext);
68
- // Copy Symbol properties
69
- if (contextAncestorBindingInfo in parentContext) {
70
- self[contextAncestorBindingInfo] = parentContext[contextAncestorBindingInfo];
71
- }
72
- }
73
- else {
74
- self.$parents = [];
75
- self.$root = dataItem;
76
- }
77
- self[contextSubscribeSymbol] = subscribable$$1;
78
- if (shouldInheritData) {
79
- dataItem = self.$data;
80
- }
81
- else {
82
- self.$rawData = dataItemOrObservable;
83
- self.$data = dataItem;
84
- }
85
- if (dataItemAlias) {
86
- self[dataItemAlias] = dataItem;
87
- }
88
- // The extendCallback function is provided when creating a child context or extending a context.
89
- // It handles the specific actions needed to finish setting up the binding context. Actions in this
90
- // function could also add dependencies to this binding context.
91
- if (extendCallback) {
92
- extendCallback(self, parentContext, dataItem);
93
- }
94
- return self.$data;
95
- }
96
- if (settings && settings.exportDependencies) {
97
- // The "exportDependencies" option means that the calling code will track any dependencies and re-create
98
- // the binding context when they change.
99
- updateContext();
100
- }
101
- else {
102
- subscribable$$1 = pureComputed(updateContext);
103
- subscribable$$1.peek();
104
- // At this point, the binding context has been initialized, and the "subscribable" computed observable is
105
- // subscribed to any observables that were accessed in the process. If there is nothing to track, the
106
- // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
107
- // the context object.
108
- if (subscribable$$1.isActive()) {
109
- self[contextSubscribeSymbol] = subscribable$$1;
110
- // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
111
- subscribable$$1['equalityComparer'] = null;
112
- }
113
- else {
114
- self[contextSubscribeSymbol] = undefined;
115
- }
116
- }
117
- }
118
- Object.assign(bindingContext.prototype, {
119
- lookup: function (token, globals, node) {
120
- // short circuits
121
- switch (token) {
122
- case '$element': return node;
123
- case '$context': return this;
124
- case 'this':
125
- case '$data': return this.$data;
126
- }
127
- var $data = this.$data;
128
- // instanceof Object covers 1. {}, 2. [], 3. function() {}, 4. new *; it excludes undefined, null, primitives.
129
- if ($data instanceof Object && token in $data) {
130
- return $data[token];
131
- }
132
- if (token in this) {
133
- return this[token];
134
- }
135
- if (token in globals) {
136
- return globals[token];
137
- }
138
- throw new Error("The variable \"" + token + "\" was not found on $data, $context, or globals.");
139
- },
140
- // Extend the binding context hierarchy with a new view model object. If the parent context is watching
141
- // any observables, the new child context will automatically get a dependency on the parent context.
142
- // But this does not mean that the $data value of the child context will also get updated. If the child
143
- // view model also depends on the parent view model, you must provide a function that returns the correct
144
- // view model on each update.
145
- createChildContext: function (dataItemOrAccessor, dataItemAlias, extendCallback, settings) {
146
- return new bindingContext(dataItemOrAccessor, this, dataItemAlias, function (self, parentContext) {
147
- // Extend the context hierarchy by setting the appropriate pointers
148
- self.$parentContext = parentContext;
149
- self.$parent = parentContext.$data;
150
- self.$parents = (parentContext.$parents || []).slice(0);
151
- self.$parents.unshift(self.$parent);
152
- if (extendCallback) {
153
- extendCallback(self);
154
- }
155
- }, settings);
156
- },
157
- // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
158
- // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
159
- // when an observable view model is updated.
160
- extend: function (properties) {
161
- // If the parent context references an observable view model, "_subscribable" will always be the
162
- // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
163
- return new bindingContext(inheritParentIndicator, this, null, function (self, parentContext) {
164
- extend(self, typeof properties === 'function' ? properties.call(self) : properties);
165
- });
166
- },
167
- createStaticChildContext: function (dataItemOrAccessor, dataItemAlias) {
168
- return this.createChildContext(dataItemOrAccessor, dataItemAlias, null, { 'exportDependencies': true });
169
- }
170
- });
171
- function storedBindingContextForNode(node) {
172
- var bindingInfo = domData.get(node, boundElementDomDataKey$1);
173
- return bindingInfo && bindingInfo.context;
174
- }
175
- // Retrieving binding context from arbitrary nodes
176
- function contextFor(node) {
177
- // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
178
- if (node && (node.nodeType === 1 || node.nodeType === 8)) {
179
- return storedBindingContextForNode(node);
180
- }
181
- }
182
- function dataFor(node) {
183
- var context = contextFor(node);
184
- return context ? context.$data : undefined;
185
- }
186
-
187
- /*! *****************************************************************************
188
- Copyright (c) Microsoft Corporation. All rights reserved.
189
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
190
- this file except in compliance with the License. You may obtain a copy of the
191
- License at http://www.apache.org/licenses/LICENSE-2.0
192
-
193
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
194
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
195
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
196
- MERCHANTABLITY OR NON-INFRINGEMENT.
197
-
198
- See the Apache Version 2.0 License for specific language governing permissions
199
- and limitations under the License.
200
- ***************************************************************************** */
201
- /* global Reflect, Promise */
202
-
203
- var extendStatics = function(d, b) {
204
- extendStatics = Object.setPrototypeOf ||
205
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
206
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
207
- return extendStatics(d, b);
208
- };
209
-
210
- function __extends(d, b) {
211
- extendStatics(d, b);
212
- function __() { this.constructor = d; }
213
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
214
- }
215
-
216
- function __awaiter(thisArg, _arguments, P, generator) {
217
- return new (P || (P = Promise))(function (resolve, reject) {
218
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
219
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
220
- function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
221
- step((generator = generator.apply(thisArg, _arguments || [])).next());
222
- });
223
- }
224
-
225
- function __generator(thisArg, body) {
226
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
227
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
228
- function verb(n) { return function (v) { return step([n, v]); }; }
229
- function step(op) {
230
- if (f) throw new TypeError("Generator is already executing.");
231
- while (_) try {
232
- 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;
233
- if (y = 0, t) op = [op[0] & 2, t.value];
234
- switch (op[0]) {
235
- case 0: case 1: t = op; break;
236
- case 4: _.label++; return { value: op[1], done: false };
237
- case 5: _.label++; y = op[1]; op = [0]; continue;
238
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
239
- default:
240
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
241
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
242
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
243
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
244
- if (t[2]) _.ops.pop();
245
- _.trys.pop(); continue;
246
- }
247
- op = body.call(thisArg, _);
248
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
249
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
250
- }
251
- }
252
-
253
- function __values(o) {
254
- var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
255
- if (m) return m.call(o);
256
- return {
257
- next: function () {
258
- if (o && i >= o.length) o = void 0;
259
- return { value: o && o[i++], done: !o };
260
- }
261
- };
262
- }
263
-
264
- function __read(o, n) {
265
- var m = typeof Symbol === "function" && o[Symbol.iterator];
266
- if (!m) return o;
267
- var i = m.call(o), r, ar = [], e;
268
- try {
269
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
270
- }
271
- catch (error) { e = { error: error }; }
272
- finally {
273
- try {
274
- if (r && !r.done && (m = i["return"])) m.call(i);
275
- }
276
- finally { if (e) throw e.error; }
277
- }
278
- return ar;
279
- }
280
-
281
- function __spread() {
282
- for (var ar = [], i = 0; i < arguments.length; i++)
283
- ar = ar.concat(__read(arguments[i]));
284
- return ar;
285
- }
286
-
287
- var BindingResult = /** @class */ (function () {
288
- function BindingResult(_a) {
289
- var asyncBindingsApplied = _a.asyncBindingsApplied, rootNode = _a.rootNode, bindingContext = _a.bindingContext;
290
- Object.assign(this, {
291
- rootNode: rootNode,
292
- bindingContext: bindingContext,
293
- isSync: asyncBindingsApplied.size === 0,
294
- isComplete: this.isSync
295
- });
296
- if (!this.isSync) {
297
- this.completionPromise = this.completeWhenBindingsFinish(asyncBindingsApplied);
298
- }
299
- }
300
- BindingResult.prototype.completeWhenBindingsFinish = function (asyncBindingsApplied) {
301
- return __awaiter(this, void 0, void 0, function () {
302
- return __generator(this, function (_a) {
303
- switch (_a.label) {
304
- case 0: return [4 /*yield*/, Promise.all(asyncBindingsApplied)];
305
- case 1:
306
- _a.sent();
307
- this.isComplete = true;
308
- return [2 /*return*/, this];
309
- }
310
- });
311
- });
312
- };
313
- return BindingResult;
314
- }());
315
-
316
- var BindingHandler = /** @class */ (function (_super) {
317
- __extends(BindingHandler, _super);
318
- function BindingHandler(params) {
319
- var _this = _super.call(this) || this;
320
- var $element = params.$element, valueAccessor = params.valueAccessor, allBindings = params.allBindings, $context = params.$context;
321
- Object.assign(_this, {
322
- valueAccessor: valueAccessor,
323
- allBindings: allBindings,
324
- $element: $element,
325
- $context: $context,
326
- $data: $context.$data
327
- });
328
- _this.anchorTo($element);
329
- return _this;
330
- }
331
- Object.defineProperty(BindingHandler.prototype, "value", {
332
- get: function () { return this.valueAccessor(); },
333
- set: function (v) {
334
- var va = this.valueAccessor();
335
- if (isWriteableObservable(va)) {
336
- va(v);
337
- }
338
- else {
339
- this.valueAccessor(v);
340
- }
341
- },
342
- enumerable: true,
343
- configurable: true
344
- });
345
- Object.defineProperty(BindingHandler.prototype, "controlsDescendants", {
346
- get: function () { return false; },
347
- enumerable: true,
348
- configurable: true
349
- });
350
- Object.defineProperty(BindingHandler, "allowVirtualElements", {
351
- get: function () { return false; },
352
- enumerable: true,
353
- configurable: true
354
- });
355
- Object.defineProperty(BindingHandler, "isBindingHandlerClass", {
356
- get: function () { return true; },
357
- enumerable: true,
358
- configurable: true
359
- });
360
- Object.defineProperty(BindingHandler.prototype, "bindingCompleted", {
361
- /* Overload this for asynchronous bindings or bindings that recursively
362
- apply bindings (e.g. components, foreach, template).
363
-
364
- A binding should be complete when it has run through once, notably
365
- in server-side bindings for pre-rendering.
366
- */
367
- get: function () { return true; },
368
- enumerable: true,
369
- configurable: true
370
- });
371
- BindingHandler.registerAs = function (name, provider) {
372
- if (provider === void 0) { provider = options.bindingProviderInstance; }
373
- provider.bindingHandlers.set(name, this);
374
- };
375
- return BindingHandler;
376
- }(LifeCycle));
377
- /**
378
- * An AsyncBindingHandler shall call `completeBinding` when the binding
379
- * is to be considered complete.
380
- */
381
- var ResolveSymbol = Symbol('Async Binding Resolved');
382
- var AsyncBindingHandler = /** @class */ (function (_super) {
383
- __extends(AsyncBindingHandler, _super);
384
- function AsyncBindingHandler(params) {
385
- var _this = _super.call(this, params) || this;
386
- _this.bindingCompletion = new Promise(function (resolve) {
387
- _this[ResolveSymbol] = resolve;
388
- });
389
- _this.completeBinding = function (bindingResult) { return _this[ResolveSymbol](bindingResult); };
390
- return _this;
391
- }
392
- Object.defineProperty(AsyncBindingHandler.prototype, "bindingCompleted", {
393
- get: function () { return this.bindingCompletion; },
394
- enumerable: true,
395
- configurable: true
396
- });
397
- return AsyncBindingHandler;
398
- }(BindingHandler));
399
-
400
- /**
401
- * We have no guarantees, for users employing legacy bindings,
402
- * that it has not been changed with a modification like
403
- *
404
- * ko.bindingHandlers[name] = { init: ...}
405
- *
406
- * ... so we have to keep track by way of a map.
407
- */
408
- var PossibleWeakMap = options.global.WeakMap || Map;
409
- var legacyBindingMap = new PossibleWeakMap();
410
- var LegacyBindingHandler = /** @class */ (function (_super) {
411
- __extends(LegacyBindingHandler, _super);
412
- function LegacyBindingHandler(params) {
413
- var _this = _super.call(this, params) || this;
414
- var handler = _this.handler;
415
- _this.onError = params.onError;
416
- if (typeof handler.dispose === 'function') {
417
- _this.addDisposable(handler);
418
- }
419
- try {
420
- _this.initReturn = handler.init && handler.init.apply(handler, __spread(_this.legacyArgs));
421
- }
422
- catch (e) {
423
- params.onError('init', e);
424
- }
425
- return _this;
426
- }
427
- LegacyBindingHandler.prototype.onValueChange = function () {
428
- var handler = this.handler;
429
- if (typeof handler.update !== 'function') {
430
- return;
431
- }
432
- try {
433
- handler.update.apply(handler, __spread(this.legacyArgs));
434
- }
435
- catch (e) {
436
- this.onError('update', e);
437
- }
438
- };
439
- Object.defineProperty(LegacyBindingHandler.prototype, "legacyArgs", {
440
- get: function () {
441
- return [
442
- this.$element, this.valueAccessor, this.allBindings,
443
- this.$data, this.$context
444
- ];
445
- },
446
- enumerable: true,
447
- configurable: true
448
- });
449
- Object.defineProperty(LegacyBindingHandler.prototype, "controlsDescendants", {
450
- get: function () {
451
- var objectToTest = this.initReturn || this.handler || {};
452
- return objectToTest.controlsDescendantBindings;
453
- },
454
- enumerable: true,
455
- configurable: true
456
- });
457
- /**
458
- * Create a handler instance from the `origin`, which may be:
459
- *
460
- * 1. an object (becomes LegacyBindingHandler)
461
- * 2. a function (becomes LegacyBindingHandler with `init: function`)
462
- *
463
- * If given an object (the only kind supported in knockout 3.x and before), it
464
- * shall draw the `init`, `update`, and `allowVirtualElements` properties
465
- */
466
- LegacyBindingHandler.getOrCreateFor = function (key, handler) {
467
- if (legacyBindingMap.has(handler)) {
468
- return legacyBindingMap.get(handler);
469
- }
470
- var newLegacyHandler = this.createFor(key, handler);
471
- legacyBindingMap.set(handler, newLegacyHandler);
472
- return newLegacyHandler;
473
- };
474
- LegacyBindingHandler.createFor = function (key, handler) {
475
- if (typeof handler === 'function') {
476
- var _a = __read([handler, handler.dispose], 2), initFn_1 = _a[0], disposeFn_1 = _a[1];
477
- return /** @class */ (function (_super) {
478
- __extends(class_1, _super);
479
- function class_1() {
480
- return _super !== null && _super.apply(this, arguments) || this;
481
- }
482
- Object.defineProperty(class_1.prototype, "handler", {
483
- get: function () {
484
- var init = initFn_1.bind(this);
485
- var dispose = disposeFn_1 ? disposeFn_1.bind(this) : null;
486
- return { init: init, dispose: dispose };
487
- },
488
- enumerable: true,
489
- configurable: true
490
- });
491
- Object.defineProperty(class_1, "after", {
492
- get: function () { return handler.after; },
493
- enumerable: true,
494
- configurable: true
495
- });
496
- Object.defineProperty(class_1, "allowVirtualElements", {
497
- get: function () {
498
- return handler.allowVirtualElements || virtualElements.allowedBindings[key];
499
- },
500
- enumerable: true,
501
- configurable: true
502
- });
503
- return class_1;
504
- }(LegacyBindingHandler));
505
- }
506
- if (typeof handler === 'object') {
507
- return /** @class */ (function (_super) {
508
- __extends(class_2, _super);
509
- function class_2() {
510
- return _super !== null && _super.apply(this, arguments) || this;
511
- }
512
- Object.defineProperty(class_2.prototype, "handler", {
513
- get: function () { return handler; },
514
- enumerable: true,
515
- configurable: true
516
- });
517
- Object.defineProperty(class_2, "after", {
518
- get: function () { return handler.after; },
519
- enumerable: true,
520
- configurable: true
521
- });
522
- Object.defineProperty(class_2, "allowVirtualElements", {
523
- get: function () {
524
- return handler.allowVirtualElements || virtualElements.allowedBindings[key];
525
- },
526
- enumerable: true,
527
- configurable: true
528
- });
529
- return class_2;
530
- }(LegacyBindingHandler));
531
- }
532
- throw new Error('The given handler is not an appropriate type.');
533
- };
534
- return LegacyBindingHandler;
535
- }(BindingHandler));
536
-
537
- /* eslint no-cond-assign: 0 */
538
- // The following element types will not be recursed into during binding.
539
- var bindingDoesNotRecurseIntoElementTypes = {
540
- // Don't want bindings that operate on text nodes to mutate <script> and <textarea> contents,
541
- // because it's unexpected and a potential XSS issue.
542
- // Also bindings should not operate on <template> elements since this breaks in Internet Explorer
543
- // and because such elements' contents are always intended to be bound in a different context
544
- // from where they appear in the document.
545
- 'script': true,
546
- 'textarea': true,
547
- 'template': true
548
- };
549
- function getBindingProvider() {
550
- return options.bindingProviderInstance.instance || options.bindingProviderInstance;
551
- }
552
- function isProviderForNode(provider, node) {
553
- var nodeTypes = provider.FOR_NODE_TYPES || [1, 3, 8];
554
- return nodeTypes.includes(node.nodeType);
555
- }
556
- function asProperHandlerClass(handler, bindingKey) {
557
- if (!handler) {
558
- return;
559
- }
560
- return handler.isBindingHandlerClass ? handler
561
- : LegacyBindingHandler.getOrCreateFor(bindingKey, handler);
562
- }
563
- function getBindingHandlerFromComponent(bindingKey, $component) {
564
- if (!$component || typeof $component.getBindingHandler !== 'function') {
565
- return;
566
- }
567
- return asProperHandlerClass($component.getBindingHandler(bindingKey));
568
- }
569
- function getBindingHandler(bindingKey) {
570
- var bindingDefinition = options.getBindingHandler(bindingKey) || getBindingProvider().bindingHandlers.get(bindingKey);
571
- return asProperHandlerClass(bindingDefinition, bindingKey);
572
- }
573
- // Returns the value of a valueAccessor function
574
- function evaluateValueAccessor(valueAccessor) {
575
- return valueAccessor();
576
- }
577
- function applyBindingsToDescendantsInternal(bindingContext$$1, elementOrVirtualElement, asyncBindingsApplied) {
578
- var nextInQueue = virtualElements.firstChild(elementOrVirtualElement);
579
- if (!nextInQueue) {
580
- return;
581
- }
582
- var currentChild;
583
- var provider = getBindingProvider();
584
- var preprocessNode = provider.preprocessNode;
585
- // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
586
- // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
587
- // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
588
- // trigger insertion of <template> contents at that point in the document.
589
- if (preprocessNode) {
590
- while (currentChild = nextInQueue) {
591
- nextInQueue = virtualElements.nextSibling(currentChild);
592
- preprocessNode.call(provider, currentChild);
593
- }
594
- // Reset nextInQueue for the next loop
595
- nextInQueue = virtualElements.firstChild(elementOrVirtualElement);
596
- }
597
- while (currentChild = nextInQueue) {
598
- // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
599
- nextInQueue = virtualElements.nextSibling(currentChild);
600
- applyBindingsToNodeAndDescendantsInternal(bindingContext$$1, currentChild, asyncBindingsApplied);
601
- }
602
- bindingEvent.notify(elementOrVirtualElement, bindingEvent.childrenComplete);
603
- }
604
- function hasBindings(node) {
605
- var provider = getBindingProvider();
606
- return isProviderForNode(provider, node) && provider.nodeHasBindings(node);
607
- }
608
- function nodeOrChildHasBindings(node) {
609
- return hasBindings(node) || __spread(node.childNodes).some(function (c) { return nodeOrChildHasBindings(c); });
610
- }
611
- function applyBindingsToNodeAndDescendantsInternal(bindingContext$$1, nodeVerified, asyncBindingsApplied) {
612
- var isElement = nodeVerified.nodeType === 1;
613
- if (isElement) { // Workaround IE <= 8 HTML parsing weirdness
614
- virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
615
- }
616
- // Perf optimisation: Apply bindings only if...
617
- // (1) We need to store the binding info for the node (all element nodes)
618
- // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
619
- var shouldApplyBindings = isElement || // Case (1)
620
- hasBindings(nodeVerified); // Case (2)
621
- var shouldBindDescendants = (shouldApplyBindings
622
- ? applyBindingsToNodeInternal(nodeVerified, null, bindingContext$$1, asyncBindingsApplied)
623
- : { shouldBindDescendants: true }).shouldBindDescendants;
624
- if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[tagNameLower(nodeVerified)]) {
625
- // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
626
- // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
627
- // hence bindingContextsMayDifferFromDomParentElement is false
628
- // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
629
- // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
630
- // hence bindingContextsMayDifferFromDomParentElement is true
631
- applyBindingsToDescendantsInternal(bindingContext$$1, nodeVerified, asyncBindingsApplied);
632
- }
633
- }
634
- function topologicalSortBindings(bindings, $component) {
635
- var e_1, _a, results, bindingsConsidered, cyclicDependencyStack, results_1, results_1_1, result, e_1_1;
636
- return __generator(this, function (_b) {
637
- switch (_b.label) {
638
- case 0:
639
- results = [];
640
- bindingsConsidered = {} // A temporary record of which bindings are already in 'result'
641
- ;
642
- cyclicDependencyStack = [] // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
643
- ;
644
- objectForEach(bindings, function pushBinding(bindingKey) {
645
- if (!bindingsConsidered[bindingKey]) {
646
- var binding = getBindingHandlerFromComponent(bindingKey, $component) || getBindingHandler(bindingKey);
647
- if (!binding) {
648
- return;
649
- }
650
- // First add dependencies (if any) of the current binding
651
- if (binding.after) {
652
- cyclicDependencyStack.push(bindingKey);
653
- arrayForEach(binding.after, function (bindingDependencyKey) {
654
- if (!bindings[bindingDependencyKey]) {
655
- return;
656
- }
657
- if (arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
658
- throw Error('Cannot combine the following bindings, because they have a cyclic dependency: ' + cyclicDependencyStack.join(', '));
659
- }
660
- else {
661
- pushBinding(bindingDependencyKey);
662
- }
663
- });
664
- cyclicDependencyStack.length--;
665
- }
666
- // Next add the current binding
667
- results.push([bindingKey, binding]);
668
- }
669
- bindingsConsidered[bindingKey] = true;
670
- });
671
- _b.label = 1;
672
- case 1:
673
- _b.trys.push([1, 6, 7, 8]);
674
- results_1 = __values(results), results_1_1 = results_1.next();
675
- _b.label = 2;
676
- case 2:
677
- if (!!results_1_1.done) return [3 /*break*/, 5];
678
- result = results_1_1.value;
679
- return [4 /*yield*/, result];
680
- case 3:
681
- _b.sent();
682
- _b.label = 4;
683
- case 4:
684
- results_1_1 = results_1.next();
685
- return [3 /*break*/, 2];
686
- case 5: return [3 /*break*/, 8];
687
- case 6:
688
- e_1_1 = _b.sent();
689
- e_1 = { error: e_1_1 };
690
- return [3 /*break*/, 8];
691
- case 7:
692
- try {
693
- if (results_1_1 && !results_1_1.done && (_a = results_1["return"])) _a.call(results_1);
694
- }
695
- finally { if (e_1) throw e_1.error; }
696
- return [7 /*endfinally*/];
697
- case 8: return [2 /*return*/];
698
- }
699
- });
700
- }
701
- function applyBindingsToNodeInternal(node, sourceBindings, bindingContext$$1, asyncBindingsApplied) {
702
- var e_2, _a;
703
- var bindingInfo = domData.getOrSet(node, boundElementDomDataKey$1, {});
704
- // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
705
- var alreadyBound = bindingInfo.alreadyBound;
706
- if (!sourceBindings) {
707
- if (alreadyBound) {
708
- if (!nodeOrChildHasBindings(node)) {
709
- return false;
710
- }
711
- onBindingError({
712
- during: 'apply',
713
- errorCaptured: new Error('You cannot apply bindings multiple times to the same element.'),
714
- element: node,
715
- bindingContext: bindingContext$$1
716
- });
717
- return false;
718
- }
719
- bindingInfo.alreadyBound = true;
720
- }
721
- if (!alreadyBound) {
722
- bindingInfo.context = bindingContext$$1;
723
- }
724
- // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
725
- var bindings;
726
- if (sourceBindings && typeof sourceBindings !== 'function') {
727
- bindings = sourceBindings;
728
- }
729
- else {
730
- var provider_1 = getBindingProvider();
731
- var getBindings_1 = provider_1.getBindingAccessors;
732
- if (isProviderForNode(provider_1, node)) {
733
- // Get the binding from the provider within a computed observable so that we can update the bindings whenever
734
- // the binding context is updated or if the binding provider accesses observables.
735
- var bindingsUpdater = computed(function () {
736
- bindings = sourceBindings ? sourceBindings(bindingContext$$1, node) : getBindings_1.call(provider_1, node, bindingContext$$1);
737
- // Register a dependency on the binding context to support observable view models.
738
- if (bindings && bindingContext$$1[contextSubscribeSymbol]) {
739
- bindingContext$$1[contextSubscribeSymbol]();
740
- }
741
- return bindings;
742
- }, null, { disposeWhenNodeIsRemoved: node });
743
- if (!bindings || !bindingsUpdater.isActive()) {
744
- bindingsUpdater = null;
745
- }
746
- }
747
- }
748
- var bindingHandlerThatControlsDescendantBindings;
749
- if (bindings) {
750
- var $component = bindingContext$$1.$component || {};
751
- var allBindingHandlers = {};
752
- domData.set(node, 'bindingHandlers', allBindingHandlers);
753
- // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
754
- // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
755
- // the latest binding value and registers a dependency on the binding updater.
756
- var getValueAccessor_1 = bindingsUpdater
757
- ? function (bindingKey) { return function (optionalValue) {
758
- var valueAccessor = bindingsUpdater()[bindingKey];
759
- if (arguments.length === 0) {
760
- return evaluateValueAccessor(valueAccessor);
761
- }
762
- else {
763
- return valueAccessor(optionalValue);
764
- }
765
- }; } : function (bindingKey) { return bindings[bindingKey]; };
766
- // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
767
- function allBindings() {
768
- return objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
769
- }
770
- // The following is the 3.x allBindings API
771
- allBindings.has = function (key) { return key in bindings; };
772
- allBindings.get = function (key) { return bindings[key] && evaluateValueAccessor(getValueAccessor_1(key)); };
773
- if (bindingEvent.childrenComplete in bindings) {
774
- bindingEvent.subscribe(node, bindingEvent.childrenComplete, function () {
775
- var callback = evaluateValueAccessor(bindings[bindingEvent.childrenComplete]);
776
- if (!callback) {
777
- return;
778
- }
779
- var nodes = virtualElements.childNodes(node);
780
- if (nodes.length) {
781
- callback(nodes, dataFor(nodes[0]));
782
- }
783
- });
784
- }
785
- var bindingsGenerated = topologicalSortBindings(bindings, $component);
786
- var nodeAsyncBindingPromises = new Set();
787
- var _loop_1 = function (key, BindingHandlerClass) {
788
- // Go through the sorted bindings, calling init and update for each
789
- function reportBindingError(during, errorCaptured) {
790
- onBindingError({
791
- during: during,
792
- errorCaptured: errorCaptured,
793
- bindings: bindings,
794
- allBindings: allBindings,
795
- bindingKey: key,
796
- bindingContext: bindingContext$$1,
797
- element: node,
798
- valueAccessor: getValueAccessor_1(key)
799
- });
800
- }
801
- if (node.nodeType === 8 && !BindingHandlerClass.allowVirtualElements) {
802
- throw new Error("The binding '" + key + "' cannot be used with virtual elements");
803
- }
804
- try {
805
- var bindingHandler_1 = dependencyDetection.ignore(function () {
806
- return new BindingHandlerClass({
807
- allBindings: allBindings,
808
- $element: node,
809
- $context: bindingContext$$1,
810
- onError: reportBindingError,
811
- valueAccessor: function () {
812
- var v = [];
813
- for (var _i = 0; _i < arguments.length; _i++) {
814
- v[_i] = arguments[_i];
815
- }
816
- return getValueAccessor_1(key).apply(void 0, __spread(v));
817
- }
818
- });
819
- });
820
- if (bindingHandler_1.onValueChange) {
821
- dependencyDetection.ignore(function () {
822
- return bindingHandler_1.computed('onValueChange');
823
- });
824
- }
825
- // Expose the bindings via domData.
826
- allBindingHandlers[key] = bindingHandler_1;
827
- if (bindingHandler_1.controlsDescendants) {
828
- if (bindingHandlerThatControlsDescendantBindings !== undefined) {
829
- throw new Error('Multiple bindings (' + bindingHandlerThatControlsDescendantBindings + ' and ' + key + ') are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.');
830
- }
831
- bindingHandlerThatControlsDescendantBindings = key;
832
- }
833
- if (bindingHandler_1.bindingCompleted instanceof Promise) {
834
- asyncBindingsApplied.add(bindingHandler_1.bindingCompleted);
835
- nodeAsyncBindingPromises.add(bindingHandler_1.bindingCompleted);
836
- }
837
- }
838
- catch (err) {
839
- reportBindingError('creation', err);
840
- }
841
- };
842
- try {
843
- for (var bindingsGenerated_1 = __values(bindingsGenerated), bindingsGenerated_1_1 = bindingsGenerated_1.next(); !bindingsGenerated_1_1.done; bindingsGenerated_1_1 = bindingsGenerated_1.next()) {
844
- var _b = __read(bindingsGenerated_1_1.value, 2), key = _b[0], BindingHandlerClass = _b[1];
845
- _loop_1(key, BindingHandlerClass);
846
- }
847
- }
848
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
849
- finally {
850
- try {
851
- if (bindingsGenerated_1_1 && !bindingsGenerated_1_1.done && (_a = bindingsGenerated_1["return"])) _a.call(bindingsGenerated_1);
852
- }
853
- finally { if (e_2) throw e_2.error; }
854
- }
855
- triggerDescendantsComplete(node, bindings, nodeAsyncBindingPromises);
856
- }
857
- var shouldBindDescendants = bindingHandlerThatControlsDescendantBindings === undefined;
858
- return { shouldBindDescendants: shouldBindDescendants };
859
- }
860
- /**
861
- *
862
- * @param {HTMLElement} node
863
- * @param {Object} bindings
864
- * @param {[Promise]} nodeAsyncBindingPromises
865
- */
866
- function triggerDescendantsComplete(node, bindings, nodeAsyncBindingPromises) {
867
- /** descendantsComplete ought to be an instance of the descendantsComplete
868
- * binding handler. */
869
- var hasBindingHandler = bindingEvent.descendantsComplete in bindings;
870
- var hasFirstChild = virtualElements.firstChild(node);
871
- var accessor = hasBindingHandler && evaluateValueAccessor(bindings[bindingEvent.descendantsComplete]);
872
- var callback = function () {
873
- bindingEvent.notify(node, bindingEvent.descendantsComplete);
874
- if (accessor && hasFirstChild) {
875
- accessor(node);
876
- }
877
- };
878
- if (nodeAsyncBindingPromises.size) {
879
- Promise.all(nodeAsyncBindingPromises).then(callback);
880
- }
881
- else {
882
- callback();
883
- }
884
- }
885
- function getBindingContext(viewModelOrBindingContext, extendContextCallback) {
886
- return viewModelOrBindingContext && (viewModelOrBindingContext instanceof bindingContext)
887
- ? viewModelOrBindingContext
888
- : new bindingContext(viewModelOrBindingContext, undefined, undefined, extendContextCallback);
889
- }
890
- function applyBindingAccessorsToNode(node, bindings, viewModelOrBindingContext, asyncBindingsApplied) {
891
- if (node.nodeType === 1) { // If it's an element, workaround IE <= 8 HTML parsing weirdness
892
- virtualElements.normaliseVirtualElementDomStructure(node);
893
- }
894
- return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), asyncBindingsApplied);
895
- }
896
- function applyBindingsToNode(node, bindings, viewModelOrBindingContext) {
897
- var asyncBindingsApplied = new Set();
898
- var bindingContext$$1 = getBindingContext(viewModelOrBindingContext);
899
- var bindingAccessors = getBindingProvider().makeBindingAccessors(bindings, bindingContext$$1, node);
900
- applyBindingAccessorsToNode(node, bindingAccessors, bindingContext$$1, asyncBindingsApplied);
901
- return new BindingResult({ asyncBindingsApplied: asyncBindingsApplied, rootNode: node, bindingContext: bindingContext$$1 });
902
- }
903
- function applyBindingsToDescendants(viewModelOrBindingContext, rootNode) {
904
- var asyncBindingsApplied = new Set();
905
- if (rootNode.nodeType === 1 || rootNode.nodeType === 8) {
906
- var bindingContext_1 = getBindingContext(viewModelOrBindingContext);
907
- applyBindingsToDescendantsInternal(bindingContext_1, rootNode, asyncBindingsApplied);
908
- return new BindingResult({ asyncBindingsApplied: asyncBindingsApplied, rootNode: rootNode, bindingContext: bindingContext_1 });
909
- }
910
- return new BindingResult({ asyncBindingsApplied: asyncBindingsApplied, rootNode: rootNode });
911
- }
912
- function applyBindings(viewModelOrBindingContext, rootNode, extendContextCallback) {
913
- var asyncBindingsApplied = new Set();
914
- // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
915
- if (!options.jQuery === undefined && options.jQuery) {
916
- options.jQuery = options.jQuery;
917
- }
918
- // rootNode is optional
919
- if (!rootNode) {
920
- rootNode = window.document.body;
921
- if (!rootNode) {
922
- throw Error('ko.applyBindings: could not find window.document.body; has the document been loaded?');
923
- }
924
- }
925
- else if (rootNode.nodeType !== 1 && rootNode.nodeType !== 8) {
926
- throw Error('ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node');
927
- }
928
- var rootContext = getBindingContext(viewModelOrBindingContext, extendContextCallback);
929
- applyBindingsToNodeAndDescendantsInternal(rootContext, rootNode, asyncBindingsApplied);
930
- return Promise.all(asyncBindingsApplied);
931
- }
932
- function onBindingError(spec) {
933
- var error;
934
- if (spec.bindingKey) {
935
- // During: 'init' or initial 'update'
936
- error = spec.errorCaptured;
937
- spec.message = 'Unable to process binding "' + spec.bindingKey +
938
- '" in binding "' + spec.bindingKey +
939
- '"\nMessage: ' + (error.message ? error.message : error);
940
- }
941
- else {
942
- // During: 'apply'
943
- error = spec.errorCaptured;
944
- }
945
- try {
946
- extend(error, spec);
947
- }
948
- catch (e) {
949
- // Read-only error e.g. a DOMEXception.
950
- spec.stack = error.stack;
951
- error = new Error(error.message ? error.message : error);
952
- extend(error, spec);
953
- }
954
- options.onError(error);
955
- }
956
-
957
- /* eslint no-cond-assign: 0 */
958
- // Objective:
959
- // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
960
- // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
961
- // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
962
- // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
963
- // previously mapped - retain those nodes, and just insert/delete other ones
964
- // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
965
- // You can use this, for example, to activate bindings on those nodes.
966
- function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
967
- // Map this array value inside a dependentObservable so we re-map when any dependency changes
968
- var mappedNodes = [];
969
- var dependentObservable = computed(function () {
970
- var newMappedNodes = mapping(valueToMap, index, fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
971
- // On subsequent evaluations, just replace the previously-inserted DOM nodes
972
- if (mappedNodes.length > 0) {
973
- replaceDomNodes(mappedNodes, newMappedNodes);
974
- if (callbackAfterAddingNodes) {
975
- dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
976
- }
977
- }
978
- // Replace the contents of the mappedNodes array, thereby updating the record
979
- // of which nodes would be deleted if valueToMap was itself later removed
980
- mappedNodes.length = 0;
981
- arrayPushAll(mappedNodes, newMappedNodes);
982
- }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function () { return !anyDomNodeIsAttachedToDocument(mappedNodes); } });
983
- return { mappedNodes: mappedNodes, dependentObservable: (dependentObservable.isActive() ? dependentObservable : undefined) };
984
- }
985
- var lastMappingResultDomDataKey = domData.nextKey();
986
- var deletedItemDummyValue = domData.nextKey();
987
- function setDomNodeChildrenFromArrayMapping(domNode, array, mapping, options$$1, callbackAfterAddingNodes, editScript) {
988
- // Compare the provided array against the previous one
989
- array = array || [];
990
- if (typeof array.length === 'undefined') {
991
- array = [array];
992
- }
993
- options$$1 = options$$1 || {};
994
- var lastMappingResult = domData.get(domNode, lastMappingResultDomDataKey);
995
- var isFirstExecution = !lastMappingResult;
996
- // Build the new mapping result
997
- var newMappingResult = [];
998
- var lastMappingResultIndex = 0;
999
- var newMappingResultIndex = 0;
1000
- var nodesToDelete = [];
1001
- var itemsToProcess = [];
1002
- var itemsForBeforeRemoveCallbacks = [];
1003
- var itemsForMoveCallbacks = [];
1004
- var itemsForAfterAddCallbacks = [];
1005
- var mapData;
1006
- var countWaitingForRemove = 0;
1007
- function itemAdded(value) {
1008
- mapData = { arrayEntry: value, indexObservable: observable(newMappingResultIndex++) };
1009
- newMappingResult.push(mapData);
1010
- itemsToProcess.push(mapData);
1011
- if (!isFirstExecution) {
1012
- itemsForAfterAddCallbacks.push(mapData);
1013
- }
1014
- }
1015
- function itemMovedOrRetained(oldPosition) {
1016
- mapData = lastMappingResult[oldPosition];
1017
- if (newMappingResultIndex !== oldPosition) {
1018
- itemsForMoveCallbacks.push(mapData);
1019
- }
1020
- // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
1021
- mapData.indexObservable(newMappingResultIndex++);
1022
- fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
1023
- newMappingResult.push(mapData);
1024
- itemsToProcess.push(mapData);
1025
- }
1026
- function callCallback(callback, items) {
1027
- if (callback) {
1028
- for (var i = 0, n = items.length; i < n; i++) {
1029
- arrayForEach(items[i].mappedNodes, function (node) {
1030
- callback(node, i, items[i].arrayEntry);
1031
- });
1032
- }
1033
- }
1034
- }
1035
- if (isFirstExecution) {
1036
- arrayForEach(array, itemAdded);
1037
- }
1038
- else {
1039
- if (!editScript || (lastMappingResult && lastMappingResult['_countWaitingForRemove'])) {
1040
- // Compare the provided array against the previous one
1041
- var lastArray = isFirstExecution ? [] : arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
1042
- var compareOptions = {
1043
- 'dontLimitMoves': options$$1['dontLimitMoves'],
1044
- 'sparse': true
1045
- };
1046
- editScript = compareArrays(lastArray, array, compareOptions);
1047
- }
1048
- for (var i = 0, editScriptItem, movedIndex, itemIndex; editScriptItem = editScript[i]; i++) {
1049
- movedIndex = editScriptItem['moved'];
1050
- itemIndex = editScriptItem['index'];
1051
- switch (editScriptItem['status']) {
1052
- case 'deleted':
1053
- while (lastMappingResultIndex < itemIndex) {
1054
- itemMovedOrRetained(lastMappingResultIndex++);
1055
- }
1056
- if (movedIndex === undefined) {
1057
- mapData = lastMappingResult[lastMappingResultIndex];
1058
- // Stop tracking changes to the mapping for these nodes
1059
- if (mapData.dependentObservable) {
1060
- mapData.dependentObservable.dispose();
1061
- mapData.dependentObservable = undefined;
1062
- }
1063
- // Queue these nodes for later removal
1064
- if (fixUpContinuousNodeArray(mapData.mappedNodes, domNode).length) {
1065
- if (options$$1['beforeRemove']) {
1066
- newMappingResult.push(mapData);
1067
- itemsToProcess.push(mapData);
1068
- countWaitingForRemove++;
1069
- if (mapData.arrayEntry === deletedItemDummyValue) {
1070
- mapData = null;
1071
- }
1072
- else {
1073
- itemsForBeforeRemoveCallbacks.push(mapData);
1074
- }
1075
- }
1076
- if (mapData) {
1077
- nodesToDelete.push.apply(nodesToDelete, mapData.mappedNodes);
1078
- }
1079
- }
1080
- }
1081
- lastMappingResultIndex++;
1082
- break;
1083
- case 'added':
1084
- while (newMappingResultIndex < itemIndex) {
1085
- itemMovedOrRetained(lastMappingResultIndex++);
1086
- }
1087
- if (movedIndex !== undefined) {
1088
- itemMovedOrRetained(movedIndex);
1089
- }
1090
- else {
1091
- itemAdded(editScriptItem['value']);
1092
- }
1093
- break;
1094
- }
1095
- }
1096
- while (newMappingResultIndex < array.length) {
1097
- itemMovedOrRetained(lastMappingResultIndex++);
1098
- }
1099
- // Record that the current view may still contain deleted items
1100
- // because it means we won't be able to use a provided editScript.
1101
- newMappingResult['_countWaitingForRemove'] = countWaitingForRemove;
1102
- }
1103
- // Store a copy of the array items we just considered so we can difference it next time
1104
- domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
1105
- // Call beforeMove first before any changes have been made to the DOM
1106
- callCallback(options$$1['beforeMove'], itemsForMoveCallbacks);
1107
- // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
1108
- arrayForEach(nodesToDelete, options$$1['beforeRemove'] ? cleanNode : removeNode);
1109
- // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
1110
- i = 0;
1111
- for (var nextNode = virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
1112
- // Get nodes for newly added items
1113
- if (!mapData.mappedNodes) {
1114
- extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
1115
- }
1116
- // Put nodes in the right place if they aren't there already
1117
- for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
1118
- if (node !== nextNode) {
1119
- virtualElements.insertAfter(domNode, node, lastNode);
1120
- }
1121
- }
1122
- // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
1123
- if (!mapData.initialized && callbackAfterAddingNodes) {
1124
- callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
1125
- mapData.initialized = true;
1126
- }
1127
- }
1128
- // If there's a beforeRemove callback, call it after reordering.
1129
- // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
1130
- // some sort of animation, which is why we first reorder the nodes that will be removed. If the
1131
- // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
1132
- // Perhaps we'll make that change in the future if this scenario becomes more common.
1133
- callCallback(options$$1['beforeRemove'], itemsForBeforeRemoveCallbacks);
1134
- // Replace the stored values of deleted items with a dummy value. This provides two benefits: it marks this item
1135
- // as already "removed" so we won't call beforeRemove for it again, and it ensures that the item won't match up
1136
- // with an actual item in the array and appear as "retained" or "moved".
1137
- for (i = 0; i < itemsForBeforeRemoveCallbacks.length; ++i) {
1138
- itemsForBeforeRemoveCallbacks[i].arrayEntry = deletedItemDummyValue;
1139
- }
1140
- // Finally call afterMove and afterAdd callbacks
1141
- callCallback(options$$1['afterMove'], itemsForMoveCallbacks);
1142
- callCallback(options$$1['afterAdd'], itemsForAfterAddCallbacks);
1143
- }
1144
-
1145
- /**
1146
- * This DescendantBindingHandler is a base class for bindings that control
1147
- * descendants, such as the `if`, `with`, `component`, `foreach` and `template`
1148
- * bindings.
1149
- */
1150
- var DescendantBindingHandler = /** @class */ (function (_super) {
1151
- __extends(DescendantBindingHandler, _super);
1152
- function DescendantBindingHandler() {
1153
- return _super !== null && _super.apply(this, arguments) || this;
1154
- }
1155
- Object.defineProperty(DescendantBindingHandler.prototype, "controlsDescendants", {
1156
- get: function () { return true; },
1157
- enumerable: true,
1158
- configurable: true
1159
- });
1160
- DescendantBindingHandler.prototype.applyBindingsToDescendants = function (childContext, callback) {
1161
- return __awaiter(this, void 0, void 0, function () {
1162
- var bindingResult;
1163
- return __generator(this, function (_a) {
1164
- switch (_a.label) {
1165
- case 0:
1166
- bindingResult = applyBindingsToDescendants(childContext, this.$element);
1167
- if (!bindingResult.isSync) return [3 /*break*/, 1];
1168
- this.bindingCompletion = bindingResult;
1169
- return [3 /*break*/, 3];
1170
- case 1: return [4 /*yield*/, bindingResult.completionPromise];
1171
- case 2:
1172
- _a.sent();
1173
- _a.label = 3;
1174
- case 3:
1175
- if (callback) {
1176
- callback(bindingResult);
1177
- }
1178
- this.completeBinding(bindingResult);
1179
- return [2 /*return*/];
1180
- }
1181
- });
1182
- });
1183
- };
1184
- return DescendantBindingHandler;
1185
- }(AsyncBindingHandler));
1186
-
1187
- export { BindingHandler, AsyncBindingHandler, DescendantBindingHandler, bindingEvent, boundElementDomDataKey$1 as boundElementDomDataKey, contextSubscribeSymbol, bindingContext, storedBindingContextForNode, contextFor, dataFor, getBindingHandler, applyBindingAccessorsToNode, applyBindingsToNode, applyBindingsToDescendants, applyBindings, setDomNodeChildrenFromArrayMapping };
1188
- //# sourceMappingURL=bind.js.map