UNPKG

75.8 kBJavaScriptView Raw
1import { Container, inject, Optional } from 'aurelia-dependency-injection';
2import { DOM, FEATURE } from 'aurelia-pal';
3import { TaskQueue } from 'aurelia-task-queue';
4import { bindable, noView, customElement, CompositionEngine, ViewSlot, ViewResources, customAttribute, templateController, BoundViewFactory, TargetInstruction, Animator, resource, useView, useShadowDOM, ViewEngine } from 'aurelia-templating';
5import { createOverrideContext, bindingMode, BindingBehavior, ValueConverter, sourceContext, mergeSplice, ObserverLocator, valueConverter, DataAttributeObserver, bindingBehavior, targetContext, EventSubscriber } from 'aurelia-binding';
6import { Loader } from 'aurelia-loader';
7import { relativeToFile } from 'aurelia-path';
8import { mixin } from 'aurelia-metadata';
9import { getLogger } from 'aurelia-logging';
10
11/*! *****************************************************************************
12Copyright (c) Microsoft Corporation.
13
14Permission to use, copy, modify, and/or distribute this software for any
15purpose with or without fee is hereby granted.
16
17THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23PERFORMANCE OF THIS SOFTWARE.
24***************************************************************************** */
25/* global Reflect, Promise */
26
27var extendStatics = function(d, b) {
28 extendStatics = Object.setPrototypeOf ||
29 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
31 return extendStatics(d, b);
32};
33
34function __extends(d, b) {
35 if (typeof b !== "function" && b !== null)
36 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37 extendStatics(d, b);
38 function __() { this.constructor = d; }
39 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40}
41
42function __decorate(decorators, target, key, desc) {
43 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
44 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
45 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;
46 return c > 3 && r && Object.defineProperty(target, key, r), r;
47}
48
49var ActivationStrategy;
50(function (ActivationStrategy) {
51 ActivationStrategy["InvokeLifecycle"] = "invoke-lifecycle";
52 ActivationStrategy["Replace"] = "replace";
53})(ActivationStrategy || (ActivationStrategy = {}));
54var Compose = (function () {
55 function Compose(element, container, compositionEngine, viewSlot, viewResources, taskQueue) {
56 this.activationStrategy = ActivationStrategy.InvokeLifecycle;
57 this.element = element;
58 this.container = container;
59 this.compositionEngine = compositionEngine;
60 this.viewSlot = viewSlot;
61 this.viewResources = viewResources;
62 this.taskQueue = taskQueue;
63 this.currentController = null;
64 this.currentViewModel = null;
65 this.changes = Object.create(null);
66 }
67 Compose.inject = function () {
68 return [DOM.Element, Container, CompositionEngine, ViewSlot, ViewResources, TaskQueue];
69 };
70 Compose.prototype.created = function (owningView) {
71 this.owningView = owningView;
72 };
73 Compose.prototype.bind = function (bindingContext, overrideContext) {
74 this.bindingContext = bindingContext;
75 this.overrideContext = overrideContext;
76 var changes = this.changes;
77 changes.view = this.view;
78 changes.viewModel = this.viewModel;
79 changes.model = this.model;
80 if (!this.pendingTask) {
81 processChanges(this);
82 }
83 };
84 Compose.prototype.unbind = function () {
85 this.changes = Object.create(null);
86 this.bindingContext = null;
87 this.overrideContext = null;
88 var returnToCache = true;
89 var skipAnimation = true;
90 this.viewSlot.removeAll(returnToCache, skipAnimation);
91 };
92 Compose.prototype.modelChanged = function (newValue, oldValue) {
93 this.changes.model = newValue;
94 requestUpdate(this);
95 };
96 Compose.prototype.viewChanged = function (newValue, oldValue) {
97 this.changes.view = newValue;
98 requestUpdate(this);
99 };
100 Compose.prototype.viewModelChanged = function (newValue, oldValue) {
101 this.changes.viewModel = newValue;
102 requestUpdate(this);
103 };
104 __decorate([
105 bindable
106 ], Compose.prototype, "model", void 0);
107 __decorate([
108 bindable
109 ], Compose.prototype, "view", void 0);
110 __decorate([
111 bindable
112 ], Compose.prototype, "viewModel", void 0);
113 __decorate([
114 bindable
115 ], Compose.prototype, "activationStrategy", void 0);
116 __decorate([
117 bindable
118 ], Compose.prototype, "swapOrder", void 0);
119 Compose = __decorate([
120 noView,
121 customElement('compose')
122 ], Compose);
123 return Compose;
124}());
125function isEmpty(obj) {
126 for (var _ in obj) {
127 return false;
128 }
129 return true;
130}
131function tryActivateViewModel(vm, model) {
132 if (vm && typeof vm.activate === 'function') {
133 return Promise.resolve(vm.activate(model));
134 }
135}
136function createInstruction(composer, instruction) {
137 return Object.assign(instruction, {
138 bindingContext: composer.bindingContext,
139 overrideContext: composer.overrideContext,
140 owningView: composer.owningView,
141 container: composer.container,
142 viewSlot: composer.viewSlot,
143 viewResources: composer.viewResources,
144 currentController: composer.currentController,
145 host: composer.element,
146 swapOrder: composer.swapOrder
147 });
148}
149function processChanges(composer) {
150 var changes = composer.changes;
151 composer.changes = Object.create(null);
152 if (needsReInitialization(composer, changes)) {
153 var instruction = {
154 view: composer.view,
155 viewModel: composer.currentViewModel || composer.viewModel,
156 model: composer.model
157 };
158 instruction = Object.assign(instruction, changes);
159 instruction = createInstruction(composer, instruction);
160 composer.pendingTask = composer.compositionEngine.compose(instruction).then(function (controller) {
161 composer.currentController = controller;
162 composer.currentViewModel = controller ? controller.viewModel : null;
163 });
164 }
165 else {
166 composer.pendingTask = tryActivateViewModel(composer.currentViewModel, changes.model);
167 if (!composer.pendingTask) {
168 return;
169 }
170 }
171 composer.pendingTask = composer.pendingTask
172 .then(function () {
173 completeCompositionTask(composer);
174 }, function (reason) {
175 completeCompositionTask(composer);
176 throw reason;
177 });
178}
179function completeCompositionTask(composer) {
180 composer.pendingTask = null;
181 if (!isEmpty(composer.changes)) {
182 processChanges(composer);
183 }
184}
185function requestUpdate(composer) {
186 if (composer.pendingTask || composer.updateRequested) {
187 return;
188 }
189 composer.updateRequested = true;
190 composer.taskQueue.queueMicroTask(function () {
191 composer.updateRequested = false;
192 processChanges(composer);
193 });
194}
195function needsReInitialization(composer, changes) {
196 var activationStrategy = composer.activationStrategy;
197 var vm = composer.currentViewModel;
198 if (vm && typeof vm.determineActivationStrategy === 'function') {
199 activationStrategy = vm.determineActivationStrategy();
200 }
201 return 'view' in changes
202 || 'viewModel' in changes
203 || activationStrategy === ActivationStrategy.Replace;
204}
205
206var IfCore = (function () {
207 function IfCore(viewFactory, viewSlot) {
208 this.viewFactory = viewFactory;
209 this.viewSlot = viewSlot;
210 this.view = null;
211 this.bindingContext = null;
212 this.overrideContext = null;
213 this.showing = false;
214 this.cache = true;
215 }
216 IfCore.prototype.bind = function (bindingContext, overrideContext) {
217 this.bindingContext = bindingContext;
218 this.overrideContext = overrideContext;
219 };
220 IfCore.prototype.unbind = function () {
221 if (this.view === null) {
222 return;
223 }
224 this.view.unbind();
225 if (!this.viewFactory.isCaching) {
226 return;
227 }
228 if (this.showing) {
229 this.showing = false;
230 this.viewSlot.remove(this.view, true, true);
231 }
232 else {
233 this.view.returnToCache();
234 }
235 this.view = null;
236 };
237 IfCore.prototype._show = function () {
238 if (this.showing) {
239 if (!this.view.isBound) {
240 this.view.bind(this.bindingContext, this.overrideContext);
241 }
242 return;
243 }
244 if (this.view === null) {
245 this.view = this.viewFactory.create();
246 }
247 if (!this.view.isBound) {
248 this.view.bind(this.bindingContext, this.overrideContext);
249 }
250 this.showing = true;
251 return this.viewSlot.add(this.view);
252 };
253 IfCore.prototype._hide = function () {
254 var _this = this;
255 if (!this.showing) {
256 return;
257 }
258 this.showing = false;
259 var removed = this.viewSlot.remove(this.view);
260 if (removed instanceof Promise) {
261 return removed.then(function () {
262 _this._unbindView();
263 });
264 }
265 this._unbindView();
266 };
267 IfCore.prototype._unbindView = function () {
268 var cache = this.cache === 'false' ? false : !!this.cache;
269 this.view.unbind();
270 if (!cache) {
271 this.view = null;
272 }
273 };
274 return IfCore;
275}());
276
277var If = (function (_super) {
278 __extends(If, _super);
279 function If() {
280 var _this = _super !== null && _super.apply(this, arguments) || this;
281 _this.cache = true;
282 return _this;
283 }
284 If.prototype.bind = function (bindingContext, overrideContext) {
285 _super.prototype.bind.call(this, bindingContext, overrideContext);
286 if (this.condition) {
287 this._show();
288 }
289 else {
290 this._hide();
291 }
292 };
293 If.prototype.conditionChanged = function (newValue) {
294 this._update(newValue);
295 };
296 If.prototype._update = function (show) {
297 var _this = this;
298 if (this.animating) {
299 return;
300 }
301 var promise;
302 if (this.elseVm) {
303 promise = show ? this._swap(this.elseVm, this) : this._swap(this, this.elseVm);
304 }
305 else {
306 promise = show ? this._show() : this._hide();
307 }
308 if (promise) {
309 this.animating = true;
310 promise.then(function () {
311 _this.animating = false;
312 if (_this.condition !== _this.showing) {
313 _this._update(_this.condition);
314 }
315 });
316 }
317 };
318 If.prototype._swap = function (remove, add) {
319 switch (this.swapOrder) {
320 case 'before':
321 return Promise.resolve(add._show()).then(function () { return remove._hide(); });
322 case 'with':
323 return Promise.all([remove._hide(), add._show()]);
324 default:
325 var promise = remove._hide();
326 return promise ? promise.then(function () { return add._show(); }) : add._show();
327 }
328 };
329 __decorate([
330 bindable({ primaryProperty: true })
331 ], If.prototype, "condition", void 0);
332 __decorate([
333 bindable
334 ], If.prototype, "swapOrder", void 0);
335 __decorate([
336 bindable
337 ], If.prototype, "cache", void 0);
338 If = __decorate([
339 customAttribute('if'),
340 templateController,
341 inject(BoundViewFactory, ViewSlot)
342 ], If);
343 return If;
344}(IfCore));
345
346var Else = (function (_super) {
347 __extends(Else, _super);
348 function Else(viewFactory, viewSlot) {
349 var _this = _super.call(this, viewFactory, viewSlot) || this;
350 _this._registerInIf();
351 return _this;
352 }
353 Else.prototype.bind = function (bindingContext, overrideContext) {
354 _super.prototype.bind.call(this, bindingContext, overrideContext);
355 if (this.ifVm.condition) {
356 this._hide();
357 }
358 else {
359 this._show();
360 }
361 };
362 Else.prototype._registerInIf = function () {
363 var previous = this.viewSlot.anchor.previousSibling;
364 while (previous && !previous.au) {
365 previous = previous.previousSibling;
366 }
367 if (!previous || !previous.au.if) {
368 throw new Error("Can't find matching If for Else custom attribute.");
369 }
370 this.ifVm = previous.au.if.viewModel;
371 this.ifVm.elseVm = this;
372 };
373 Else = __decorate([
374 customAttribute('else'),
375 templateController,
376 inject(BoundViewFactory, ViewSlot)
377 ], Else);
378 return Else;
379}(IfCore));
380
381var With = (function () {
382 function With(viewFactory, viewSlot) {
383 this.viewFactory = viewFactory;
384 this.viewSlot = viewSlot;
385 this.parentOverrideContext = null;
386 this.view = null;
387 }
388 With.prototype.bind = function (bindingContext, overrideContext) {
389 this.parentOverrideContext = overrideContext;
390 this.valueChanged(this.value);
391 };
392 With.prototype.valueChanged = function (newValue) {
393 var overrideContext = createOverrideContext(newValue, this.parentOverrideContext);
394 var view = this.view;
395 if (!view) {
396 view = this.view = this.viewFactory.create();
397 view.bind(newValue, overrideContext);
398 this.viewSlot.add(view);
399 }
400 else {
401 view.bind(newValue, overrideContext);
402 }
403 };
404 With.prototype.unbind = function () {
405 var view = this.view;
406 this.parentOverrideContext = null;
407 if (view) {
408 view.unbind();
409 }
410 };
411 With = __decorate([
412 customAttribute('with'),
413 templateController,
414 inject(BoundViewFactory, ViewSlot)
415 ], With);
416 return With;
417}());
418
419var oneTime = bindingMode.oneTime;
420function updateOverrideContexts(views, startIndex) {
421 var length = views.length;
422 if (startIndex > 0) {
423 startIndex = startIndex - 1;
424 }
425 for (; startIndex < length; ++startIndex) {
426 updateOverrideContext(views[startIndex].overrideContext, startIndex, length);
427 }
428}
429function createFullOverrideContext(repeat, data, index, length, key) {
430 var bindingContext = {};
431 var overrideContext = createOverrideContext(bindingContext, repeat.scope.overrideContext);
432 if (typeof key !== 'undefined') {
433 bindingContext[repeat.key] = key;
434 bindingContext[repeat.value] = data;
435 }
436 else {
437 bindingContext[repeat.local] = data;
438 }
439 updateOverrideContext(overrideContext, index, length);
440 return overrideContext;
441}
442function updateOverrideContext(overrideContext, index, length) {
443 var first = (index === 0);
444 var last = (index === length - 1);
445 var even = index % 2 === 0;
446 overrideContext.$index = index;
447 overrideContext.$first = first;
448 overrideContext.$last = last;
449 overrideContext.$middle = !(first || last);
450 overrideContext.$odd = !even;
451 overrideContext.$even = even;
452}
453function getItemsSourceExpression(instruction, attrName) {
454 return instruction.behaviorInstructions
455 .filter(function (bi) { return bi.originalAttrName === attrName; })[0]
456 .attributes
457 .items
458 .sourceExpression;
459}
460function unwrapExpression(expression) {
461 var unwrapped = false;
462 while (expression instanceof BindingBehavior) {
463 expression = expression.expression;
464 }
465 while (expression instanceof ValueConverter) {
466 expression = expression.expression;
467 unwrapped = true;
468 }
469 return unwrapped ? expression : null;
470}
471function isOneTime(expression) {
472 while (expression instanceof BindingBehavior) {
473 if (expression.name === 'oneTime') {
474 return true;
475 }
476 expression = expression.expression;
477 }
478 return false;
479}
480function updateOneTimeBinding(binding) {
481 if (binding.call && binding.mode === oneTime) {
482 binding.call(sourceContext);
483 }
484 else if (binding.updateOneTimeBindings) {
485 binding.updateOneTimeBindings();
486 }
487}
488function indexOf(array, item, matcher, startIndex) {
489 if (!matcher) {
490 return array.indexOf(item);
491 }
492 var length = array.length;
493 for (var index = startIndex || 0; index < length; index++) {
494 if (matcher(array[index], item)) {
495 return index;
496 }
497 }
498 return -1;
499}
500
501var ArrayRepeatStrategy = (function () {
502 function ArrayRepeatStrategy() {
503 }
504 ArrayRepeatStrategy.prototype.getCollectionObserver = function (observerLocator, items) {
505 return observerLocator.getArrayObserver(items);
506 };
507 ArrayRepeatStrategy.prototype.instanceChanged = function (repeat, items) {
508 var _this = this;
509 var $repeat = repeat;
510 var itemsLength = items.length;
511 if (!items || itemsLength === 0) {
512 $repeat.removeAllViews(true, !$repeat.viewsRequireLifecycle);
513 return;
514 }
515 var children = $repeat.views();
516 var viewsLength = children.length;
517 if (viewsLength === 0) {
518 this._standardProcessInstanceChanged($repeat, items);
519 return;
520 }
521 if ($repeat.viewsRequireLifecycle) {
522 var childrenSnapshot = children.slice(0);
523 var itemNameInBindingContext = $repeat.local;
524 var matcher_1 = $repeat.matcher();
525 var itemsPreviouslyInViews_1 = [];
526 var viewsToRemove = [];
527 for (var index = 0; index < viewsLength; index++) {
528 var view = childrenSnapshot[index];
529 var oldItem = view.bindingContext[itemNameInBindingContext];
530 if (indexOf(items, oldItem, matcher_1) === -1) {
531 viewsToRemove.push(view);
532 }
533 else {
534 itemsPreviouslyInViews_1.push(oldItem);
535 }
536 }
537 var updateViews = void 0;
538 var removePromise = void 0;
539 if (itemsPreviouslyInViews_1.length > 0) {
540 removePromise = $repeat.removeViews(viewsToRemove, true, !$repeat.viewsRequireLifecycle);
541 updateViews = function () {
542 for (var index = 0; index < itemsLength; index++) {
543 var item = items[index];
544 var indexOfView = indexOf(itemsPreviouslyInViews_1, item, matcher_1, index);
545 var view = void 0;
546 if (indexOfView === -1) {
547 var overrideContext = createFullOverrideContext($repeat, items[index], index, itemsLength);
548 $repeat.insertView(index, overrideContext.bindingContext, overrideContext);
549 itemsPreviouslyInViews_1.splice(index, 0, undefined);
550 }
551 else if (indexOfView === index) {
552 view = children[indexOfView];
553 itemsPreviouslyInViews_1[indexOfView] = undefined;
554 }
555 else {
556 view = children[indexOfView];
557 $repeat.moveView(indexOfView, index);
558 itemsPreviouslyInViews_1.splice(indexOfView, 1);
559 itemsPreviouslyInViews_1.splice(index, 0, undefined);
560 }
561 if (view) {
562 updateOverrideContext(view.overrideContext, index, itemsLength);
563 }
564 }
565 _this._inPlaceProcessItems($repeat, items);
566 };
567 }
568 else {
569 removePromise = $repeat.removeAllViews(true, !$repeat.viewsRequireLifecycle);
570 updateViews = function () { return _this._standardProcessInstanceChanged($repeat, items); };
571 }
572 if (removePromise instanceof Promise) {
573 removePromise.then(updateViews);
574 }
575 else {
576 updateViews();
577 }
578 }
579 else {
580 this._inPlaceProcessItems($repeat, items);
581 }
582 };
583 ArrayRepeatStrategy.prototype._standardProcessInstanceChanged = function (repeat, items) {
584 for (var i = 0, ii = items.length; i < ii; i++) {
585 var overrideContext = createFullOverrideContext(repeat, items[i], i, ii);
586 repeat.addView(overrideContext.bindingContext, overrideContext);
587 }
588 };
589 ArrayRepeatStrategy.prototype._inPlaceProcessItems = function (repeat, items) {
590 var itemsLength = items.length;
591 var viewsLength = repeat.viewCount();
592 while (viewsLength > itemsLength) {
593 viewsLength--;
594 repeat.removeView(viewsLength, true, !repeat.viewsRequireLifecycle);
595 }
596 var local = repeat.local;
597 for (var i = 0; i < viewsLength; i++) {
598 var view = repeat.view(i);
599 var last = i === itemsLength - 1;
600 var middle = i !== 0 && !last;
601 var bindingContext = view.bindingContext;
602 var overrideContext = view.overrideContext;
603 if (bindingContext[local] === items[i]
604 && overrideContext.$middle === middle
605 && overrideContext.$last === last) {
606 continue;
607 }
608 bindingContext[local] = items[i];
609 overrideContext.$middle = middle;
610 overrideContext.$last = last;
611 repeat.updateBindings(view);
612 }
613 for (var i = viewsLength; i < itemsLength; i++) {
614 var overrideContext = createFullOverrideContext(repeat, items[i], i, itemsLength);
615 repeat.addView(overrideContext.bindingContext, overrideContext);
616 }
617 };
618 ArrayRepeatStrategy.prototype.instanceMutated = function (repeat, array, splices) {
619 var _this = this;
620 if (repeat.__queuedSplices) {
621 for (var i = 0, ii = splices.length; i < ii; ++i) {
622 var _a = splices[i], index = _a.index, removed = _a.removed, addedCount = _a.addedCount;
623 mergeSplice(repeat.__queuedSplices, index, removed, addedCount);
624 }
625 repeat.__array = array.slice(0);
626 return;
627 }
628 var maybePromise = this._runSplices(repeat, array.slice(0), splices);
629 if (maybePromise instanceof Promise) {
630 var queuedSplices_1 = repeat.__queuedSplices = [];
631 var runQueuedSplices_1 = function () {
632 if (!queuedSplices_1.length) {
633 repeat.__queuedSplices = undefined;
634 repeat.__array = undefined;
635 return;
636 }
637 var nextPromise = _this._runSplices(repeat, repeat.__array, queuedSplices_1) || Promise.resolve();
638 queuedSplices_1 = repeat.__queuedSplices = [];
639 nextPromise.then(runQueuedSplices_1);
640 };
641 maybePromise.then(runQueuedSplices_1);
642 }
643 };
644 ArrayRepeatStrategy.prototype._runSplices = function (repeat, array, splices) {
645 var _this = this;
646 var removeDelta = 0;
647 var rmPromises = [];
648 for (var i = 0, ii = splices.length; i < ii; ++i) {
649 var splice = splices[i];
650 var removed = splice.removed;
651 for (var j = 0, jj = removed.length; j < jj; ++j) {
652 var viewOrPromise = repeat.removeView(splice.index + removeDelta + rmPromises.length, true);
653 if (viewOrPromise instanceof Promise) {
654 rmPromises.push(viewOrPromise);
655 }
656 }
657 removeDelta -= splice.addedCount;
658 }
659 if (rmPromises.length > 0) {
660 return Promise.all(rmPromises).then(function () {
661 var spliceIndexLow = _this._handleAddedSplices(repeat, array, splices);
662 updateOverrideContexts(repeat.views(), spliceIndexLow);
663 });
664 }
665 var spliceIndexLow = this._handleAddedSplices(repeat, array, splices);
666 updateOverrideContexts(repeat.views(), spliceIndexLow);
667 return undefined;
668 };
669 ArrayRepeatStrategy.prototype._handleAddedSplices = function (repeat, array, splices) {
670 var spliceIndex;
671 var spliceIndexLow;
672 var arrayLength = array.length;
673 for (var i = 0, ii = splices.length; i < ii; ++i) {
674 var splice = splices[i];
675 var addIndex = spliceIndex = splice.index;
676 var end = splice.index + splice.addedCount;
677 if (typeof spliceIndexLow === 'undefined' || spliceIndexLow === null || spliceIndexLow > splice.index) {
678 spliceIndexLow = spliceIndex;
679 }
680 for (; addIndex < end; ++addIndex) {
681 var overrideContext = createFullOverrideContext(repeat, array[addIndex], addIndex, arrayLength);
682 repeat.insertView(addIndex, overrideContext.bindingContext, overrideContext);
683 }
684 }
685 return spliceIndexLow;
686 };
687 return ArrayRepeatStrategy;
688}());
689
690var MapRepeatStrategy = (function () {
691 function MapRepeatStrategy() {
692 }
693 MapRepeatStrategy.prototype.getCollectionObserver = function (observerLocator, items) {
694 return observerLocator.getMapObserver(items);
695 };
696 MapRepeatStrategy.prototype.instanceChanged = function (repeat, items) {
697 var _this = this;
698 var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
699 if (removePromise instanceof Promise) {
700 removePromise.then(function () { return _this._standardProcessItems(repeat, items); });
701 return;
702 }
703 this._standardProcessItems(repeat, items);
704 };
705 MapRepeatStrategy.prototype._standardProcessItems = function (repeat, items) {
706 var index = 0;
707 var overrideContext;
708 items.forEach(function (value, key) {
709 overrideContext = createFullOverrideContext(repeat, value, index, items.size, key);
710 repeat.addView(overrideContext.bindingContext, overrideContext);
711 ++index;
712 });
713 };
714 MapRepeatStrategy.prototype.instanceMutated = function (repeat, map, records) {
715 var key;
716 var i;
717 var ii;
718 var overrideContext;
719 var removeIndex;
720 var addIndex;
721 var record;
722 var rmPromises = [];
723 var viewOrPromise;
724 for (i = 0, ii = records.length; i < ii; ++i) {
725 record = records[i];
726 key = record.key;
727 switch (record.type) {
728 case 'update':
729 removeIndex = this._getViewIndexByKey(repeat, key);
730 viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
731 if (viewOrPromise instanceof Promise) {
732 rmPromises.push(viewOrPromise);
733 }
734 overrideContext = createFullOverrideContext(repeat, map.get(key), removeIndex, map.size, key);
735 repeat.insertView(removeIndex, overrideContext.bindingContext, overrideContext);
736 break;
737 case 'add':
738 addIndex = repeat.viewCount() <= map.size - 1 ? repeat.viewCount() : map.size - 1;
739 overrideContext = createFullOverrideContext(repeat, map.get(key), addIndex, map.size, key);
740 repeat.insertView(map.size - 1, overrideContext.bindingContext, overrideContext);
741 break;
742 case 'delete':
743 if (record.oldValue === undefined) {
744 return;
745 }
746 removeIndex = this._getViewIndexByKey(repeat, key);
747 viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
748 if (viewOrPromise instanceof Promise) {
749 rmPromises.push(viewOrPromise);
750 }
751 break;
752 case 'clear':
753 repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
754 break;
755 default:
756 continue;
757 }
758 }
759 if (rmPromises.length > 0) {
760 Promise.all(rmPromises).then(function () {
761 updateOverrideContexts(repeat.views(), 0);
762 });
763 }
764 else {
765 updateOverrideContexts(repeat.views(), 0);
766 }
767 };
768 MapRepeatStrategy.prototype._getViewIndexByKey = function (repeat, key) {
769 var i;
770 var ii;
771 var child;
772 for (i = 0, ii = repeat.viewCount(); i < ii; ++i) {
773 child = repeat.view(i);
774 if (child.bindingContext[repeat.key] === key) {
775 return i;
776 }
777 }
778 return undefined;
779 };
780 return MapRepeatStrategy;
781}());
782
783var NullRepeatStrategy = (function () {
784 function NullRepeatStrategy() {
785 }
786 NullRepeatStrategy.prototype.instanceChanged = function (repeat, items) {
787 repeat.removeAllViews(true);
788 };
789 NullRepeatStrategy.prototype.getCollectionObserver = function (observerLocator, items) {
790 };
791 return NullRepeatStrategy;
792}());
793
794var NumberRepeatStrategy = (function () {
795 function NumberRepeatStrategy() {
796 }
797 NumberRepeatStrategy.prototype.getCollectionObserver = function () {
798 return null;
799 };
800 NumberRepeatStrategy.prototype.instanceChanged = function (repeat, value) {
801 var _this = this;
802 var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
803 if (removePromise instanceof Promise) {
804 removePromise.then(function () { return _this._standardProcessItems(repeat, value); });
805 return;
806 }
807 this._standardProcessItems(repeat, value);
808 };
809 NumberRepeatStrategy.prototype._standardProcessItems = function (repeat, value) {
810 var childrenLength = repeat.viewCount();
811 var i;
812 var ii;
813 var overrideContext;
814 var viewsToRemove;
815 value = Math.floor(value);
816 viewsToRemove = childrenLength - value;
817 if (viewsToRemove > 0) {
818 if (viewsToRemove > childrenLength) {
819 viewsToRemove = childrenLength;
820 }
821 for (i = 0, ii = viewsToRemove; i < ii; ++i) {
822 repeat.removeView(childrenLength - (i + 1), true, !repeat.viewsRequireLifecycle);
823 }
824 return;
825 }
826 for (i = childrenLength, ii = value; i < ii; ++i) {
827 overrideContext = createFullOverrideContext(repeat, i, i, ii);
828 repeat.addView(overrideContext.bindingContext, overrideContext);
829 }
830 updateOverrideContexts(repeat.views(), 0);
831 };
832 return NumberRepeatStrategy;
833}());
834
835var SetRepeatStrategy = (function () {
836 function SetRepeatStrategy() {
837 }
838 SetRepeatStrategy.prototype.getCollectionObserver = function (observerLocator, items) {
839 return observerLocator.getSetObserver(items);
840 };
841 SetRepeatStrategy.prototype.instanceChanged = function (repeat, items) {
842 var _this = this;
843 var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
844 if (removePromise instanceof Promise) {
845 removePromise.then(function () { return _this._standardProcessItems(repeat, items); });
846 return;
847 }
848 this._standardProcessItems(repeat, items);
849 };
850 SetRepeatStrategy.prototype._standardProcessItems = function (repeat, items) {
851 var index = 0;
852 var overrideContext;
853 items.forEach(function (value) {
854 overrideContext = createFullOverrideContext(repeat, value, index, items.size);
855 repeat.addView(overrideContext.bindingContext, overrideContext);
856 ++index;
857 });
858 };
859 SetRepeatStrategy.prototype.instanceMutated = function (repeat, set, records) {
860 var value;
861 var i;
862 var ii;
863 var overrideContext;
864 var removeIndex;
865 var record;
866 var rmPromises = [];
867 var viewOrPromise;
868 for (i = 0, ii = records.length; i < ii; ++i) {
869 record = records[i];
870 value = record.value;
871 switch (record.type) {
872 case 'add':
873 var size = Math.max(set.size - 1, 0);
874 overrideContext = createFullOverrideContext(repeat, value, size, set.size);
875 repeat.insertView(size, overrideContext.bindingContext, overrideContext);
876 break;
877 case 'delete':
878 removeIndex = this._getViewIndexByValue(repeat, value);
879 viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
880 if (viewOrPromise instanceof Promise) {
881 rmPromises.push(viewOrPromise);
882 }
883 break;
884 case 'clear':
885 repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
886 break;
887 default:
888 continue;
889 }
890 }
891 if (rmPromises.length > 0) {
892 Promise.all(rmPromises).then(function () {
893 updateOverrideContexts(repeat.views(), 0);
894 });
895 }
896 else {
897 updateOverrideContexts(repeat.views(), 0);
898 }
899 };
900 SetRepeatStrategy.prototype._getViewIndexByValue = function (repeat, value) {
901 var i;
902 var ii;
903 var child;
904 for (i = 0, ii = repeat.viewCount(); i < ii; ++i) {
905 child = repeat.view(i);
906 if (child.bindingContext[repeat.local] === value) {
907 return i;
908 }
909 }
910 return undefined;
911 };
912 return SetRepeatStrategy;
913}());
914
915var RepeatStrategyLocator = (function () {
916 function RepeatStrategyLocator() {
917 this.matchers = [];
918 this.strategies = [];
919 this.addStrategy(function (items) { return items === null || items === undefined; }, new NullRepeatStrategy());
920 this.addStrategy(function (items) { return items instanceof Array; }, new ArrayRepeatStrategy());
921 this.addStrategy(function (items) { return items instanceof Map; }, new MapRepeatStrategy());
922 this.addStrategy(function (items) { return items instanceof Set; }, new SetRepeatStrategy());
923 this.addStrategy(function (items) { return typeof items === 'number'; }, new NumberRepeatStrategy());
924 }
925 RepeatStrategyLocator.prototype.addStrategy = function (matcher, strategy) {
926 this.matchers.push(matcher);
927 this.strategies.push(strategy);
928 };
929 RepeatStrategyLocator.prototype.getStrategy = function (items) {
930 var matchers = this.matchers;
931 for (var i = 0, ii = matchers.length; i < ii; ++i) {
932 if (matchers[i](items)) {
933 return this.strategies[i];
934 }
935 }
936 return null;
937 };
938 return RepeatStrategyLocator;
939}());
940
941var lifecycleOptionalBehaviors = ['focus', 'if', 'else', 'repeat', 'show', 'hide', 'with'];
942function behaviorRequiresLifecycle(instruction) {
943 var t = instruction.type;
944 var name = t.elementName !== null ? t.elementName : t.attributeName;
945 return lifecycleOptionalBehaviors.indexOf(name) === -1 && (t.handlesAttached || t.handlesBind || t.handlesCreated || t.handlesDetached || t.handlesUnbind)
946 || t.viewFactory && viewsRequireLifecycle(t.viewFactory)
947 || instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory);
948}
949function targetRequiresLifecycle(instruction) {
950 var behaviors = instruction.behaviorInstructions;
951 if (behaviors) {
952 var i = behaviors.length;
953 while (i--) {
954 if (behaviorRequiresLifecycle(behaviors[i])) {
955 return true;
956 }
957 }
958 }
959 return instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory);
960}
961function viewsRequireLifecycle(viewFactory) {
962 if ('_viewsRequireLifecycle' in viewFactory) {
963 return viewFactory._viewsRequireLifecycle;
964 }
965 viewFactory._viewsRequireLifecycle = false;
966 if (viewFactory.viewFactory) {
967 viewFactory._viewsRequireLifecycle = viewsRequireLifecycle(viewFactory.viewFactory);
968 return viewFactory._viewsRequireLifecycle;
969 }
970 if (viewFactory.template.querySelector('.au-animate')) {
971 viewFactory._viewsRequireLifecycle = true;
972 return true;
973 }
974 for (var id in viewFactory.instructions) {
975 if (targetRequiresLifecycle(viewFactory.instructions[id])) {
976 viewFactory._viewsRequireLifecycle = true;
977 return true;
978 }
979 }
980 viewFactory._viewsRequireLifecycle = false;
981 return false;
982}
983
984var AbstractRepeater = (function () {
985 function AbstractRepeater(options) {
986 Object.assign(this, {
987 local: 'items',
988 viewsRequireLifecycle: true
989 }, options);
990 }
991 AbstractRepeater.prototype.viewCount = function () {
992 throw new Error('subclass must implement `viewCount`');
993 };
994 AbstractRepeater.prototype.views = function () {
995 throw new Error('subclass must implement `views`');
996 };
997 AbstractRepeater.prototype.view = function (index) {
998 throw new Error('subclass must implement `view`');
999 };
1000 AbstractRepeater.prototype.matcher = function () {
1001 throw new Error('subclass must implement `matcher`');
1002 };
1003 AbstractRepeater.prototype.addView = function (bindingContext, overrideContext) {
1004 throw new Error('subclass must implement `addView`');
1005 };
1006 AbstractRepeater.prototype.insertView = function (index, bindingContext, overrideContext) {
1007 throw new Error('subclass must implement `insertView`');
1008 };
1009 AbstractRepeater.prototype.moveView = function (sourceIndex, targetIndex) {
1010 throw new Error('subclass must implement `moveView`');
1011 };
1012 AbstractRepeater.prototype.removeAllViews = function (returnToCache, skipAnimation) {
1013 throw new Error('subclass must implement `removeAllViews`');
1014 };
1015 AbstractRepeater.prototype.removeViews = function (viewsToRemove, returnToCache, skipAnimation) {
1016 throw new Error('subclass must implement `removeView`');
1017 };
1018 AbstractRepeater.prototype.removeView = function (index, returnToCache, skipAnimation) {
1019 throw new Error('subclass must implement `removeView`');
1020 };
1021 AbstractRepeater.prototype.updateBindings = function (view) {
1022 throw new Error('subclass must implement `updateBindings`');
1023 };
1024 return AbstractRepeater;
1025}());
1026
1027var matcherExtractionMarker = '__marker_extracted__';
1028var Repeat = (function (_super) {
1029 __extends(Repeat, _super);
1030 function Repeat(viewFactory, instruction, viewSlot, viewResources, observerLocator, strategyLocator) {
1031 var _this = _super.call(this, {
1032 local: 'item',
1033 viewsRequireLifecycle: viewsRequireLifecycle(viewFactory)
1034 }) || this;
1035 _this.viewFactory = viewFactory;
1036 _this.instruction = instruction;
1037 _this.viewSlot = viewSlot;
1038 _this.lookupFunctions = viewResources.lookupFunctions;
1039 _this.observerLocator = observerLocator;
1040 _this.key = 'key';
1041 _this.value = 'value';
1042 _this.strategyLocator = strategyLocator;
1043 _this.ignoreMutation = false;
1044 _this.sourceExpression = getItemsSourceExpression(_this.instruction, 'repeat.for');
1045 _this.isOneTime = isOneTime(_this.sourceExpression);
1046 _this.viewsRequireLifecycle = viewsRequireLifecycle(viewFactory);
1047 return _this;
1048 }
1049 Repeat_1 = Repeat;
1050 Repeat.prototype.call = function (context, changes) {
1051 this[context](this.items, changes);
1052 };
1053 Repeat.prototype.bind = function (bindingContext, overrideContext) {
1054 this.scope = { bindingContext: bindingContext, overrideContext: overrideContext };
1055 var instruction = this.instruction;
1056 if (!(matcherExtractionMarker in instruction)) {
1057 instruction[matcherExtractionMarker] = this._captureAndRemoveMatcherBinding();
1058 }
1059 this.matcherBinding = instruction[matcherExtractionMarker];
1060 this.itemsChanged();
1061 };
1062 Repeat.prototype.unbind = function () {
1063 this.scope = null;
1064 this.items = null;
1065 this.matcherBinding = null;
1066 this.viewSlot.removeAll(true, true);
1067 this._unsubscribeCollection();
1068 };
1069 Repeat.prototype._unsubscribeCollection = function () {
1070 if (this.collectionObserver) {
1071 this.collectionObserver.unsubscribe(this.callContext, this);
1072 this.collectionObserver = null;
1073 this.callContext = null;
1074 }
1075 };
1076 Repeat.prototype.itemsChanged = function () {
1077 var _this = this;
1078 this._unsubscribeCollection();
1079 if (!this.scope) {
1080 return;
1081 }
1082 var items = this.items;
1083 this.strategy = this.strategyLocator.getStrategy(items);
1084 if (!this.strategy) {
1085 throw new Error("Value for '".concat(this.sourceExpression, "' is non-repeatable"));
1086 }
1087 if (!this.isOneTime && !this._observeInnerCollection()) {
1088 this._observeCollection();
1089 }
1090 this.ignoreMutation = true;
1091 this.strategy.instanceChanged(this, items);
1092 this.observerLocator.taskQueue.queueMicroTask(function () {
1093 _this.ignoreMutation = false;
1094 });
1095 };
1096 Repeat.prototype._getInnerCollection = function () {
1097 var expression = unwrapExpression(this.sourceExpression);
1098 if (!expression) {
1099 return null;
1100 }
1101 return expression.evaluate(this.scope, null);
1102 };
1103 Repeat.prototype.handleCollectionMutated = function (collection, changes) {
1104 if (!this.collectionObserver) {
1105 return;
1106 }
1107 if (this.ignoreMutation) {
1108 return;
1109 }
1110 this.strategy.instanceMutated(this, collection, changes);
1111 };
1112 Repeat.prototype.handleInnerCollectionMutated = function (collection, changes) {
1113 var _this = this;
1114 if (!this.collectionObserver) {
1115 return;
1116 }
1117 if (this.ignoreMutation) {
1118 return;
1119 }
1120 this.ignoreMutation = true;
1121 var newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions);
1122 this.observerLocator.taskQueue.queueMicroTask(function () { return _this.ignoreMutation = false; });
1123 if (newItems === this.items) {
1124 this.itemsChanged();
1125 }
1126 else {
1127 this.items = newItems;
1128 }
1129 };
1130 Repeat.prototype._observeInnerCollection = function () {
1131 var items = this._getInnerCollection();
1132 var strategy = this.strategyLocator.getStrategy(items);
1133 if (!strategy) {
1134 return false;
1135 }
1136 this.collectionObserver = strategy.getCollectionObserver(this.observerLocator, items);
1137 if (!this.collectionObserver) {
1138 return false;
1139 }
1140 this.callContext = 'handleInnerCollectionMutated';
1141 this.collectionObserver.subscribe(this.callContext, this);
1142 return true;
1143 };
1144 Repeat.prototype._observeCollection = function () {
1145 var items = this.items;
1146 this.collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, items);
1147 if (this.collectionObserver) {
1148 this.callContext = 'handleCollectionMutated';
1149 this.collectionObserver.subscribe(this.callContext, this);
1150 }
1151 };
1152 Repeat.prototype._captureAndRemoveMatcherBinding = function () {
1153 var viewFactory = this.viewFactory.viewFactory;
1154 if (viewFactory) {
1155 var template = viewFactory.template;
1156 var instructions = viewFactory.instructions;
1157 if (Repeat_1.useInnerMatcher) {
1158 return extractMatcherBindingExpression(instructions);
1159 }
1160 if (getChildrenCount(template) > 1) {
1161 return undefined;
1162 }
1163 var repeatedElement = getFirstElementChild(template);
1164 if (!repeatedElement.hasAttribute('au-target-id')) {
1165 return undefined;
1166 }
1167 var repeatedElementTargetId = repeatedElement.getAttribute('au-target-id');
1168 return extractMatcherBindingExpression(instructions, repeatedElementTargetId);
1169 }
1170 return undefined;
1171 };
1172 Repeat.prototype.viewCount = function () { return this.viewSlot.children.length; };
1173 Repeat.prototype.views = function () { return this.viewSlot.children; };
1174 Repeat.prototype.view = function (index) { return this.viewSlot.children[index]; };
1175 Repeat.prototype.matcher = function () {
1176 var matcherBinding = this.matcherBinding;
1177 return matcherBinding
1178 ? matcherBinding.sourceExpression.evaluate(this.scope, matcherBinding.lookupFunctions)
1179 : null;
1180 };
1181 Repeat.prototype.addView = function (bindingContext, overrideContext) {
1182 var view = this.viewFactory.create();
1183 view.bind(bindingContext, overrideContext);
1184 this.viewSlot.add(view);
1185 };
1186 Repeat.prototype.insertView = function (index, bindingContext, overrideContext) {
1187 var view = this.viewFactory.create();
1188 view.bind(bindingContext, overrideContext);
1189 this.viewSlot.insert(index, view);
1190 };
1191 Repeat.prototype.moveView = function (sourceIndex, targetIndex) {
1192 this.viewSlot.move(sourceIndex, targetIndex);
1193 };
1194 Repeat.prototype.removeAllViews = function (returnToCache, skipAnimation) {
1195 return this.viewSlot.removeAll(returnToCache, skipAnimation);
1196 };
1197 Repeat.prototype.removeViews = function (viewsToRemove, returnToCache, skipAnimation) {
1198 return this.viewSlot.removeMany(viewsToRemove, returnToCache, skipAnimation);
1199 };
1200 Repeat.prototype.removeView = function (index, returnToCache, skipAnimation) {
1201 return this.viewSlot.removeAt(index, returnToCache, skipAnimation);
1202 };
1203 Repeat.prototype.updateBindings = function (view) {
1204 var $view = view;
1205 var j = $view.bindings.length;
1206 while (j--) {
1207 updateOneTimeBinding($view.bindings[j]);
1208 }
1209 j = $view.controllers.length;
1210 while (j--) {
1211 var k = $view.controllers[j].boundProperties.length;
1212 while (k--) {
1213 var binding = $view.controllers[j].boundProperties[k].binding;
1214 updateOneTimeBinding(binding);
1215 }
1216 }
1217 };
1218 var Repeat_1;
1219 Repeat.useInnerMatcher = true;
1220 __decorate([
1221 bindable
1222 ], Repeat.prototype, "items", void 0);
1223 __decorate([
1224 bindable
1225 ], Repeat.prototype, "local", void 0);
1226 __decorate([
1227 bindable
1228 ], Repeat.prototype, "key", void 0);
1229 __decorate([
1230 bindable
1231 ], Repeat.prototype, "value", void 0);
1232 Repeat = Repeat_1 = __decorate([
1233 customAttribute('repeat'),
1234 templateController,
1235 inject(BoundViewFactory, TargetInstruction, ViewSlot, ViewResources, ObserverLocator, RepeatStrategyLocator)
1236 ], Repeat);
1237 return Repeat;
1238}(AbstractRepeater));
1239var extractMatcherBindingExpression = function (instructions, targetedElementId) {
1240 var instructionIds = Object.keys(instructions);
1241 for (var i = 0; i < instructionIds.length; i++) {
1242 var instructionId = instructionIds[i];
1243 if (targetedElementId !== undefined && instructionId !== targetedElementId) {
1244 continue;
1245 }
1246 var expressions = instructions[instructionId].expressions;
1247 if (expressions) {
1248 for (var ii = 0; ii < expressions.length; ii++) {
1249 if (expressions[ii].targetProperty === 'matcher') {
1250 var matcherBindingExpression = expressions[ii];
1251 expressions.splice(ii, 1);
1252 return matcherBindingExpression;
1253 }
1254 }
1255 }
1256 }
1257};
1258var getChildrenCount = function (el) {
1259 var childNodes = el.childNodes;
1260 var count = 0;
1261 for (var i = 0, ii = childNodes.length; ii > i; ++i) {
1262 if (childNodes[i].nodeType === 1) {
1263 ++count;
1264 }
1265 }
1266 return count;
1267};
1268var getFirstElementChild = function (el) {
1269 var firstChild = el.firstChild;
1270 while (firstChild !== null) {
1271 if (firstChild.nodeType === 1) {
1272 return firstChild;
1273 }
1274 firstChild = firstChild.nextSibling;
1275 }
1276 return null;
1277};
1278
1279var aureliaHideClassName = 'aurelia-hide';
1280var aureliaHideClass = ".".concat(aureliaHideClassName, " { display:none !important; }");
1281function injectAureliaHideStyleAtHead() {
1282 DOM.injectStyles(aureliaHideClass);
1283}
1284function injectAureliaHideStyleAtBoundary(domBoundary) {
1285 if (FEATURE.shadowDOM && domBoundary && !domBoundary.hasAureliaHideStyle) {
1286 domBoundary.hasAureliaHideStyle = true;
1287 DOM.injectStyles(aureliaHideClass, domBoundary);
1288 }
1289}
1290
1291var Show = (function () {
1292 function Show(element, animator, domBoundary) {
1293 this.element = element;
1294 this.animator = animator;
1295 this.domBoundary = domBoundary;
1296 }
1297 Show.inject = function () {
1298 return [DOM.Element, Animator, Optional.of(DOM.boundary, true)];
1299 };
1300 Show.prototype.created = function () {
1301 injectAureliaHideStyleAtBoundary(this.domBoundary);
1302 };
1303 Show.prototype.valueChanged = function (newValue) {
1304 var element = this.element;
1305 var animator = this.animator;
1306 if (newValue) {
1307 animator.removeClass(element, aureliaHideClassName);
1308 }
1309 else {
1310 animator.addClass(element, aureliaHideClassName);
1311 }
1312 };
1313 Show.prototype.bind = function (bindingContext) {
1314 this.valueChanged(this.value);
1315 };
1316 Show = __decorate([
1317 customAttribute('show')
1318 ], Show);
1319 return Show;
1320}());
1321
1322var Hide = (function () {
1323 function Hide(element, animator, domBoundary) {
1324 this.element = element;
1325 this.animator = animator;
1326 this.domBoundary = domBoundary;
1327 }
1328 Hide.inject = function () {
1329 return [DOM.Element, Animator, Optional.of(DOM.boundary, true)];
1330 };
1331 Hide.prototype.created = function () {
1332 injectAureliaHideStyleAtBoundary(this.domBoundary);
1333 };
1334 Hide.prototype.valueChanged = function (newValue) {
1335 if (newValue) {
1336 this.animator.addClass(this.element, aureliaHideClassName);
1337 }
1338 else {
1339 this.animator.removeClass(this.element, aureliaHideClassName);
1340 }
1341 };
1342 Hide.prototype.bind = function (bindingContext) {
1343 this.valueChanged(this.value);
1344 };
1345 Hide.prototype.value = function (value) {
1346 throw new Error('Method not implemented.');
1347 };
1348 Hide = __decorate([
1349 customAttribute('hide')
1350 ], Hide);
1351 return Hide;
1352}());
1353
1354var HTMLSanitizer = (function () {
1355 function HTMLSanitizer() {
1356 }
1357 HTMLSanitizer.prototype.sanitize = function (input) {
1358 throw new Error("To protect the application against a wide variety of sophisticated XSS attacks.\nPlease see https://aurelia.io/docs/binding/basics#element-content for instructions on how to use a secure solution like DOMPurify or sanitize-html.");
1359 };
1360 return HTMLSanitizer;
1361}());
1362
1363var SanitizeHTMLValueConverter = (function () {
1364 function SanitizeHTMLValueConverter(sanitizer) {
1365 this.sanitizer = sanitizer;
1366 }
1367 SanitizeHTMLValueConverter.prototype.toView = function (untrustedMarkup) {
1368 if (untrustedMarkup === null || untrustedMarkup === undefined) {
1369 return null;
1370 }
1371 return this.sanitizer.sanitize(untrustedMarkup);
1372 };
1373 SanitizeHTMLValueConverter = __decorate([
1374 valueConverter('sanitizeHTML'),
1375 inject(HTMLSanitizer)
1376 ], SanitizeHTMLValueConverter);
1377 return SanitizeHTMLValueConverter;
1378}());
1379
1380var Replaceable = (function () {
1381 function Replaceable(viewFactory, viewSlot) {
1382 this.viewFactory = viewFactory;
1383 this.viewSlot = viewSlot;
1384 this.view = null;
1385 }
1386 Replaceable.prototype.bind = function (bindingContext, overrideContext) {
1387 if (this.view === null) {
1388 this.view = this.viewFactory.create();
1389 this.viewSlot.add(this.view);
1390 }
1391 this.view.bind(bindingContext, overrideContext);
1392 };
1393 Replaceable.prototype.unbind = function () {
1394 this.view.unbind();
1395 };
1396 Replaceable = __decorate([
1397 customAttribute('replaceable'),
1398 templateController,
1399 inject(BoundViewFactory, ViewSlot)
1400 ], Replaceable);
1401 return Replaceable;
1402}());
1403
1404var Focus = (function () {
1405 function Focus(element, taskQueue) {
1406 this.element = element;
1407 this.taskQueue = taskQueue;
1408 this.isAttached = false;
1409 this.needsApply = false;
1410 }
1411 Focus.inject = function () {
1412 return [DOM.Element, TaskQueue];
1413 };
1414 Focus.prototype.valueChanged = function () {
1415 if (this.isAttached) {
1416 this._apply();
1417 }
1418 else {
1419 this.needsApply = true;
1420 }
1421 };
1422 Focus.prototype._apply = function () {
1423 var _this = this;
1424 if (this.value) {
1425 this.taskQueue.queueMicroTask(function () {
1426 if (_this.value) {
1427 _this.element.focus();
1428 }
1429 });
1430 }
1431 else {
1432 this.element.blur();
1433 }
1434 };
1435 Focus.prototype.attached = function () {
1436 this.isAttached = true;
1437 if (this.needsApply) {
1438 this.needsApply = false;
1439 this._apply();
1440 }
1441 this.element.addEventListener('focus', this);
1442 this.element.addEventListener('blur', this);
1443 };
1444 Focus.prototype.detached = function () {
1445 this.isAttached = false;
1446 this.element.removeEventListener('focus', this);
1447 this.element.removeEventListener('blur', this);
1448 };
1449 Focus.prototype.handleEvent = function (e) {
1450 if (e.type === 'focus') {
1451 this.value = true;
1452 }
1453 else if (DOM.activeElement !== this.element) {
1454 this.value = false;
1455 }
1456 };
1457 Focus = __decorate([
1458 customAttribute('focus', bindingMode.twoWay)
1459 ], Focus);
1460 return Focus;
1461}());
1462
1463var cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi;
1464function fixupCSSUrls(address, css) {
1465 if (typeof css !== 'string') {
1466 throw new Error("Failed loading required CSS file: ".concat(address));
1467 }
1468 return css.replace(cssUrlMatcher, function (match, p1) {
1469 var quote = p1.charAt(0);
1470 if (quote === '\'' || quote === '"') {
1471 p1 = p1.substr(1, p1.length - 2);
1472 }
1473 return 'url(\'' + relativeToFile(p1, address) + '\')';
1474 });
1475}
1476var CSSResource = (function () {
1477 function CSSResource(address) {
1478 this.address = address;
1479 this._scoped = null;
1480 this._global = false;
1481 this._alreadyGloballyInjected = false;
1482 }
1483 CSSResource.prototype.initialize = function (container, Target) {
1484 this._scoped = new Target(this);
1485 };
1486 CSSResource.prototype.register = function (registry, name) {
1487 if (name === 'scoped') {
1488 registry.registerViewEngineHooks(this._scoped);
1489 }
1490 else {
1491 this._global = true;
1492 }
1493 };
1494 CSSResource.prototype.load = function (container) {
1495 var _this = this;
1496 return container.get(Loader)
1497 .loadText(this.address)
1498 .catch(function () { return null; })
1499 .then(function (text) {
1500 text = fixupCSSUrls(_this.address, text);
1501 _this._scoped.css = text;
1502 if (_this._global) {
1503 _this._alreadyGloballyInjected = true;
1504 DOM.injectStyles(text);
1505 }
1506 return _this;
1507 });
1508 };
1509 return CSSResource;
1510}());
1511var CSSViewEngineHooks = (function () {
1512 function CSSViewEngineHooks(owner) {
1513 this.owner = owner;
1514 this.css = null;
1515 }
1516 CSSViewEngineHooks.prototype.beforeCompile = function (content, resources, instruction) {
1517 if (instruction.targetShadowDOM) {
1518 DOM.injectStyles(this.css, content, true);
1519 }
1520 else if (FEATURE.scopedCSS) {
1521 var styleNode = DOM.injectStyles(this.css, content, true);
1522 styleNode.setAttribute('scoped', 'scoped');
1523 }
1524 else if (this._global && !this.owner._alreadyGloballyInjected) {
1525 DOM.injectStyles(this.css);
1526 this.owner._alreadyGloballyInjected = true;
1527 }
1528 };
1529 return CSSViewEngineHooks;
1530}());
1531function _createCSSResource(address) {
1532 var ViewCSS = (function (_super) {
1533 __extends(ViewCSS, _super);
1534 function ViewCSS() {
1535 return _super !== null && _super.apply(this, arguments) || this;
1536 }
1537 ViewCSS = __decorate([
1538 resource(new CSSResource(address))
1539 ], ViewCSS);
1540 return ViewCSS;
1541 }(CSSViewEngineHooks));
1542 return ViewCSS;
1543}
1544
1545var AttrBindingBehavior = (function () {
1546 function AttrBindingBehavior() {
1547 }
1548 AttrBindingBehavior.prototype.bind = function (binding, source) {
1549 binding.targetObserver = new DataAttributeObserver(binding.target, binding.targetProperty);
1550 };
1551 AttrBindingBehavior.prototype.unbind = function (binding, source) {
1552 };
1553 AttrBindingBehavior = __decorate([
1554 bindingBehavior('attr')
1555 ], AttrBindingBehavior);
1556 return AttrBindingBehavior;
1557}());
1558
1559var modeBindingBehavior = {
1560 bind: function (binding, source, lookupFunctions) {
1561 binding.originalMode = binding.mode;
1562 binding.mode = this.mode;
1563 },
1564 unbind: function (binding, source) {
1565 binding.mode = binding.originalMode;
1566 binding.originalMode = null;
1567 }
1568};
1569var OneTimeBindingBehavior = (function () {
1570 function OneTimeBindingBehavior() {
1571 this.mode = bindingMode.oneTime;
1572 }
1573 OneTimeBindingBehavior = __decorate([
1574 mixin(modeBindingBehavior),
1575 bindingBehavior('oneTime')
1576 ], OneTimeBindingBehavior);
1577 return OneTimeBindingBehavior;
1578}());
1579var OneWayBindingBehavior = (function () {
1580 function OneWayBindingBehavior() {
1581 this.mode = bindingMode.toView;
1582 }
1583 OneWayBindingBehavior = __decorate([
1584 mixin(modeBindingBehavior),
1585 bindingBehavior('oneWay')
1586 ], OneWayBindingBehavior);
1587 return OneWayBindingBehavior;
1588}());
1589var ToViewBindingBehavior = (function () {
1590 function ToViewBindingBehavior() {
1591 this.mode = bindingMode.toView;
1592 }
1593 ToViewBindingBehavior = __decorate([
1594 mixin(modeBindingBehavior),
1595 bindingBehavior('toView')
1596 ], ToViewBindingBehavior);
1597 return ToViewBindingBehavior;
1598}());
1599var FromViewBindingBehavior = (function () {
1600 function FromViewBindingBehavior() {
1601 this.mode = bindingMode.fromView;
1602 }
1603 FromViewBindingBehavior = __decorate([
1604 mixin(modeBindingBehavior),
1605 bindingBehavior('fromView')
1606 ], FromViewBindingBehavior);
1607 return FromViewBindingBehavior;
1608}());
1609var TwoWayBindingBehavior = (function () {
1610 function TwoWayBindingBehavior() {
1611 this.mode = bindingMode.twoWay;
1612 }
1613 TwoWayBindingBehavior = __decorate([
1614 mixin(modeBindingBehavior),
1615 bindingBehavior('twoWay')
1616 ], TwoWayBindingBehavior);
1617 return TwoWayBindingBehavior;
1618}());
1619
1620function throttle(newValue) {
1621 var _this = this;
1622 var state = this.throttleState;
1623 var elapsed = +new Date() - state.last;
1624 if (elapsed >= state.delay) {
1625 clearTimeout(state.timeoutId);
1626 state.timeoutId = null;
1627 state.last = +new Date();
1628 this.throttledMethod(newValue);
1629 return;
1630 }
1631 state.newValue = newValue;
1632 if (state.timeoutId === null) {
1633 state.timeoutId = setTimeout(function () {
1634 state.timeoutId = null;
1635 state.last = +new Date();
1636 _this.throttledMethod(state.newValue);
1637 }, state.delay - elapsed);
1638 }
1639}
1640var ThrottleBindingBehavior = (function () {
1641 function ThrottleBindingBehavior() {
1642 }
1643 ThrottleBindingBehavior.prototype.bind = function (binding, source, delay) {
1644 if (delay === void 0) { delay = 200; }
1645 var methodToThrottle = 'updateTarget';
1646 if (binding.callSource) {
1647 methodToThrottle = 'callSource';
1648 }
1649 else if (binding.updateSource && binding.mode === bindingMode.twoWay) {
1650 methodToThrottle = 'updateSource';
1651 }
1652 binding.throttledMethod = binding[methodToThrottle];
1653 binding.throttledMethod.originalName = methodToThrottle;
1654 binding[methodToThrottle] = throttle;
1655 binding.throttleState = {
1656 delay: delay,
1657 last: 0,
1658 timeoutId: null
1659 };
1660 };
1661 ThrottleBindingBehavior.prototype.unbind = function (binding, source) {
1662 var methodToRestore = binding.throttledMethod.originalName;
1663 binding[methodToRestore] = binding.throttledMethod;
1664 binding.throttledMethod = null;
1665 clearTimeout(binding.throttleState.timeoutId);
1666 binding.throttleState = null;
1667 };
1668 ThrottleBindingBehavior = __decorate([
1669 bindingBehavior('throttle')
1670 ], ThrottleBindingBehavior);
1671 return ThrottleBindingBehavior;
1672}());
1673
1674var unset = {};
1675function debounceCallSource(event) {
1676 var _this = this;
1677 var state = this.debounceState;
1678 clearTimeout(state.timeoutId);
1679 state.timeoutId = setTimeout(function () { return _this.debouncedMethod(event); }, state.delay);
1680}
1681function debounceCall(context, newValue, oldValue) {
1682 var _this = this;
1683 var state = this.debounceState;
1684 clearTimeout(state.timeoutId);
1685 if (context !== state.callContextToDebounce) {
1686 state.oldValue = unset;
1687 this.debouncedMethod(context, newValue, oldValue);
1688 return;
1689 }
1690 if (state.oldValue === unset) {
1691 state.oldValue = oldValue;
1692 }
1693 state.timeoutId = setTimeout(function () {
1694 var _oldValue = state.oldValue;
1695 state.oldValue = unset;
1696 _this.debouncedMethod(context, newValue, _oldValue);
1697 }, state.delay);
1698}
1699var DebounceBindingBehavior = (function () {
1700 function DebounceBindingBehavior() {
1701 }
1702 DebounceBindingBehavior.prototype.bind = function (binding, source, delay) {
1703 if (delay === void 0) { delay = 200; }
1704 var isCallSource = binding.callSource !== undefined;
1705 var methodToDebounce = isCallSource ? 'callSource' : 'call';
1706 var debouncer = isCallSource ? debounceCallSource : debounceCall;
1707 var mode = binding.mode;
1708 var callContextToDebounce = mode === bindingMode.twoWay || mode === bindingMode.fromView ? targetContext : sourceContext;
1709 binding.debouncedMethod = binding[methodToDebounce];
1710 binding.debouncedMethod.originalName = methodToDebounce;
1711 binding[methodToDebounce] = debouncer;
1712 binding.debounceState = {
1713 callContextToDebounce: callContextToDebounce,
1714 delay: delay,
1715 timeoutId: 0,
1716 oldValue: unset
1717 };
1718 };
1719 DebounceBindingBehavior.prototype.unbind = function (binding, source) {
1720 var methodToRestore = binding.debouncedMethod.originalName;
1721 binding[methodToRestore] = binding.debouncedMethod;
1722 binding.debouncedMethod = null;
1723 clearTimeout(binding.debounceState.timeoutId);
1724 binding.debounceState = null;
1725 };
1726 DebounceBindingBehavior = __decorate([
1727 bindingBehavior('debounce')
1728 ], DebounceBindingBehavior);
1729 return DebounceBindingBehavior;
1730}());
1731
1732function findOriginalEventTarget(event) {
1733 return (event.path && event.path[0]) || (event.deepPath && event.deepPath[0]) || event.target;
1734}
1735function handleSelfEvent(event) {
1736 var target = findOriginalEventTarget(event);
1737 if (this.target !== target) {
1738 return;
1739 }
1740 this.selfEventCallSource(event);
1741}
1742var SelfBindingBehavior = (function () {
1743 function SelfBindingBehavior() {
1744 }
1745 SelfBindingBehavior.prototype.bind = function (binding, source) {
1746 if (!binding.callSource || !binding.targetEvent) {
1747 throw new Error('Self binding behavior only supports event.');
1748 }
1749 binding.selfEventCallSource = binding.callSource;
1750 binding.callSource = handleSelfEvent;
1751 };
1752 SelfBindingBehavior.prototype.unbind = function (binding, source) {
1753 binding.callSource = binding.selfEventCallSource;
1754 binding.selfEventCallSource = null;
1755 };
1756 SelfBindingBehavior = __decorate([
1757 bindingBehavior('self')
1758 ], SelfBindingBehavior);
1759 return SelfBindingBehavior;
1760}());
1761
1762var BindingSignaler = (function () {
1763 function BindingSignaler() {
1764 this.signals = {};
1765 }
1766 BindingSignaler.prototype.signal = function (name) {
1767 var bindings = this.signals[name];
1768 if (!bindings) {
1769 return;
1770 }
1771 var i = bindings.length;
1772 while (i--) {
1773 bindings[i].call(sourceContext);
1774 }
1775 };
1776 return BindingSignaler;
1777}());
1778
1779var SignalBindingBehavior = (function () {
1780 function SignalBindingBehavior(bindingSignaler) {
1781 this.signals = bindingSignaler.signals;
1782 }
1783 SignalBindingBehavior.inject = function () { return [BindingSignaler]; };
1784 SignalBindingBehavior.prototype.bind = function (binding, source) {
1785 var names = [];
1786 for (var _i = 2; _i < arguments.length; _i++) {
1787 names[_i - 2] = arguments[_i];
1788 }
1789 if (!binding.updateTarget) {
1790 throw new Error('Only property bindings and string interpolation bindings can be signaled. Trigger, delegate and call bindings cannot be signaled.');
1791 }
1792 var signals = this.signals;
1793 if (names.length === 1) {
1794 var name_1 = names[0];
1795 var bindings = signals[name_1] || (signals[name_1] = []);
1796 bindings.push(binding);
1797 binding.signalName = name_1;
1798 }
1799 else if (names.length > 1) {
1800 var i = names.length;
1801 while (i--) {
1802 var name_2 = names[i];
1803 var bindings = signals[name_2] || (signals[name_2] = []);
1804 bindings.push(binding);
1805 }
1806 binding.signalName = names;
1807 }
1808 else {
1809 throw new Error('Signal name is required.');
1810 }
1811 };
1812 SignalBindingBehavior.prototype.unbind = function (binding, source) {
1813 var signals = this.signals;
1814 var name = binding.signalName;
1815 binding.signalName = null;
1816 if (Array.isArray(name)) {
1817 var names = name;
1818 var i = names.length;
1819 while (i--) {
1820 var n = names[i];
1821 var bindings = signals[n];
1822 bindings.splice(bindings.indexOf(binding), 1);
1823 }
1824 }
1825 else {
1826 var bindings = signals[name];
1827 bindings.splice(bindings.indexOf(binding), 1);
1828 }
1829 };
1830 SignalBindingBehavior = __decorate([
1831 bindingBehavior('signal')
1832 ], SignalBindingBehavior);
1833 return SignalBindingBehavior;
1834}());
1835
1836var eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">';
1837var notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way/ from-view bindings on input/select elements.';
1838var UpdateTriggerBindingBehavior = (function () {
1839 function UpdateTriggerBindingBehavior() {
1840 }
1841 UpdateTriggerBindingBehavior.prototype.bind = function (binding, source) {
1842 var events = [];
1843 for (var _i = 2; _i < arguments.length; _i++) {
1844 events[_i - 2] = arguments[_i];
1845 }
1846 if (events.length === 0) {
1847 throw new Error(eventNamesRequired);
1848 }
1849 if (binding.mode !== bindingMode.twoWay && binding.mode !== bindingMode.fromView) {
1850 throw new Error(notApplicableMessage);
1851 }
1852 var targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty);
1853 if (!targetObserver.handler) {
1854 throw new Error(notApplicableMessage);
1855 }
1856 binding.targetObserver = targetObserver;
1857 targetObserver.originalHandler = binding.targetObserver.handler;
1858 var handler = new EventSubscriber(events);
1859 targetObserver.handler = handler;
1860 };
1861 UpdateTriggerBindingBehavior.prototype.unbind = function (binding, source) {
1862 var targetObserver = binding.targetObserver;
1863 targetObserver.handler.dispose();
1864 targetObserver.handler = targetObserver.originalHandler;
1865 targetObserver.originalHandler = null;
1866 };
1867 UpdateTriggerBindingBehavior = __decorate([
1868 bindingBehavior('updateTrigger')
1869 ], UpdateTriggerBindingBehavior);
1870 return UpdateTriggerBindingBehavior;
1871}());
1872
1873function _createDynamicElement(_a) {
1874 var name = _a.name, viewUrl = _a.viewUrl, bindableNames = _a.bindableNames, useShadowDOMmode = _a.useShadowDOMmode;
1875 var DynamicElement = (function () {
1876 function DynamicElement() {
1877 }
1878 DynamicElement.prototype.bind = function (bindingContext) {
1879 this.$parent = bindingContext;
1880 };
1881 DynamicElement = __decorate([
1882 customElement(name),
1883 useView(viewUrl)
1884 ], DynamicElement);
1885 return DynamicElement;
1886 }());
1887 for (var i = 0, ii = bindableNames.length; i < ii; ++i) {
1888 bindable(bindableNames[i])(DynamicElement);
1889 }
1890 switch (useShadowDOMmode) {
1891 case 'open':
1892 useShadowDOM({ mode: 'open' })(DynamicElement);
1893 break;
1894 case 'closed':
1895 useShadowDOM({ mode: 'closed' })(DynamicElement);
1896 break;
1897 case '':
1898 useShadowDOM(DynamicElement);
1899 break;
1900 case null:
1901 break;
1902 default:
1903 getLogger('aurelia-html-only-element')
1904 .warn("Expected 'use-shadow-dom' value to be \"close\", \"open\" or \"\", received ".concat(useShadowDOMmode));
1905 break;
1906 }
1907 return DynamicElement;
1908}
1909
1910function getElementName(address) {
1911 return /([^\/^\?]+)\.html/i.exec(address)[1].toLowerCase();
1912}
1913function configure$1(config) {
1914 var viewEngine = config.container.get(ViewEngine);
1915 var loader = config.aurelia.loader;
1916 viewEngine.addResourcePlugin('.html', {
1917 'fetch': function (viewUrl) {
1918 return loader.loadTemplate(viewUrl).then(function (registryEntry) {
1919 var _a;
1920 var bindableNames = registryEntry.template.getAttribute('bindable');
1921 var useShadowDOMmode = registryEntry.template.getAttribute('use-shadow-dom');
1922 var name = getElementName(viewUrl);
1923 if (bindableNames) {
1924 bindableNames = bindableNames.split(',').map(function (x) { return x.trim(); });
1925 registryEntry.template.removeAttribute('bindable');
1926 }
1927 else {
1928 bindableNames = [];
1929 }
1930 return _a = {}, _a[name] = _createDynamicElement({ name: name, viewUrl: viewUrl, bindableNames: bindableNames, useShadowDOMmode: useShadowDOMmode }), _a;
1931 });
1932 }
1933 });
1934}
1935
1936function configure(config) {
1937 injectAureliaHideStyleAtHead();
1938 config.globalResources(Compose, If, Else, With, Repeat, Show, Hide, Replaceable, Focus, SanitizeHTMLValueConverter, OneTimeBindingBehavior, OneWayBindingBehavior, ToViewBindingBehavior, FromViewBindingBehavior, TwoWayBindingBehavior, ThrottleBindingBehavior, DebounceBindingBehavior, SelfBindingBehavior, SignalBindingBehavior, UpdateTriggerBindingBehavior, AttrBindingBehavior);
1939 configure$1(config);
1940 var viewEngine = config.container.get(ViewEngine);
1941 var styleResourcePlugin = {
1942 fetch: function (address) {
1943 var _a;
1944 return _a = {}, _a[address] = _createCSSResource(address), _a;
1945 }
1946 };
1947 ['.css', '.less', '.sass', '.scss', '.styl'].forEach(function (ext) { return viewEngine.addResourcePlugin(ext, styleResourcePlugin); });
1948}
1949
1950export { AbstractRepeater, ArrayRepeatStrategy, AttrBindingBehavior, BindingSignaler, Compose, DebounceBindingBehavior, Else, Focus, FromViewBindingBehavior, HTMLSanitizer, Hide, If, MapRepeatStrategy, NullRepeatStrategy, NumberRepeatStrategy, OneTimeBindingBehavior, OneWayBindingBehavior, Repeat, RepeatStrategyLocator, Replaceable, SanitizeHTMLValueConverter, SelfBindingBehavior, SetRepeatStrategy, Show, SignalBindingBehavior, ThrottleBindingBehavior, ToViewBindingBehavior, TwoWayBindingBehavior, UpdateTriggerBindingBehavior, With, configure, createFullOverrideContext, getItemsSourceExpression, isOneTime, unwrapExpression, updateOneTimeBinding, updateOverrideContext, viewsRequireLifecycle };
1951//# sourceMappingURL=aurelia-templating-resources.js.map