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