import { ensure } from "ensured"; import { raf } from "./raf"; export type VirtualListNode = { index: number; key: string; style: Record; data: T; }; type Options = { itemHeight: number; overscanCount?: number; items: T[]; onEndReached?: (event: null) => void; }; function deepEqual(a: any, b: any): boolean { if (a === b) return true; if (typeof a !== typeof b || a === null || b === null) return false; if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; return a.every((val, i) => deepEqual(val, b[i])); } if (typeof a === "object" && typeof b === "object") { const keysA = Object.keys(a); const keysB = Object.keys(b); if (keysA.length !== keysB.length) return false; return keysA.every(key => deepEqual(a[key], b[key])); } return false; } export class VirtualListManager { private itemHeight: number; private overscanCount: number; private items: T[] = []; private itemHeights: Record = {}; private scrollTop = 0; private visible: VirtualListNode[] = []; private onEndReached: ((event: null) => void) | null = null; private endReachedForLength = 0; private container: HTMLElement | null = null; private wrapper: HTMLElement | null = null; private onChange: ((nodes: VirtualListNode[]) => void) | null = null; private mutationObserver: MutationObserver | null = null; private resizeObserver: ResizeObserver | null = null; private scrollController: AbortController | null = null; constructor(opts: Options) { this.itemHeight = opts.itemHeight; this.overscanCount = opts.overscanCount ?? 1; this.items = opts.items; this.onEndReached = opts.onEndReached ?? null; } connect(container: HTMLDivElement, onChange: (nodes: VirtualListNode[]) => void) { this.disconnect(); this.container = container; this.wrapper = container.firstElementChild as HTMLElement; if (!this.wrapper) return; this.onChange = onChange; this.mutationObserver = new MutationObserver(raf(() => this.updateHeights())); this.mutationObserver.observe(this.wrapper, { childList: true }); this.resizeObserver = new ResizeObserver(raf(() => this.updateHeights())); this.resizeObserver.observe(this.wrapper); this.scrollController = new AbortController(); this.container.addEventListener("scroll", raf(event => this.onScroll(event)), { signal: this.scrollController.signal }); this.updateHeights(); this.emitVisible(); } disconnect() { this.mutationObserver?.disconnect(); this.mutationObserver = null; this.resizeObserver?.disconnect(); this.resizeObserver = null; this.scrollController?.abort(); this.scrollController = null; this.container = null; this.wrapper = null; this.onChange = null; } setOnEndReached(onEndReached?: (event: null) => void) { this.onEndReached = onEndReached ?? null; } setItems(items: any[]) { this.items = items; if (items.length < this.endReachedForLength) { this.endReachedForLength = 0; } this.updateHeights(); } private onScroll(event: Event) { this.scrollTop = (event.target as HTMLElement)?.scrollTop; this.emitVisible(); } get totalHeight(): number { const known = Object.values(this.itemHeights).reduce((a, b) => a + b, 0); return known + (this.items.length - Object.keys(this.itemHeights).length) * this.itemHeight; } private emitVisible() { const nextVisible = this.computeVisibleItems(); const shouldNotifyEnd = this.shouldNotifyEndReached(nextVisible); if (!deepEqual(this.visible, nextVisible)) { this.visible = nextVisible; this.onChange?.(this.visible); } if (shouldNotifyEnd) { this.onEndReached?.(null); } } private shouldNotifyEndReached(visible: VirtualListNode[]) { if (!this.onEndReached || !this.items.length || !visible.length) { return false; } const lastVisibleIndex = visible[visible.length - 1]!.index; const threshold = Math.max(0, this.items.length - 1 - this.overscanCount); if (lastVisibleIndex < threshold) return false; if (this.endReachedForLength === this.items.length) return false; this.endReachedForLength = this.items.length; return true; } private updateHeights() { if (!this.wrapper) return; const children = Array.from(this.wrapper.children) as HTMLElement[]; for (const child of children) { const id = child.dataset.id!; ensure(id, `virtual-list: items must have an 'id' property`); this.itemHeights[id] = child.getBoundingClientRect().height; } this.cleanupItemHeights(); this.emitVisible(); } private cleanupItemHeights() { const ids = new Set(this.items.map(x => x.id)); this.itemHeights = Object.fromEntries(Object.entries(this.itemHeights).filter(([id]) => ids.has(id))); } private computeVisibleItems(): VirtualListNode[] { const containerHeight = this.container?.clientHeight ?? 0; const start = this.findStartIndex(); const end = this.findEndIndex(this.scrollTop + containerHeight); const first = Math.max(0, start - this.overscanCount); const last = Math.min(this.items.length, end + this.overscanCount); const nodes: VirtualListNode[] = []; for (let index = first; index < last; index++) { const data = this.items[index]!; nodes.push({ index, key: `${index}-${data.id}`, data, style: { position: "absolute", top: `${this.getTop(index)}px`, left: "0", right: "0" } }); } return nodes; } private getTop(index: number): number { let top = 0; for (let i = 0; i < index; i++) { top += this.getHeight(i); } return top; } private getHeight(index: number): number { const id = this.items[index]?.id as string; return this.itemHeights[id] ?? this.itemHeight; } private findStartIndex(): number { for (let i = 0; i < this.items.length; i++) { if (this.getTop(i) + this.getHeight(i) >= this.scrollTop) return i; } return 0; } private findEndIndex(scrollBottom: number): number { for (let i = 0; i < this.items.length; i++) { if (this.getTop(i) >= scrollBottom) return i; } return this.items.length; } }