@tanstack/react-virtual 3.0.0-beta.2 → 3.0.0-beta.21

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.
@@ -44,76 +44,6 @@
44
44
  *
45
45
  * @license MIT
46
46
  */
47
- var props = ["bottom", "height", "left", "right", "top", "width"];
48
-
49
- var rectChanged = function rectChanged(a, b) {
50
- if (a === void 0) {
51
- a = {};
52
- }
53
-
54
- if (b === void 0) {
55
- b = {};
56
- }
57
-
58
- return props.some(function (prop) {
59
- return a[prop] !== b[prop];
60
- });
61
- };
62
-
63
- var observedNodes = /*#__PURE__*/new Map();
64
- var rafId;
65
-
66
- var run = function run() {
67
- var changedStates = [];
68
- observedNodes.forEach(function (state, node) {
69
- var newRect = node.getBoundingClientRect();
70
-
71
- if (rectChanged(newRect, state.rect)) {
72
- state.rect = newRect;
73
- changedStates.push(state);
74
- }
75
- });
76
- changedStates.forEach(function (state) {
77
- state.callbacks.forEach(function (cb) {
78
- return cb(state.rect);
79
- });
80
- });
81
- rafId = window.requestAnimationFrame(run);
82
- };
83
-
84
- function observeRect(node, cb) {
85
- return {
86
- observe: function observe() {
87
- var wasEmpty = observedNodes.size === 0;
88
-
89
- if (observedNodes.has(node)) {
90
- observedNodes.get(node).callbacks.push(cb);
91
- } else {
92
- observedNodes.set(node, {
93
- rect: undefined,
94
- hasRectChanged: false,
95
- callbacks: [cb]
96
- });
97
- }
98
-
99
- if (wasEmpty) run();
100
- },
101
- unobserve: function unobserve() {
102
- var state = observedNodes.get(node);
103
-
104
- if (state) {
105
- // Remove the callback
106
- var index = state.callbacks.indexOf(cb);
107
- if (index >= 0) state.callbacks.splice(index, 1); // Remove the node reference
108
-
109
- if (!state.callbacks.length) observedNodes["delete"](node); // Stop the loop
110
-
111
- if (!observedNodes.size) cancelAnimationFrame(rafId);
112
- }
113
- }
114
- };
115
- }
116
-
117
47
  function memo(getDeps, fn, opts) {
118
48
  let deps = [];
119
49
  let result;
@@ -168,9 +98,29 @@
168
98
 
169
99
  return arr;
170
100
  };
101
+
102
+ const memoRectCallback = (instance, cb) => {
103
+ let prev = {
104
+ height: -1,
105
+ width: -1
106
+ };
107
+ return rect => {
108
+ if (instance.options.horizontal ? rect.width !== prev.width : rect.height !== prev.height) {
109
+ cb(rect);
110
+ }
111
+
112
+ prev = rect;
113
+ };
114
+ };
115
+
171
116
  const observeElementRect = (instance, cb) => {
172
- const observer = observeRect(instance.scrollElement, rect => {
173
- cb(rect);
117
+ const observer = new ResizeObserver(entries => {
118
+ var _entries$, _entries$2;
119
+
120
+ cb({
121
+ width: (_entries$ = entries[0]) == null ? void 0 : _entries$.contentRect.width,
122
+ height: (_entries$2 = entries[0]) == null ? void 0 : _entries$2.contentRect.height
123
+ });
174
124
  });
175
125
 
176
126
  if (!instance.scrollElement) {
@@ -178,18 +128,18 @@
178
128
  }
179
129
 
180
130
  cb(instance.scrollElement.getBoundingClientRect());
181
- observer.observe();
131
+ observer.observe(instance.scrollElement);
182
132
  return () => {
183
- observer.unobserve();
133
+ observer.unobserve(instance.scrollElement);
184
134
  };
185
135
  };
186
136
  const observeWindowRect = (instance, cb) => {
187
- const onResize = () => {
188
- cb({
189
- width: instance.scrollElement.innerWidth,
190
- height: instance.scrollElement.innerHeight
191
- });
192
- };
137
+ const memoizedCallback = memoRectCallback(instance, cb);
138
+
139
+ const onResize = () => memoizedCallback({
140
+ width: instance.scrollElement.innerWidth,
141
+ height: instance.scrollElement.innerHeight
142
+ });
193
143
 
194
144
  if (!instance.scrollElement) {
195
145
  return;
@@ -204,52 +154,80 @@
204
154
  instance.scrollElement.removeEventListener('resize', onResize);
205
155
  };
206
156
  };
207
- const observeElementOffset = (instance, cb) => {
208
- const onScroll = () => cb(instance.scrollElement[instance.options.horizontal ? 'scrollLeft' : 'scrollTop']);
157
+ const scrollProps = {
158
+ element: ['scrollLeft', 'scrollTop'],
159
+ window: ['scrollX', 'scrollY']
160
+ };
209
161
 
210
- if (!instance.scrollElement) {
211
- return;
212
- }
162
+ const createOffsetObserver = mode => {
163
+ return (instance, cb) => {
164
+ if (!instance.scrollElement) {
165
+ return;
166
+ }
213
167
 
214
- onScroll();
215
- instance.scrollElement.addEventListener('scroll', onScroll, {
216
- capture: false,
217
- passive: true
218
- });
219
- return () => {
220
- instance.scrollElement.removeEventListener('scroll', onScroll);
221
- };
222
- };
223
- const observeWindowOffset = (instance, cb) => {
224
- const onScroll = () => cb(instance.scrollElement[instance.options.horizontal ? 'scrollX' : 'scrollY']);
168
+ const propX = scrollProps[mode][0];
169
+ const propY = scrollProps[mode][1];
170
+ let prevX = instance.scrollElement[propX];
171
+ let prevY = instance.scrollElement[propY];
225
172
 
226
- if (!instance.scrollElement) {
227
- return;
228
- }
173
+ const scroll = () => {
174
+ const offset = instance.scrollElement[instance.options.horizontal ? propX : propY];
175
+ cb(Math.max(0, offset - instance.options.scrollMargin));
176
+ };
229
177
 
230
- onScroll();
231
- instance.scrollElement.addEventListener('scroll', onScroll, {
232
- capture: false,
233
- passive: true
234
- });
235
- return () => {
236
- instance.scrollElement.removeEventListener('scroll', onScroll);
178
+ scroll();
179
+
180
+ const onScroll = e => {
181
+ const target = e.currentTarget;
182
+ const scrollX = target[propX];
183
+ const scrollY = target[propY];
184
+
185
+ if (instance.options.horizontal ? prevX - scrollX : prevY - scrollY) {
186
+ scroll();
187
+ }
188
+
189
+ prevX = scrollX;
190
+ prevY = scrollY;
191
+ };
192
+
193
+ instance.scrollElement.addEventListener('scroll', onScroll, {
194
+ capture: false,
195
+ passive: true
196
+ });
197
+ return () => {
198
+ instance.scrollElement.removeEventListener('scroll', onScroll);
199
+ };
237
200
  };
238
201
  };
202
+
203
+ const observeElementOffset = createOffsetObserver('element');
204
+ const observeWindowOffset = createOffsetObserver('window');
239
205
  const measureElement = (element, instance) => {
240
- return element.getBoundingClientRect()[instance.options.horizontal ? 'width' : 'height'];
206
+ return Math.round(element.getBoundingClientRect()[instance.options.horizontal ? 'width' : 'height']);
241
207
  };
242
- const windowScroll = (offset, canSmooth, instance) => {
208
+ const windowScroll = (offset, _ref, instance) => {
243
209
  var _instance$scrollEleme;
244
- (_instance$scrollEleme = instance.scrollElement) == null ? void 0 : _instance$scrollEleme.scrollTo({
245
- [instance.options.horizontal ? 'left' : 'top']: offset,
210
+
211
+ let {
212
+ canSmooth,
213
+ sync
214
+ } = _ref;
215
+ const toOffset = sync ? offset : offset + instance.options.scrollMargin;
216
+ (_instance$scrollEleme = instance.scrollElement) == null ? void 0 : _instance$scrollEleme.scrollTo == null ? void 0 : _instance$scrollEleme.scrollTo({
217
+ [instance.options.horizontal ? 'left' : 'top']: toOffset,
246
218
  behavior: canSmooth ? 'smooth' : undefined
247
219
  });
248
220
  };
249
- const elementScroll = (offset, canSmooth, instance) => {
221
+ const elementScroll = (offset, _ref2, instance) => {
250
222
  var _instance$scrollEleme2;
251
- (_instance$scrollEleme2 = instance.scrollElement) == null ? void 0 : _instance$scrollEleme2.scrollTo({
252
- [instance.options.horizontal ? 'left' : 'top']: offset,
223
+
224
+ let {
225
+ canSmooth,
226
+ sync
227
+ } = _ref2;
228
+ const toOffset = sync ? offset : offset + instance.options.scrollMargin;
229
+ (_instance$scrollEleme2 = instance.scrollElement) == null ? void 0 : _instance$scrollEleme2.scrollTo == null ? void 0 : _instance$scrollEleme2.scrollTo({
230
+ [instance.options.horizontal ? 'left' : 'top']: toOffset,
253
231
  behavior: canSmooth ? 'smooth' : undefined
254
232
  });
255
233
  };
@@ -259,13 +237,26 @@
259
237
 
260
238
  this.unsubs = [];
261
239
  this.scrollElement = null;
240
+ this.isScrolling = false;
241
+ this.isScrollingTimeoutId = null;
262
242
  this.measurementsCache = [];
263
243
  this.itemMeasurementsCache = {};
264
244
  this.pendingMeasuredCacheIndexes = [];
245
+ this.scrollDelta = 0;
246
+ this.measureElementCache = {};
247
+ this.ro = new ResizeObserver(entries => {
248
+ entries.forEach(entry => {
249
+ this._measureElement(entry.target, false);
250
+ });
251
+ });
252
+ this.range = {
253
+ startIndex: 0,
254
+ endIndex: 0
255
+ };
265
256
 
266
257
  this.setOptions = opts => {
267
- Object.entries(opts).forEach(_ref => {
268
- let [key, value] = _ref;
258
+ Object.entries(opts).forEach(_ref3 => {
259
+ let [key, value] = _ref3;
269
260
  if (typeof value === 'undefined') delete opts[key];
270
261
  });
271
262
  this.options = {
@@ -286,6 +277,9 @@
286
277
  width: 0,
287
278
  height: 0
288
279
  },
280
+ scrollMargin: 0,
281
+ scrollingDelay: 150,
282
+ indexAttribute: 'data-index',
289
283
  ...opts
290
284
  };
291
285
  };
@@ -299,10 +293,13 @@
299
293
  this.cleanup = () => {
300
294
  this.unsubs.filter(Boolean).forEach(d => d());
301
295
  this.unsubs = [];
296
+ this.scrollElement = null;
302
297
  };
303
298
 
304
299
  this._didMount = () => {
305
300
  return () => {
301
+ this.ro.disconnect();
302
+ this.measureElementCache = {};
306
303
  this.cleanup();
307
304
  };
308
305
  };
@@ -313,14 +310,41 @@
313
310
  if (this.scrollElement !== scrollElement) {
314
311
  this.cleanup();
315
312
  this.scrollElement = scrollElement;
313
+
314
+ this._scrollToOffset(this.scrollOffset, {
315
+ canSmooth: false,
316
+ sync: true,
317
+ requested: false
318
+ });
319
+
316
320
  this.unsubs.push(this.options.observeElementRect(this, rect => {
317
321
  this.scrollRect = rect;
318
- this.notify();
322
+ this.calculateRange();
319
323
  }));
320
324
  this.unsubs.push(this.options.observeElementOffset(this, offset => {
321
- this.scrollOffset = offset;
322
- this.notify();
325
+ if (this.isScrollingTimeoutId !== null) {
326
+ clearTimeout(this.isScrollingTimeoutId);
327
+ this.isScrollingTimeoutId = null;
328
+ }
329
+
330
+ if (this.scrollOffset !== offset) {
331
+ this.scrollOffset = offset;
332
+ this.isScrolling = true;
333
+ this.scrollDelta = 0;
334
+ this.isScrollingTimeoutId = setTimeout(() => {
335
+ this.isScrollingTimeoutId = null;
336
+ this.isScrolling = false;
337
+ this.notify();
338
+ }, this.options.scrollingDelay);
339
+ } else {
340
+ this.isScrolling = false;
341
+ this.scrollDelta = 0;
342
+ }
343
+
344
+ this.calculateRange();
323
345
  }));
346
+ } else if (!this.isScrolling) {
347
+ this.calculateRange();
324
348
  }
325
349
  };
326
350
 
@@ -355,104 +379,166 @@
355
379
  debug: () => this.options.debug
356
380
  });
357
381
  this.calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.scrollOffset], (measurements, outerSize, scrollOffset) => {
358
- return calculateRange({
382
+ const range = calculateRange({
359
383
  measurements,
360
384
  outerSize,
361
385
  scrollOffset
362
386
  });
387
+
388
+ if (range.startIndex !== this.range.startIndex || range.endIndex !== this.range.endIndex) {
389
+ this.range = range;
390
+ this.notify();
391
+ }
392
+
393
+ return this.range;
363
394
  }, {
364
395
  key: 'calculateRange',
365
396
  debug: () => this.options.debug
366
397
  });
367
- this.getIndexes = memo(() => [this.options.rangeExtractor, this.calculateRange(), this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
398
+ this.getIndexes = memo(() => [this.options.rangeExtractor, this.range, this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
368
399
  return rangeExtractor({ ...range,
369
400
  overscan,
370
401
  count: count
371
402
  });
372
403
  }, {
373
- key: 'getIndexes'
404
+ key: 'getIndexes',
405
+ debug: () => this.options.debug
374
406
  });
375
- this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements(), this.options.measureElement], (indexes, measurements, measureElement) => {
407
+
408
+ this.indexFromElement = node => {
409
+ const attributeName = this.options.indexAttribute;
410
+ const indexStr = node.getAttribute(attributeName);
411
+
412
+ if (!indexStr) {
413
+ console.warn("Missing attribute name '" + attributeName + "={index}' on measured element.");
414
+ return -1;
415
+ }
416
+
417
+ return parseInt(indexStr, 10);
418
+ };
419
+
420
+ this._measureElement = (node, _sync) => {
421
+ var _this$itemMeasurement;
422
+
423
+ const index = this.indexFromElement(node);
424
+ const item = this.measurementsCache[index];
425
+
426
+ if (!item) {
427
+ return;
428
+ }
429
+
430
+ const key = String(item.key);
431
+ const prevNode = this.measureElementCache[key];
432
+
433
+ if (!node.isConnected) {
434
+ if (prevNode) {
435
+ this.ro.unobserve(prevNode);
436
+ delete this.measureElementCache[key];
437
+ }
438
+
439
+ return;
440
+ }
441
+
442
+ if (!prevNode || prevNode !== node) {
443
+ if (prevNode) {
444
+ this.ro.unobserve(prevNode);
445
+ }
446
+
447
+ this.measureElementCache[key] = node;
448
+ this.ro.observe(node);
449
+ }
450
+
451
+ const measuredItemSize = this.options.measureElement(node, this);
452
+ const itemSize = (_this$itemMeasurement = this.itemMeasurementsCache[item.key]) != null ? _this$itemMeasurement : item.size;
453
+
454
+ if (measuredItemSize !== itemSize) {
455
+ if (item.start < this.scrollOffset) {
456
+ if (this.options.debug) {
457
+ console.info('correction', measuredItemSize - itemSize);
458
+ }
459
+
460
+ if (this.destinationOffset === undefined) {
461
+ this.scrollDelta += measuredItemSize - itemSize;
462
+
463
+ this._scrollToOffset(this.scrollOffset + this.scrollDelta, {
464
+ canSmooth: false,
465
+ sync: false,
466
+ requested: false
467
+ });
468
+ }
469
+ }
470
+
471
+ this.pendingMeasuredCacheIndexes.push(index);
472
+ this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
473
+ [item.key]: measuredItemSize
474
+ };
475
+ this.notify();
476
+ }
477
+ };
478
+
479
+ this.measureElement = node => {
480
+ if (!node) {
481
+ return;
482
+ }
483
+
484
+ this._measureElement(node, true);
485
+ };
486
+
487
+ this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements()], (indexes, measurements) => {
376
488
  const virtualItems = [];
377
489
 
378
490
  for (let k = 0, len = indexes.length; k < len; k++) {
379
491
  const i = indexes[k];
380
492
  const measurement = measurements[i];
381
- const item = { ...measurement,
382
- measureElement: measurableItem => {
383
- if (measurableItem) {
384
- const measuredItemSize = measureElement(measurableItem, this);
385
-
386
- if (measuredItemSize !== item.size) {
387
- if (item.start < this.scrollOffset) {
388
- if (this.options.debug) console.info('correction', measuredItemSize - item.size);
389
-
390
- if (!this.destinationOffset) {
391
- this._scrollToOffset(this.scrollOffset + (measuredItemSize - item.size), false);
392
- }
393
- }
394
-
395
- this.pendingMeasuredCacheIndexes.push(i);
396
- this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
397
- [item.key]: measuredItemSize
398
- };
399
- this.notify();
400
- }
401
- }
402
- }
403
- };
404
- virtualItems.push(item);
493
+ virtualItems.push(measurement);
405
494
  }
406
495
 
407
496
  return virtualItems;
408
497
  }, {
409
- key: 'getIndexes'
498
+ key: 'getIndexes',
499
+ debug: () => this.options.debug
410
500
  });
411
501
 
412
502
  this.scrollToOffset = function (toOffset, _temp) {
413
503
  let {
414
- align
415
- } = _temp === void 0 ? {
416
- align: 'start'
417
- } : _temp;
418
-
419
- const attempt = () => {
420
- const offset = _this.scrollOffset;
504
+ align = 'start',
505
+ smoothScroll = _this.options.enableSmoothScroll
506
+ } = _temp === void 0 ? {} : _temp;
507
+ const offset = _this.scrollOffset;
421
508
 
422
- const size = _this.getSize();
509
+ const size = _this.getSize();
423
510
 
424
- if (align === 'auto') {
425
- if (toOffset <= offset) {
426
- align = 'start';
427
- } else if (toOffset >= offset + size) {
428
- align = 'end';
429
- } else {
430
- align = 'start';
431
- }
511
+ if (align === 'auto') {
512
+ if (toOffset <= offset) {
513
+ align = 'start';
514
+ } else if (toOffset >= offset + size) {
515
+ align = 'end';
516
+ } else {
517
+ align = 'start';
432
518
  }
519
+ }
433
520
 
434
- if (align === 'start') {
435
- _this._scrollToOffset(toOffset, true);
436
- } else if (align === 'end') {
437
- _this._scrollToOffset(toOffset - size, true);
438
- } else if (align === 'center') {
439
- _this._scrollToOffset(toOffset - size / 2, true);
440
- }
521
+ const options = {
522
+ canSmooth: smoothScroll,
523
+ sync: false,
524
+ requested: true
441
525
  };
442
526
 
443
- attempt();
444
- requestAnimationFrame(() => {
445
- attempt();
446
- });
527
+ if (align === 'start') {
528
+ _this._scrollToOffset(toOffset, options);
529
+ } else if (align === 'end') {
530
+ _this._scrollToOffset(toOffset - size, options);
531
+ } else if (align === 'center') {
532
+ _this._scrollToOffset(toOffset - size / 2, options);
533
+ }
447
534
  };
448
535
 
449
536
  this.scrollToIndex = function (index, _temp2) {
450
537
  let {
451
- align,
538
+ align = 'auto',
539
+ smoothScroll = _this.options.enableSmoothScroll,
452
540
  ...rest
453
- } = _temp2 === void 0 ? {
454
- align: 'auto'
455
- } : _temp2;
541
+ } = _temp2 === void 0 ? {} : _temp2;
456
542
 
457
543
  const measurements = _this.getMeasurements();
458
544
 
@@ -483,6 +569,7 @@
483
569
 
484
570
  _this.scrollToOffset(toOffset, {
485
571
  align,
572
+ smoothScroll,
486
573
  ...rest
487
574
  });
488
575
  };
@@ -493,10 +580,22 @@
493
580
  return (((_this$getMeasurements = this.getMeasurements()[this.options.count - 1]) == null ? void 0 : _this$getMeasurements.end) || this.options.paddingStart) + this.options.paddingEnd;
494
581
  };
495
582
 
496
- this._scrollToOffset = (offset, canSmooth) => {
583
+ this._scrollToOffset = (offset, _ref4) => {
584
+ let {
585
+ requested,
586
+ canSmooth,
587
+ sync
588
+ } = _ref4;
497
589
  clearTimeout(this.scrollCheckFrame);
498
- this.destinationOffset = offset;
499
- this.options.scrollToFn(offset, this.options.enableSmoothScroll && canSmooth, this);
590
+
591
+ if (requested) {
592
+ this.destinationOffset = offset;
593
+ }
594
+
595
+ this.options.scrollToFn(offset, {
596
+ canSmooth,
597
+ sync
598
+ }, this);
500
599
  let scrollCheckFrame;
501
600
 
502
601
  const check = () => {
@@ -527,6 +626,7 @@
527
626
  this.setOptions(_opts);
528
627
  this.scrollRect = this.options.initialRect;
529
628
  this.scrollOffset = this.options.initialOffset;
629
+ this.calculateRange();
530
630
  }
531
631
 
532
632
  }
@@ -552,12 +652,12 @@
552
652
  }
553
653
  };
554
654
 
555
- function calculateRange(_ref2) {
655
+ function calculateRange(_ref5) {
556
656
  let {
557
657
  measurements,
558
658
  outerSize,
559
659
  scrollOffset
560
- } = _ref2;
660
+ } = _ref5;
561
661
  const count = measurements.length - 1;
562
662
 
563
663
  const getOffset = index => measurements[index].start;