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

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
182
  return 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,21 @@ 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.range = {
224
+ startIndex: 0,
225
+ endIndex: 0
226
+ };
241
227
 
242
228
  this.setOptions = opts => {
243
- Object.entries(opts).forEach(_ref => {
244
- let [key, value] = _ref;
229
+ Object.entries(opts).forEach(_ref3 => {
230
+ let [key, value] = _ref3;
245
231
  if (typeof value === 'undefined') delete opts[key];
246
232
  });
247
233
  this.options = {
@@ -262,6 +248,8 @@ class Virtualizer {
262
248
  width: 0,
263
249
  height: 0
264
250
  },
251
+ scrollMargin: 0,
252
+ scrollingDelay: 150,
265
253
  ...opts
266
254
  };
267
255
  };
@@ -275,6 +263,7 @@ class Virtualizer {
275
263
  this.cleanup = () => {
276
264
  this.unsubs.filter(Boolean).forEach(d => d());
277
265
  this.unsubs = [];
266
+ this.scrollElement = null;
278
267
  };
279
268
 
280
269
  this._didMount = () => {
@@ -289,14 +278,41 @@ class Virtualizer {
289
278
  if (this.scrollElement !== scrollElement) {
290
279
  this.cleanup();
291
280
  this.scrollElement = scrollElement;
281
+
282
+ this._scrollToOffset(this.scrollOffset, {
283
+ canSmooth: false,
284
+ sync: true,
285
+ requested: false
286
+ });
287
+
292
288
  this.unsubs.push(this.options.observeElementRect(this, rect => {
293
289
  this.scrollRect = rect;
294
- this.notify();
290
+ this.calculateRange();
295
291
  }));
296
292
  this.unsubs.push(this.options.observeElementOffset(this, offset => {
297
- this.scrollOffset = offset;
298
- this.notify();
293
+ if (this.isScrollingTimeoutId !== null) {
294
+ clearTimeout(this.isScrollingTimeoutId);
295
+ this.isScrollingTimeoutId = null;
296
+ }
297
+
298
+ if (this.scrollOffset !== offset) {
299
+ this.scrollOffset = offset;
300
+ this.isScrolling = true;
301
+ this.scrollDelta = 0;
302
+ this.isScrollingTimeoutId = setTimeout(() => {
303
+ this.isScrollingTimeoutId = null;
304
+ this.isScrolling = false;
305
+ this.notify();
306
+ }, this.options.scrollingDelay);
307
+ } else {
308
+ this.isScrolling = false;
309
+ this.scrollDelta = 0;
310
+ }
311
+
312
+ this.calculateRange();
299
313
  }));
314
+ } else if (!this.isScrolling) {
315
+ this.calculateRange();
300
316
  }
301
317
  };
302
318
 
@@ -327,108 +343,134 @@ class Virtualizer {
327
343
  this.measurementsCache = measurements;
328
344
  return measurements;
329
345
  }, {
330
- key: process.env.NODE_ENV === 'development' && 'getMeasurements',
346
+ key: process.env.NODE_ENV !== 'production' && 'getMeasurements',
331
347
  debug: () => this.options.debug
332
348
  });
333
349
  this.calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.scrollOffset], (measurements, outerSize, scrollOffset) => {
334
- return calculateRange({
350
+ const range = calculateRange({
335
351
  measurements,
336
352
  outerSize,
337
353
  scrollOffset
338
354
  });
355
+
356
+ if (range.startIndex !== this.range.startIndex || range.endIndex !== this.range.endIndex) {
357
+ this.range = range;
358
+ this.notify();
359
+ }
360
+
361
+ return this.range;
339
362
  }, {
340
- key: process.env.NODE_ENV === 'development' && 'calculateRange',
363
+ key: process.env.NODE_ENV !== 'production' && 'calculateRange',
341
364
  debug: () => this.options.debug
342
365
  });
343
- this.getIndexes = memo(() => [this.options.rangeExtractor, this.calculateRange(), this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
366
+ this.getIndexes = memo(() => [this.options.rangeExtractor, this.range, this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
344
367
  return rangeExtractor({ ...range,
345
368
  overscan,
346
369
  count: count
347
370
  });
348
371
  }, {
349
- key: process.env.NODE_ENV === 'development' && 'getIndexes'
372
+ key: process.env.NODE_ENV !== 'production' && 'getIndexes',
373
+ debug: () => this.options.debug
350
374
  });
351
375
  this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements(), this.options.measureElement], (indexes, measurements, measureElement) => {
376
+ const makeMeasureElement = index => measurableItem => {
377
+ var _this$itemMeasurement;
378
+
379
+ const item = this.measurementsCache[index];
380
+
381
+ if (!measurableItem) {
382
+ return;
383
+ }
384
+
385
+ const measuredItemSize = measureElement(measurableItem, this);
386
+ const itemSize = (_this$itemMeasurement = this.itemMeasurementsCache[item.key]) != null ? _this$itemMeasurement : item.size;
387
+
388
+ if (measuredItemSize !== itemSize) {
389
+ if (item.start < this.scrollOffset) {
390
+ if (process.env.NODE_ENV !== 'production' && this.options.debug) {
391
+ console.info('correction', measuredItemSize - itemSize);
392
+ }
393
+
394
+ if (this.destinationOffset === undefined) {
395
+ this.scrollDelta += measuredItemSize - itemSize;
396
+
397
+ this._scrollToOffset(this.scrollOffset + this.scrollDelta, {
398
+ canSmooth: false,
399
+ sync: false,
400
+ requested: false
401
+ });
402
+ }
403
+ }
404
+
405
+ this.pendingMeasuredCacheIndexes.push(index);
406
+ this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
407
+ [item.key]: measuredItemSize
408
+ };
409
+ this.notify();
410
+ }
411
+ };
412
+
352
413
  const virtualItems = [];
414
+ const currentMeasureElements = {};
353
415
 
354
416
  for (let k = 0, len = indexes.length; k < len; k++) {
417
+ var _this$measureElementC;
418
+
355
419
  const i = indexes[k];
356
420
  const measurement = measurements[i];
357
421
  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
- }
422
+ measureElement: currentMeasureElements[i] = (_this$measureElementC = this.measureElementCache[i]) != null ? _this$measureElementC : makeMeasureElement(i)
379
423
  };
380
424
  virtualItems.push(item);
381
425
  }
382
426
 
427
+ this.measureElementCache = currentMeasureElements;
383
428
  return virtualItems;
384
429
  }, {
385
- key: process.env.NODE_ENV === 'development' && 'getIndexes'
430
+ key: process.env.NODE_ENV !== 'production' && 'getIndexes',
431
+ debug: () => this.options.debug
386
432
  });
387
433
 
388
434
  this.scrollToOffset = function (toOffset, _temp) {
389
435
  let {
390
- align
391
- } = _temp === void 0 ? {
392
- align: 'start'
393
- } : _temp;
394
-
395
- const attempt = () => {
396
- const offset = _this.scrollOffset;
436
+ align = 'start',
437
+ smoothScroll = _this.options.enableSmoothScroll
438
+ } = _temp === void 0 ? {} : _temp;
439
+ const offset = _this.scrollOffset;
397
440
 
398
- const size = _this.getSize();
441
+ const size = _this.getSize();
399
442
 
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
- }
443
+ if (align === 'auto') {
444
+ if (toOffset <= offset) {
445
+ align = 'start';
446
+ } else if (toOffset >= offset + size) {
447
+ align = 'end';
448
+ } else {
449
+ align = 'start';
408
450
  }
451
+ }
409
452
 
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
- }
453
+ const options = {
454
+ canSmooth: smoothScroll,
455
+ sync: false,
456
+ requested: true
417
457
  };
418
458
 
419
- attempt();
420
- requestAnimationFrame(() => {
421
- attempt();
422
- });
459
+ if (align === 'start') {
460
+ _this._scrollToOffset(toOffset, options);
461
+ } else if (align === 'end') {
462
+ _this._scrollToOffset(toOffset - size, options);
463
+ } else if (align === 'center') {
464
+ _this._scrollToOffset(toOffset - size / 2, options);
465
+ }
423
466
  };
424
467
 
425
468
  this.scrollToIndex = function (index, _temp2) {
426
469
  let {
427
- align,
470
+ align = 'auto',
471
+ smoothScroll = _this.options.enableSmoothScroll,
428
472
  ...rest
429
- } = _temp2 === void 0 ? {
430
- align: 'auto'
431
- } : _temp2;
473
+ } = _temp2 === void 0 ? {} : _temp2;
432
474
 
433
475
  const measurements = _this.getMeasurements();
434
476
 
@@ -459,6 +501,7 @@ class Virtualizer {
459
501
 
460
502
  _this.scrollToOffset(toOffset, {
461
503
  align,
504
+ smoothScroll,
462
505
  ...rest
463
506
  });
464
507
  };
@@ -469,10 +512,22 @@ class Virtualizer {
469
512
  return (((_this$getMeasurements = this.getMeasurements()[this.options.count - 1]) == null ? void 0 : _this$getMeasurements.end) || this.options.paddingStart) + this.options.paddingEnd;
470
513
  };
471
514
 
472
- this._scrollToOffset = (offset, canSmooth) => {
515
+ this._scrollToOffset = (offset, _ref4) => {
516
+ let {
517
+ requested,
518
+ canSmooth,
519
+ sync
520
+ } = _ref4;
473
521
  clearTimeout(this.scrollCheckFrame);
474
- this.destinationOffset = offset;
475
- this.options.scrollToFn(offset, this.options.enableSmoothScroll && canSmooth, this);
522
+
523
+ if (requested) {
524
+ this.destinationOffset = offset;
525
+ }
526
+
527
+ this.options.scrollToFn(offset, {
528
+ canSmooth,
529
+ sync
530
+ }, this);
476
531
  let scrollCheckFrame;
477
532
 
478
533
  const check = () => {
@@ -503,6 +558,7 @@ class Virtualizer {
503
558
  this.setOptions(_opts);
504
559
  this.scrollRect = this.options.initialRect;
505
560
  this.scrollOffset = this.options.initialOffset;
561
+ this.calculateRange();
506
562
  }
507
563
 
508
564
  }
@@ -528,12 +584,12 @@ const findNearestBinarySearch = (low, high, getCurrentValue, value) => {
528
584
  }
529
585
  };
530
586
 
531
- function calculateRange(_ref2) {
587
+ function calculateRange(_ref5) {
532
588
  let {
533
589
  measurements,
534
590
  outerSize,
535
591
  scrollOffset
536
- } = _ref2;
592
+ } = _ref5;
537
593
  const count = measurements.length - 1;
538
594
 
539
595
  const getOffset = index => measurements[index].start;