Files
frontend-svelte/src/shared/lib/helpers/createVirtualizer/createVirtualizer.svelte.ts

268 lines
8.9 KiB
TypeScript
Raw Normal View History

/**
* Represents a virtualized list item with layout information.
*
* Used to render visible items with absolute positioning based on computed offsets.
*/
export interface VirtualItem {
/** Index of the item in the data array */
index: number;
/** Offset from the top of the list in pixels */
start: number;
/** Height/size of the item in pixels */
size: number;
/** End position in pixels (start + size) */
end: number;
/** Unique key for the item (for Svelte's {#each} keying) */
key: string | number;
}
/**
* Configuration options for {@link createVirtualizer}.
*
* Options are reactive - pass them through a function getter to enable updates.
*/
export interface VirtualizerOptions {
/** Total number of items in the data array */
count: number;
/**
* Function to estimate the size of an item at a given index.
* Used for initial layout before actual measurements are available.
*/
estimateSize: (index: number) => number;
/** Number of extra items to render outside viewport for smoother scrolling (default: 5) */
overscan?: number;
/**
* Function to get the key of an item at a given index.
* Defaults to using the index directly. Useful for stable keys when items reorder.
*/
getItemKey?: (index: number) => string | number;
/**
* Optional margin in pixels for scroll calculations.
* Can be useful for handling sticky headers or other UI elements.
*/
scrollMargin?: number;
}
/**
* Creates a reactive virtualizer for efficiently rendering large lists by only rendering visible items.
*
* Uses Svelte 5 runes ($state, $derived) for reactive state management and optimizes rendering
* through scroll position tracking and item height measurement. Supports dynamic item heights
* and programmatic scrolling.
*
* @param optionsGetter - Function that returns reactive virtualizer options
* @returns Virtualizer instance with computed properties and action functions
*
* @example
* ```svelte
* <script lang="ts">
* const virtualizer = createVirtualizer(() => ({
* count: 1000,
* estimateSize: (i) => i % 3 === 0 ? 100 : 50,
* overscan: 5,
* getItemKey: (i) => `item-${i}`
* }));
* </script>
*
* <div use:virtualizer.container style="height: 500px; overflow: auto;">
* <div style="height: {virtualizer.totalSize}px;">
* {#each virtualizer.items as item (item.key)}
* <div
* use:virtualizer.measureElement
* data-index={item.index}
* style="position: absolute; top: {item.start}px; height: {item.size}px;"
* >
* Item {item.index}
* </div>
* {/each}
* </div>
* </div>
* ```
*/
export function createVirtualizer(optionsGetter: () => VirtualizerOptions) {
// Reactive State
let scrollOffset = $state(0);
let containerHeight = $state(0);
let measuredSizes = $state<Record<number, number>>({});
// Non-reactive ref for DOM manipulation (avoiding unnecessary state tracking)
let elementRef: HTMLElement | null = null;
// Reactive Options
const options = $derived(optionsGetter());
// Optimized Memoization (The Cache Layer)
// Only recalculates when item count or measured sizes change.
const offsets = $derived.by(() => {
const count = options.count;
const result = Array.from<number>({ length: count });
let accumulated = 0;
for (let i = 0; i < count; i++) {
result[i] = accumulated;
accumulated += measuredSizes[i] ?? options.estimateSize(i);
}
return result;
});
const totalSize = $derived(
options.count > 0
? offsets[options.count - 1]
+ (measuredSizes[options.count - 1] ?? options.estimateSize(options.count - 1))
: 0,
);
// Visible Range Calculation
// Svelte tracks dependencies automatically here.
const items = $derived.by((): VirtualItem[] => {
const count = options.count;
if (count === 0 || containerHeight === 0) return [];
const overscan = options.overscan ?? 5;
const viewportStart = scrollOffset;
const viewportEnd = scrollOffset + containerHeight;
// Find Start (Linear Scan)
let startIdx = 0;
while (startIdx < count && offsets[startIdx + 1] < viewportStart) {
startIdx++;
}
// Find End
let endIdx = startIdx;
while (endIdx < count && offsets[endIdx] < viewportEnd) {
endIdx++;
}
const start = Math.max(0, startIdx - overscan);
const end = Math.min(count, endIdx + overscan);
const result: VirtualItem[] = [];
for (let i = start; i < end; i++) {
const size = measuredSizes[i] ?? options.estimateSize(i);
result.push({
index: i,
start: offsets[i],
size,
end: offsets[i] + size,
key: options.getItemKey?.(i) ?? i,
});
}
return result;
});
// Svelte Actions (The DOM Interface)
/**
* Svelte action to attach to the scrollable container element.
*
* Sets up scroll tracking, container height monitoring, and cleanup on destroy.
*
* @param node - The DOM element to attach to (should be the scrollable container)
* @returns Object with destroy method for cleanup
*/
function container(node: HTMLElement) {
elementRef = node;
containerHeight = node.offsetHeight;
const handleScroll = () => {
scrollOffset = node.scrollTop;
};
const resizeObserver = new ResizeObserver(([entry]) => {
if (entry) containerHeight = entry.contentRect.height;
});
node.addEventListener('scroll', handleScroll, { passive: true });
resizeObserver.observe(node);
return {
destroy() {
node.removeEventListener('scroll', handleScroll);
resizeObserver.disconnect();
elementRef = null;
},
};
}
/**
* Svelte action to measure individual item elements for dynamic height support.
*
* Attaches a ResizeObserver to track actual element height and updates
* measured sizes when dimensions change. Requires `data-index` attribute on the element.
*
* @param node - The DOM element to measure (should have `data-index` attribute)
* @returns Object with destroy method for cleanup
*/
function measureElement(node: HTMLElement) {
// Use a ResizeObserver on individual items for dynamic height support
const resizeObserver = new ResizeObserver(([entry]) => {
if (entry) {
const index = parseInt(node.dataset.index || '', 10);
const height = entry.borderBoxSize[0]?.blockSize ?? node.offsetHeight;
// Only update if height actually changed to prevent loops
if (!isNaN(index) && measuredSizes[index] !== height) {
measuredSizes[index] = height;
}
}
});
resizeObserver.observe(node);
return {
destroy: () => resizeObserver.disconnect(),
};
}
// Programmatic Scroll
/**
* Scrolls the container to bring the specified item into view.
*
* @param index - Index of the item to scroll to
* @param align - Scroll alignment: 'start', 'center', 'end', or 'auto' (default)
*
* @example
* ```ts
* virtualizer.scrollToIndex(50, 'center'); // Scroll to item 50 and center it
* ```
*/
function scrollToIndex(index: number, align: 'start' | 'center' | 'end' | 'auto' = 'auto') {
if (!elementRef || index < 0 || index >= options.count) return;
const itemStart = offsets[index];
const itemSize = measuredSizes[index] ?? options.estimateSize(index);
let target = itemStart;
if (align === 'center') target = itemStart - containerHeight / 2 + itemSize / 2;
if (align === 'end') target = itemStart - containerHeight + itemSize;
elementRef.scrollTo({ top: target, behavior: 'smooth' });
}
return {
/** Computed array of visible items to render (reactive) */
get items() {
return items;
},
/** Total height of all items in pixels (reactive) */
get totalSize() {
return totalSize;
},
/** Svelte action for the scrollable container element */
container,
/** Svelte action for measuring individual item elements */
measureElement,
/** Programmatic scroll method to scroll to a specific item */
scrollToIndex,
};
}
/**
* Virtualizer instance returned by {@link createVirtualizer}.
*
* Provides reactive computed properties for visible items and total size,
* along with action functions for DOM integration and element measurement.
*/
export type Virtualizer = ReturnType<typeof createVirtualizer>;