Skip to content
Source
Sign inSign up
TanStack/virtual
Open History to see the last commit

index.ts

1,139 lines28.4 KB

1import { approxEqual, debounce, memo, notUndefined } from './utils'
2​
3export * from './utils'
4​
5//
6​
7type ScrollDirection = 'forward' | 'backward'
8​
9type ScrollAlignment = 'start' | 'center' | 'end' | 'auto'
10​
11type ScrollBehavior = 'auto' | 'smooth'
12​
13export interface ScrollToOptions {
14 align?: ScrollAlignment
15 behavior?: ScrollBehavior
17​
18type ScrollToOffsetOptions = ScrollToOptions
19​
20type ScrollToIndexOptions = ScrollToOptions
21​
22export interface Range {
23 startIndex: number
24 endIndex: number
25 overscan: number
26 count: number
28​
29type Key = number | string | bigint
30​
31export interface VirtualItem {
32 key: Key
33 index: number
34 start: number
35 end: number
36 size: number
37 lane: number
39​
40export interface Rect {
41 width: number
42 height: number
44​
45//
46​
47export const defaultKeyExtractor = (index: number) => index
48​
49export const defaultRangeExtractor = (range: Range) => {
50 const start = Math.max(range.startIndex - range.overscan, 0)
51 const end = Math.min(range.endIndex + range.overscan, range.count - 1)
52​
53 const arr = []
54​
55 for (let i = start; i <= end; i++) {
56 arr.push(i)
57 }
58​
59 return arr
61​
62export const observeElementRect = <T extends Element>(
63 instance: Virtualizer<T, any>,
64 cb: (rect: Rect) => void,
65) => {
66 const element = instance.scrollElement
67 if (!element) {
68 return
69 }
70 const targetWindow = instance.targetWindow
71 if (!targetWindow) {
72 return
73 }
74​
75 const handler = (rect: Rect) => {
76 const { width, height } = rect
77 cb({ width: Math.round(width), height: Math.round(height) })
78 }
79​
80 handler(element.getBoundingClientRect())
81​
82 if (!targetWindow.ResizeObserver) {
83 return () => {}
84 }
85​
86 const observer = new targetWindow.ResizeObserver((entries) => {
87 const run = () => {
88 const entry = entries[0]
89 if (entry?.borderBoxSize) {
90 const box = entry.borderBoxSize[0]
91 if (box) {
92 handler({ width: box.inlineSize, height: box.blockSize })
93 return
94 }
95 }
96 handler(element.getBoundingClientRect())
97 }
98​
99 instance.options.useAnimationFrameWithResizeObserver
100 ? requestAnimationFrame(run)
101 : run()
102 })
103​
104 observer.observe(element, { box: 'border-box' })
105​
106 return () => {
107 observer.unobserve(element)
108 }
110​
111const addEventListenerOptions = {
112 passive: true,
114​
115export const observeWindowRect = (
116 instance: Virtualizer<Window, any>,
117 cb: (rect: Rect) => void,
118) => {
119 const element = instance.scrollElement
120 if (!element) {
121 return
122 }
123​
124 const handler = () => {
125 cb({ width: element.innerWidth, height: element.innerHeight })
126 }
127 handler()
128​
129 element.addEventListener('resize', handler, addEventListenerOptions)
130​
131 return () => {
132 element.removeEventListener('resize', handler)
133 }
135​
136const supportsScrollend =
137 typeof window == 'undefined' ? true : 'onscrollend' in window
138​
139type ObserveOffsetCallBack = (offset: number, isScrolling: boolean) => void
140​
141export const observeElementOffset = <T extends Element>(
142 instance: Virtualizer<T, any>,
143 cb: ObserveOffsetCallBack,
144) => {
145 const element = instance.scrollElement
146 if (!element) {
147 return
148 }
149 const targetWindow = instance.targetWindow
150 if (!targetWindow) {
151 return
152 }
153​
154 let offset = 0
155 const fallback =
156 instance.options.useScrollendEvent && supportsScrollend
157 ? () => undefined
158 : debounce(
159 targetWindow,
160 () => {
161 cb(offset, false)
162 },
163 instance.options.isScrollingResetDelay,
164 )
165​
166 const createHandler = (isScrolling: boolean) => () => {
167 const { horizontal, isRtl } = instance.options
168 offset = horizontal
169 ? element['scrollLeft'] * ((isRtl && -1) || 1)
170 : element['scrollTop']
171 fallback()
172 cb(offset, isScrolling)
173 }
174 const handler = createHandler(true)
175 const endHandler = createHandler(false)
176 endHandler()
177​
178 element.addEventListener('scroll', handler, addEventListenerOptions)
179 const registerScrollendEvent =
180 instance.options.useScrollendEvent && supportsScrollend
181 if (registerScrollendEvent) {
182 element.addEventListener('scrollend', endHandler, addEventListenerOptions)
183 }
184 return () => {
185 element.removeEventListener('scroll', handler)
186 if (registerScrollendEvent) {
187 element.removeEventListener('scrollend', endHandler)
188 }
189 }
191​
192export const observeWindowOffset = (
193 instance: Virtualizer<Window, any>,
194 cb: ObserveOffsetCallBack,
195) => {
196 const element = instance.scrollElement
197 if (!element) {
198 return
199 }
200 const targetWindow = instance.targetWindow
201 if (!targetWindow) {
202 return
203 }
204​
205 let offset = 0
206 const fallback =
207 instance.options.useScrollendEvent && supportsScrollend
208 ? () => undefined
209 : debounce(
210 targetWindow,
211 () => {
212 cb(offset, false)
213 },
214 instance.options.isScrollingResetDelay,
215 )
216​
217 const createHandler = (isScrolling: boolean) => () => {
218 offset = element[instance.options.horizontal ? 'scrollX' : 'scrollY']
219 fallback()
220 cb(offset, isScrolling)
221 }
222 const handler = createHandler(true)
223 const endHandler = createHandler(false)
224 endHandler()
225​
226 element.addEventListener('scroll', handler, addEventListenerOptions)
227 const registerScrollendEvent =
228 instance.options.useScrollendEvent && supportsScrollend
229 if (registerScrollendEvent) {
230 element.addEventListener('scrollend', endHandler, addEventListenerOptions)
231 }
232 return () => {
233 element.removeEventListener('scroll', handler)
234 if (registerScrollendEvent) {
235 element.removeEventListener('scrollend', endHandler)
236 }
237 }
239​
240export const measureElement = <TItemElement extends Element>(
241 element: TItemElement,
242 entry: ResizeObserverEntry | undefined,
243 instance: Virtualizer<any, TItemElement>,
244) => {
245 if (entry?.borderBoxSize) {
246 const box = entry.borderBoxSize[0]
247 if (box) {
248 const size = Math.round(
249 box[instance.options.horizontal ? 'inlineSize' : 'blockSize'],
250 )
251 return size
252 }
253 }
254 return Math.round(
255 element.getBoundingClientRect()[
256 instance.options.horizontal ? 'width' : 'height'
257 ],
258 )
260​
261export const windowScroll = <T extends Window>(
262 offset: number,
263 {
264 adjustments = 0,
265 behavior,
266 }: { adjustments?: number; behavior?: ScrollBehavior },
267 instance: Virtualizer<T, any>,
268) => {
269 const toOffset = offset + adjustments
270​
271 instance.scrollElement?.scrollTo?.({
272 [instance.options.horizontal ? 'left' : 'top']: toOffset,
273 behavior,
274 })
276​
277export const elementScroll = <T extends Element>(
278 offset: number,
279 {
280 adjustments = 0,
281 behavior,
282 }: { adjustments?: number; behavior?: ScrollBehavior },
283 instance: Virtualizer<T, any>,
284) => {
285 const toOffset = offset + adjustments
286​
287 instance.scrollElement?.scrollTo?.({
288 [instance.options.horizontal ? 'left' : 'top']: toOffset,
289 behavior,
290 })
292​
293export interface VirtualizerOptions<
294 TScrollElement extends Element | Window,
295 TItemElement extends Element,
296> {
297 // Required from the user
298 count: number
299 getScrollElement: () => TScrollElement | null
300 estimateSize: (index: number) => number
301​
302 // Required from the framework adapter (but can be overridden)
303 scrollToFn: (
304 offset: number,
305 options: { adjustments?: number; behavior?: ScrollBehavior },
306 instance: Virtualizer<TScrollElement, TItemElement>,
307 ) => void
308 observeElementRect: (
309 instance: Virtualizer<TScrollElement, TItemElement>,
310 cb: (rect: Rect) => void,
311 ) => void | (() => void)
312 observeElementOffset: (
313 instance: Virtualizer<TScrollElement, TItemElement>,
314 cb: ObserveOffsetCallBack,
315 ) => void | (() => void)
316 // Optional
317 debug?: boolean
318 initialRect?: Rect
319 onChange?: (
320 instance: Virtualizer<TScrollElement, TItemElement>,
321 sync: boolean,
322 ) => void
323 measureElement?: (
324 element: TItemElement,
325 entry: ResizeObserverEntry | undefined,
326 instance: Virtualizer<TScrollElement, TItemElement>,
327 ) => number
328 overscan?: number
329 horizontal?: boolean
330 paddingStart?: number
331 paddingEnd?: number
332 scrollPaddingStart?: number
333 scrollPaddingEnd?: number
334 initialOffset?: number | (() => number)
335 getItemKey?: (index: number) => Key
336 rangeExtractor?: (range: Range) => Array<number>
337 scrollMargin?: number
338 gap?: number
339 indexAttribute?: string
340 initialMeasurementsCache?: Array<VirtualItem>
341 lanes?: number
342 isScrollingResetDelay?: number
343 useScrollendEvent?: boolean
344 enabled?: boolean
345 isRtl?: boolean
346 useAnimationFrameWithResizeObserver?: boolean
348​
349export class Virtualizer<
350 TScrollElement extends Element | Window,
351 TItemElement extends Element,
352> {
353 private unsubs: Array<void | (() => void)> = []
354 options!: Required<VirtualizerOptions<TScrollElement, TItemElement>>
355 scrollElement: TScrollElement | null = null
356 targetWindow: (Window & typeof globalThis) | null = null
357 isScrolling = false
358 private scrollToIndexTimeoutId: number | null = null
359 measurementsCache: Array<VirtualItem> = []
360 private itemSizeCache = new Map<Key, number>()
361 private pendingMeasuredCacheIndexes: Array<number> = []
362 scrollRect: Rect | null = null
363 scrollOffset: number | null = null
364 scrollDirection: ScrollDirection | null = null
365 private scrollAdjustments = 0
366 shouldAdjustScrollPositionOnItemSizeChange:
367 | undefined
368 | ((
369 item: VirtualItem,
370 delta: number,
371 instance: Virtualizer<TScrollElement, TItemElement>,
372 ) => boolean)
373 elementsCache = new Map<Key, TItemElement>()
374 private observer = (() => {
375 let _ro: ResizeObserver | null = null
376​
377 const get = () => {
378 if (_ro) {
379 return _ro
380 }
381​
382 if (!this.targetWindow || !this.targetWindow.ResizeObserver) {
383 return null
384 }
385​
386 return (_ro = new this.targetWindow.ResizeObserver((entries) => {
387 entries.forEach((entry) => {
388 const run = () => {
389 this._measureElement(entry.target as TItemElement, entry)
390 }
391 this.options.useAnimationFrameWithResizeObserver
392 ? requestAnimationFrame(run)
393 : run()
394 })
395 }))
396 }
397​
398 return {
399 disconnect: () => {
400 get()?.disconnect()
401 _ro = null
402 },
403 observe: (target: Element) =>
404 get()?.observe(target, { box: 'border-box' }),
405 unobserve: (target: Element) => get()?.unobserve(target),
406 }
407 })()
408 range: { startIndex: number; endIndex: number } | null = null
409​
410 constructor(opts: VirtualizerOptions<TScrollElement, TItemElement>) {
411 this.setOptions(opts)
412 }
413​
414 setOptions = (opts: VirtualizerOptions<TScrollElement, TItemElement>) => {
415 Object.entries(opts).forEach(([key, value]) => {
416 if (typeof value === 'undefined') delete (opts as any)[key]
417 })
418​
419 this.options = {
420 debug: false,
421 initialOffset: 0,
422 overscan: 1,
423 paddingStart: 0,
424 paddingEnd: 0,
425 scrollPaddingStart: 0,
426 scrollPaddingEnd: 0,
427 horizontal: false,
428 getItemKey: defaultKeyExtractor,
429 rangeExtractor: defaultRangeExtractor,
430 onChange: () => {},
431 measureElement,
432 initialRect: { width: 0, height: 0 },
433 scrollMargin: 0,
434 gap: 0,
435 indexAttribute: 'data-index',
436 initialMeasurementsCache: [],
437 lanes: 1,
438 isScrollingResetDelay: 150,
439 enabled: true,
440 isRtl: false,
441 useScrollendEvent: true,
442 useAnimationFrameWithResizeObserver: false,
443 ...opts,
444 }
445 }
446​
447 private notify = (sync: boolean) => {
448 this.options.onChange?.(this, sync)
449 }
450​
451 private maybeNotify = memo(
452 () => {
453 this.calculateRange()
454​
455 return [
456 this.isScrolling,
457 this.range ? this.range.startIndex : null,
458 this.range ? this.range.endIndex : null,
459 ]
460 },
461 (isScrolling) => {
462 this.notify(isScrolling)
463 },
464 {
465 key: process.env.NODE_ENV !== 'production' && 'maybeNotify',
466 debug: () => this.options.debug,
467 initialDeps: [
468 this.isScrolling,
469 this.range ? this.range.startIndex : null,
470 this.range ? this.range.endIndex : null,
471 ] as [boolean, number | null, number | null],
472 },
473 )
474​
475 private cleanup = () => {
476 this.unsubs.filter(Boolean).forEach((d) => d!())
477 this.unsubs = []
478 this.observer.disconnect()
479 this.scrollElement = null
480 this.targetWindow = null
481 }
482​
483 _didMount = () => {
484 return () => {
485 this.cleanup()
486 }
487 }
488​
489 _willUpdate = () => {
490 const scrollElement = this.options.enabled
491 ? this.options.getScrollElement()
492 : null
493​
494 if (this.scrollElement !== scrollElement) {
495 this.cleanup()
496​
497 if (!scrollElement) {
498 this.maybeNotify()
499 return
500 }
501​
502 this.scrollElement = scrollElement
503​
504 if (this.scrollElement && 'ownerDocument' in this.scrollElement) {
505 this.targetWindow = this.scrollElement.ownerDocument.defaultView
506 } else {
507 this.targetWindow = this.scrollElement?.window ?? null
508 }
509​
510 this.elementsCache.forEach((cached) => {
511 this.observer.observe(cached)
512 })
513​
514 this._scrollToOffset(this.getScrollOffset(), {
515 adjustments: undefined,
516 behavior: undefined,
517 })
518​
519 this.unsubs.push(
520 this.options.observeElementRect(this, (rect) => {
521 this.scrollRect = rect
522 this.maybeNotify()
523 }),
524 )
525​
526 this.unsubs.push(
527 this.options.observeElementOffset(this, (offset, isScrolling) => {
528 this.scrollAdjustments = 0
529 this.scrollDirection = isScrolling
530 ? this.getScrollOffset() < offset
531 ? 'forward'
532 : 'backward'
533 : null
534 this.scrollOffset = offset
535 this.isScrolling = isScrolling
536​
537 this.maybeNotify()
538 }),
539 )
540 }
541 }
542​
543 private getSize = () => {
544 if (!this.options.enabled) {
545 this.scrollRect = null
546 return 0
547 }
548​
549 this.scrollRect = this.scrollRect ?? this.options.initialRect
550​
551 return this.scrollRect[this.options.horizontal ? 'width' : 'height']
552 }
553​
554 private getScrollOffset = () => {
555 if (!this.options.enabled) {
556 this.scrollOffset = null
557 return 0
558 }
559​
560 this.scrollOffset =
561 this.scrollOffset ??
562 (typeof this.options.initialOffset === 'function'
563 ? this.options.initialOffset()
564 : this.options.initialOffset)
565​
566 return this.scrollOffset
567 }
568​
569 private getFurthestMeasurement = (
570 measurements: Array<VirtualItem>,
571 index: number,
572 ) => {
573 const furthestMeasurementsFound = new Map<number, true>()
574 const furthestMeasurements = new Map<number, VirtualItem>()
575 for (let m = index - 1; m >= 0; m--) {
576 const measurement = measurements[m]!
577​
578 if (furthestMeasurementsFound.has(measurement.lane)) {
579 continue
580 }
581​
582 const previousFurthestMeasurement = furthestMeasurements.get(
583 measurement.lane,
584 )
585 if (
586 previousFurthestMeasurement == null ||
587 measurement.end > previousFurthestMeasurement.end
588 ) {
589 furthestMeasurements.set(measurement.lane, measurement)
590 } else if (measurement.end < previousFurthestMeasurement.end) {
591 furthestMeasurementsFound.set(measurement.lane, true)
592 }
593​
594 if (furthestMeasurementsFound.size === this.options.lanes) {
595 break
596 }
597 }
598​
599 return furthestMeasurements.size === this.options.lanes
600 ? Array.from(furthestMeasurements.values()).sort((a, b) => {
601 if (a.end === b.end) {
602 return a.index - b.index
603 }
604​
605 return a.end - b.end
606 })[0]
607 : undefined
608 }
609​
610 private getMeasurementOptions = memo(
611 () => [
612 this.options.count,
613 this.options.paddingStart,
614 this.options.scrollMargin,
615 this.options.getItemKey,
616 this.options.enabled,
617 ],
618 (count, paddingStart, scrollMargin, getItemKey, enabled) => {
619 this.pendingMeasuredCacheIndexes = []
620 return {
621 count,
622 paddingStart,
623 scrollMargin,
624 getItemKey,
625 enabled,
626 }
627 },
628 {
629 key: false,
630 },
631 )
632​
633 private getMeasurements = memo(
634 () => [this.getMeasurementOptions(), this.itemSizeCache],
635 (
636 { count, paddingStart, scrollMargin, getItemKey, enabled },
637 itemSizeCache,
638 ) => {
639 if (!enabled) {
640 this.measurementsCache = []
641 this.itemSizeCache.clear()
642 return []
643 }
644​
645 if (this.measurementsCache.length === 0) {
646 this.measurementsCache = this.options.initialMeasurementsCache
647 this.measurementsCache.forEach((item) => {
648 this.itemSizeCache.set(item.key, item.size)
649 })
650 }
651​
652 const min =
653 this.pendingMeasuredCacheIndexes.length > 0
654 ? Math.min(...this.pendingMeasuredCacheIndexes)
655 : 0
656 this.pendingMeasuredCacheIndexes = []
657​
658 const measurements = this.measurementsCache.slice(0, min)
659​
660 for (let i = min; i < count; i++) {
661 const key = getItemKey(i)
662​
663 const furthestMeasurement =
664 this.options.lanes === 1
665 ? measurements[i - 1]
666 : this.getFurthestMeasurement(measurements, i)
667​
668 const start = furthestMeasurement
669 ? furthestMeasurement.end + this.options.gap
670 : paddingStart + scrollMargin
671​
672 const measuredSize = itemSizeCache.get(key)
673 const size =
674 typeof measuredSize === 'number'
675 ? measuredSize
676 : this.options.estimateSize(i)
677​
678 const end = start + size
679​
680 const lane = furthestMeasurement
681 ? furthestMeasurement.lane
682 : i % this.options.lanes
683​
684 measurements[i] = {
685 index: i,
686 start,
687 size,
688 end,
689 key,
690 lane,
691 }
692 }
693​
694 this.measurementsCache = measurements
695​
696 return measurements
697 },
698 {
699 key: process.env.NODE_ENV !== 'production' && 'getMeasurements',
700 debug: () => this.options.debug,
701 },
702 )
703​
704 calculateRange = memo(
705 () => [
706 this.getMeasurements(),
707 this.getSize(),
708 this.getScrollOffset(),
709 this.options.lanes,
710 ],
711 (measurements, outerSize, scrollOffset, lanes) => {
712 return (this.range =
713 measurements.length > 0 && outerSize > 0
714 ? calculateRange({
715 measurements,
716 outerSize,
717 scrollOffset,
718 lanes,
719 })
720 : null)
721 },
722 {
723 key: process.env.NODE_ENV !== 'production' && 'calculateRange',
724 debug: () => this.options.debug,
725 },
726 )
727​
728 getVirtualIndexes = memo(
729 () => {
730 let startIndex: number | null = null
731 let endIndex: number | null = null
732 const range = this.calculateRange()
733 if (range) {
734 startIndex = range.startIndex
735 endIndex = range.endIndex
736 }
737 return [
738 this.options.rangeExtractor,
739 this.options.overscan,
740 this.options.count,
741 startIndex,
742 endIndex,
743 ]
744 },
745 (rangeExtractor, overscan, count, startIndex, endIndex) => {
746 return startIndex === null || endIndex === null
747 ? []
748 : rangeExtractor({
749 startIndex,
750 endIndex,
751 overscan,
752 count,
753 })
754 },
755 {
756 key: process.env.NODE_ENV !== 'production' && 'getVirtualIndexes',
757 debug: () => this.options.debug,
758 },
759 )
760​
761 indexFromElement = (node: TItemElement) => {
762 const attributeName = this.options.indexAttribute
763 const indexStr = node.getAttribute(attributeName)
764​
765 if (!indexStr) {
766 console.warn(
767 `Missing attribute name '${attributeName}={index}' on measured element.`,
768 )
769 return -1
770 }
771​
772 return parseInt(indexStr, 10)
773 }
774​
775 private _measureElement = (
776 node: TItemElement,
777 entry: ResizeObserverEntry | undefined,
778 ) => {
779 const index = this.indexFromElement(node)
780 const item = this.measurementsCache[index]
781 if (!item) {
782 return
783 }
784 const key = item.key
785 const prevNode = this.elementsCache.get(key)
786​
787 if (prevNode !== node) {
788 if (prevNode) {
789 this.observer.unobserve(prevNode)
790 }
791 this.observer.observe(node)
792 this.elementsCache.set(key, node)
793 }
794​
795 if (node.isConnected) {
796 this.resizeItem(index, this.options.measureElement(node, entry, this))
797 }
798 }
799​
800 resizeItem = (index: number, size: number) => {
801 const item = this.measurementsCache[index]
802 if (!item) {
803 return
804 }
805 const itemSize = this.itemSizeCache.get(item.key) ?? item.size
806 const delta = size - itemSize
807​
808 if (delta !== 0) {
809 if (
810 this.shouldAdjustScrollPositionOnItemSizeChange !== undefined
811 ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this)
812 : item.start < this.getScrollOffset() + this.scrollAdjustments
813 ) {
814 if (process.env.NODE_ENV !== 'production' && this.options.debug) {
815 console.info('correction', delta)
816 }
817​
818 this._scrollToOffset(this.getScrollOffset(), {
819 adjustments: (this.scrollAdjustments += delta),
820 behavior: undefined,
821 })
822 }
823​
824 this.pendingMeasuredCacheIndexes.push(item.index)
825 this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size))
826​
827 this.notify(false)
828 }
829 }
830​
831 measureElement = (node: TItemElement | null | undefined) => {
832 if (!node) {
833 this.elementsCache.forEach((cached, key) => {
834 if (!cached.isConnected) {
835 this.observer.unobserve(cached)
836 this.elementsCache.delete(key)
837 }
838 })
839 return
840 }
841​
842 this._measureElement(node, undefined)
843 }
844​
845 getVirtualItems = memo(
846 () => [this.getVirtualIndexes(), this.getMeasurements()],
847 (indexes, measurements) => {
848 const virtualItems: Array<VirtualItem> = []
849​
850 for (let k = 0, len = indexes.length; k < len; k++) {
851 const i = indexes[k]!
852 const measurement = measurements[i]!
853​
854 virtualItems.push(measurement)
855 }
856​
857 return virtualItems
858 },
859 {
860 key: process.env.NODE_ENV !== 'production' && 'getVirtualItems',
861 debug: () => this.options.debug,
862 },
863 )
864​
865 getVirtualItemForOffset = (offset: number) => {
866 const measurements = this.getMeasurements()
867 if (measurements.length === 0) {
868 return undefined
869 }
870 return notUndefined(
871 measurements[
872 findNearestBinarySearch(
873 0,
874 measurements.length - 1,
875 (index: number) => notUndefined(measurements[index]).start,
876 offset,
877 )
878 ],
879 )
880 }
881​
882 getOffsetForAlignment = (
883 toOffset: number,
884 align: ScrollAlignment,
885 itemSize = 0,
886 ) => {
887 const size = this.getSize()
888 const scrollOffset = this.getScrollOffset()
889​
890 if (align === 'auto') {
891 align = toOffset >= scrollOffset + size ? 'end' : 'start'
892 }
893​
894 if (align === 'center') {
895 // When aligning to a particular item (e.g. with scrollToIndex),
896 // adjust offset by the size of the item to center on the item
897 toOffset += (itemSize - size) / 2
898 } else if (align === 'end') {
899 toOffset -= size
900 }
901​
902 const scrollSizeProp = this.options.horizontal
903 ? 'scrollWidth'
904 : 'scrollHeight'
905 const scrollSize = this.scrollElement
906 ? 'document' in this.scrollElement
907 ? this.scrollElement.document.documentElement[scrollSizeProp]
908 : this.scrollElement[scrollSizeProp]
909 : 0
910​
911 const maxOffset = scrollSize - size
912​
913 return Math.max(Math.min(maxOffset, toOffset), 0)
914 }
915​
916 getOffsetForIndex = (index: number, align: ScrollAlignment = 'auto') => {
917 index = Math.max(0, Math.min(index, this.options.count - 1))
918​
919 const item = this.measurementsCache[index]
920 if (!item) {
921 return undefined
922 }
923​
924 const size = this.getSize()
925 const scrollOffset = this.getScrollOffset()
926​
927 if (align === 'auto') {
928 if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {
929 align = 'end'
930 } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {
931 align = 'start'
932 } else {
933 return [scrollOffset, align] as const
934 }
935 }
936​
937 const toOffset =
938 align === 'end'
939 ? item.end + this.options.scrollPaddingEnd
940 : item.start - this.options.scrollPaddingStart
941​
942 return [
943 this.getOffsetForAlignment(toOffset, align, item.size),
944 align,
945 ] as const
946 }
947​
948 private isDynamicMode = () => this.elementsCache.size > 0
949​
950 private cancelScrollToIndex = () => {
951 if (this.scrollToIndexTimeoutId !== null && this.targetWindow) {
952 this.targetWindow.clearTimeout(this.scrollToIndexTimeoutId)
953 this.scrollToIndexTimeoutId = null
954 }
955 }
956​
957 scrollToOffset = (
958 toOffset: number,
959 { align = 'start', behavior }: ScrollToOffsetOptions = {},
960 ) => {
961 this.cancelScrollToIndex()
962​
963 if (behavior === 'smooth' && this.isDynamicMode()) {
964 console.warn(
965 'The `smooth` scroll behavior is not fully supported with dynamic size.',
966 )
967 }
968​
969 this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {
970 adjustments: undefined,
971 behavior,
972 })
973 }
974​
975 scrollToIndex = (
976 index: number,
977 { align: initialAlign = 'auto', behavior }: ScrollToIndexOptions = {},
978 ) => {
979 index = Math.max(0, Math.min(index, this.options.count - 1))
980​
981 this.cancelScrollToIndex()
982​
983 if (behavior === 'smooth' && this.isDynamicMode()) {
984 console.warn(
985 'The `smooth` scroll behavior is not fully supported with dynamic size.',
986 )
987 }
988​
989 const offsetAndAlign = this.getOffsetForIndex(index, initialAlign)
990 if (!offsetAndAlign) return
991​
992 const [offset, align] = offsetAndAlign
993​
994 this._scrollToOffset(offset, { adjustments: undefined, behavior })
995​
996 if (behavior !== 'smooth' && this.isDynamicMode() && this.targetWindow) {
997 this.scrollToIndexTimeoutId = this.targetWindow.setTimeout(() => {
998 this.scrollToIndexTimeoutId = null
999​
1000 const elementInDOM = this.elementsCache.has(
1001 this.options.getItemKey(index),
1003​
1004 if (elementInDOM) {
1005 const [latestOffset] = notUndefined(
1006 this.getOffsetForIndex(index, align),
1008​
1009 if (!approxEqual(latestOffset, this.getScrollOffset())) {
1010 this.scrollToIndex(index, { align, behavior })
1012 } else {
1013 this.scrollToIndex(index, { align, behavior })
1015 })
1018​
1019 scrollBy = (delta: number, { behavior }: ScrollToOffsetOptions = {}) => {
1020 this.cancelScrollToIndex()
1021​
1022 if (behavior === 'smooth' && this.isDynamicMode()) {
1023 console.warn(
1024 'The `smooth` scroll behavior is not fully supported with dynamic size.',
1027​
1028 this._scrollToOffset(this.getScrollOffset() + delta, {
1029 adjustments: undefined,
1030 behavior,
1031 })
1033​
1034 getTotalSize = () => {
1035 const measurements = this.getMeasurements()
1036​
1037 let end: number
1038 // If there are no measurements, set the end to paddingStart
1039 if (measurements.length === 0) {
1040 end = this.options.paddingStart
1041 } else {
1042 // If lanes is 1, use the last measurement's end, otherwise find the maximum end value among all measurements
1043 end =
1044 this.options.lanes === 1
1045 ? (measurements[measurements.length - 1]?.end ?? 0)
1046 : Math.max(
1047 ...measurements.slice(-this.options.lanes).map((m) => m.end),
1050​
1051 return Math.max(
1052 end - this.options.scrollMargin + this.options.paddingEnd,
1053 0,
1056​
1057 private _scrollToOffset = (
1058 offset: number,
1060 adjustments,
1061 behavior,
1062 }: {
1063 adjustments: number | undefined
1064 behavior: ScrollBehavior | undefined
1065 },
1066 ) => {
1067 this.options.scrollToFn(offset, { behavior, adjustments }, this)
1069​
1070 measure = () => {
1071 this.itemSizeCache = new Map()
1072 this.notify(false)
1075​
1076const findNearestBinarySearch = (
1077 low: number,
1078 high: number,
1079 getCurrentValue: (i: number) => number,
1080 value: number,
1081) => {
1082 while (low <= high) {
1083 const middle = ((low + high) / 2) | 0
1084 const currentValue = getCurrentValue(middle)
1085​
1086 if (currentValue < value) {
1087 low = middle + 1
1088 } else if (currentValue > value) {
1089 high = middle - 1
1090 } else {
1091 return middle
1094​
1095 if (low > 0) {
1096 return low - 1
1097 } else {
1098 return 0
1101​
1102function calculateRange({
1103 measurements,
1104 outerSize,
1105 scrollOffset,
1106 lanes,
1107}: {
1108 measurements: Array<VirtualItem>
1109 outerSize: number
1110 scrollOffset: number
1111 lanes: number
1112}) {
1113 const lastIndex = measurements.length - 1
1114 const getOffset = (index: number) => measurements[index]!.start
1115​
1116 let startIndex = findNearestBinarySearch(
1117 0,
1118 lastIndex,
1119 getOffset,
1120 scrollOffset,
1122 let endIndex = startIndex
1123​
1124 while (
1125 endIndex < lastIndex &&
1126 measurements[endIndex]!.end < scrollOffset + outerSize
1127 ) {
1128 endIndex++
1130​
1131 if (lanes > 1) {
1132 // Align startIndex to the beginning of its lane
1133 startIndex = Math.max(0, startIndex - (startIndex % lanes))
1134 // Align endIndex to the end of its lane
1135 endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - (endIndex % lanes)))
1137​
1138 return { startIndex, endIndex }