UNPKG

2.92 kBPlain TextView Raw
1import {createFullOverrideContext, updateOverrideContexts} from './repeat-utilities';
2
3/**
4 * A strategy for repeating a template over a Set.
5 */
6export class SetRepeatStrategy {
7 /**
8 * Gets a Set observer.
9 * @param items The items to be observed.
10 */
11 getCollectionObserver(observerLocator, items) {
12 return observerLocator.getSetObserver(items);
13 }
14
15 /**
16 * Process the provided Set entries.
17 * @param items The entries to process.
18 */
19 instanceChanged(repeat, items) {
20 let removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
21 if (removePromise instanceof Promise) {
22 removePromise.then(() => this._standardProcessItems(repeat, items));
23 return;
24 }
25 this._standardProcessItems(repeat, items);
26 }
27
28 /**
29 * @internal
30 */
31 _standardProcessItems(repeat, items) {
32 let index = 0;
33 let overrideContext;
34
35 items.forEach(value => {
36 overrideContext = createFullOverrideContext(repeat, value, index, items.size);
37 repeat.addView(overrideContext.bindingContext, overrideContext);
38 ++index;
39 });
40 }
41
42 /**
43 * Handle changes in a Set collection.
44 * @param repeat The repeat instance.
45 * @param set The underlying Set collection.
46 * @param records The change records.
47 */
48 instanceMutated(repeat, set, records) {
49 let value;
50 let i;
51 let ii;
52 let overrideContext;
53 let removeIndex;
54 let record;
55 let rmPromises = [];
56 let viewOrPromise;
57
58 for (i = 0, ii = records.length; i < ii; ++i) {
59 record = records[i];
60 value = record.value;
61 switch (record.type) {
62 case 'add':
63 let size = Math.max(set.size - 1, 0);
64 overrideContext = createFullOverrideContext(repeat, value, size, set.size);
65 repeat.insertView(size, overrideContext.bindingContext, overrideContext);
66 break;
67 case 'delete':
68 removeIndex = this._getViewIndexByValue(repeat, value);
69 viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
70 if (viewOrPromise instanceof Promise) {
71 rmPromises.push(viewOrPromise);
72 }
73 break;
74 case 'clear':
75 repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
76 break;
77 default:
78 continue;
79 }
80 }
81
82 if (rmPromises.length > 0) {
83 Promise.all(rmPromises).then(() => {
84 updateOverrideContexts(repeat.views(), 0);
85 });
86 } else {
87 updateOverrideContexts(repeat.views(), 0);
88 }
89 }
90
91 /**
92 * @internal
93 */
94 _getViewIndexByValue(repeat, value) {
95 let i;
96 let ii;
97 let child;
98
99 for (i = 0, ii = repeat.viewCount(); i < ii; ++i) {
100 child = repeat.view(i);
101 if (child.bindingContext[repeat.local] === value) {
102 return i;
103 }
104 }
105
106 return undefined;
107 }
108}