ng-virtual-list 14.7.0 → 14.7.2

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