-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
aurelia-templating-resources.js
2389 lines (2110 loc) · 68.1 KB
/
aurelia-templating-resources.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {inject,Container,Optional} from 'aurelia-dependency-injection';
import {BoundViewFactory,ViewSlot,customAttribute,templateController,useView,customElement,bindable,useShadowDOM,ViewResources,resource,ViewCompileInstruction,CompositionEngine,CompositionContext,noView,View,ViewEngine,Animator,TargetInstruction} from 'aurelia-templating';
import {createOverrideContext,bindingMode,EventSubscriber,bindingBehavior,BindingBehavior,ValueConverter,sourceContext,targetContext,DataAttributeObserver,mergeSplice,valueConverter,ObserverLocator} from 'aurelia-binding';
import {getLogger} from 'aurelia-logging';
import {TaskQueue} from 'aurelia-task-queue';
import {DOM,FEATURE} from 'aurelia-pal';
import {Loader} from 'aurelia-loader';
import {relativeToFile} from 'aurelia-path';
import {mixin} from 'aurelia-metadata';
/**
* Creates a binding context for decandant elements to bind to.
*/
@customAttribute('with')
@templateController
@inject(BoundViewFactory, ViewSlot)
export class With {
/**
* Creates an instance of With.
* @param viewFactory The factory generating the view.
* @param viewSlot The slot the view is injected in to.
*/
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.parentOverrideContext = null;
this.view = null;
}
/**
* Binds the With with provided binding context and override context.
* @param bindingContext The binding context.
* @param overrideContext An override context for binding.
*/
bind(bindingContext, overrideContext) {
this.parentOverrideContext = overrideContext;
this.valueChanged(this.value);
}
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue) {
let overrideContext = createOverrideContext(newValue, this.parentOverrideContext);
if (!this.view) {
this.view = this.viewFactory.create();
this.view.bind(newValue, overrideContext);
this.viewSlot.add(this.view);
} else {
this.view.bind(newValue, overrideContext);
}
}
/**
* Unbinds With
*/
unbind() {
this.parentOverrideContext = null;
if (this.view) {
this.view.unbind();
}
}
}
const eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">';
const notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way/ from-view bindings on input/select elements.';
@bindingBehavior('updateTrigger')
export class UpdateTriggerBindingBehavior {
bind(binding, source, ...events) {
if (events.length === 0) {
throw new Error(eventNamesRequired);
}
if (binding.mode !== bindingMode.twoWay && binding.mode !== bindingMode.fromView) {
throw new Error(notApplicableMessage);
}
// ensure the binding's target observer has been set.
let targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty);
if (!targetObserver.handler) {
throw new Error(notApplicableMessage);
}
binding.targetObserver = targetObserver;
// stash the original element subscribe function.
targetObserver.originalHandler = binding.targetObserver.handler;
// replace the element subscribe function with one that uses the correct events.
let handler = new EventSubscriber(events);
targetObserver.handler = handler;
}
unbind(binding, source) {
// restore the state of the binding.
binding.targetObserver.handler.dispose();
binding.targetObserver.handler = binding.targetObserver.originalHandler;
binding.targetObserver.originalHandler = null;
}
}
function throttle(newValue) {
let state = this.throttleState;
let elapsed = +new Date() - state.last;
if (elapsed >= state.delay) {
clearTimeout(state.timeoutId);
state.timeoutId = null;
state.last = +new Date();
this.throttledMethod(newValue);
return;
}
state.newValue = newValue;
if (state.timeoutId === null) {
state.timeoutId = setTimeout(
() => {
state.timeoutId = null;
state.last = +new Date();
this.throttledMethod(state.newValue);
},
state.delay - elapsed);
}
}
@bindingBehavior('throttle')
export class ThrottleBindingBehavior {
bind(binding, source, delay = 200) {
// determine which method to throttle.
let methodToThrottle = 'updateTarget'; // one-way bindings or interpolation bindings
if (binding.callSource) {
methodToThrottle = 'callSource'; // listener and call bindings
} else if (binding.updateSource && binding.mode === bindingMode.twoWay) {
methodToThrottle = 'updateSource'; // two-way bindings
}
// stash the original method and it's name.
// note: a generic name like "originalMethod" is not used to avoid collisions
// with other binding behavior types.
binding.throttledMethod = binding[methodToThrottle];
binding.throttledMethod.originalName = methodToThrottle;
// replace the original method with the throttling version.
binding[methodToThrottle] = throttle;
// create the throttle state.
binding.throttleState = {
delay: delay,
last: 0,
timeoutId: null
};
}
unbind(binding, source) {
// restore the state of the binding.
let methodToRestore = binding.throttledMethod.originalName;
binding[methodToRestore] = binding.throttledMethod;
binding.throttledMethod = null;
clearTimeout(binding.throttleState.timeoutId);
binding.throttleState = null;
}
}
function findOriginalEventTarget(event) {
return (event.path && event.path[0]) || (event.deepPath && event.deepPath[0]) || event.target;
}
function handleSelfEvent(event) {
let target = findOriginalEventTarget(event);
if (this.target !== target) return;
this.selfEventCallSource(event);
}
@bindingBehavior('self')
export class SelfBindingBehavior {
bind(binding, source) {
if (!binding.callSource || !binding.targetEvent) throw new Error('Self binding behavior only supports event.');
binding.selfEventCallSource = binding.callSource;
binding.callSource = handleSelfEvent;
}
unbind(binding, source) {
binding.callSource = binding.selfEventCallSource;
binding.selfEventCallSource = null;
}
}
/**
* Marks any part of a view to be replacable by the consumer.
*/
@customAttribute('replaceable')
@templateController
@inject(BoundViewFactory, ViewSlot)
export class Replaceable {
/**
* @param viewFactory target The factory generating the view.
* @param viewSlot viewSlot The slot the view is injected in to.
*/
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory; //This is referenced internally in the Controller's bind method.
this.viewSlot = viewSlot;
this.view = null;
}
/**
* Binds the replaceable to the binding context and override context.
* @param bindingContext The binding context.
* @param overrideContext An override context for binding.
*/
bind(bindingContext, overrideContext) {
if (this.view === null) {
this.view = this.viewFactory.create();
this.viewSlot.add(this.view);
}
this.view.bind(bindingContext, overrideContext);
}
/**
* Unbinds the replaceable.
*/
unbind() {
this.view.unbind();
}
}
const oneTime = bindingMode.oneTime;
/**
* Update the override context.
* @param startIndex index in collection where to start updating.
*/
export function updateOverrideContexts(views, startIndex) {
let length = views.length;
if (startIndex > 0) {
startIndex = startIndex - 1;
}
for (; startIndex < length; ++startIndex) {
updateOverrideContext(views[startIndex].overrideContext, startIndex, length);
}
}
/**
* Creates a complete override context.
* @param data The item's value.
* @param index The item's index.
* @param length The collections total length.
* @param key The key in a key/value pair.
*/
export function createFullOverrideContext(repeat, data, index, length, key) {
let bindingContext = {};
let overrideContext = createOverrideContext(bindingContext, repeat.scope.overrideContext);
// is key/value pair (Map)
if (typeof key !== 'undefined') {
bindingContext[repeat.key] = key;
bindingContext[repeat.value] = data;
} else {
bindingContext[repeat.local] = data;
}
updateOverrideContext(overrideContext, index, length);
return overrideContext;
}
/**
* Updates the override context.
* @param context The context to be updated.
* @param index The context's index.
* @param length The collection's length.
*/
export function updateOverrideContext(overrideContext, index, length) {
let first = (index === 0);
let last = (index === length - 1);
let even = index % 2 === 0;
overrideContext.$index = index;
overrideContext.$first = first;
overrideContext.$last = last;
overrideContext.$middle = !(first || last);
overrideContext.$odd = !even;
overrideContext.$even = even;
}
/**
* Gets a repeat instruction's source expression.
*/
export function getItemsSourceExpression(instruction, attrName) {
return instruction.behaviorInstructions
.filter(bi => bi.originalAttrName === attrName)[0]
.attributes
.items
.sourceExpression;
}
/**
* Unwraps an expression to expose the inner, pre-converted / behavior-free expression.
*/
export function unwrapExpression(expression) {
let unwrapped = false;
while (expression instanceof BindingBehavior) {
expression = expression.expression;
}
while (expression instanceof ValueConverter) {
expression = expression.expression;
unwrapped = true;
}
return unwrapped ? expression : null;
}
/**
* Returns whether an expression has the OneTimeBindingBehavior applied.
*/
export function isOneTime(expression) {
while (expression instanceof BindingBehavior) {
if (expression.name === 'oneTime') {
return true;
}
expression = expression.expression;
}
return false;
}
/**
* Forces a binding instance to reevaluate.
*/
export function updateOneTimeBinding(binding) {
if (binding.call && binding.mode === oneTime) {
binding.call(sourceContext);
} else if (binding.updateOneTimeBindings) {
binding.updateOneTimeBindings();
}
}
/**
* Returns the index of the element in an array, optionally using a matcher function.
*/
export function indexOf(array, item, matcher, startIndex) {
if (!matcher) {
// native indexOf is more performant than a for loop
return array.indexOf(item);
}
const length = array.length;
for (let index = startIndex || 0; index < length; index++) {
if (matcher(array[index], item)) {
return index;
}
}
return -1;
}
/**
* A strategy for repeating a template over null or undefined (does nothing)
*/
export class NullRepeatStrategy {
instanceChanged(repeat, items) {
repeat.removeAllViews(true);
}
getCollectionObserver(observerLocator, items) {
}
}
/**
* For internal use only. May change without warning.
*/
export class IfCore {
constructor(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.view = null;
this.bindingContext = null;
this.overrideContext = null;
// If the child view is animated, `value` might not reflect the internal
// state anymore, so we use `showing` for that.
// Eventually, `showing` and `value` should be consistent.
this.showing = false;
this.cache = true;
}
bind(bindingContext, overrideContext) {
// Store parent bindingContext, so we can pass it down
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
}
unbind() {
if (this.view === null) {
return;
}
this.view.unbind();
// It seems to me that this code is subject to race conditions when animating.
// For example a view could be returned to the cache and reused while it's still
// attached to the DOM and animated.
if (!this.viewFactory.isCaching) {
return;
}
if (this.showing) {
this.showing = false;
this.viewSlot.remove(this.view, /*returnToCache:*/true, /*skipAnimation:*/true);
} else {
this.view.returnToCache();
}
this.view = null;
}
_show() {
if (this.showing) {
// Ensures the view is bound.
// It might not be the case when the if was unbound but not detached, then rebound.
// Typical case where this happens is nested ifs
if (!this.view.isBound) {
this.view.bind(this.bindingContext, this.overrideContext);
}
return;
}
if (this.view === null) {
this.view = this.viewFactory.create();
}
if (!this.view.isBound) {
this.view.bind(this.bindingContext, this.overrideContext);
}
this.showing = true;
return this.viewSlot.add(this.view); // Promise or void
}
_hide() {
if (!this.showing) {
return;
}
this.showing = false;
let removed = this.viewSlot.remove(this.view); // Promise or View
if (removed instanceof Promise) {
return removed.then(() => {
this._unbindView();
});
}
this._unbindView();
}
_unbindView() {
const cache = this.cache === 'false' ? false : !!this.cache;
this.view.unbind();
if (!cache) {
this.view = null;
}
}
}
const SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
let needsToWarn = true;
/**
* Default Html Sanitizer to prevent script injection.
*/
export class HTMLSanitizer {
/**
* Sanitizes the provided input.
* @param input The input to be sanitized.
*/
sanitize(input) {
if (needsToWarn) {
needsToWarn = false;
getLogger('html-sanitizer')
.warn(`CAUTION: The default HTMLSanitizer does NOT provide security against a wide variety of sophisticated XSS attacks,
and should not be relied on for sanitizing input from unknown sources.
Please see https://aurelia.io/docs/binding/basics#element-content for instructions on how to use a secure solution like DOMPurify or sanitize-html.`);
}
return input.replace(SCRIPT_REGEX, '');
}
}
/**
* CustomAttribute that binds provided DOM element's focus attribute with a property on the viewmodel.
*/
@customAttribute('focus', bindingMode.twoWay)
export class Focus {
static inject() {
return [DOM.Element, TaskQueue];
}
/**
* Creates an instance of Focus.
* @paramelement Target element on where attribute is placed on.
* @param taskQueue The TaskQueue instance.
*/
constructor(element, taskQueue) {
this.element = element;
this.taskQueue = taskQueue;
this.isAttached = false;
this.needsApply = false;
}
/**
* Invoked everytime the bound value changes.
* @param newValue The new value.
*/
valueChanged(newValue) {
if (this.isAttached) {
this._apply();
} else {
this.needsApply = true;
}
}
_apply() {
if (this.value) {
this.taskQueue.queueMicroTask(() => {
if (this.value) {
this.element.focus();
}
});
} else {
this.element.blur();
}
}
/**
* Invoked when the attribute is attached to the DOM.
*/
attached() {
this.isAttached = true;
if (this.needsApply) {
this.needsApply = false;
this._apply();
}
this.element.addEventListener('focus', this);
this.element.addEventListener('blur', this);
}
/**
* Invoked when the attribute is detached from the DOM.
*/
detached() {
this.isAttached = false;
this.element.removeEventListener('focus', this);
this.element.removeEventListener('blur', this);
}
handleEvent(e) {
if (e.type === 'focus') {
this.value = true;
} else if (DOM.activeElement !== this.element) {
this.value = false;
}
}
}
/*eslint padded-blocks:0*/
export function _createDynamicElement({ name, viewUrl, bindableNames, useShadowDOMmode } : {
name: string,
viewUrl: string,
bindableNames: string[],
useShadowDOMmode: null | '' | 'open' | 'closed'
}): Function {
@customElement(name)
@useView(viewUrl)
class DynamicElement {
bind(bindingContext) {
this.$parent = bindingContext;
}
}
for (let i = 0, ii = bindableNames.length; i < ii; ++i) {
bindable(bindableNames[i])(DynamicElement);
}
switch (useShadowDOMmode) {
case 'open':
useShadowDOM({ mode: 'open' })(DynamicElement);
break;
case 'closed':
useShadowDOM({ mode: 'closed' })(DynamicElement);
break;
case '':
useShadowDOM(DynamicElement);
break;
case null:
// Do not use shadow dom
break;
default:
getLogger('aurelia-html-only-element')
.warn(`Expected 'use-shadow-dom' value to be "close", "open" or "", received ${useShadowDOMmode}`);
break;
}
return DynamicElement;
}
const unset = {};
function debounceCallSource(event) {
const state = this.debounceState;
clearTimeout(state.timeoutId);
state.timeoutId = setTimeout(() => this.debouncedMethod(event), state.delay);
}
function debounceCall(context, newValue, oldValue) {
const state = this.debounceState;
clearTimeout(state.timeoutId);
if (context !== state.callContextToDebounce) {
state.oldValue = unset;
this.debouncedMethod(context, newValue, oldValue);
return;
}
if (state.oldValue === unset) {
state.oldValue = oldValue;
}
state.timeoutId = setTimeout(() => {
const _oldValue = state.oldValue;
state.oldValue = unset;
this.debouncedMethod(context, newValue, _oldValue);
}, state.delay);
}
@bindingBehavior('debounce')
export class DebounceBindingBehavior {
bind(binding, source, delay = 200) {
const isCallSource = binding.callSource !== undefined;
const methodToDebounce = isCallSource ? 'callSource' : 'call';
const debouncer = isCallSource ? debounceCallSource : debounceCall;
const mode = binding.mode;
const callContextToDebounce = mode === bindingMode.twoWay || mode === bindingMode.fromView ? targetContext : sourceContext;
// stash the original method and it's name.
// note: a generic name like "originalMethod" is not used to avoid collisions
// with other binding behavior types.
binding.debouncedMethod = binding[methodToDebounce];
binding.debouncedMethod.originalName = methodToDebounce;
// replace the original method with the debouncing version.
binding[methodToDebounce] = debouncer;
// create the debounce state.
binding.debounceState = {
callContextToDebounce,
delay,
timeoutId: 0,
oldValue: unset
};
}
unbind(binding, source) {
// restore the state of the binding.
const methodToRestore = binding.debouncedMethod.originalName;
binding[methodToRestore] = binding.debouncedMethod;
binding.debouncedMethod = null;
clearTimeout(binding.debounceState.timeoutId);
binding.debounceState = null;
}
}
/*eslint new-cap:0, padded-blocks:0*/
let cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi;
function fixupCSSUrls(address, css) {
if (typeof css !== 'string') {
throw new Error(`Failed loading required CSS file: ${address}`);
}
return css.replace(cssUrlMatcher, (match, p1) => {
let quote = p1.charAt(0);
if (quote === '\'' || quote === '"') {
p1 = p1.substr(1, p1.length - 2);
}
return 'url(\'' + relativeToFile(p1, address) + '\')';
});
}
class CSSResource {
constructor(address: string) {
this.address = address;
this._scoped = null;
this._global = false;
this._alreadyGloballyInjected = false;
}
initialize(container: Container, target: Function): void {
this._scoped = new target(this);
}
register(registry: ViewResources, name?: string): void {
if (name === 'scoped') {
registry.registerViewEngineHooks(this._scoped);
} else {
this._global = true;
}
}
load(container: Container): Promise<CSSResource> {
return container.get(Loader)
.loadText(this.address)
.catch(err => null)
.then(text => {
text = fixupCSSUrls(this.address, text);
this._scoped.css = text;
if (this._global) {
this._alreadyGloballyInjected = true;
DOM.injectStyles(text);
}
});
}
}
class CSSViewEngineHooks {
constructor(owner: CSSResource) {
this.owner = owner;
this.css = null;
}
beforeCompile(content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction): void {
if (instruction.targetShadowDOM) {
DOM.injectStyles(this.css, content, true);
} else if (FEATURE.scopedCSS) {
let styleNode = DOM.injectStyles(this.css, content, true);
styleNode.setAttribute('scoped', 'scoped');
} else if (this._global && !this.owner._alreadyGloballyInjected) {
DOM.injectStyles(this.css);
this.owner._alreadyGloballyInjected = true;
}
}
}
export function _createCSSResource(address: string): Function {
@resource(new CSSResource(address))
class ViewCSS extends CSSViewEngineHooks {}
return ViewCSS;
}
/**
* Used to compose a new view / view-model template or bind to an existing instance.
*/
@customElement('compose')
@noView
export class Compose {
static inject() {
return [DOM.Element, Container, CompositionEngine, ViewSlot, ViewResources, TaskQueue];
}
/**
* Model to bind the custom element to.
*
* @property model
* @type {CustomElement}
*/
@bindable model;
/**
* View to bind the custom element to.
*
* @property view
* @type {HtmlElement}
*/
@bindable view;
/**
* View-model to bind the custom element's template to.
*
* @property viewModel
* @type {Class}
*/
@bindable viewModel;
/**
* SwapOrder to control the swapping order of the custom element's view.
*
* @property view
* @type {String}
*/
@bindable swapOrder;
/**
* Creates an instance of Compose.
* @param element The Compose element.
* @param container The dependency injection container instance.
* @param compositionEngine CompositionEngine instance to compose the element.
* @param viewSlot The slot the view is injected in to.
* @param viewResources Collection of resources used to compile the the view.
* @param taskQueue The TaskQueue instance.
*/
constructor(element, container, compositionEngine, viewSlot, viewResources, taskQueue) {
this.element = element;
this.container = container;
this.compositionEngine = compositionEngine;
this.viewSlot = viewSlot;
this.viewResources = viewResources;
this.taskQueue = taskQueue;
this.currentController = null;
this.currentViewModel = null;
this.changes = Object.create(null);
}
/**
* Invoked when the component has been created.
*
* @param owningView The view that this component was created inside of.
*/
created(owningView: View) {
this.owningView = owningView;
}
/**
* Used to set the bindingContext.
*
* @param bindingContext The context in which the view model is executed in.
* @param overrideContext The context in which the view model is executed in.
*/
bind(bindingContext, overrideContext) {
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
this.changes.view = this.view;
this.changes.viewModel = this.viewModel;
this.changes.model = this.model;
if (!this.pendingTask) {
processChanges(this);
}
}
/**
* Unbinds the Compose.
*/
unbind() {
this.changes = Object.create(null);
this.bindingContext = null;
this.overrideContext = null;
let returnToCache = true;
let skipAnimation = true;
this.viewSlot.removeAll(returnToCache, skipAnimation);
}
/**
* Invoked everytime the bound model changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
modelChanged(newValue, oldValue) {
this.changes.model = newValue;
requestUpdate(this);
}
/**
* Invoked everytime the bound view changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
viewChanged(newValue, oldValue) {
this.changes.view = newValue;
requestUpdate(this);
}
/**
* Invoked everytime the bound view model changes.
* @param newValue The new value.
* @param oldValue The old value.
*/
viewModelChanged(newValue, oldValue) {
this.changes.viewModel = newValue;
requestUpdate(this);
}
}
function isEmpty(obj) {
for (const key in obj) {
return false;
}
return true;
}
function tryActivateViewModel(vm, model) {
if (vm && typeof vm.activate === 'function') {
return Promise.resolve(vm.activate(model));
}
}
function createInstruction(composer: Compose, instruction: CompositionContext): CompositionContext {
return Object.assign(instruction, {
bindingContext: composer.bindingContext,
overrideContext: composer.overrideContext,
owningView: composer.owningView,
container: composer.container,
viewSlot: composer.viewSlot,
viewResources: composer.viewResources,
currentController: composer.currentController,
host: composer.element,
swapOrder: composer.swapOrder
});
}
function processChanges(composer: Compose) {
const changes = composer.changes;
composer.changes = Object.create(null);
if (!('view' in changes) && !('viewModel' in changes) && ('model' in changes)) {
// just try to activate the current view model
composer.pendingTask = tryActivateViewModel(composer.currentViewModel, changes.model);
if (!composer.pendingTask) { return; }
} else {
// init context
let instruction = {
view: composer.view,
viewModel: composer.currentViewModel || composer.viewModel,
model: composer.model
};
// apply changes
instruction = Object.assign(instruction, changes);
// create context
instruction = createInstruction(composer, instruction);
composer.pendingTask = composer.compositionEngine.compose(instruction).then(controller => {
composer.currentController = controller;
composer.currentViewModel = controller ? controller.viewModel : null;
});
}
composer.pendingTask = composer.pendingTask
.then(() => {
completeCompositionTask(composer);
}, reason => {
completeCompositionTask(composer);
throw reason;
});
}
function completeCompositionTask(composer) {
composer.pendingTask = null;
if (!isEmpty(composer.changes)) {
processChanges(composer);
}
}
function requestUpdate(composer: Compose) {
if (composer.pendingTask || composer.updateRequested) { return; }
composer.updateRequested = true;
composer.taskQueue.queueMicroTask(() => {
composer.updateRequested = false;
processChanges(composer);
});
}
export class BindingSignaler {
signals = {};
signal(name: string): void {
let bindings = this.signals[name];
if (!bindings) {
return;
}
let i = bindings.length;
while (i--) {
bindings[i].call(sourceContext);
}
}
}
let modeBindingBehavior = {
bind(binding, source, lookupFunctions) {
binding.originalMode = binding.mode;
binding.mode = this.mode;
},
unbind(binding, source) {
binding.mode = binding.originalMode;
binding.originalMode = null;
}
};
@mixin(modeBindingBehavior)
@bindingBehavior('oneTime')
export class OneTimeBindingBehavior {
constructor() {
this.mode = bindingMode.oneTime;
}
}
@mixin(modeBindingBehavior)
@bindingBehavior('oneWay')
export class OneWayBindingBehavior {
constructor() {
this.mode = bindingMode.toView;
}
}
@mixin(modeBindingBehavior)
@bindingBehavior('toView')
export class ToViewBindingBehavior {