@tanstack/react-virtual 3.0.0-beta.23 → 3.0.0-beta.28

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.
@@ -1,708 +0,0 @@
1
- /**
2
- * react-virtual
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import * as React from 'react';
12
-
13
- /**
14
- * virtual-core
15
- *
16
- * Copyright (c) TanStack
17
- *
18
- * This source code is licensed under the MIT license found in the
19
- * LICENSE.md file in the root directory of this source tree.
20
- *
21
- * @license MIT
22
- */
23
- function memo(getDeps, fn, opts) {
24
- let deps = [];
25
- let result;
26
- return () => {
27
- let depTime;
28
- if (opts.key && opts.debug != null && opts.debug()) depTime = Date.now();
29
- const newDeps = getDeps();
30
- const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);
31
-
32
- if (!depsChanged) {
33
- return result;
34
- }
35
-
36
- deps = newDeps;
37
- let resultTime;
38
- if (opts.key && opts.debug != null && opts.debug()) resultTime = Date.now();
39
- result = fn(...newDeps);
40
- opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result);
41
-
42
- if (opts.key && opts.debug != null && opts.debug()) {
43
- const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
44
- const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
45
- const resultFpsPercentage = resultEndTime / 16;
46
-
47
- const pad = (str, num) => {
48
- str = String(str);
49
-
50
- while (str.length < num) {
51
- str = ' ' + str;
52
- }
53
-
54
- return str;
55
- };
56
-
57
- console.info("%c\u23F1 " + pad(resultEndTime, 5) + " /" + pad(depEndTime, 5) + " ms", "\n font-size: .6rem;\n font-weight: bold;\n color: hsl(" + Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120)) + "deg 100% 31%);", opts == null ? void 0 : opts.key);
58
- }
59
-
60
- return result;
61
- };
62
- }
63
-
64
- //
65
- const defaultKeyExtractor = index => index;
66
- const defaultRangeExtractor = range => {
67
- const start = Math.max(range.startIndex - range.overscan, 0);
68
- const end = Math.min(range.endIndex + range.overscan, range.count - 1);
69
- const arr = [];
70
-
71
- for (let i = start; i <= end; i++) {
72
- arr.push(i);
73
- }
74
-
75
- return arr;
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
-
92
- const observeElementRect = (instance, cb) => {
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
- });
100
- });
101
-
102
- if (!instance.scrollElement) {
103
- return;
104
- }
105
-
106
- cb(instance.scrollElement.getBoundingClientRect());
107
- observer.observe(instance.scrollElement);
108
- return () => {
109
- observer.unobserve(instance.scrollElement);
110
- };
111
- };
112
- const observeWindowRect = (instance, cb) => {
113
- const memoizedCallback = memoRectCallback(instance, cb);
114
-
115
- const onResize = () => memoizedCallback({
116
- width: instance.scrollElement.innerWidth,
117
- height: instance.scrollElement.innerHeight
118
- });
119
-
120
- if (!instance.scrollElement) {
121
- return;
122
- }
123
-
124
- onResize();
125
- instance.scrollElement.addEventListener('resize', onResize, {
126
- capture: false,
127
- passive: true
128
- });
129
- return () => {
130
- instance.scrollElement.removeEventListener('resize', onResize);
131
- };
132
- };
133
- const scrollProps = {
134
- element: ['scrollLeft', 'scrollTop'],
135
- window: ['scrollX', 'scrollY']
136
- };
137
-
138
- const createOffsetObserver = mode => {
139
- return (instance, cb) => {
140
- if (!instance.scrollElement) {
141
- return;
142
- }
143
-
144
- const propX = scrollProps[mode][0];
145
- const propY = scrollProps[mode][1];
146
- let prevX = instance.scrollElement[propX];
147
- let prevY = instance.scrollElement[propY];
148
-
149
- const scroll = () => {
150
- const offset = instance.scrollElement[instance.options.horizontal ? propX : propY];
151
- cb(Math.max(0, offset - instance.options.scrollMargin));
152
- };
153
-
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
- };
176
- };
177
- };
178
-
179
- const observeElementOffset = createOffsetObserver('element');
180
- const observeWindowOffset = createOffsetObserver('window');
181
- const measureElement = (element, instance) => {
182
- return Math.round(element.getBoundingClientRect()[instance.options.horizontal ? 'width' : 'height']);
183
- };
184
- const windowScroll = (offset, _ref, instance) => {
185
- var _instance$scrollEleme;
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,
194
- behavior: canSmooth ? 'smooth' : undefined
195
- });
196
- };
197
- const elementScroll = (offset, _ref2, instance) => {
198
- var _instance$scrollEleme2;
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,
207
- behavior: canSmooth ? 'smooth' : undefined
208
- });
209
- };
210
- class Virtualizer {
211
- constructor(_opts) {
212
- var _this = this;
213
-
214
- this.unsubs = [];
215
- this.scrollElement = null;
216
- this.isScrolling = false;
217
- this.isScrollingTimeoutId = null;
218
- this.measurementsCache = [];
219
- this.itemMeasurementsCache = {};
220
- this.pendingMeasuredCacheIndexes = [];
221
- this.scrollDelta = 0;
222
- this.measureElementCache = {};
223
-
224
- this.getResizeObserver = (() => {
225
- let _ro = null;
226
- return () => {
227
- if (_ro) {
228
- return _ro;
229
- } else if (typeof ResizeObserver !== 'undefined') {
230
- return _ro = new ResizeObserver(entries => {
231
- entries.forEach(entry => {
232
- this._measureElement(entry.target, false);
233
- });
234
- });
235
- } else {
236
- return null;
237
- }
238
- };
239
- })();
240
-
241
- this.range = {
242
- startIndex: 0,
243
- endIndex: 0
244
- };
245
-
246
- this.setOptions = opts => {
247
- Object.entries(opts).forEach(_ref3 => {
248
- let [key, value] = _ref3;
249
- if (typeof value === 'undefined') delete opts[key];
250
- });
251
- this.options = {
252
- debug: false,
253
- initialOffset: 0,
254
- overscan: 1,
255
- paddingStart: 0,
256
- paddingEnd: 0,
257
- scrollPaddingStart: 0,
258
- scrollPaddingEnd: 0,
259
- horizontal: false,
260
- getItemKey: defaultKeyExtractor,
261
- rangeExtractor: defaultRangeExtractor,
262
- enableSmoothScroll: true,
263
- onChange: () => {},
264
- measureElement,
265
- initialRect: {
266
- width: 0,
267
- height: 0
268
- },
269
- scrollMargin: 0,
270
- scrollingDelay: 150,
271
- indexAttribute: 'data-index',
272
- ...opts
273
- };
274
- };
275
-
276
- this.notify = () => {
277
- var _this$options$onChang, _this$options;
278
-
279
- (_this$options$onChang = (_this$options = this.options).onChange) == null ? void 0 : _this$options$onChang.call(_this$options, this);
280
- };
281
-
282
- this.cleanup = () => {
283
- this.unsubs.filter(Boolean).forEach(d => d());
284
- this.unsubs = [];
285
- this.scrollElement = null;
286
- };
287
-
288
- this._didMount = () => {
289
- return () => {
290
- var _this$getResizeObserv;
291
-
292
- (_this$getResizeObserv = this.getResizeObserver()) == null ? void 0 : _this$getResizeObserv.disconnect();
293
- this.measureElementCache = {};
294
- this.cleanup();
295
- };
296
- };
297
-
298
- this._willUpdate = () => {
299
- const scrollElement = this.options.getScrollElement();
300
-
301
- if (this.scrollElement !== scrollElement) {
302
- this.cleanup();
303
- this.scrollElement = scrollElement;
304
-
305
- this._scrollToOffset(this.scrollOffset, {
306
- canSmooth: false,
307
- sync: true,
308
- requested: false
309
- });
310
-
311
- this.unsubs.push(this.options.observeElementRect(this, rect => {
312
- this.scrollRect = rect;
313
- this.calculateRange();
314
- }));
315
- this.unsubs.push(this.options.observeElementOffset(this, offset => {
316
- if (this.isScrollingTimeoutId !== null) {
317
- clearTimeout(this.isScrollingTimeoutId);
318
- this.isScrollingTimeoutId = null;
319
- }
320
-
321
- if (this.scrollOffset !== offset) {
322
- this.scrollOffset = offset;
323
- this.isScrolling = true;
324
- this.scrollDelta = 0;
325
- this.isScrollingTimeoutId = setTimeout(() => {
326
- this.isScrollingTimeoutId = null;
327
- this.isScrolling = false;
328
- this.notify();
329
- }, this.options.scrollingDelay);
330
- } else {
331
- this.isScrolling = false;
332
- this.scrollDelta = 0;
333
- }
334
-
335
- this.calculateRange();
336
- }));
337
- } else if (!this.isScrolling) {
338
- this.calculateRange();
339
- }
340
- };
341
-
342
- this.getSize = () => {
343
- return this.scrollRect[this.options.horizontal ? 'width' : 'height'];
344
- };
345
-
346
- this.getMeasurements = memo(() => [this.options.count, this.options.paddingStart, this.options.getItemKey, this.itemMeasurementsCache], (count, paddingStart, getItemKey, measurementsCache) => {
347
- const min = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;
348
- this.pendingMeasuredCacheIndexes = [];
349
- const measurements = this.measurementsCache.slice(0, min);
350
-
351
- for (let i = min; i < count; i++) {
352
- const key = getItemKey(i);
353
- const measuredSize = measurementsCache[key];
354
- const start = measurements[i - 1] ? measurements[i - 1].end : paddingStart;
355
- const size = typeof measuredSize === 'number' ? measuredSize : this.options.estimateSize(i);
356
- const end = start + size;
357
- measurements[i] = {
358
- index: i,
359
- start,
360
- size,
361
- end,
362
- key
363
- };
364
- }
365
-
366
- this.measurementsCache = measurements;
367
- return measurements;
368
- }, {
369
- key: process.env.NODE_ENV !== 'production' && 'getMeasurements',
370
- debug: () => this.options.debug
371
- });
372
- this.calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.scrollOffset], (measurements, outerSize, scrollOffset) => {
373
- const range = calculateRange({
374
- measurements,
375
- outerSize,
376
- scrollOffset
377
- });
378
-
379
- if (range.startIndex !== this.range.startIndex || range.endIndex !== this.range.endIndex) {
380
- this.range = range;
381
- this.notify();
382
- }
383
-
384
- return this.range;
385
- }, {
386
- key: process.env.NODE_ENV !== 'production' && 'calculateRange',
387
- debug: () => this.options.debug
388
- });
389
- this.getIndexes = memo(() => [this.options.rangeExtractor, this.range, this.options.overscan, this.options.count], (rangeExtractor, range, overscan, count) => {
390
- return rangeExtractor({ ...range,
391
- overscan,
392
- count: count
393
- });
394
- }, {
395
- key: process.env.NODE_ENV !== 'production' && 'getIndexes',
396
- debug: () => this.options.debug
397
- });
398
-
399
- this.indexFromElement = node => {
400
- const attributeName = this.options.indexAttribute;
401
- const indexStr = node.getAttribute(attributeName);
402
-
403
- if (!indexStr) {
404
- console.warn("Missing attribute name '" + attributeName + "={index}' on measured element.");
405
- return -1;
406
- }
407
-
408
- return parseInt(indexStr, 10);
409
- };
410
-
411
- this._measureElement = (node, _sync) => {
412
- var _this$itemMeasurement;
413
-
414
- const index = this.indexFromElement(node);
415
- const item = this.measurementsCache[index];
416
-
417
- if (!item) {
418
- return;
419
- }
420
-
421
- const prevNode = this.measureElementCache[item.key];
422
- const ro = this.getResizeObserver();
423
-
424
- if (!node.isConnected) {
425
- if (prevNode) {
426
- ro == null ? void 0 : ro.unobserve(prevNode);
427
- delete this.measureElementCache[item.key];
428
- }
429
-
430
- return;
431
- }
432
-
433
- if (!prevNode || prevNode !== node) {
434
- if (prevNode) {
435
- ro == null ? void 0 : ro.unobserve(prevNode);
436
- }
437
-
438
- this.measureElementCache[item.key] = node;
439
- ro == null ? void 0 : ro.observe(node);
440
- }
441
-
442
- const measuredItemSize = this.options.measureElement(node, this);
443
- const itemSize = (_this$itemMeasurement = this.itemMeasurementsCache[item.key]) != null ? _this$itemMeasurement : item.size;
444
- const delta = measuredItemSize - itemSize;
445
-
446
- if (delta !== 0) {
447
- if (item.start < this.scrollOffset && this.isScrolling && this.destinationOffset === undefined) {
448
- if (process.env.NODE_ENV !== 'production' && this.options.debug) {
449
- console.info('correction', delta);
450
- }
451
-
452
- this.scrollDelta += delta;
453
-
454
- this._scrollToOffset(this.scrollOffset + this.scrollDelta, {
455
- canSmooth: false,
456
- sync: false,
457
- requested: false
458
- });
459
- }
460
-
461
- this.pendingMeasuredCacheIndexes.push(index);
462
- this.itemMeasurementsCache = { ...this.itemMeasurementsCache,
463
- [item.key]: measuredItemSize
464
- };
465
- this.notify();
466
- }
467
- };
468
-
469
- this.measureElement = node => {
470
- if (!node) {
471
- return;
472
- }
473
-
474
- this._measureElement(node, true);
475
- };
476
-
477
- this.getVirtualItems = memo(() => [this.getIndexes(), this.getMeasurements()], (indexes, measurements) => {
478
- const virtualItems = [];
479
-
480
- for (let k = 0, len = indexes.length; k < len; k++) {
481
- const i = indexes[k];
482
- const measurement = measurements[i];
483
- virtualItems.push(measurement);
484
- }
485
-
486
- return virtualItems;
487
- }, {
488
- key: process.env.NODE_ENV !== 'production' && 'getIndexes',
489
- debug: () => this.options.debug
490
- });
491
-
492
- this.scrollToOffset = function (toOffset, _temp) {
493
- let {
494
- align = 'start',
495
- smoothScroll = _this.options.enableSmoothScroll
496
- } = _temp === void 0 ? {} : _temp;
497
- const offset = _this.scrollOffset;
498
-
499
- const size = _this.getSize();
500
-
501
- if (align === 'auto') {
502
- if (toOffset <= offset) {
503
- align = 'start';
504
- } else if (toOffset >= offset + size) {
505
- align = 'end';
506
- } else {
507
- align = 'start';
508
- }
509
- }
510
-
511
- const options = {
512
- canSmooth: smoothScroll,
513
- sync: false,
514
- requested: true
515
- };
516
-
517
- if (align === 'start') {
518
- _this._scrollToOffset(toOffset, options);
519
- } else if (align === 'end') {
520
- _this._scrollToOffset(toOffset - size, options);
521
- } else if (align === 'center') {
522
- _this._scrollToOffset(toOffset - size / 2, options);
523
- }
524
- };
525
-
526
- this.scrollToIndex = function (index, _temp2) {
527
- let {
528
- align = 'auto',
529
- smoothScroll = _this.options.enableSmoothScroll,
530
- ...rest
531
- } = _temp2 === void 0 ? {} : _temp2;
532
-
533
- const measurements = _this.getMeasurements();
534
-
535
- const offset = _this.scrollOffset;
536
-
537
- const size = _this.getSize();
538
-
539
- const {
540
- count
541
- } = _this.options;
542
- const measurement = measurements[Math.max(0, Math.min(index, count - 1))];
543
-
544
- if (!measurement) {
545
- return;
546
- }
547
-
548
- if (align === 'auto') {
549
- if (measurement.end >= offset + size - _this.options.scrollPaddingEnd) {
550
- align = 'end';
551
- } else if (measurement.start <= offset + _this.options.scrollPaddingStart) {
552
- align = 'start';
553
- } else {
554
- return;
555
- }
556
- }
557
-
558
- const toOffset = align === 'end' ? measurement.end + _this.options.scrollPaddingEnd : measurement.start - _this.options.scrollPaddingStart;
559
-
560
- _this.scrollToOffset(toOffset, {
561
- align,
562
- smoothScroll,
563
- ...rest
564
- });
565
- };
566
-
567
- this.getTotalSize = () => {
568
- var _this$getMeasurements;
569
-
570
- return (((_this$getMeasurements = this.getMeasurements()[this.options.count - 1]) == null ? void 0 : _this$getMeasurements.end) || this.options.paddingStart) + this.options.paddingEnd;
571
- };
572
-
573
- this._scrollToOffset = (offset, _ref4) => {
574
- let {
575
- requested,
576
- canSmooth,
577
- sync
578
- } = _ref4;
579
- clearTimeout(this.scrollCheckFrame);
580
-
581
- if (requested) {
582
- this.destinationOffset = offset;
583
- }
584
-
585
- this.options.scrollToFn(offset, {
586
- canSmooth,
587
- sync
588
- }, this);
589
- let scrollCheckFrame;
590
-
591
- const check = () => {
592
- let lastOffset = this.scrollOffset;
593
- this.scrollCheckFrame = scrollCheckFrame = setTimeout(() => {
594
- if (this.scrollCheckFrame !== scrollCheckFrame) {
595
- return;
596
- }
597
-
598
- if (this.scrollOffset === lastOffset) {
599
- this.destinationOffset = undefined;
600
- return;
601
- }
602
-
603
- lastOffset = this.scrollOffset;
604
- check();
605
- }, 100);
606
- };
607
-
608
- check();
609
- };
610
-
611
- this.measure = () => {
612
- this.itemMeasurementsCache = {};
613
- this.notify();
614
- };
615
-
616
- this.setOptions(_opts);
617
- this.scrollRect = this.options.initialRect;
618
- this.scrollOffset = this.options.initialOffset;
619
- this.calculateRange();
620
- }
621
-
622
- }
623
-
624
- const findNearestBinarySearch = (low, high, getCurrentValue, value) => {
625
- while (low <= high) {
626
- const middle = (low + high) / 2 | 0;
627
- const currentValue = getCurrentValue(middle);
628
-
629
- if (currentValue < value) {
630
- low = middle + 1;
631
- } else if (currentValue > value) {
632
- high = middle - 1;
633
- } else {
634
- return middle;
635
- }
636
- }
637
-
638
- if (low > 0) {
639
- return low - 1;
640
- } else {
641
- return 0;
642
- }
643
- };
644
-
645
- function calculateRange(_ref5) {
646
- let {
647
- measurements,
648
- outerSize,
649
- scrollOffset
650
- } = _ref5;
651
- const count = measurements.length - 1;
652
-
653
- const getOffset = index => measurements[index].start;
654
-
655
- const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset);
656
- let endIndex = startIndex;
657
-
658
- while (endIndex < count && measurements[endIndex].end < scrollOffset + outerSize) {
659
- endIndex++;
660
- }
661
-
662
- return {
663
- startIndex,
664
- endIndex
665
- };
666
- }
667
-
668
- const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
669
-
670
- function useVirtualizerBase(options) {
671
- const rerender = React.useReducer(() => ({}), {})[1];
672
- const resolvedOptions = { ...options,
673
- onChange: instance => {
674
- rerender();
675
- options.onChange == null ? void 0 : options.onChange(instance);
676
- }
677
- };
678
- const [instance] = React.useState(() => new Virtualizer(resolvedOptions));
679
- instance.setOptions(resolvedOptions);
680
- React.useEffect(() => {
681
- return instance._didMount();
682
- }, []);
683
- useIsomorphicLayoutEffect(() => {
684
- return instance._willUpdate();
685
- });
686
- return instance;
687
- }
688
-
689
- function useVirtualizer(options) {
690
- return useVirtualizerBase({
691
- observeElementRect: observeElementRect,
692
- observeElementOffset: observeElementOffset,
693
- scrollToFn: elementScroll,
694
- ...options
695
- });
696
- }
697
- function useWindowVirtualizer(options) {
698
- return useVirtualizerBase({
699
- getScrollElement: () => typeof window !== 'undefined' ? window : null,
700
- observeElementRect: observeWindowRect,
701
- observeElementOffset: observeWindowOffset,
702
- scrollToFn: windowScroll,
703
- ...options
704
- });
705
- }
706
-
707
- export { Virtualizer, defaultKeyExtractor, defaultRangeExtractor, elementScroll, measureElement, memo, observeElementOffset, observeElementRect, observeWindowOffset, observeWindowRect, useVirtualizer, useWindowVirtualizer, windowScroll };
708
- //# sourceMappingURL=index.js.map