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