ng-virtual-list 16.4.2 → 16.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +35 -2
  2. package/esm2020/lib/components/ng-virtual-list-item.component.mjs +131 -0
  3. package/esm2020/lib/const/index.mjs +44 -0
  4. package/esm2020/lib/enums/direction.mjs +2 -0
  5. package/esm2020/lib/enums/directions.mjs +18 -0
  6. package/esm2020/lib/enums/index.mjs +4 -0
  7. package/esm2020/lib/enums/snapping-method.mjs +2 -0
  8. package/esm2020/lib/enums/snapping-methods.mjs +18 -0
  9. package/esm2020/lib/models/base-virtual-list-item-component.mjs +9 -0
  10. package/esm2020/lib/models/collection.model.mjs +3 -0
  11. package/esm2020/lib/models/component.model.mjs +2 -0
  12. package/esm2020/lib/models/index.mjs +2 -0
  13. package/esm2020/lib/models/item.model.mjs +2 -0
  14. package/esm2020/lib/models/render-collection.model.mjs +3 -0
  15. package/esm2020/lib/models/render-item-config.model.mjs +2 -0
  16. package/esm2020/lib/models/render-item.model.mjs +3 -0
  17. package/esm2020/lib/models/scroll-direction.model.mjs +2 -0
  18. package/esm2020/lib/models/scroll-event.model.mjs +2 -0
  19. package/esm2020/lib/models/sticky-map.model.mjs +2 -0
  20. package/esm2020/lib/ng-virtual-list.component.mjs +675 -0
  21. package/esm2020/lib/ng-virtual-list.module.mjs +20 -0
  22. package/esm2020/lib/types/id.mjs +2 -0
  23. package/esm2020/lib/types/index.mjs +2 -0
  24. package/esm2020/lib/types/rect.mjs +2 -0
  25. package/esm2020/lib/types/size.mjs +2 -0
  26. package/esm2020/lib/utils/browser.mjs +3 -0
  27. package/esm2020/lib/utils/buffer-interpolation.mjs +27 -0
  28. package/esm2020/lib/utils/cacheMap.mjs +167 -0
  29. package/esm2020/lib/utils/debounce.mjs +31 -0
  30. package/esm2020/lib/utils/disposableComponent.mjs +29 -0
  31. package/esm2020/lib/utils/eventEmitter.mjs +106 -0
  32. package/esm2020/lib/utils/index.mjs +5 -0
  33. package/esm2020/lib/utils/isDirection.mjs +15 -0
  34. package/esm2020/lib/utils/scrollEvent.mjs +42 -0
  35. package/esm2020/lib/utils/snapping-method.mjs +9 -0
  36. package/esm2020/lib/utils/toggleClassName.mjs +15 -0
  37. package/esm2020/lib/utils/trackBox.mjs +756 -0
  38. package/esm2020/lib/utils/tracker.mjs +143 -0
  39. package/esm2020/ng-virtual-list.mjs +5 -0
  40. package/esm2020/public-api.mjs +10 -0
  41. package/esm2022/lib/utils/tracker.mjs +18 -9
  42. package/fesm2015/ng-virtual-list.mjs +2232 -0
  43. package/fesm2015/ng-virtual-list.mjs.map +1 -0
  44. package/fesm2020/ng-virtual-list.mjs +2237 -0
  45. package/fesm2020/ng-virtual-list.mjs.map +1 -0
  46. package/fesm2022/ng-virtual-list.mjs +16 -8
  47. package/fesm2022/ng-virtual-list.mjs.map +1 -1
  48. package/lib/utils/disposableComponent.d.ts +15 -0
  49. package/lib/utils/tracker.d.ts +3 -7
  50. package/package.json +1 -1
@@ -0,0 +1,2232 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Component, ChangeDetectionStrategy, EventEmitter as EventEmitter$1, ViewContainerRef, ElementRef, ViewEncapsulation, ViewChild, Output, Input, NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
3
+ import * as i1 from '@angular/common';
4
+ import { CommonModule } from '@angular/common';
5
+ import { Subject, BehaviorSubject, takeUntil, tap, filter, map, combineLatest, distinctUntilChanged, switchMap, of } from 'rxjs';
6
+
7
+ /**
8
+ * Axis of the arrangement of virtual list elements.
9
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/enums/directions.ts
10
+ * @author Evgenii Grebennikov
11
+ * @email djonnyx@gmail.com
12
+ */
13
+ var Directions;
14
+ (function (Directions) {
15
+ /**
16
+ * Horizontal axis.
17
+ */
18
+ Directions["HORIZONTAL"] = "horizontal";
19
+ /**
20
+ * Vertical axis.
21
+ */
22
+ Directions["VERTICAL"] = "vertical";
23
+ })(Directions || (Directions = {}));
24
+
25
+ /**
26
+ * Snapping method.
27
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/enums/snapping-method.ts
28
+ * @author Evgenii Grebennikov
29
+ * @email djonnyx@gmail.com
30
+ */
31
+ var SnappingMethods;
32
+ (function (SnappingMethods) {
33
+ /**
34
+ * Normal group rendering.
35
+ */
36
+ SnappingMethods["NORMAL"] = "normal";
37
+ /**
38
+ * The group is rendered on a transparent background. List items below the group are not rendered.
39
+ */
40
+ SnappingMethods["ADVANCED"] = "advanced";
41
+ })(SnappingMethods || (SnappingMethods = {}));
42
+
43
+ const DEFAULT_ITEM_SIZE = 24;
44
+ const DEFAULT_BUFFER_SIZE = 2;
45
+ const DEFAULT_MAX_BUFFER_SIZE = 100;
46
+ const DEFAULT_LIST_SIZE = 400;
47
+ const DEFAULT_SNAP = false;
48
+ const DEFAULT_ENABLED_BUFFER_OPTIMIZATION = false;
49
+ const DEFAULT_DYNAMIC_SIZE = false;
50
+ const TRACK_BY_PROPERTY_NAME = 'id';
51
+ const DEFAULT_DIRECTION = Directions.VERTICAL;
52
+ const DISPLAY_OBJECTS_LENGTH_MESUREMENT_ERROR = 1;
53
+ const MAX_SCROLL_TO_ITERATIONS = 5;
54
+ const DEFAULT_SNAPPING_METHOD = SnappingMethods.NORMAL;
55
+ // presets
56
+ const BEHAVIOR_AUTO = 'auto';
57
+ const BEHAVIOR_INSTANT = 'instant';
58
+ const BEHAVIOR_SMOOTH = 'smooth';
59
+ const DISPLAY_BLOCK = 'block';
60
+ const DISPLAY_NONE = 'none';
61
+ const OPACITY_0 = '0';
62
+ const OPACITY_100 = '100';
63
+ const VISIBILITY_VISIBLE = 'visible';
64
+ const VISIBILITY_HIDDEN = 'hidden';
65
+ const SIZE_100_PERSENT = '100%';
66
+ const SIZE_AUTO = 'auto';
67
+ const POSITION_ABSOLUTE = 'absolute';
68
+ const POSITION_STICKY = 'sticky';
69
+ const TRANSLATE_3D = 'translate3d';
70
+ const ZEROS_TRANSLATE_3D = `${TRANSLATE_3D}(0,0,0)`;
71
+ const HIDDEN_ZINDEX = '-1';
72
+ const DEFAULT_ZINDEX = '0';
73
+ const TOP_PROP_NAME = 'top';
74
+ const LEFT_PROP_NAME = 'left';
75
+ const X_PROP_NAME = 'x';
76
+ const Y_PROP_NAME = 'y';
77
+ const WIDTH_PROP_NAME = 'width';
78
+ const HEIGHT_PROP_NAME = 'height';
79
+ const PX = 'px';
80
+ const SCROLL = 'scroll';
81
+ const SCROLL_END = 'scrollend';
82
+ const CLASS_LIST_VERTICAL = 'vertical';
83
+ const CLASS_LIST_HORIZONTAL = 'horizontal';
84
+
85
+ /**
86
+ * Virtual List Item Interface
87
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/models/base-virtual-list-item-component.ts
88
+ * @author Evgenii Grebennikov
89
+ * @email djonnyx@gmail.com
90
+ */
91
+ class BaseVirtualListItemComponent {
92
+ }
93
+
94
+ /**
95
+ * Virtual list item component
96
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/components/ng-virtual-list-item.component.ts
97
+ * @author Evgenii Grebennikov
98
+ * @email djonnyx@gmail.com
99
+ */
100
+ class NgVirtualListItemComponent extends BaseVirtualListItemComponent {
101
+ get id() {
102
+ return this._id;
103
+ }
104
+ set item(v) {
105
+ if (this.data === v) {
106
+ return;
107
+ }
108
+ this.data = v;
109
+ this.update();
110
+ this._cdr.detectChanges();
111
+ }
112
+ set regularLength(v) {
113
+ if (this._regularLength === v) {
114
+ return;
115
+ }
116
+ this._regularLength = v;
117
+ this.update();
118
+ this._cdr.detectChanges();
119
+ }
120
+ get item() {
121
+ return this.data;
122
+ }
123
+ get itemId() {
124
+ var _a;
125
+ return (_a = this.data) === null || _a === void 0 ? void 0 : _a.id;
126
+ }
127
+ set renderer(v) {
128
+ if (this.itemRenderer === v) {
129
+ return;
130
+ }
131
+ this.itemRenderer = v;
132
+ this._cdr.markForCheck();
133
+ }
134
+ get element() {
135
+ return this._elementRef.nativeElement;
136
+ }
137
+ constructor(_cdr, _elementRef) {
138
+ super();
139
+ this._cdr = _cdr;
140
+ this._elementRef = _elementRef;
141
+ this.regular = false;
142
+ this._regularLength = SIZE_100_PERSENT;
143
+ this._id = NgVirtualListItemComponent.__nextId = NgVirtualListItemComponent.__nextId === Number.MAX_SAFE_INTEGER
144
+ ? 0 : NgVirtualListItemComponent.__nextId + 1;
145
+ }
146
+ update() {
147
+ const data = this.data, regular = this.regular, length = this._regularLength;
148
+ if (data) {
149
+ const styles = this._elementRef.nativeElement.style;
150
+ styles.zIndex = data.config.zIndex;
151
+ if (data.config.snapped) {
152
+ styles.transform = data.config.sticky === 1 ? ZEROS_TRANSLATE_3D : `${TRANSLATE_3D}(${data.config.isVertical ? 0 : data.measures.x}${PX}, ${data.config.isVertical ? data.measures.y : 0}${PX} , 0)`;
153
+ ;
154
+ if (!data.config.isSnappingMethodAdvanced) {
155
+ styles.position = POSITION_STICKY;
156
+ }
157
+ }
158
+ else {
159
+ styles.position = POSITION_ABSOLUTE;
160
+ if (regular) {
161
+ styles.transform = `${TRANSLATE_3D}(${data.config.isVertical ? 0 : data.measures.delta}${PX}, ${data.config.isVertical ? data.measures.delta : 0}${PX} , 0)`;
162
+ }
163
+ else {
164
+ styles.transform = `${TRANSLATE_3D}(${data.config.isVertical ? 0 : data.measures.x}${PX}, ${data.config.isVertical ? data.measures.y : 0}${PX} , 0)`;
165
+ }
166
+ }
167
+ styles.height = data.config.isVertical ? data.config.dynamic ? SIZE_AUTO : `${data.measures.height}${PX}` : regular ? length : SIZE_100_PERSENT;
168
+ styles.width = data.config.isVertical ? regular ? length : SIZE_100_PERSENT : data.config.dynamic ? SIZE_AUTO : `${data.measures.width}${PX}`;
169
+ }
170
+ this._cdr.markForCheck();
171
+ }
172
+ getBounds() {
173
+ const el = this._elementRef.nativeElement, { width, height } = el.getBoundingClientRect();
174
+ return { width, height };
175
+ }
176
+ show() {
177
+ var _a, _b, _c;
178
+ const styles = this._elementRef.nativeElement.style;
179
+ if (this.regular) {
180
+ if (styles.display === DISPLAY_BLOCK) {
181
+ return;
182
+ }
183
+ styles.display = DISPLAY_BLOCK;
184
+ }
185
+ else {
186
+ if (styles.visibility === VISIBILITY_VISIBLE) {
187
+ return;
188
+ }
189
+ styles.visibility = VISIBILITY_VISIBLE;
190
+ }
191
+ styles.zIndex = (_c = (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.config) === null || _b === void 0 ? void 0 : _b.zIndex) !== null && _c !== void 0 ? _c : DEFAULT_ZINDEX;
192
+ }
193
+ hide() {
194
+ const styles = this._elementRef.nativeElement.style;
195
+ if (this.regular) {
196
+ if (styles.display === DISPLAY_NONE) {
197
+ return;
198
+ }
199
+ styles.display = DISPLAY_NONE;
200
+ }
201
+ else {
202
+ if (styles.visibility === VISIBILITY_HIDDEN) {
203
+ return;
204
+ }
205
+ styles.visibility = VISIBILITY_HIDDEN;
206
+ }
207
+ styles.position = POSITION_ABSOLUTE;
208
+ styles.transform = ZEROS_TRANSLATE_3D;
209
+ styles.zIndex = HIDDEN_ZINDEX;
210
+ }
211
+ }
212
+ NgVirtualListItemComponent.__nextId = 0;
213
+ NgVirtualListItemComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListItemComponent, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component });
214
+ NgVirtualListItemComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: NgVirtualListItemComponent, selector: "ng-virtual-list-item", host: { classAttribute: "ngvl__item" }, usesInheritance: true, ngImport: i0, template: "<ng-container *ngIf=\"data\">\r\n <li #listItem part=\"item\" class=\"ngvl-item__container\" [ngClass]=\"{'snapped': data.config.snapped,\r\n 'snapped-out': data.config.snappedOut}\">\r\n <ng-container *ngIf=\"itemRenderer\">\r\n <ng-container [ngTemplateOutlet]=\"itemRenderer\"\r\n [ngTemplateOutletContext]=\"{data: data.data || {}, config: data.config}\" />\r\n </ng-container>\r\n </li>\r\n</ng-container>", styles: [":host{display:block;position:absolute;left:0;top:0;box-sizing:border-box;overflow:hidden}.ngvl-item__container{margin:0;padding:0;overflow:hidden;background-color:#fff;width:inherit;height:inherit}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
215
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListItemComponent, decorators: [{
216
+ type: Component,
217
+ args: [{ selector: 'ng-virtual-list-item', host: {
218
+ 'class': 'ngvl__item',
219
+ }, changeDetection: ChangeDetectionStrategy.OnPush, template: "<ng-container *ngIf=\"data\">\r\n <li #listItem part=\"item\" class=\"ngvl-item__container\" [ngClass]=\"{'snapped': data.config.snapped,\r\n 'snapped-out': data.config.snappedOut}\">\r\n <ng-container *ngIf=\"itemRenderer\">\r\n <ng-container [ngTemplateOutlet]=\"itemRenderer\"\r\n [ngTemplateOutletContext]=\"{data: data.data || {}, config: data.config}\" />\r\n </ng-container>\r\n </li>\r\n</ng-container>", styles: [":host{display:block;position:absolute;left:0;top:0;box-sizing:border-box;overflow:hidden}.ngvl-item__container{margin:0;padding:0;overflow:hidden;background-color:#fff;width:inherit;height:inherit}\n"] }]
220
+ }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }]; } });
221
+
222
+ /**
223
+ * Simple debounce function.
224
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/debounce.ts
225
+ * @author Evgenii Grebennikov
226
+ * @email djonnyx@gmail.com
227
+ */
228
+ const debounce = (cb, debounceTime = 0) => {
229
+ let timeout;
230
+ const dispose = () => {
231
+ if (timeout !== undefined) {
232
+ clearTimeout(timeout);
233
+ }
234
+ };
235
+ const execute = (...args) => {
236
+ dispose();
237
+ timeout = setTimeout(() => {
238
+ cb(...args);
239
+ }, debounceTime);
240
+ };
241
+ return {
242
+ /**
243
+ * Call handling method
244
+ */
245
+ execute,
246
+ /**
247
+ * Method of destroying handlers
248
+ */
249
+ dispose,
250
+ };
251
+ };
252
+
253
+ /**
254
+ * Switch css classes
255
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/toggleClassName.ts
256
+ * @author Evgenii Grebennikov
257
+ * @email djonnyx@gmail.com
258
+ */
259
+ const toggleClassName = (el, className, removeClassName) => {
260
+ if (!el.classList.contains(className)) {
261
+ el.classList.add(className);
262
+ }
263
+ if (removeClassName) {
264
+ el.classList.remove(removeClassName);
265
+ }
266
+ };
267
+
268
+ /**
269
+ * Scroll event.
270
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/scrollEvent.ts
271
+ * @author Evgenii Grebennikov
272
+ * @email djonnyx@gmail.com
273
+ */
274
+ class ScrollEvent {
275
+ get direction() { return this._direction; }
276
+ get scrollSize() { return this._scrollSize; }
277
+ get scrollWeight() { return this._scrollWeight; }
278
+ get isVertical() { return this._isVertical; }
279
+ get listSize() { return this._listSize; }
280
+ get size() { return this._size; }
281
+ get isStart() { return this._isStart; }
282
+ get isEnd() { return this._isEnd; }
283
+ get delta() { return this._delta; }
284
+ get scrollDelta() { return this._scrollDelta; }
285
+ constructor(params) {
286
+ this._direction = 1;
287
+ this._scrollSize = 0;
288
+ this._scrollWeight = 0;
289
+ this._isVertical = true;
290
+ this._listSize = 0;
291
+ this._size = 0;
292
+ this._isStart = true;
293
+ this._isEnd = false;
294
+ this._delta = 0;
295
+ this._scrollDelta = 0;
296
+ const { direction, isVertical, container, list, delta, scrollDelta } = params;
297
+ this._direction = direction;
298
+ this._isVertical = isVertical;
299
+ this._scrollSize = isVertical ? container.scrollTop : container.scrollLeft;
300
+ this._scrollWeight = isVertical ? container.scrollHeight : container.scrollWidth;
301
+ this._listSize = isVertical ? list.offsetHeight : list.offsetWidth;
302
+ this._size = isVertical ? container.offsetHeight : container.offsetWidth;
303
+ this._isEnd = (this._scrollSize + this._size) === this._scrollWeight;
304
+ this._delta = delta;
305
+ this._scrollDelta = scrollDelta;
306
+ this._isStart = this._scrollSize === 0;
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Simple event emitter
312
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/eventEmitter.ts
313
+ * @author Evgenii Grebennikov
314
+ * @email djonnyx@gmail.com
315
+ */
316
+ class EventEmitter {
317
+ constructor() {
318
+ this._listeners = {};
319
+ this._disposed = false;
320
+ }
321
+ /**
322
+ * Emits the event
323
+ */
324
+ dispatch(event, ...args) {
325
+ const ctx = this;
326
+ const listeners = this._listeners[event];
327
+ if (Array.isArray(listeners)) {
328
+ for (let i = 0, l = listeners.length; i < l; i++) {
329
+ const listener = listeners[i];
330
+ if (listener) {
331
+ listener.apply(ctx, args);
332
+ }
333
+ }
334
+ }
335
+ }
336
+ /**
337
+ * Emits the event async
338
+ */
339
+ dispatchAsync(event, ...args) {
340
+ queueMicrotask(() => {
341
+ if (this._disposed) {
342
+ return;
343
+ }
344
+ this.dispatch(event, ...args);
345
+ });
346
+ }
347
+ /**
348
+ * Returns true if the event listener is already subscribed.
349
+ */
350
+ hasEventListener(eventName, handler) {
351
+ const event = eventName;
352
+ if (this._listeners.hasOwnProperty(event)) {
353
+ const listeners = this._listeners[event];
354
+ const index = listeners.findIndex(v => v === handler);
355
+ if (index > -1) {
356
+ return true;
357
+ }
358
+ }
359
+ return false;
360
+ }
361
+ /**
362
+ * Add event listener
363
+ */
364
+ addEventListener(eventName, handler) {
365
+ const event = eventName;
366
+ if (!this._listeners.hasOwnProperty(event)) {
367
+ this._listeners[event] = [];
368
+ }
369
+ this._listeners[event].push(handler);
370
+ }
371
+ /**
372
+ * Remove event listener
373
+ */
374
+ removeEventListener(eventName, handler) {
375
+ const event = eventName;
376
+ if (!this._listeners.hasOwnProperty(event)) {
377
+ return;
378
+ }
379
+ const listeners = this._listeners[event], index = listeners.findIndex(v => v === handler);
380
+ if (index > -1) {
381
+ listeners.splice(index, 1);
382
+ if (listeners.length === 0) {
383
+ delete this._listeners[event];
384
+ }
385
+ }
386
+ }
387
+ /**
388
+ * Remove all listeners
389
+ */
390
+ removeAllListeners() {
391
+ const events = Object.keys(this._listeners);
392
+ while (events.length > 0) {
393
+ const event = events.pop();
394
+ if (event) {
395
+ const listeners = this._listeners[event];
396
+ if (Array.isArray(listeners)) {
397
+ while (listeners.length > 0) {
398
+ const listener = listeners.pop();
399
+ if (listener) {
400
+ this.removeEventListener(event, listener);
401
+ }
402
+ }
403
+ }
404
+ }
405
+ }
406
+ }
407
+ /**
408
+ * Method of destroying handlers
409
+ */
410
+ dispose() {
411
+ this._disposed = true;
412
+ this.removeAllListeners();
413
+ }
414
+ }
415
+
416
+ class CMap {
417
+ constructor(dict) {
418
+ this._dict = {};
419
+ if (dict) {
420
+ this._dict = Object.assign({}, dict._dict);
421
+ }
422
+ }
423
+ get(key) {
424
+ const k = String(key);
425
+ return this._dict[k];
426
+ }
427
+ set(key, value) {
428
+ const k = String(key);
429
+ this._dict[k] = value;
430
+ return this;
431
+ }
432
+ has(key) {
433
+ return this._dict.hasOwnProperty(String(key));
434
+ }
435
+ delete(key) {
436
+ const k = String(key);
437
+ delete this._dict[k];
438
+ }
439
+ clear() {
440
+ this._dict = {};
441
+ }
442
+ }
443
+ const CACHE_BOX_CHANGE_EVENT_NAME = 'change';
444
+ const MAX_SCROLL_DIRECTION_POOL = 50, CLEAR_SCROLL_DIRECTION_TO = 10, DIR_BACK = '-1', DIR_NONE = '0', DIR_FORWARD = '1';
445
+ /**
446
+ * Cache map.
447
+ * Emits a change event on each mutation.
448
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/cacheMap.ts
449
+ * @author Evgenii Grebennikov
450
+ * @email djonnyx@gmail.com
451
+ */
452
+ class CacheMap extends EventEmitter {
453
+ get delta() {
454
+ return this._delta;
455
+ }
456
+ set deltaDirection(v) {
457
+ this._deltaDirection = v;
458
+ this._scrollDirection = this.calcScrollDirection(v);
459
+ }
460
+ get deltaDirection() {
461
+ return this._deltaDirection;
462
+ }
463
+ get scrollDirection() {
464
+ return this._scrollDirection;
465
+ }
466
+ get version() {
467
+ return this._version;
468
+ }
469
+ constructor() {
470
+ super();
471
+ this._map = new CMap();
472
+ this._snapshot = new CMap();
473
+ this._version = 0;
474
+ this._previousVersion = this._version;
475
+ this._delta = 0;
476
+ this._deltaDirection = 0;
477
+ this._scrollDirectionCache = [];
478
+ this._scrollDirection = 0;
479
+ this._clearScrollDirectionDebounce = debounce(() => {
480
+ while (this._scrollDirectionCache.length > CLEAR_SCROLL_DIRECTION_TO) {
481
+ this._scrollDirectionCache.shift();
482
+ }
483
+ }, 10);
484
+ this.lifeCircle();
485
+ }
486
+ changesDetected() {
487
+ return this._version !== this._previousVersion;
488
+ }
489
+ stopLifeCircle() {
490
+ clearTimeout(this._lifeCircleTimeout);
491
+ }
492
+ nextTick(cb) {
493
+ if (this._disposed) {
494
+ return;
495
+ }
496
+ this._lifeCircleTimeout = setTimeout(() => {
497
+ cb();
498
+ });
499
+ return this._lifeCircleTimeout;
500
+ }
501
+ lifeCircle() {
502
+ this.fireChangeIfNeed();
503
+ this.lifeCircleDo();
504
+ }
505
+ lifeCircleDo() {
506
+ this._previousVersion = this._version;
507
+ this.nextTick(() => {
508
+ this.lifeCircle();
509
+ });
510
+ }
511
+ clearScrollDirectionCache() {
512
+ this._clearScrollDirectionDebounce.execute();
513
+ }
514
+ calcScrollDirection(v) {
515
+ while (this._scrollDirectionCache.length >= MAX_SCROLL_DIRECTION_POOL) {
516
+ this._scrollDirectionCache.shift();
517
+ }
518
+ this._scrollDirectionCache.push(v);
519
+ const dict = { [DIR_BACK]: 0, [DIR_NONE]: 0, [DIR_FORWARD]: 0 };
520
+ for (let i = 0, l = this._scrollDirectionCache.length, li = l - 1; i < l; i++) {
521
+ const dir = String(this._scrollDirectionCache[i]);
522
+ dict[dir] += 1;
523
+ if (i === li) {
524
+ for (let d in dict) {
525
+ if (d === String(v)) {
526
+ continue;
527
+ }
528
+ dict[d] -= 1;
529
+ }
530
+ }
531
+ }
532
+ if (dict[DIR_BACK] > dict[DIR_NONE] && dict[DIR_BACK] > dict[DIR_FORWARD]) {
533
+ return -1;
534
+ }
535
+ else if (dict[DIR_FORWARD] > dict[DIR_BACK] && dict[DIR_FORWARD] > dict[DIR_NONE]) {
536
+ return 1;
537
+ }
538
+ return 0;
539
+ }
540
+ bumpVersion() {
541
+ if (this.changesDetected()) {
542
+ return;
543
+ }
544
+ const v = this._version === Number.MAX_SAFE_INTEGER ? 0 : this._version + 1;
545
+ this._version = v;
546
+ }
547
+ fireChangeIfNeed() {
548
+ if (this.changesDetected()) {
549
+ this.dispatch(CACHE_BOX_CHANGE_EVENT_NAME, this.version);
550
+ }
551
+ }
552
+ set(id, bounds) {
553
+ if (this._map.has(id)) {
554
+ const b = this._map.get(id), bb = bounds;
555
+ if (b.width === bb.width && b.height === bb.height) {
556
+ return this._map;
557
+ }
558
+ return this._map;
559
+ }
560
+ const v = this._map.set(id, bounds);
561
+ this.bumpVersion();
562
+ return v;
563
+ }
564
+ has(id) {
565
+ return this._map.has(id);
566
+ }
567
+ get(id) {
568
+ return this._map.get(id);
569
+ }
570
+ snapshot() {
571
+ this._snapshot = new CMap(this._map);
572
+ }
573
+ dispose() {
574
+ super.dispose();
575
+ this.stopLifeCircle();
576
+ this._snapshot.clear();
577
+ this._map.clear();
578
+ }
579
+ }
580
+
581
+ /**
582
+ * Tracks display items by property
583
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/tracker.ts
584
+ * @author Evgenii Grebennikov
585
+ * @email djonnyx@gmail.com
586
+ */
587
+ class Tracker {
588
+ set displayObjectIndexMapById(v) {
589
+ if (this._displayObjectIndexMapById === v) {
590
+ return;
591
+ }
592
+ this._displayObjectIndexMapById = v;
593
+ }
594
+ get displayObjectIndexMapById() {
595
+ return this._displayObjectIndexMapById;
596
+ }
597
+ get trackMap() {
598
+ return this._trackMap;
599
+ }
600
+ set trackingPropertyName(v) {
601
+ this._trackingPropertyName = v;
602
+ }
603
+ constructor(trackingPropertyName) {
604
+ /**
605
+ * display objects dictionary of indexes by id
606
+ */
607
+ this._displayObjectIndexMapById = {};
608
+ /**
609
+ * Dictionary displayItems propertyNameId by items propertyNameId
610
+ */
611
+ this._trackMap = new CMap();
612
+ this._trackingPropertyName = trackingPropertyName;
613
+ }
614
+ /**
615
+ * tracking by propName
616
+ */
617
+ track(items, components, snapedComponent, direction) {
618
+ var _a;
619
+ if (!items) {
620
+ return;
621
+ }
622
+ const idPropName = this._trackingPropertyName, untrackedItems = [...components], newTrackItems = [], isDown = direction === 0 || direction === 1;
623
+ let isRegularSnapped = false;
624
+ for (let i = isDown ? 0 : items.length - 1, l = isDown ? items.length : 0; isDown ? i < l : i >= l; isDown ? i++ : i--) {
625
+ const item = items[i], itemTrackingProperty = item[idPropName];
626
+ if (this._trackMap) {
627
+ if (this._trackMap.has(itemTrackingProperty)) {
628
+ const diId = this._trackMap.get(itemTrackingProperty), compIndex = this._displayObjectIndexMapById[diId], comp = components[compIndex];
629
+ const compId = (_a = comp === null || comp === void 0 ? void 0 : comp.instance) === null || _a === void 0 ? void 0 : _a.id;
630
+ if (comp !== undefined && compId === diId) {
631
+ const indexByUntrackedItems = untrackedItems.findIndex(v => {
632
+ return v.instance.id === compId;
633
+ });
634
+ if (indexByUntrackedItems > -1) {
635
+ if (snapedComponent) {
636
+ if (item['config']['snapped'] || item['config']['snappedOut']) {
637
+ isRegularSnapped = true;
638
+ snapedComponent.instance.item = item;
639
+ snapedComponent.instance.show();
640
+ }
641
+ }
642
+ comp.instance.item = item;
643
+ if (snapedComponent) {
644
+ if (item['config']['snapped'] || item['config']['snappedOut']) {
645
+ comp.instance.hide();
646
+ }
647
+ else {
648
+ comp.instance.show();
649
+ }
650
+ }
651
+ else {
652
+ comp.instance.show();
653
+ }
654
+ untrackedItems.splice(indexByUntrackedItems, 1);
655
+ continue;
656
+ }
657
+ }
658
+ this._trackMap.delete(itemTrackingProperty);
659
+ }
660
+ }
661
+ if (untrackedItems.length > 0) {
662
+ newTrackItems.push(item);
663
+ }
664
+ }
665
+ for (let i = 0, l = newTrackItems.length; i < l; i++) {
666
+ const item = newTrackItems[i], itemTrackingProperty = item[idPropName];
667
+ if (untrackedItems.length > 0) {
668
+ const comp = untrackedItems.shift(), item = items[i];
669
+ if (comp) {
670
+ if (snapedComponent) {
671
+ if (item['config']['snapped'] || item['config']['snappedOut']) {
672
+ isRegularSnapped = true;
673
+ snapedComponent.instance.item = item;
674
+ snapedComponent.instance.show();
675
+ }
676
+ }
677
+ comp.instance.item = item;
678
+ if (snapedComponent) {
679
+ if (item['config']['snapped'] || item['config']['snappedOut']) {
680
+ comp.instance.hide();
681
+ }
682
+ else {
683
+ comp.instance.show();
684
+ }
685
+ }
686
+ else {
687
+ comp.instance.show();
688
+ }
689
+ if (this._trackMap) {
690
+ this._trackMap.set(itemTrackingProperty, comp.instance.id);
691
+ }
692
+ }
693
+ }
694
+ }
695
+ if (untrackedItems.length) {
696
+ for (let i = 0, l = untrackedItems.length; i < l; i++) {
697
+ const comp = untrackedItems[i];
698
+ comp.instance.hide();
699
+ }
700
+ }
701
+ if (!isRegularSnapped) {
702
+ if (snapedComponent) {
703
+ snapedComponent.instance.item = null;
704
+ snapedComponent.instance.hide();
705
+ }
706
+ }
707
+ }
708
+ untrackComponentByIdProperty(component) {
709
+ if (!component) {
710
+ return;
711
+ }
712
+ const propertyIdName = this._trackingPropertyName;
713
+ if (this._trackMap && component[propertyIdName] !== undefined) {
714
+ this._trackMap.delete(propertyIdName);
715
+ }
716
+ }
717
+ dispose() {
718
+ if (this._trackMap) {
719
+ this._trackMap.clear();
720
+ }
721
+ }
722
+ }
723
+
724
+ const DEFAULT_EXTRA = {
725
+ extremumThreshold: 2,
726
+ bufferSize: 10,
727
+ };
728
+ const bufferInterpolation = (currentBufferValue, array, value, extra) => {
729
+ const { extremumThreshold = DEFAULT_EXTRA.extremumThreshold, bufferSize = DEFAULT_EXTRA.bufferSize, } = extra !== null && extra !== void 0 ? extra : DEFAULT_EXTRA;
730
+ if (currentBufferValue < value) {
731
+ let i = 0;
732
+ while (i < extremumThreshold) {
733
+ array.push(value);
734
+ i++;
735
+ }
736
+ }
737
+ else {
738
+ array.push(value);
739
+ }
740
+ while (array.length >= bufferSize) {
741
+ array.shift();
742
+ }
743
+ const l = array.length;
744
+ let buffer = 0;
745
+ for (let i = 0; i < l; i++) {
746
+ buffer += array[i];
747
+ }
748
+ return Math.ceil(buffer / l);
749
+ };
750
+
751
+ const TRACK_BOX_CHANGE_EVENT_NAME = 'change';
752
+ var ItemDisplayMethods;
753
+ (function (ItemDisplayMethods) {
754
+ ItemDisplayMethods[ItemDisplayMethods["CREATE"] = 0] = "CREATE";
755
+ ItemDisplayMethods[ItemDisplayMethods["UPDATE"] = 1] = "UPDATE";
756
+ ItemDisplayMethods[ItemDisplayMethods["DELETE"] = 2] = "DELETE";
757
+ ItemDisplayMethods[ItemDisplayMethods["NOT_CHANGED"] = 3] = "NOT_CHANGED";
758
+ })(ItemDisplayMethods || (ItemDisplayMethods = {}));
759
+ const DEFAULT_BUFFER_EXTREMUM_THRESHOLD = 15, DEFAULT_MAX_BUFFER_SEQUENCE_LENGTH = 30, DEFAULT_RESET_BUFFER_SIZE_TIMEOUT = 10000;
760
+ /**
761
+ * An object that performs tracking, calculations and caching.
762
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/trackBox.ts
763
+ * @author Evgenii Grebennikov
764
+ * @email djonnyx@gmail.com
765
+ */
766
+ class TrackBox extends CacheMap {
767
+ set items(v) {
768
+ if (this._items === v) {
769
+ return;
770
+ }
771
+ this._items = v;
772
+ }
773
+ set displayComponents(v) {
774
+ if (this._displayComponents === v) {
775
+ return;
776
+ }
777
+ this._displayComponents = v;
778
+ }
779
+ set snapedDisplayComponent(v) {
780
+ if (this._snapedDisplayComponent === v) {
781
+ return;
782
+ }
783
+ this._snapedDisplayComponent = v;
784
+ }
785
+ set isSnappingMethodAdvanced(v) {
786
+ if (this._isSnappingMethodAdvanced === v) {
787
+ return;
788
+ }
789
+ this._isSnappingMethodAdvanced = v;
790
+ }
791
+ /**
792
+ * Set the trackBy property
793
+ */
794
+ set trackingPropertyName(v) {
795
+ this._trackingPropertyName = this._tracker.trackingPropertyName = v;
796
+ }
797
+ constructor(trackingPropertyName) {
798
+ super();
799
+ this._isSnappingMethodAdvanced = false;
800
+ this._trackingPropertyName = TRACK_BY_PROPERTY_NAME;
801
+ this._deletedItemsMap = {};
802
+ this._crudDetected = false;
803
+ this._previousTotalSize = 0;
804
+ this._scrollDelta = 0;
805
+ this.isAdaptiveBuffer = true;
806
+ this._bufferSequenceExtraThreshold = DEFAULT_BUFFER_EXTREMUM_THRESHOLD;
807
+ this._maxBufferSequenceLength = DEFAULT_MAX_BUFFER_SEQUENCE_LENGTH;
808
+ this._bufferSizeSequence = [];
809
+ this._bufferSize = 0;
810
+ this._defaultBufferSize = 0;
811
+ this._maxBufferSize = this._defaultBufferSize;
812
+ this._resetBufferSizeTimeout = DEFAULT_RESET_BUFFER_SIZE_TIMEOUT;
813
+ this._previousScrollSize = 0;
814
+ this._trackingPropertyName = trackingPropertyName;
815
+ this.initialize();
816
+ }
817
+ initialize() {
818
+ this._tracker = new Tracker(this._trackingPropertyName);
819
+ }
820
+ set(id, bounds) {
821
+ if (this._map.has(id)) {
822
+ const b = this._map.get(id);
823
+ if ((b === null || b === void 0 ? void 0 : b.width) === bounds.width && b.height === bounds.height) {
824
+ return this._map;
825
+ }
826
+ }
827
+ const v = this._map.set(id, bounds);
828
+ this.bumpVersion();
829
+ return v;
830
+ }
831
+ get crudDetected() { return this._crudDetected; }
832
+ fireChangeIfNeed() {
833
+ if (this.changesDetected()) {
834
+ this.dispatch(TRACK_BOX_CHANGE_EVENT_NAME, this._version);
835
+ }
836
+ }
837
+ get scrollDelta() { return this._scrollDelta; }
838
+ get bufferSize() { return this._bufferSize; }
839
+ lifeCircle() {
840
+ this.fireChangeIfNeed();
841
+ this.lifeCircleDo();
842
+ }
843
+ /**
844
+ * Scans the collection for deleted items and flushes the deleted item cache.
845
+ */
846
+ resetCollection(currentCollection, itemSize) {
847
+ if (currentCollection !== undefined && currentCollection !== null && currentCollection === this._previousCollection) {
848
+ console.warn('Attention! The collection must be immutable.');
849
+ return;
850
+ }
851
+ this.updateCache(this._previousCollection, currentCollection, itemSize);
852
+ this._previousCollection = currentCollection;
853
+ }
854
+ /**
855
+ * Update the cache of items from the list
856
+ */
857
+ updateCache(previousCollection, currentCollection, itemSize) {
858
+ let crudDetected = false;
859
+ if (!currentCollection || currentCollection.length === 0) {
860
+ if (previousCollection) {
861
+ // deleted
862
+ for (let i = 0, l = previousCollection.length; i < l; i++) {
863
+ const item = previousCollection[i], id = item.id;
864
+ crudDetected = true;
865
+ if (this._map.has(id)) {
866
+ this._map.delete(id);
867
+ }
868
+ }
869
+ }
870
+ return;
871
+ }
872
+ if (!previousCollection || previousCollection.length === 0) {
873
+ if (currentCollection) {
874
+ // added
875
+ for (let i = 0, l = currentCollection.length; i < l; i++) {
876
+ crudDetected = true;
877
+ const item = currentCollection[i], id = item.id;
878
+ this._map.set(id, { width: itemSize, height: itemSize, method: ItemDisplayMethods.CREATE });
879
+ }
880
+ }
881
+ return;
882
+ }
883
+ const collectionDict = {};
884
+ for (let i = 0, l = currentCollection.length; i < l; i++) {
885
+ const item = currentCollection[i];
886
+ if (item) {
887
+ collectionDict[item.id] = item;
888
+ }
889
+ }
890
+ const notChangedMap = {}, deletedMap = {}, deletedItemsMap = {}, updatedMap = {};
891
+ for (let i = 0, l = previousCollection.length; i < l; i++) {
892
+ const item = previousCollection[i], id = item.id;
893
+ if (item) {
894
+ if (collectionDict.hasOwnProperty(id)) {
895
+ if (item === collectionDict[id]) {
896
+ // not changed
897
+ notChangedMap[item.id] = item;
898
+ this._map.set(id, Object.assign(Object.assign({}, (this._map.get(id) || { width: itemSize, height: itemSize })), { method: ItemDisplayMethods.NOT_CHANGED }));
899
+ continue;
900
+ }
901
+ else {
902
+ // updated
903
+ crudDetected = true;
904
+ updatedMap[item.id] = item;
905
+ this._map.set(id, Object.assign(Object.assign({}, (this._map.get(id) || { width: itemSize, height: itemSize })), { method: ItemDisplayMethods.UPDATE }));
906
+ continue;
907
+ }
908
+ }
909
+ // deleted
910
+ crudDetected = true;
911
+ deletedMap[item.id] = item;
912
+ deletedItemsMap[i] = this._map.get(item.id);
913
+ this._map.delete(id);
914
+ }
915
+ }
916
+ for (let i = 0, l = currentCollection.length; i < l; i++) {
917
+ const item = currentCollection[i], id = item.id;
918
+ if (item && !deletedMap.hasOwnProperty(id) && !updatedMap.hasOwnProperty(id) && !notChangedMap.hasOwnProperty(id)) {
919
+ // added
920
+ crudDetected = true;
921
+ this._map.set(id, { width: itemSize, height: itemSize, method: ItemDisplayMethods.CREATE });
922
+ }
923
+ }
924
+ this._crudDetected = crudDetected;
925
+ this._deletedItemsMap = deletedItemsMap;
926
+ }
927
+ /**
928
+ * Finds the position of a collection element by the given Id
929
+ */
930
+ getItemPosition(id, stickyMap, options) {
931
+ const opt = Object.assign({ fromItemId: id, stickyMap }, options);
932
+ this._defaultBufferSize = opt.bufferSize;
933
+ this._maxBufferSize = opt.maxBufferSize;
934
+ const { scrollSize, isFromItemIdFound } = this.recalculateMetrics(Object.assign(Object.assign({}, opt), { dynamicSize: this._crudDetected || opt.dynamicSize, previousTotalSize: this._previousTotalSize, crudDetected: this._crudDetected, deletedItemsMap: this._deletedItemsMap }));
935
+ return isFromItemIdFound ? scrollSize : -1;
936
+ }
937
+ /**
938
+ * Updates the collection of display objects
939
+ */
940
+ updateCollection(items, stickyMap, options) {
941
+ const opt = Object.assign({ stickyMap }, options), crudDetected = this._crudDetected, deletedItemsMap = this._deletedItemsMap;
942
+ if (opt.dynamicSize) {
943
+ this.cacheElements();
944
+ }
945
+ this._defaultBufferSize = opt.bufferSize;
946
+ this._maxBufferSize = opt.maxBufferSize;
947
+ const metrics = this.recalculateMetrics(Object.assign(Object.assign({}, opt), { collection: items, previousTotalSize: this._previousTotalSize, crudDetected: this._crudDetected, deletedItemsMap }));
948
+ this._delta += metrics.delta;
949
+ this.updateAdaptiveBufferParams(metrics, items.length);
950
+ this._previousTotalSize = metrics.totalSize;
951
+ this._deletedItemsMap = {};
952
+ this._crudDetected = false;
953
+ if (opt.dynamicSize) {
954
+ this.snapshot();
955
+ }
956
+ const displayItems = this.generateDisplayCollection(items, stickyMap, Object.assign({}, metrics));
957
+ return { displayItems, totalSize: metrics.totalSize, delta: metrics.delta, crudDetected };
958
+ }
959
+ /**
960
+ * Finds the closest element in the collection by scrollSize
961
+ */
962
+ getNearestItem(scrollSize, items, itemSize, isVertical) {
963
+ return this.getElementFromStart(scrollSize, items, this._map, itemSize, isVertical);
964
+ }
965
+ updateAdaptiveBufferParams(metrics, totalItemsLength) {
966
+ this.disposeClearBufferSizeTimer();
967
+ const scrollSize = metrics.scrollSize + this._delta, delta = Math.abs(this._previousScrollSize - scrollSize);
968
+ this._previousScrollSize = scrollSize;
969
+ const bufferRawSize = Math.min(Math.floor(delta / metrics.typicalItemSize) * 5, totalItemsLength), minBufferSize = bufferRawSize < this._defaultBufferSize ? this._defaultBufferSize : bufferRawSize, bufferValue = minBufferSize > this._maxBufferSize ? this._maxBufferSize : minBufferSize;
970
+ this._bufferSize = bufferInterpolation(this._bufferSize, this._bufferSizeSequence, bufferValue, {
971
+ extremumThreshold: this._bufferSequenceExtraThreshold,
972
+ bufferSize: this._maxBufferSequenceLength,
973
+ });
974
+ this.startResetBufferSizeTimer();
975
+ }
976
+ startResetBufferSizeTimer() {
977
+ this._resetBufferSizeTimer = setTimeout(() => {
978
+ this._bufferSize = this._defaultBufferSize;
979
+ this._bufferSizeSequence = [];
980
+ }, this._resetBufferSizeTimeout);
981
+ }
982
+ disposeClearBufferSizeTimer() {
983
+ clearTimeout(this._resetBufferSizeTimer);
984
+ }
985
+ /**
986
+ * Calculates the position of an element based on the given scrollSize
987
+ */
988
+ getElementFromStart(scrollSize, collection, map, typicalItemSize, isVertical) {
989
+ const sizeProperty = isVertical ? HEIGHT_PROP_NAME : WIDTH_PROP_NAME;
990
+ let offset = 0;
991
+ for (let i = 0, l = collection.length; i < l; i++) {
992
+ const item = collection[i];
993
+ let itemSize = 0;
994
+ if (map.has(item.id)) {
995
+ const bounds = map.get(item.id);
996
+ itemSize = bounds ? bounds[sizeProperty] : typicalItemSize;
997
+ }
998
+ else {
999
+ itemSize = typicalItemSize;
1000
+ }
1001
+ if (offset > scrollSize) {
1002
+ return item;
1003
+ }
1004
+ offset += itemSize;
1005
+ }
1006
+ return undefined;
1007
+ }
1008
+ /**
1009
+ * Calculates the entry into the overscroll area and returns the number of overscroll elements
1010
+ */
1011
+ getElementNumToEnd(i, collection, map, typicalItemSize, size, isVertical, indexOffset = 0) {
1012
+ const sizeProperty = isVertical ? HEIGHT_PROP_NAME : WIDTH_PROP_NAME;
1013
+ let offset = 0, num = 0;
1014
+ for (let j = collection.length - indexOffset - 1; j >= i; j--) {
1015
+ const item = collection[j];
1016
+ let itemSize = 0;
1017
+ if (map.has(item.id)) {
1018
+ const bounds = map.get(item.id);
1019
+ itemSize = bounds ? bounds[sizeProperty] : typicalItemSize;
1020
+ }
1021
+ else {
1022
+ itemSize = typicalItemSize;
1023
+ }
1024
+ offset += itemSize;
1025
+ num++;
1026
+ if (offset > size) {
1027
+ return { num: 0, offset };
1028
+ }
1029
+ }
1030
+ return { num, offset };
1031
+ }
1032
+ /**
1033
+ * Calculates list metrics
1034
+ */
1035
+ recalculateMetrics(options) {
1036
+ var _a, _b, _c, _d;
1037
+ const { fromItemId, bounds, collection, dynamicSize, isVertical, itemSize, bufferSize: minBufferSize, scrollSize, snap, stickyMap, enabledBufferOptimization, previousTotalSize, crudDetected, deletedItemsMap } = options;
1038
+ const bufferSize = Math.max(minBufferSize, this._bufferSize), { width, height } = bounds, sizeProperty = isVertical ? HEIGHT_PROP_NAME : WIDTH_PROP_NAME, size = isVertical ? height : width, totalLength = collection.length, typicalItemSize = itemSize, w = isVertical ? width : typicalItemSize, h = isVertical ? typicalItemSize : height, map = this._map, snapshot = this._snapshot, checkOverscrollItemsLimit = Math.ceil(size / typicalItemSize), snippedPos = Math.floor(scrollSize), leftItemsWeights = [], isFromId = fromItemId !== undefined && (typeof fromItemId === 'number' && fromItemId > -1)
1039
+ || (typeof fromItemId === 'string' && fromItemId > '-1');
1040
+ let leftItemsOffset = 0, rightItemsOffset = 0;
1041
+ if (enabledBufferOptimization) {
1042
+ switch (this.scrollDirection) {
1043
+ case 1: {
1044
+ leftItemsOffset = 0;
1045
+ rightItemsOffset = bufferSize;
1046
+ break;
1047
+ }
1048
+ case -1: {
1049
+ leftItemsOffset = bufferSize;
1050
+ rightItemsOffset = 0;
1051
+ break;
1052
+ }
1053
+ case 0:
1054
+ default: {
1055
+ leftItemsOffset = rightItemsOffset = bufferSize;
1056
+ }
1057
+ }
1058
+ }
1059
+ else {
1060
+ leftItemsOffset = rightItemsOffset = bufferSize;
1061
+ }
1062
+ let itemsFromStartToScrollEnd = -1, itemsFromDisplayEndToOffsetEnd = 0, itemsFromStartToDisplayEnd = -1, leftItemLength = 0, rightItemLength = 0, leftItemsWeight = 0, rightItemsWeight = 0, leftHiddenItemsWeight = 0, totalItemsToDisplayEndWeight = 0, leftSizeOfAddedItems = 0, leftSizeOfUpdatedItems = 0, leftSizeOfDeletedItems = 0, itemById = undefined, itemByIdPos = 0, targetDisplayItemIndex = -1, isTargetInOverscroll = false, actualScrollSize = itemByIdPos, totalSize = 0, startIndex, isFromItemIdFound = false;
1063
+ // If the list is dynamic or there are new elements in the collection, then it switches to the long algorithm.
1064
+ if (dynamicSize) {
1065
+ let y = 0, stickyCollectionItem = undefined, stickyComponentSize = 0;
1066
+ for (let i = 0, l = collection.length; i < l; i++) {
1067
+ const ii = i + 1, collectionItem = collection[i], id = collectionItem.id;
1068
+ let componentSize = 0, componentSizeDelta = 0, itemDisplayMethod = ItemDisplayMethods.NOT_CHANGED;
1069
+ if (map.has(id)) {
1070
+ const bounds = map.get(id) || { width: typicalItemSize, height: typicalItemSize };
1071
+ componentSize = bounds[sizeProperty];
1072
+ itemDisplayMethod = (_a = bounds === null || bounds === void 0 ? void 0 : bounds.method) !== null && _a !== void 0 ? _a : ItemDisplayMethods.UPDATE;
1073
+ switch (itemDisplayMethod) {
1074
+ case ItemDisplayMethods.UPDATE: {
1075
+ const snapshotBounds = snapshot.get(id);
1076
+ const componentSnapshotSize = componentSize - (snapshotBounds ? snapshotBounds[sizeProperty] : typicalItemSize);
1077
+ componentSizeDelta = componentSnapshotSize;
1078
+ map.set(id, Object.assign(Object.assign({}, bounds), { method: ItemDisplayMethods.NOT_CHANGED }));
1079
+ break;
1080
+ }
1081
+ case ItemDisplayMethods.CREATE: {
1082
+ componentSizeDelta = typicalItemSize;
1083
+ map.set(id, Object.assign(Object.assign({}, bounds), { method: ItemDisplayMethods.NOT_CHANGED }));
1084
+ break;
1085
+ }
1086
+ }
1087
+ }
1088
+ if (deletedItemsMap.hasOwnProperty(i)) {
1089
+ const bounds = deletedItemsMap[i], size = (_b = bounds === null || bounds === void 0 ? void 0 : bounds[sizeProperty]) !== null && _b !== void 0 ? _b : typicalItemSize;
1090
+ if (y < scrollSize - size) {
1091
+ leftSizeOfDeletedItems += size;
1092
+ }
1093
+ }
1094
+ totalSize += componentSize;
1095
+ if (isFromId) {
1096
+ if (itemById === undefined) {
1097
+ if (id !== fromItemId && stickyMap && stickyMap[id] === 1) {
1098
+ stickyComponentSize = componentSize;
1099
+ stickyCollectionItem = collectionItem;
1100
+ }
1101
+ if (id === fromItemId) {
1102
+ isFromItemIdFound = true;
1103
+ targetDisplayItemIndex = i;
1104
+ if (stickyCollectionItem && stickyMap) {
1105
+ const { num } = this.getElementNumToEnd(i, collection, map, typicalItemSize, size, isVertical);
1106
+ if (num > 0) {
1107
+ isTargetInOverscroll = true;
1108
+ y -= size - componentSize;
1109
+ }
1110
+ else {
1111
+ if (stickyMap && !stickyMap[collectionItem.id] && y >= scrollSize && y < scrollSize + stickyComponentSize) {
1112
+ const snappedY = scrollSize - stickyComponentSize;
1113
+ leftHiddenItemsWeight -= (snappedY - y);
1114
+ y = snappedY;
1115
+ }
1116
+ else {
1117
+ y -= stickyComponentSize;
1118
+ leftHiddenItemsWeight -= stickyComponentSize;
1119
+ }
1120
+ }
1121
+ }
1122
+ itemById = collectionItem;
1123
+ itemByIdPos = y;
1124
+ }
1125
+ else {
1126
+ leftItemsWeights.push(componentSize);
1127
+ leftHiddenItemsWeight += componentSize;
1128
+ itemsFromStartToScrollEnd = ii;
1129
+ }
1130
+ }
1131
+ }
1132
+ else if (y <= scrollSize - componentSize) {
1133
+ leftItemsWeights.push(componentSize);
1134
+ leftHiddenItemsWeight += componentSize;
1135
+ itemsFromStartToScrollEnd = ii;
1136
+ }
1137
+ if (isFromId) {
1138
+ if (itemById === undefined || y < itemByIdPos + size + componentSize) {
1139
+ itemsFromStartToDisplayEnd = ii;
1140
+ totalItemsToDisplayEndWeight += componentSize;
1141
+ itemsFromDisplayEndToOffsetEnd = itemsFromStartToDisplayEnd + rightItemsOffset;
1142
+ }
1143
+ }
1144
+ else if (y <= scrollSize + size + componentSize) {
1145
+ itemsFromStartToDisplayEnd = ii;
1146
+ totalItemsToDisplayEndWeight += componentSize;
1147
+ itemsFromDisplayEndToOffsetEnd = itemsFromStartToDisplayEnd + rightItemsOffset;
1148
+ if (y <= scrollSize - componentSize) {
1149
+ switch (itemDisplayMethod) {
1150
+ case ItemDisplayMethods.CREATE: {
1151
+ leftSizeOfAddedItems += componentSizeDelta;
1152
+ break;
1153
+ }
1154
+ case ItemDisplayMethods.UPDATE: {
1155
+ leftSizeOfUpdatedItems += componentSizeDelta;
1156
+ break;
1157
+ }
1158
+ case ItemDisplayMethods.DELETE: {
1159
+ leftSizeOfDeletedItems += componentSizeDelta;
1160
+ break;
1161
+ }
1162
+ }
1163
+ }
1164
+ }
1165
+ else {
1166
+ if (i < itemsFromDisplayEndToOffsetEnd) {
1167
+ rightItemsWeight += componentSize;
1168
+ }
1169
+ }
1170
+ y += componentSize;
1171
+ }
1172
+ if (isTargetInOverscroll) {
1173
+ const { num } = this.getElementNumToEnd(collection.length - (checkOverscrollItemsLimit < 0 ? 0 : collection.length - checkOverscrollItemsLimit), collection, map, typicalItemSize, size, isVertical, collection.length - (collection.length - (targetDisplayItemIndex + 1)));
1174
+ if (num > 0) {
1175
+ itemsFromStartToScrollEnd -= num;
1176
+ }
1177
+ }
1178
+ if (itemsFromStartToScrollEnd <= -1) {
1179
+ itemsFromStartToScrollEnd = 0;
1180
+ }
1181
+ if (itemsFromStartToDisplayEnd <= -1) {
1182
+ itemsFromStartToDisplayEnd = 0;
1183
+ }
1184
+ actualScrollSize = isFromId ? itemByIdPos : scrollSize;
1185
+ leftItemsWeights.splice(0, leftItemsWeights.length - leftItemsOffset);
1186
+ leftItemsWeights.forEach(v => {
1187
+ leftItemsWeight += v;
1188
+ });
1189
+ leftItemLength = Math.min(itemsFromStartToScrollEnd, leftItemsOffset);
1190
+ rightItemLength = itemsFromStartToDisplayEnd + rightItemsOffset > totalLength
1191
+ ? totalLength - itemsFromStartToDisplayEnd : rightItemsOffset;
1192
+ }
1193
+ else
1194
+ // Buffer optimization does not work on fast linear algorithm
1195
+ {
1196
+ if (crudDetected) {
1197
+ let y = 0;
1198
+ for (let i = 0, l = collection.length; i < l; i++) {
1199
+ const collectionItem = collection[i], id = collectionItem.id;
1200
+ let componentSize = typicalItemSize, itemDisplayMethod = ItemDisplayMethods.NOT_CHANGED;
1201
+ if (map.has(id)) {
1202
+ const bounds = map.get(id);
1203
+ itemDisplayMethod = (_c = bounds === null || bounds === void 0 ? void 0 : bounds.method) !== null && _c !== void 0 ? _c : ItemDisplayMethods.UPDATE;
1204
+ if (itemDisplayMethod === ItemDisplayMethods.CREATE) {
1205
+ map.set(id, Object.assign(Object.assign({}, bounds), { method: ItemDisplayMethods.NOT_CHANGED }));
1206
+ }
1207
+ }
1208
+ if (deletedItemsMap.hasOwnProperty(i)) {
1209
+ const bounds = deletedItemsMap[i], size = (_d = bounds === null || bounds === void 0 ? void 0 : bounds[sizeProperty]) !== null && _d !== void 0 ? _d : typicalItemSize;
1210
+ if (y < scrollSize - size) {
1211
+ leftSizeOfDeletedItems += size;
1212
+ }
1213
+ }
1214
+ if (y < scrollSize - componentSize) {
1215
+ switch (itemDisplayMethod) {
1216
+ case ItemDisplayMethods.CREATE: {
1217
+ leftSizeOfUpdatedItems += componentSize;
1218
+ break;
1219
+ }
1220
+ case ItemDisplayMethods.UPDATE: {
1221
+ leftSizeOfUpdatedItems += componentSize;
1222
+ break;
1223
+ }
1224
+ case ItemDisplayMethods.DELETE: {
1225
+ leftSizeOfDeletedItems += componentSize;
1226
+ break;
1227
+ }
1228
+ }
1229
+ }
1230
+ y += componentSize;
1231
+ }
1232
+ }
1233
+ itemsFromStartToScrollEnd = Math.floor(scrollSize / typicalItemSize);
1234
+ itemsFromStartToDisplayEnd = Math.ceil((scrollSize + size) / typicalItemSize);
1235
+ leftItemLength = Math.min(itemsFromStartToScrollEnd, bufferSize);
1236
+ rightItemLength = itemsFromStartToDisplayEnd + bufferSize > totalLength
1237
+ ? totalLength - itemsFromStartToDisplayEnd : bufferSize;
1238
+ leftItemsWeight = leftItemLength * typicalItemSize;
1239
+ rightItemsWeight = rightItemLength * typicalItemSize;
1240
+ leftHiddenItemsWeight = itemsFromStartToScrollEnd * typicalItemSize;
1241
+ totalItemsToDisplayEndWeight = itemsFromStartToDisplayEnd * typicalItemSize;
1242
+ totalSize = totalLength * typicalItemSize;
1243
+ const k = totalSize !== 0 ? previousTotalSize / totalSize : 0;
1244
+ actualScrollSize = scrollSize * k;
1245
+ }
1246
+ startIndex = Math.min(itemsFromStartToScrollEnd - leftItemLength, totalLength > 0 ? totalLength - 1 : 0);
1247
+ const itemsOnDisplayWeight = totalItemsToDisplayEndWeight - leftItemsWeight, itemsOnDisplayLength = itemsFromStartToDisplayEnd - itemsFromStartToScrollEnd, startPosition = leftHiddenItemsWeight - leftItemsWeight, renderItems = itemsOnDisplayLength + leftItemLength + rightItemLength, delta = leftSizeOfUpdatedItems + leftSizeOfAddedItems - leftSizeOfDeletedItems;
1248
+ const metrics = {
1249
+ delta,
1250
+ normalizedItemWidth: w,
1251
+ normalizedItemHeight: h,
1252
+ width,
1253
+ height,
1254
+ dynamicSize,
1255
+ itemSize,
1256
+ itemsFromStartToScrollEnd,
1257
+ itemsFromStartToDisplayEnd,
1258
+ itemsOnDisplayWeight,
1259
+ itemsOnDisplayLength,
1260
+ isVertical,
1261
+ leftHiddenItemsWeight,
1262
+ leftItemLength,
1263
+ leftItemsWeight,
1264
+ renderItems,
1265
+ rightItemLength,
1266
+ rightItemsWeight,
1267
+ scrollSize: actualScrollSize,
1268
+ leftSizeOfAddedItems,
1269
+ sizeProperty,
1270
+ snap,
1271
+ snippedPos,
1272
+ startIndex,
1273
+ startPosition,
1274
+ totalItemsToDisplayEndWeight,
1275
+ totalLength,
1276
+ totalSize,
1277
+ typicalItemSize,
1278
+ isFromItemIdFound,
1279
+ };
1280
+ return metrics;
1281
+ }
1282
+ clearDeltaDirection() {
1283
+ this.clearScrollDirectionCache();
1284
+ }
1285
+ clearDelta(clearDirectionDetector = false) {
1286
+ this._delta = 0;
1287
+ if (clearDirectionDetector) {
1288
+ this.clearScrollDirectionCache();
1289
+ }
1290
+ }
1291
+ changes() {
1292
+ this.bumpVersion();
1293
+ }
1294
+ generateDisplayCollection(items, stickyMap, metrics) {
1295
+ var _a, _b, _c;
1296
+ const { width, height, normalizedItemWidth, normalizedItemHeight, dynamicSize, itemsOnDisplayLength, itemsFromStartToScrollEnd, isVertical, renderItems: renderItemsLength, scrollSize, sizeProperty, snap, snippedPos, startPosition, totalLength, startIndex, typicalItemSize, } = metrics, displayItems = [];
1297
+ if (items.length) {
1298
+ const actualSnippedPosition = snippedPos, isSnappingMethodAdvanced = this.isSnappingMethodAdvanced, boundsSize = isVertical ? height : width, actualEndSnippedPosition = boundsSize;
1299
+ let pos = startPosition, renderItems = renderItemsLength, stickyItem, nextSticky, stickyItemIndex = -1, stickyItemSize = 0, endStickyItem, nextEndSticky, endStickyItemIndex = -1, endStickyItemSize = 0;
1300
+ if (snap) {
1301
+ for (let i = Math.min(itemsFromStartToScrollEnd > 0 ? itemsFromStartToScrollEnd : 0, totalLength - 1); i >= 0; i--) {
1302
+ if (!items[i]) {
1303
+ continue;
1304
+ }
1305
+ const id = items[i].id, sticky = stickyMap[id], size = dynamicSize ? ((_a = this.get(id)) === null || _a === void 0 ? void 0 : _a[sizeProperty]) || typicalItemSize : typicalItemSize;
1306
+ if (sticky === 1) {
1307
+ const measures = {
1308
+ x: isVertical ? 0 : actualSnippedPosition,
1309
+ y: isVertical ? actualSnippedPosition : 0,
1310
+ width: isVertical ? normalizedItemWidth : size,
1311
+ height: isVertical ? size : normalizedItemHeight,
1312
+ delta: 0,
1313
+ }, config = {
1314
+ isVertical,
1315
+ sticky,
1316
+ snap,
1317
+ snapped: true,
1318
+ snappedOut: false,
1319
+ dynamic: dynamicSize,
1320
+ isSnappingMethodAdvanced,
1321
+ zIndex: '1',
1322
+ };
1323
+ const itemData = items[i];
1324
+ stickyItem = { id, measures, data: itemData, config };
1325
+ stickyItemIndex = i;
1326
+ stickyItemSize = size;
1327
+ displayItems.push(stickyItem);
1328
+ break;
1329
+ }
1330
+ }
1331
+ }
1332
+ if (snap) {
1333
+ const startIndex = itemsFromStartToScrollEnd + itemsOnDisplayLength - 1;
1334
+ for (let i = Math.min(startIndex, totalLength > 0 ? totalLength - 1 : 0), l = totalLength; i < l; i++) {
1335
+ if (!items[i]) {
1336
+ continue;
1337
+ }
1338
+ const id = items[i].id, sticky = stickyMap[id], size = dynamicSize
1339
+ ? ((_b = this.get(id)) === null || _b === void 0 ? void 0 : _b[sizeProperty]) || typicalItemSize
1340
+ : typicalItemSize;
1341
+ if (sticky === 2) {
1342
+ const w = isVertical ? normalizedItemWidth : size, h = isVertical ? size : normalizedItemHeight, measures = {
1343
+ x: isVertical ? 0 : actualEndSnippedPosition - w,
1344
+ y: isVertical ? actualEndSnippedPosition - h : 0,
1345
+ width: w,
1346
+ height: h,
1347
+ delta: 0,
1348
+ }, config = {
1349
+ isVertical,
1350
+ sticky,
1351
+ snap,
1352
+ snapped: true,
1353
+ snappedOut: false,
1354
+ dynamic: dynamicSize,
1355
+ isSnappingMethodAdvanced,
1356
+ zIndex: '1',
1357
+ };
1358
+ const itemData = items[i];
1359
+ endStickyItem = { id, measures, data: itemData, config };
1360
+ endStickyItemIndex = i;
1361
+ endStickyItemSize = size;
1362
+ displayItems.push(endStickyItem);
1363
+ break;
1364
+ }
1365
+ }
1366
+ }
1367
+ let i = startIndex;
1368
+ while (renderItems > 0) {
1369
+ if (i >= totalLength) {
1370
+ break;
1371
+ }
1372
+ if (!items[i]) {
1373
+ continue;
1374
+ }
1375
+ const id = items[i].id, size = dynamicSize ? ((_c = this.get(id)) === null || _c === void 0 ? void 0 : _c[sizeProperty]) || typicalItemSize : typicalItemSize;
1376
+ if (id !== (stickyItem === null || stickyItem === void 0 ? void 0 : stickyItem.id) && id !== (endStickyItem === null || endStickyItem === void 0 ? void 0 : endStickyItem.id)) {
1377
+ const snapped = snap && (stickyMap[id] === 1 && pos <= scrollSize || stickyMap[id] === 2 && pos >= scrollSize + boundsSize - size), measures = {
1378
+ x: isVertical ? stickyMap[id] === 1 ? 0 : boundsSize - size : pos,
1379
+ y: isVertical ? pos : stickyMap[id] === 2 ? boundsSize - size : 0,
1380
+ width: isVertical ? normalizedItemWidth : size,
1381
+ height: isVertical ? size : normalizedItemHeight,
1382
+ delta: 0,
1383
+ }, config = {
1384
+ isVertical,
1385
+ sticky: stickyMap[id],
1386
+ snap,
1387
+ snapped: false,
1388
+ snappedOut: false,
1389
+ dynamic: dynamicSize,
1390
+ isSnappingMethodAdvanced,
1391
+ zIndex: '0',
1392
+ };
1393
+ if (snapped) {
1394
+ config.zIndex = '2';
1395
+ }
1396
+ const itemData = items[i];
1397
+ const item = { id, measures, data: itemData, config };
1398
+ if (!nextSticky && stickyItemIndex < i && stickyMap[id] === 1 && (pos <= scrollSize + size + stickyItemSize)) {
1399
+ item.measures.x = isVertical ? 0 : snapped ? actualSnippedPosition : pos;
1400
+ item.measures.y = isVertical ? snapped ? actualSnippedPosition : pos : 0;
1401
+ nextSticky = item;
1402
+ nextSticky.config.snapped = snapped;
1403
+ nextSticky.measures.delta = isVertical ? (item.measures.y - scrollSize) : (item.measures.x - scrollSize);
1404
+ nextSticky.config.zIndex = '3';
1405
+ }
1406
+ else if (!nextEndSticky && endStickyItemIndex > i && stickyMap[id] === 2 && (pos >= scrollSize + boundsSize - size - endStickyItemSize)) {
1407
+ item.measures.x = isVertical ? 0 : snapped ? actualEndSnippedPosition - size : pos;
1408
+ item.measures.y = isVertical ? snapped ? actualEndSnippedPosition - size : pos : 0;
1409
+ nextEndSticky = item;
1410
+ nextEndSticky.config.zIndex = '3';
1411
+ nextEndSticky.config.snapped = snapped;
1412
+ nextEndSticky.measures.delta = isVertical ? (item.measures.y - scrollSize) : (item.measures.x - scrollSize);
1413
+ }
1414
+ displayItems.push(item);
1415
+ }
1416
+ renderItems -= 1;
1417
+ pos += size;
1418
+ i++;
1419
+ }
1420
+ const axis = isVertical ? Y_PROP_NAME : X_PROP_NAME;
1421
+ if (nextSticky && stickyItem && nextSticky.measures[axis] <= scrollSize + stickyItemSize) {
1422
+ if (nextSticky.measures[axis] > scrollSize) {
1423
+ stickyItem.measures[axis] = nextSticky.measures[axis] - stickyItemSize;
1424
+ stickyItem.config.snapped = nextSticky.config.snapped = false;
1425
+ stickyItem.config.snappedOut = true;
1426
+ stickyItem.config.sticky = 1;
1427
+ stickyItem.measures.delta = isVertical ? stickyItem.measures.y - scrollSize : stickyItem.measures.x - scrollSize;
1428
+ }
1429
+ else {
1430
+ nextSticky.config.snapped = true;
1431
+ nextSticky.measures.delta = isVertical ? nextSticky.measures.y - scrollSize : nextSticky.measures.x - scrollSize;
1432
+ }
1433
+ }
1434
+ if (nextEndSticky && endStickyItem && nextEndSticky.measures[axis] >= scrollSize + boundsSize - endStickyItemSize - nextEndSticky.measures[sizeProperty]) {
1435
+ if (nextEndSticky.measures[axis] < scrollSize + boundsSize - endStickyItemSize) {
1436
+ endStickyItem.measures[axis] = nextEndSticky.measures[axis] + nextEndSticky.measures[sizeProperty];
1437
+ endStickyItem.config.snapped = nextEndSticky.config.snapped = false;
1438
+ endStickyItem.config.snappedOut = true;
1439
+ endStickyItem.config.sticky = 2;
1440
+ endStickyItem.measures.delta = isVertical ? endStickyItem.measures.y - scrollSize : endStickyItem.measures.x - scrollSize;
1441
+ }
1442
+ else {
1443
+ nextEndSticky.config.snapped = true;
1444
+ nextEndSticky.measures.delta = isVertical ? nextEndSticky.measures.y - scrollSize : nextEndSticky.measures.x - scrollSize;
1445
+ }
1446
+ }
1447
+ }
1448
+ return displayItems;
1449
+ }
1450
+ /**
1451
+ * tracking by propName
1452
+ */
1453
+ track() {
1454
+ if (!this._items || !this._displayComponents) {
1455
+ return;
1456
+ }
1457
+ this._tracker.track(this._items, this._displayComponents, this._snapedDisplayComponent, this.scrollDirection);
1458
+ }
1459
+ setDisplayObjectIndexMapById(v) {
1460
+ this._tracker.displayObjectIndexMapById = v;
1461
+ }
1462
+ untrackComponentByIdProperty(component) {
1463
+ this._tracker.untrackComponentByIdProperty(component);
1464
+ }
1465
+ getItemBounds(id) {
1466
+ if (this.has(id)) {
1467
+ return this.get(id);
1468
+ }
1469
+ return undefined;
1470
+ }
1471
+ cacheElements() {
1472
+ if (!this._displayComponents) {
1473
+ return;
1474
+ }
1475
+ for (let i = 0, l = this._displayComponents.length; i < l; i++) {
1476
+ const component = this._displayComponents[i], itemId = component.instance.itemId;
1477
+ if (itemId === undefined) {
1478
+ continue;
1479
+ }
1480
+ const bounds = component.instance.getBounds();
1481
+ this.set(itemId, bounds);
1482
+ }
1483
+ }
1484
+ dispose() {
1485
+ super.dispose();
1486
+ this.disposeClearBufferSizeTimer();
1487
+ if (this._tracker) {
1488
+ this._tracker.dispose();
1489
+ }
1490
+ }
1491
+ }
1492
+
1493
+ /**
1494
+ * Base disposable component
1495
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/disposableComponent.ts
1496
+ * @author Evgenii Grebennikov
1497
+ * @email djonnyx@gmail.com
1498
+ */
1499
+ class DisposableComponent {
1500
+ constructor() {
1501
+ this._$unsubscribe = new Subject();
1502
+ }
1503
+ ngOnDestroy() {
1504
+ if (this._$unsubscribe) {
1505
+ this._$unsubscribe.next();
1506
+ this._$unsubscribe.complete();
1507
+ }
1508
+ }
1509
+ }
1510
+ DisposableComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: DisposableComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
1511
+ DisposableComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: DisposableComponent, selector: "ng-component", ngImport: i0, template: ``, isInline: true });
1512
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: DisposableComponent, decorators: [{
1513
+ type: Component,
1514
+ args: [{
1515
+ template: ``,
1516
+ }]
1517
+ }] });
1518
+
1519
+ const ADVANCED_PATTERNS = [SnappingMethods.ADVANCED, 'advanced'], DEFAULT_PATTERN = [SnappingMethods.NORMAL, 'normal'];
1520
+ const isSnappingMethodAdvenced = (method) => {
1521
+ return ADVANCED_PATTERNS.includes(method);
1522
+ };
1523
+ const isSnappingMethodDefault = (method) => {
1524
+ return DEFAULT_PATTERN.includes(method);
1525
+ };
1526
+
1527
+ const IS_FIREFOX = navigator.userAgent.toLowerCase().includes('firefox');
1528
+ const FIREFOX_SCROLLBAR_OVERLAP_SIZE = 12;
1529
+
1530
+ const HORIZONTAL_ALIASES = [Directions.HORIZONTAL, 'horizontal'], VERTICAL_ALIASES = [Directions.VERTICAL, 'vertical'];
1531
+ /**
1532
+ * Determines the axis membership of a virtual list
1533
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/utils/isDirection.ts
1534
+ * @author Evgenii Grebennikov
1535
+ * @email djonnyx@gmail.com
1536
+ */
1537
+ const isDirection = (src, expected) => {
1538
+ if (HORIZONTAL_ALIASES.includes(expected)) {
1539
+ return HORIZONTAL_ALIASES.includes(src);
1540
+ }
1541
+ return VERTICAL_ALIASES.includes(src);
1542
+ };
1543
+
1544
+ /**
1545
+ * Virtual list component.
1546
+ * Maximum performance for extremely large lists.
1547
+ * It is based on algorithms for virtualization of screen objects.
1548
+ * @link https://github.com/DjonnyX/ng-virtual-list/blob/15.x/projects/ng-virtual-list/src/lib/ng-virtual-list.component.ts
1549
+ * @author Evgenii Grebennikov
1550
+ * @email djonnyx@gmail.com
1551
+ */
1552
+ class NgVirtualListComponent extends DisposableComponent {
1553
+ /**
1554
+ * Readonly. Returns the unique identifier of the component.
1555
+ */
1556
+ get id() { return this._id; }
1557
+ /**
1558
+ * Collection of list items.
1559
+ */
1560
+ set items(v) {
1561
+ if (this._$items.getValue() === v) {
1562
+ return;
1563
+ }
1564
+ const transformedValue = this._itemsTransform(v);
1565
+ this._$items.next(transformedValue);
1566
+ this._cdr.markForCheck();
1567
+ }
1568
+ ;
1569
+ get items() { return this._$items.getValue(); }
1570
+ /**
1571
+ * Determines whether elements will snap. Default value is "true".
1572
+ */
1573
+ set snap(v) {
1574
+ if (this._$snap.getValue() === v) {
1575
+ return;
1576
+ }
1577
+ this._$snap.next(v);
1578
+ this._cdr.markForCheck();
1579
+ }
1580
+ ;
1581
+ get snap() { return this._$snap.getValue(); }
1582
+ /**
1583
+ * Experimental!
1584
+ * Enables buffer optimization.
1585
+ * Can only be used if items in the collection are not added or updated. Otherwise, artifacts in the form of twitching of the scroll area are possible.
1586
+ * Works only if the property dynamic = true
1587
+ */
1588
+ set enabledBufferOptimization(v) {
1589
+ if (this._$enabledBufferOptimization.getValue() === v) {
1590
+ return;
1591
+ }
1592
+ this._$enabledBufferOptimization.next(v);
1593
+ this._cdr.markForCheck();
1594
+ }
1595
+ ;
1596
+ get enabledBufferOptimization() { return this._$enabledBufferOptimization.getValue(); }
1597
+ /**
1598
+ * Rendering element template.
1599
+ */
1600
+ set itemRenderer(v) {
1601
+ if (this._$itemRenderer.getValue() === v) {
1602
+ return;
1603
+ }
1604
+ this._$itemRenderer.next(v);
1605
+ this._cdr.markForCheck();
1606
+ }
1607
+ ;
1608
+ get itemRenderer() { return this._$itemRenderer.getValue(); }
1609
+ /**
1610
+ * Dictionary zIndex by id of the list element. If the value is not set or equal to 0,
1611
+ * then a simple element is displayed, if the value is greater than 0, then the sticky position mode is enabled for the element.
1612
+ */
1613
+ set stickyMap(v) {
1614
+ if (this._$stickyMap.getValue() === v) {
1615
+ return;
1616
+ }
1617
+ this._$stickyMap.next(v);
1618
+ this._cdr.markForCheck();
1619
+ }
1620
+ ;
1621
+ get stickyMap() { return this._$stickyMap.getValue(); }
1622
+ /**
1623
+ * If direction = 'vertical', then the height of a typical element. If direction = 'horizontal', then the width of a typical element.
1624
+ * Ignored if the dynamicSize property is true.
1625
+ */
1626
+ set itemSize(v) {
1627
+ if (this._$itemSize.getValue() === v) {
1628
+ return;
1629
+ }
1630
+ this._$itemSize.next(this._itemSizeOptions(v));
1631
+ this._cdr.markForCheck();
1632
+ }
1633
+ ;
1634
+ get itemSize() { return this._$itemSize.getValue(); }
1635
+ /**
1636
+ * If true then the items in the list can have different sizes and the itemSize property is ignored.
1637
+ * If false then the items in the list have a fixed size specified by the itemSize property. The default value is false.
1638
+ */
1639
+ set dynamicSize(v) {
1640
+ if (this._$dynamicSize.getValue() === v) {
1641
+ return;
1642
+ }
1643
+ this._$dynamicSize.next(v);
1644
+ this._cdr.markForCheck();
1645
+ }
1646
+ ;
1647
+ get dynamicSize() { return this._$dynamicSize.getValue(); }
1648
+ /**
1649
+ * Determines the direction in which elements are placed. Default value is "vertical".
1650
+ */
1651
+ set direction(v) {
1652
+ if (this._$direction.getValue() === v) {
1653
+ return;
1654
+ }
1655
+ this._$direction.next(v);
1656
+ this._cdr.markForCheck();
1657
+ }
1658
+ ;
1659
+ get direction() { return this._$direction.getValue(); }
1660
+ /**
1661
+ * @deprecated "itemOffset" parameter is deprecated. Use "bufferSize" and "maxBufferSize".
1662
+ */
1663
+ set itemsOffset(v) {
1664
+ throw Error('"itemOffset" parameter is deprecated. Use "bufferSize" and "maxBufferSize".');
1665
+ }
1666
+ ;
1667
+ /**
1668
+ * Number of elements outside the scope of visibility. Default value is 2.
1669
+ */
1670
+ set bufferSize(v) {
1671
+ if (this._$bufferSize.getValue() === v) {
1672
+ return;
1673
+ }
1674
+ this._$bufferSize.next(v);
1675
+ }
1676
+ ;
1677
+ get bufferSize() { return this._$bufferSize.getValue(); }
1678
+ /**
1679
+ * Maximum number of elements outside the scope of visibility. Default value is 100.
1680
+ * If maxBufferSize is set to be greater than bufferSize, then adaptive buffer mode is enabled.
1681
+ * The greater the scroll size, the more elements are allocated for rendering.
1682
+ */
1683
+ set maxBufferSize(v) {
1684
+ const val = this._maxBufferSizeTransform(v);
1685
+ if (this._$maxBufferSize.getValue() === val) {
1686
+ return;
1687
+ }
1688
+ this._$maxBufferSize.next(val);
1689
+ }
1690
+ ;
1691
+ get maxBufferSize() { return this._$maxBufferSize.getValue(); }
1692
+ /**
1693
+ * The name of the property by which tracking is performed
1694
+ */
1695
+ set trackBy(v) {
1696
+ if (this._$trackBy.getValue() === v) {
1697
+ return;
1698
+ }
1699
+ this._$trackBy.next(v);
1700
+ }
1701
+ ;
1702
+ get trackBy() { return this._$trackBy.getValue(); }
1703
+ /**
1704
+ * Snapping method.
1705
+ * 'default' - Normal group rendering.
1706
+ * 'advanced' - The group is rendered on a transparent background. List items below the group are not rendered.
1707
+ */
1708
+ set snappingMethod(v) {
1709
+ if (this._$snappingMethod.getValue() === v) {
1710
+ return;
1711
+ }
1712
+ this._$snappingMethod.next(v);
1713
+ }
1714
+ ;
1715
+ get snappingMethod() { return this._$snappingMethod.getValue(); }
1716
+ get isSnappingMethodAdvanced() { return this._isSnappingMethodAdvanced; }
1717
+ get $cacheVersion() { return this._$cacheVersion.asObservable(); }
1718
+ constructor(_cdr, _elementRef) {
1719
+ super();
1720
+ this._cdr = _cdr;
1721
+ this._elementRef = _elementRef;
1722
+ this._id = NgVirtualListComponent.__nextId;
1723
+ /**
1724
+ * Fires when the list has been scrolled.
1725
+ */
1726
+ this.onScroll = new EventEmitter$1();
1727
+ /**
1728
+ * Fires when the list has completed scrolling.
1729
+ */
1730
+ this.onScrollEnd = new EventEmitter$1();
1731
+ this._$items = new BehaviorSubject(undefined);
1732
+ this.$items = this._$items.asObservable();
1733
+ this._itemsTransform = (v) => {
1734
+ this._trackBox.resetCollection(v, this._$itemSize.getValue());
1735
+ return v;
1736
+ };
1737
+ this._$snap = new BehaviorSubject(DEFAULT_SNAP);
1738
+ this.$snap = this._$snap.asObservable();
1739
+ this._$enabledBufferOptimization = new BehaviorSubject(DEFAULT_ENABLED_BUFFER_OPTIMIZATION);
1740
+ this.$enabledBufferOptimization = this._$enabledBufferOptimization.asObservable();
1741
+ this._$itemRenderer = new BehaviorSubject(undefined);
1742
+ this.$itemRenderer = this._$itemRenderer.asObservable();
1743
+ this._$renderer = new BehaviorSubject(undefined);
1744
+ this._$stickyMap = new BehaviorSubject({});
1745
+ this.$stickyMap = this._$stickyMap.asObservable();
1746
+ this._itemSizeOptions = (v) => {
1747
+ if (v === undefined) {
1748
+ return DEFAULT_ITEM_SIZE;
1749
+ }
1750
+ const val = Number(v);
1751
+ return Number.isNaN(val) || val <= 0 ? DEFAULT_ITEM_SIZE : val;
1752
+ };
1753
+ this._$itemSize = new BehaviorSubject(DEFAULT_ITEM_SIZE);
1754
+ this.$itemSize = this._$itemSize.asObservable();
1755
+ this._$dynamicSize = new BehaviorSubject(DEFAULT_DYNAMIC_SIZE);
1756
+ this.$dynamicSize = this._$dynamicSize.asObservable();
1757
+ this._$direction = new BehaviorSubject(DEFAULT_DIRECTION);
1758
+ this.$direction = this._$direction.asObservable();
1759
+ this._$bufferSize = new BehaviorSubject(DEFAULT_BUFFER_SIZE);
1760
+ this.$bufferSize = this._$bufferSize.asObservable();
1761
+ this._maxBufferSizeTransform = (v) => {
1762
+ const bufferSize = this._$bufferSize.getValue();
1763
+ if (v === undefined || v <= bufferSize) {
1764
+ return bufferSize;
1765
+ }
1766
+ return v;
1767
+ };
1768
+ this._$maxBufferSize = new BehaviorSubject(DEFAULT_MAX_BUFFER_SIZE);
1769
+ this.$maxBufferSize = this._$maxBufferSize.asObservable();
1770
+ this._$trackBy = new BehaviorSubject(TRACK_BY_PROPERTY_NAME);
1771
+ this.$trackBy = this._$trackBy.asObservable();
1772
+ this._isVertical = this.getIsVertical();
1773
+ this._$snappingMethod = new BehaviorSubject(DEFAULT_SNAPPING_METHOD);
1774
+ this.$snappingMethod = this._$snappingMethod.asObservable();
1775
+ this._isSnappingMethodAdvanced = this.getIsSnappingMethodAdvanced();
1776
+ this._displayComponents = [];
1777
+ this._$bounds = new BehaviorSubject(null);
1778
+ this._$scrollSize = new BehaviorSubject(0);
1779
+ this._resizeObserver = null;
1780
+ this._resizeSnappedComponentHandler = () => {
1781
+ var _a, _b, _c, _d, _e, _f;
1782
+ const list = this._list, container = this._container, snappedComponent = (_a = this._snapedDisplayComponent) === null || _a === void 0 ? void 0 : _a.instance;
1783
+ if (list && container && snappedComponent) {
1784
+ const isVertical = this._isVertical, listBounds = list.nativeElement.getBoundingClientRect(), listElement = list === null || list === void 0 ? void 0 : list.nativeElement, { width: lWidth, height: lHeight } = (_b = listElement === null || listElement === void 0 ? void 0 : listElement.getBoundingClientRect()) !== null && _b !== void 0 ? _b : { width: 0, height: 0 }, { width, height } = (_c = this._$bounds.getValue()) !== null && _c !== void 0 ? _c : { width: 0, height: 0 }, isScrollable = isVertical ? container.nativeElement.scrollHeight > 0 : container.nativeElement.scrollWidth > 0;
1785
+ let scrollBarSize = isVertical ? width - lWidth : height - lHeight, isScrollBarOverlap = true, overlapScrollBarSize = 0;
1786
+ if (scrollBarSize === 0 && isScrollable) {
1787
+ isScrollBarOverlap = true;
1788
+ }
1789
+ if (isScrollBarOverlap && IS_FIREFOX) {
1790
+ scrollBarSize = overlapScrollBarSize = FIREFOX_SCROLLBAR_OVERLAP_SIZE;
1791
+ }
1792
+ const { width: sWidth, height: sHeight } = (_d = snappedComponent.getBounds()) !== null && _d !== void 0 ? _d : { width: 0, height: 0 };
1793
+ snappedComponent.element.style.clipPath = `path("M 0 0 L 0 ${sHeight} L ${sWidth - overlapScrollBarSize} ${sHeight} L ${sWidth - overlapScrollBarSize} 0 Z")`;
1794
+ snappedComponent.regularLength = `${isVertical ? listBounds.width : listBounds.height}${PX}`;
1795
+ const containerElement = container.nativeElement, delta = (_f = (_e = snappedComponent.item) === null || _e === void 0 ? void 0 : _e.measures.delta) !== null && _f !== void 0 ? _f : 0;
1796
+ let left, right, top, bottom;
1797
+ if (isVertical) {
1798
+ left = 0;
1799
+ right = width - scrollBarSize;
1800
+ top = sHeight;
1801
+ bottom = height;
1802
+ containerElement.style.clipPath = `path("M 0 ${top + delta} L 0 ${height} L ${width} ${height} L ${width} 0 L ${right} 0 L ${right} ${top + delta} Z")`;
1803
+ }
1804
+ else {
1805
+ left = sWidth;
1806
+ right = width;
1807
+ top = 0;
1808
+ bottom = height - scrollBarSize;
1809
+ containerElement.style.clipPath = `path("M ${left + delta} 0 L ${left + delta} ${bottom} L 0 ${bottom} L 0 ${height} L ${width} ${height} L ${width} 0 Z")`;
1810
+ }
1811
+ }
1812
+ };
1813
+ this._resizeSnappedObserver = null;
1814
+ this._onResizeHandler = () => {
1815
+ var _a, _b;
1816
+ const bounds = (_b = (_a = this._container) === null || _a === void 0 ? void 0 : _a.nativeElement) === null || _b === void 0 ? void 0 : _b.getBoundingClientRect();
1817
+ if (bounds) {
1818
+ this._$bounds.next({ width: bounds.width, height: bounds.height });
1819
+ }
1820
+ else {
1821
+ this._$bounds.next({ width: DEFAULT_LIST_SIZE, height: DEFAULT_LIST_SIZE });
1822
+ }
1823
+ if (this._isSnappingMethodAdvanced) {
1824
+ this.updateRegularRenderer();
1825
+ }
1826
+ };
1827
+ this._onScrollHandler = (e) => {
1828
+ var _a;
1829
+ this.clearScrollToRepeatExecutionTimeout();
1830
+ const container = (_a = this._container) === null || _a === void 0 ? void 0 : _a.nativeElement;
1831
+ if (container) {
1832
+ const scrollSize = (this._isVertical ? container.scrollTop : container.scrollLeft);
1833
+ this._$scrollSize.next(scrollSize);
1834
+ }
1835
+ };
1836
+ this._$initialized = new BehaviorSubject(false);
1837
+ /**
1838
+ * Base class of the element component
1839
+ */
1840
+ this._itemComponentClass = NgVirtualListItemComponent;
1841
+ /**
1842
+ * Base class trackBox
1843
+ */
1844
+ this._trackBoxClass = TrackBox;
1845
+ /**
1846
+ * Dictionary of element sizes by their id
1847
+ */
1848
+ this._trackBox = new this._trackBoxClass(this.trackBy);
1849
+ this._onTrackBoxChangeHandler = (v) => {
1850
+ this._$cacheVersion.next(v);
1851
+ };
1852
+ this._$cacheVersion = new BehaviorSubject(-1);
1853
+ this._componentsResizeObserver = new ResizeObserver(() => {
1854
+ this._trackBox.changes();
1855
+ });
1856
+ this._onContainerScrollHandler = (e) => {
1857
+ const containerEl = this._container;
1858
+ if (containerEl) {
1859
+ const scrollSize = (this._isVertical ? containerEl.nativeElement.scrollTop : containerEl.nativeElement.scrollLeft);
1860
+ this._trackBox.deltaDirection = this._$scrollSize.getValue() > scrollSize ? -1 : this._$scrollSize.getValue() < scrollSize ? 1 : 0;
1861
+ const event = new ScrollEvent({
1862
+ direction: this._trackBox.scrollDirection, container: containerEl.nativeElement,
1863
+ list: this._list.nativeElement, delta: this._trackBox.delta,
1864
+ scrollDelta: this._trackBox.scrollDelta, isVertical: this._isVertical,
1865
+ });
1866
+ this.onScroll.emit(event);
1867
+ }
1868
+ };
1869
+ this._onContainerScrollEndHandler = (e) => {
1870
+ const containerEl = this._container;
1871
+ if (containerEl) {
1872
+ const scrollSize = (this._isVertical ? containerEl.nativeElement.scrollTop : containerEl.nativeElement.scrollLeft);
1873
+ this._trackBox.deltaDirection = this._$scrollSize.getValue() > scrollSize ? -1 : 0;
1874
+ const event = new ScrollEvent({
1875
+ direction: this._trackBox.scrollDirection, container: containerEl.nativeElement,
1876
+ list: this._list.nativeElement, delta: this._trackBox.delta,
1877
+ scrollDelta: this._trackBox.scrollDelta, isVertical: this._isVertical,
1878
+ });
1879
+ this.onScrollEnd.emit(event);
1880
+ }
1881
+ };
1882
+ NgVirtualListComponent.__nextId = NgVirtualListComponent.__nextId + 1 === Number.MAX_SAFE_INTEGER
1883
+ ? 0 : NgVirtualListComponent.__nextId + 1;
1884
+ this._id = NgVirtualListComponent.__nextId;
1885
+ this._$initialized = new BehaviorSubject(false);
1886
+ this.$initialized = this._$initialized.asObservable();
1887
+ this._trackBox.displayComponents = this._displayComponents;
1888
+ const $trackBy = this.$trackBy;
1889
+ $trackBy.pipe(takeUntil(this._$unsubscribe), tap(v => {
1890
+ this._trackBox.trackingPropertyName = v;
1891
+ })).subscribe();
1892
+ const $bounds = this._$bounds.asObservable().pipe(filter(b => !!b)), $items = this.$items.pipe(map(i => !i ? [] : i)), $scrollSize = this._$scrollSize.asObservable(), $itemSize = this.$itemSize.pipe(map(v => v <= 0 ? DEFAULT_ITEM_SIZE : v)), $bufferSize = this.$bufferSize.pipe(map(v => v < 0 ? DEFAULT_BUFFER_SIZE : v)), $maxBufferSize = this.$maxBufferSize.pipe(map(v => v < 0 ? DEFAULT_MAX_BUFFER_SIZE : v)), $stickyMap = this.$stickyMap.pipe(map(v => !v ? {} : v)), $snap = this.$snap, $isVertical = this.$direction.pipe(map(v => this.getIsVertical(v || DEFAULT_DIRECTION))), $dynamicSize = this.$dynamicSize, $enabledBufferOptimization = this.$enabledBufferOptimization, $snappingMethod = this.$snappingMethod.pipe(map(v => this.getIsSnappingMethodAdvanced(v || DEFAULT_SNAPPING_METHOD))), $cacheVersion = this.$cacheVersion;
1893
+ $isVertical.pipe(takeUntil(this._$unsubscribe), tap(v => {
1894
+ this._isVertical = v;
1895
+ const el = this._elementRef.nativeElement;
1896
+ toggleClassName(el, v ? CLASS_LIST_VERTICAL : CLASS_LIST_HORIZONTAL, v ? CLASS_LIST_HORIZONTAL : CLASS_LIST_VERTICAL);
1897
+ })).subscribe();
1898
+ $snappingMethod.pipe(takeUntil(this._$unsubscribe), tap(v => {
1899
+ this._isSnappingMethodAdvanced = this._trackBox.isSnappingMethodAdvanced = v;
1900
+ })).subscribe();
1901
+ $dynamicSize.pipe(takeUntil(this._$unsubscribe), tap(dynamicSize => {
1902
+ this.listenCacheChangesIfNeed(dynamicSize);
1903
+ })).subscribe();
1904
+ combineLatest([this.$initialized, $bounds, $items, $stickyMap, $scrollSize, $itemSize,
1905
+ $bufferSize, $maxBufferSize, $snap, $isVertical, $dynamicSize, $enabledBufferOptimization, $cacheVersion,
1906
+ ]).pipe(takeUntil(this._$unsubscribe), distinctUntilChanged(), filter(([initialized]) => !!initialized), switchMap(([, bounds, items, stickyMap, scrollSize, itemSize, bufferSize, maxBufferSize, snap, isVertical, dynamicSize, enabledBufferOptimization, cacheVersion,]) => {
1907
+ var _a, _b, _c, _d;
1908
+ let actualScrollSize = (_d = (this._isVertical ? (_b = (_a = this._container) === null || _a === void 0 ? void 0 : _a.nativeElement.scrollTop) !== null && _b !== void 0 ? _b : 0 : (_c = this._container) === null || _c === void 0 ? void 0 : _c.nativeElement.scrollLeft)) !== null && _d !== void 0 ? _d : 0;
1909
+ const { width, height } = bounds, opts = {
1910
+ bounds: { width, height }, dynamicSize, isVertical, itemSize,
1911
+ bufferSize, maxBufferSize, scrollSize: actualScrollSize, snap, enabledBufferOptimization,
1912
+ }, { displayItems, totalSize } = this._trackBox.updateCollection(items, stickyMap, opts);
1913
+ this.resetBoundsSize(isVertical, totalSize);
1914
+ this.createDisplayComponentsIfNeed(displayItems);
1915
+ this.tracking();
1916
+ if (this._isSnappingMethodAdvanced) {
1917
+ this.updateRegularRenderer();
1918
+ }
1919
+ const container = this._container;
1920
+ if (container) {
1921
+ const delta = this._trackBox.delta;
1922
+ actualScrollSize = actualScrollSize + delta;
1923
+ this._trackBox.clearDelta();
1924
+ if (scrollSize !== actualScrollSize) {
1925
+ const params = {
1926
+ [this._isVertical ? TOP_PROP_NAME : LEFT_PROP_NAME]: actualScrollSize,
1927
+ behavior: BEHAVIOR_INSTANT
1928
+ };
1929
+ container.nativeElement.scrollTo(params);
1930
+ }
1931
+ }
1932
+ return of(displayItems);
1933
+ })).subscribe();
1934
+ const $itemRenderer = this.$itemRenderer;
1935
+ $itemRenderer.pipe(takeUntil(this._$unsubscribe), distinctUntilChanged(), filter(v => !!v), tap(v => {
1936
+ this._$renderer.next(v);
1937
+ })).subscribe();
1938
+ }
1939
+ /** @internal */
1940
+ ngOnInit() {
1941
+ this.onInit();
1942
+ }
1943
+ onInit() {
1944
+ this._$initialized.next(true);
1945
+ }
1946
+ listenCacheChangesIfNeed(value) {
1947
+ if (value) {
1948
+ if (!this._trackBox.hasEventListener(TRACK_BOX_CHANGE_EVENT_NAME, this._onTrackBoxChangeHandler)) {
1949
+ this._trackBox.addEventListener(TRACK_BOX_CHANGE_EVENT_NAME, this._onTrackBoxChangeHandler);
1950
+ }
1951
+ }
1952
+ else {
1953
+ if (this._trackBox.hasEventListener(TRACK_BOX_CHANGE_EVENT_NAME, this._onTrackBoxChangeHandler)) {
1954
+ this._trackBox.removeEventListener(TRACK_BOX_CHANGE_EVENT_NAME, this._onTrackBoxChangeHandler);
1955
+ }
1956
+ }
1957
+ }
1958
+ getIsSnappingMethodAdvanced(m) {
1959
+ const method = m || this._$snappingMethod.getValue();
1960
+ return isSnappingMethodAdvenced(method);
1961
+ }
1962
+ getIsVertical(d) {
1963
+ const dir = d || this.direction;
1964
+ return isDirection(dir, Directions.VERTICAL);
1965
+ }
1966
+ createDisplayComponentsIfNeed(displayItems) {
1967
+ if (!displayItems || !this._listContainerRef) {
1968
+ this._trackBox.setDisplayObjectIndexMapById({});
1969
+ return;
1970
+ }
1971
+ if (this._isSnappingMethodAdvanced && this.snap) {
1972
+ if (!this._snapedDisplayComponent && this._snapContainerRef) {
1973
+ const comp = this._snapContainerRef.createComponent(this._itemComponentClass);
1974
+ comp.instance.regular = true;
1975
+ this._snapedDisplayComponent = comp;
1976
+ this._trackBox.snapedDisplayComponent = this._snapedDisplayComponent;
1977
+ this._resizeSnappedObserver = new ResizeObserver(this._resizeSnappedComponentHandler);
1978
+ this._resizeSnappedObserver.observe(comp.instance.element);
1979
+ }
1980
+ }
1981
+ this._trackBox.items = displayItems;
1982
+ const _listContainerRef = this._listContainerRef;
1983
+ const maxLength = displayItems.length, components = this._displayComponents;
1984
+ while (components.length < maxLength) {
1985
+ if (_listContainerRef) {
1986
+ const comp = _listContainerRef.createComponent(this._itemComponentClass);
1987
+ components.push(comp);
1988
+ this._componentsResizeObserver.observe(comp.instance.element);
1989
+ }
1990
+ }
1991
+ this.resetRenderers();
1992
+ }
1993
+ updateRegularRenderer() {
1994
+ this._resizeSnappedComponentHandler();
1995
+ }
1996
+ resetRenderers(itemRenderer) {
1997
+ const doMap = {};
1998
+ for (let i = 0, l = this._displayComponents.length; i < l; i++) {
1999
+ const item = this._displayComponents[i];
2000
+ item.instance.renderer = itemRenderer || this.itemRenderer;
2001
+ doMap[item.instance.id] = i;
2002
+ }
2003
+ if (this._isSnappingMethodAdvanced && this.snap && this._snapedDisplayComponent && this._snapContainerRef) {
2004
+ const comp = this._snapedDisplayComponent;
2005
+ comp.instance.renderer = itemRenderer || this.itemRenderer;
2006
+ }
2007
+ this._trackBox.setDisplayObjectIndexMapById(doMap);
2008
+ }
2009
+ /**
2010
+ * Tracking by id
2011
+ */
2012
+ tracking() {
2013
+ this._trackBox.track();
2014
+ }
2015
+ resetBoundsSize(isVertical, totalSize) {
2016
+ const l = this._list;
2017
+ if (l) {
2018
+ l.nativeElement.style[isVertical ? HEIGHT_PROP_NAME : WIDTH_PROP_NAME] = `${totalSize}${PX}`;
2019
+ }
2020
+ }
2021
+ /**
2022
+ * Returns the bounds of an element with a given id
2023
+ */
2024
+ getItemBounds(id) {
2025
+ return this._trackBox.getItemBounds(id);
2026
+ }
2027
+ /**
2028
+ * The method scrolls the list to the element with the given id and returns the value of the scrolled area.
2029
+ * Behavior accepts the values ​​"auto", "instant" and "smooth".
2030
+ */
2031
+ scrollTo(id, behavior = BEHAVIOR_AUTO) {
2032
+ this.scrollToExecutor(id, behavior);
2033
+ }
2034
+ clearScrollToRepeatExecutionTimeout() {
2035
+ clearTimeout(this._scrollToRepeatExecutionTimeout);
2036
+ }
2037
+ scrollToExecutor(id, behavior, iteration = 0, isLastIteration = false) {
2038
+ const items = this.items;
2039
+ if (!items || !items.length) {
2040
+ return;
2041
+ }
2042
+ const dynamicSize = this.dynamicSize, container = this._container, itemSize = this.itemSize;
2043
+ if (container) {
2044
+ this.clearScrollToRepeatExecutionTimeout();
2045
+ if (dynamicSize) {
2046
+ if (container) {
2047
+ container.nativeElement.removeEventListener(SCROLL, this._onScrollHandler);
2048
+ }
2049
+ const { width, height } = this._$bounds.getValue() || { width: 0, height: 0 }, stickyMap = this.stickyMap, items = this.items, isVertical = this._isVertical, delta = this._trackBox.delta, opts = {
2050
+ bounds: { width, height }, collection: items, dynamicSize, isVertical: this._isVertical, itemSize,
2051
+ bufferSize: this.bufferSize, maxBufferSize: this.maxBufferSize, scrollSize: (isVertical ? container.nativeElement.scrollTop : container.nativeElement.scrollLeft) + delta,
2052
+ snap: this.snap, fromItemId: id, enabledBufferOptimization: this.enabledBufferOptimization,
2053
+ }, scrollSize = this._trackBox.getItemPosition(id, stickyMap, opts), params = { [isVertical ? TOP_PROP_NAME : LEFT_PROP_NAME]: scrollSize, behavior };
2054
+ if (scrollSize === -1) {
2055
+ container.nativeElement.addEventListener(SCROLL, this._onScrollHandler);
2056
+ return;
2057
+ }
2058
+ this._trackBox.clearDelta();
2059
+ if (container) {
2060
+ const { displayItems, totalSize } = this._trackBox.updateCollection(items, stickyMap, Object.assign(Object.assign({}, opts), { scrollSize, fromItemId: isLastIteration ? undefined : id })), delta = this._trackBox.delta;
2061
+ this._trackBox.clearDelta();
2062
+ let actualScrollSize = scrollSize + delta;
2063
+ this.resetBoundsSize(isVertical, totalSize);
2064
+ this.createDisplayComponentsIfNeed(displayItems);
2065
+ this.tracking();
2066
+ const _scrollSize = this._trackBox.getItemPosition(id, stickyMap, Object.assign(Object.assign({}, opts), { scrollSize: actualScrollSize, fromItemId: id }));
2067
+ if (_scrollSize === -1) {
2068
+ container.nativeElement.addEventListener(SCROLL, this._onScrollHandler);
2069
+ return;
2070
+ }
2071
+ const notChanged = actualScrollSize === _scrollSize;
2072
+ if (!notChanged || iteration < MAX_SCROLL_TO_ITERATIONS) {
2073
+ this.clearScrollToRepeatExecutionTimeout();
2074
+ this._scrollToRepeatExecutionTimeout = setTimeout(() => {
2075
+ this.scrollToExecutor(id, BEHAVIOR_INSTANT, iteration + 1, notChanged);
2076
+ });
2077
+ }
2078
+ else {
2079
+ this._$scrollSize.next(actualScrollSize);
2080
+ container.nativeElement.addEventListener(SCROLL, this._onScrollHandler);
2081
+ }
2082
+ }
2083
+ container.nativeElement.scrollTo(params);
2084
+ this._$scrollSize.next(scrollSize);
2085
+ }
2086
+ else {
2087
+ const index = items.findIndex(item => item.id === id);
2088
+ if (index > -1) {
2089
+ const scrollSize = index * this.itemSize;
2090
+ const params = { [this._isVertical ? TOP_PROP_NAME : LEFT_PROP_NAME]: scrollSize, behavior };
2091
+ container.nativeElement.scrollTo(params);
2092
+ }
2093
+ }
2094
+ }
2095
+ }
2096
+ /**
2097
+ * Scrolls the scroll area to the desired element with the specified ID.
2098
+ */
2099
+ scrollToEnd(behavior = BEHAVIOR_INSTANT) {
2100
+ const items = this.items, latItem = items[items.length > 0 ? items.length - 1 : 0];
2101
+ this.scrollTo(latItem.id, behavior);
2102
+ }
2103
+ /** @internal */
2104
+ ngAfterViewInit() {
2105
+ this.afterViewInit();
2106
+ }
2107
+ afterViewInit() {
2108
+ const containerEl = this._container;
2109
+ if (containerEl) {
2110
+ // for direction calculation
2111
+ containerEl.nativeElement.addEventListener(SCROLL, this._onContainerScrollHandler);
2112
+ containerEl.nativeElement.addEventListener(SCROLL_END, this._onContainerScrollEndHandler);
2113
+ containerEl.nativeElement.addEventListener(SCROLL, this._onScrollHandler);
2114
+ this._resizeObserver = new ResizeObserver(this._onResizeHandler);
2115
+ this._resizeObserver.observe(containerEl.nativeElement);
2116
+ this._onResizeHandler();
2117
+ }
2118
+ }
2119
+ /** @internal */
2120
+ ngOnDestroy() {
2121
+ super.ngOnDestroy();
2122
+ this.dispose();
2123
+ }
2124
+ dispose() {
2125
+ this.clearScrollToRepeatExecutionTimeout();
2126
+ if (this._trackBox) {
2127
+ this._trackBox.dispose();
2128
+ }
2129
+ if (this._componentsResizeObserver) {
2130
+ this._componentsResizeObserver.disconnect();
2131
+ }
2132
+ if (this._resizeObserver) {
2133
+ this._resizeObserver.disconnect();
2134
+ }
2135
+ if (this._resizeSnappedObserver) {
2136
+ this._resizeSnappedObserver.disconnect();
2137
+ }
2138
+ const containerEl = this._container;
2139
+ if (containerEl) {
2140
+ containerEl.nativeElement.removeEventListener(SCROLL, this._onScrollHandler);
2141
+ containerEl.nativeElement.removeEventListener(SCROLL, this._onContainerScrollHandler);
2142
+ containerEl.nativeElement.removeEventListener(SCROLL_END, this._onContainerScrollEndHandler);
2143
+ }
2144
+ if (this._snapedDisplayComponent) {
2145
+ this._snapedDisplayComponent.destroy();
2146
+ }
2147
+ if (this._displayComponents) {
2148
+ while (this._displayComponents.length > 0) {
2149
+ const comp = this._displayComponents.pop();
2150
+ comp === null || comp === void 0 ? void 0 : comp.destroy();
2151
+ }
2152
+ }
2153
+ }
2154
+ }
2155
+ NgVirtualListComponent.__nextId = 0;
2156
+ NgVirtualListComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListComponent, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component });
2157
+ NgVirtualListComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.2.10", type: NgVirtualListComponent, selector: "ng-virtual-list", inputs: { items: "items", snap: "snap", enabledBufferOptimization: "enabledBufferOptimization", itemRenderer: "itemRenderer", stickyMap: "stickyMap", itemSize: "itemSize", dynamicSize: "dynamicSize", direction: "direction", itemsOffset: "itemsOffset", bufferSize: "bufferSize", maxBufferSize: "maxBufferSize", trackBy: "trackBy", snappingMethod: "snappingMethod" }, outputs: { onScroll: "onScroll", onScrollEnd: "onScrollEnd" }, viewQueries: [{ propertyName: "_listContainerRef", first: true, predicate: ["renderersContainer"], descendants: true, read: ViewContainerRef }, { propertyName: "_container", first: true, predicate: ["container"], descendants: true, read: (ElementRef) }, { propertyName: "_list", first: true, predicate: ["list"], descendants: true, read: (ElementRef) }, { propertyName: "_snapContainerRef", first: true, predicate: ["snapRendererContainer"], descendants: true, read: ViewContainerRef }, { propertyName: "_snappedContainer", first: true, predicate: ["snapped"], descendants: true, read: ViewContainerRef }], usesInheritance: true, ngImport: i0, template: "<div *ngIf=\"snap\" #snapped part=\"snapped-item\" class=\"ngvl__list-snapper\">\r\n <ng-container #snapRendererContainer></ng-container>\r\n</div>\r\n<div #container part=\"scroller\" class=\"ngvl__scroller\">\r\n <ul #list part=\"list\" class=\"ngvl__list\">\r\n <ng-container #renderersContainer></ng-container>\r\n </ul>\r\n</div>", styles: [":host{position:relative;display:block;width:400px;overflow:hidden}:host(.horizontal){height:48px}:host(.horizontal) .ngvl__list{display:inline-flex}:host(.horizontal) .ngvl__scroller{overflow:auto hidden}:host(.vertical) .ngvl__scroller{overflow:hidden auto}:host(.vertical){height:320px}.ngvl__scroller{overflow:auto;width:100%;height:100%}.ngvl__list-snapper{pointer-events:none;position:absolute;list-style:none;left:0;top:0;z-index:1}.ngvl__list{position:relative;list-style:none;padding:0;margin:0;width:100%;height:100%}\n"], dependencies: [{ kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.ShadowDom });
2158
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListComponent, decorators: [{
2159
+ type: Component,
2160
+ args: [{ selector: 'ng-virtual-list', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.ShadowDom, template: "<div *ngIf=\"snap\" #snapped part=\"snapped-item\" class=\"ngvl__list-snapper\">\r\n <ng-container #snapRendererContainer></ng-container>\r\n</div>\r\n<div #container part=\"scroller\" class=\"ngvl__scroller\">\r\n <ul #list part=\"list\" class=\"ngvl__list\">\r\n <ng-container #renderersContainer></ng-container>\r\n </ul>\r\n</div>", styles: [":host{position:relative;display:block;width:400px;overflow:hidden}:host(.horizontal){height:48px}:host(.horizontal) .ngvl__list{display:inline-flex}:host(.horizontal) .ngvl__scroller{overflow:auto hidden}:host(.vertical) .ngvl__scroller{overflow:hidden auto}:host(.vertical){height:320px}.ngvl__scroller{overflow:auto;width:100%;height:100%}.ngvl__list-snapper{pointer-events:none;position:absolute;list-style:none;left:0;top:0;z-index:1}.ngvl__list{position:relative;list-style:none;padding:0;margin:0;width:100%;height:100%}\n"] }]
2161
+ }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }]; }, propDecorators: { _listContainerRef: [{
2162
+ type: ViewChild,
2163
+ args: ['renderersContainer', { read: ViewContainerRef }]
2164
+ }], _container: [{
2165
+ type: ViewChild,
2166
+ args: ['container', { read: (ElementRef) }]
2167
+ }], _list: [{
2168
+ type: ViewChild,
2169
+ args: ['list', { read: (ElementRef) }]
2170
+ }], _snapContainerRef: [{
2171
+ type: ViewChild,
2172
+ args: ['snapRendererContainer', { read: ViewContainerRef }]
2173
+ }], _snappedContainer: [{
2174
+ type: ViewChild,
2175
+ args: ['snapped', { read: ViewContainerRef }]
2176
+ }], onScroll: [{
2177
+ type: Output
2178
+ }], onScrollEnd: [{
2179
+ type: Output
2180
+ }], items: [{
2181
+ type: Input
2182
+ }], snap: [{
2183
+ type: Input
2184
+ }], enabledBufferOptimization: [{
2185
+ type: Input
2186
+ }], itemRenderer: [{
2187
+ type: Input
2188
+ }], stickyMap: [{
2189
+ type: Input
2190
+ }], itemSize: [{
2191
+ type: Input
2192
+ }], dynamicSize: [{
2193
+ type: Input
2194
+ }], direction: [{
2195
+ type: Input
2196
+ }], itemsOffset: [{
2197
+ type: Input
2198
+ }], bufferSize: [{
2199
+ type: Input
2200
+ }], maxBufferSize: [{
2201
+ type: Input
2202
+ }], trackBy: [{
2203
+ type: Input
2204
+ }], snappingMethod: [{
2205
+ type: Input
2206
+ }] } });
2207
+
2208
+ class NgVirtualListModule {
2209
+ }
2210
+ NgVirtualListModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2211
+ NgVirtualListModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListModule, declarations: [NgVirtualListComponent, NgVirtualListItemComponent], imports: [CommonModule], exports: [NgVirtualListComponent] });
2212
+ NgVirtualListModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListModule, imports: [CommonModule] });
2213
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.2.10", ngImport: i0, type: NgVirtualListModule, decorators: [{
2214
+ type: NgModule,
2215
+ args: [{
2216
+ declarations: [NgVirtualListComponent, NgVirtualListItemComponent],
2217
+ exports: [NgVirtualListComponent],
2218
+ imports: [CommonModule],
2219
+ schemas: [NO_ERRORS_SCHEMA],
2220
+ }]
2221
+ }] });
2222
+
2223
+ /*
2224
+ * Public API Surface of ng-virtual-list
2225
+ */
2226
+
2227
+ /**
2228
+ * Generated bundle index. Do not edit.
2229
+ */
2230
+
2231
+ export { Directions, NgVirtualListComponent, NgVirtualListItemComponent, NgVirtualListModule, SnappingMethods };
2232
+ //# sourceMappingURL=ng-virtual-list.mjs.map