Solid Primitives virtual

# @solid-primitives/virtual [![size](https://img.shields.io/badge/size-1.73_kB-blue?style=for-the-badge)](https://bundlephobia.com/package/@solid-primitives/virtual) [![version](https://img.shields.io/npm/v/@solid-primitives/virtual?style=for-the-badge)](https://www.npmjs.com/package/@solid-primitives/virtual) [![stage](https://img.shields.io/endpoint?style=for-the-badge&url=https%3A%2F%2Fraw.githubusercontent.com%2Fsolidjs-community%2Fsolid-primitives%2Fmain%2Fassets%2Fbadges%2Fstage-0.json)](https://github.com/solidjs-community/solid-primitives#contribution-process) [![tested with vitest](https://img.shields.io/badge/tested_with-vitest-6E9F18?style=for-the-badge&logo=vitest)](https://vitest.dev) - [`createVirtualList`](#createvirtuallist) - A headless utility function for [virtualized lists](https://www.patterns.dev/vanilla/virtual-lists/) - [`VirtualList`](#virtuallist) - a basic, unstyled component based on `createVirtualList` ## Installation ```bash npm install @solid-primitives/virtual # or yarn add @solid-primitives/virtual # or pnpm add @solid-primitives/virtual ``` ## How to use it ### `createVirtualList` `createVirtualList` is a headless utility for constructing your own virtualized list components with maximum flexibility. ```tsx repl import { render } from "@solidjs/web"; import { For } from "solid-js"; import { createVirtualList } from "@solid-primitives/virtual"; const items = Array.from({ length: 10_000 }, (_, i) => `Row ${i + 1}`); function Demo() { const [virtual, onScroll] = createVirtualList({ items, rootHeight: 200, rowHeight: 24 }); return ( <>

rendered {virtual().firstIndex + 1}-{(virtual().lastIndex ?? -1) + 1} of {items.length}

{item =>
{item()}
}
); } render(() => , document.getElementById("app")!); ``` `virtual` is an accessor returning `{ containerHeight, viewerTop, visibleItems, firstIndex, lastIndex }` — call it to read the current values. When rendering `visibleItems` with ``, pass `keyed={false}` so each item is provided as an `Accessor` (`` defaults to `keyed={true}`, which passes raw values instead). - `firstIndex` is the index (into the original `items` list) of the first rendered item. - `lastIndex` is the index of the last rendered item, or `undefined` if the list is empty. Together they're useful for things like "showing items X-Y of Z" counters, since `visibleItems` alone doesn't tell you where those items sit in the original list. ```tsx function MyComp(): JSX.Element { const items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const rootHeight = 20; const rowHeight = 10; const overscanCount = 5; const [virtual, onScroll] = createVirtualList({ // the list of items - can be a signal items, // the height of the root element of the virtualizedList - can be a signal rootHeight, // the height of individual rows in the virtualizedList - can be a signal rowHeight, // the number of elements to render both before and after the visible section of the list, so passing 5 will render 5 items before the list, and 5 items after. Defaults to 1, cannot be set to zero. This is necessary to hide the blank space around list items when scrolling - can be a signal overscanCount, }); return (
{/* only virtual().visibleItems are ultimately rendered */} {/* keyed={false} is required for item to be passed as an Accessor — defaults to keyed={true}, passing raw values instead */} {item =>
{item()}
}
); } ``` ### Variable row heights `rowHeight` may also be a function `(index) => number` for rows whose heights are known up front. The fixed numeric path is untouched; the function form uses prefix sums and a binary search to find the visible range. ```ts // Type type RowHeight = number | ((index: number) => number); // Example const [virtual, onScroll, helpers] = createVirtualList({ items, rootHeight: 400, rowHeight: i => (items[i].expanded ? 120 : 40), }); virtual().offsets; // offset of each row in visibleItems, in the same order helpers.getRowOffset(25); // offset of any row; getRowOffset(items.length) is the total height helpers.scrollToIndex(25); // scrolls the container seen by onScroll (or pass one explicitly) ``` A function must declare its `index` parameter. A zero-parameter function is read as an accessor of a fixed height, as before. ### Measured row heights For unknown heights, pass `estimatedRowHeight`. Rows are assumed to be that tall until you report their real height with `helpers.measureElement`, which reads the row index from the element's `data-index` attribute (or takes it as a second argument), measures it and keeps it up to date with a `ResizeObserver` where available. Offsets, total height and the visible range update as measurements arrive. Elements with no layout (height 0) are ignored, and measurements are cleared for indexes beyond a shrunken list. ```tsx // Type type MeasureElement = (el: Element | null | undefined, index?: number) => void; // Example const [virtual, onScroll, { measureElement }] = createVirtualList({ items, rootHeight: 400, estimatedRowHeight: 48, }); // // {(item, i) =>
{item()}
} //
``` Other helpers: `getRowHeight(index)`, `unmeasureElement(el)` (also done automatically for disconnected elements) and `resetMeasurements()`. `` does all of this for you by wrapping each row in a measured element. ### `` `` is a basic, unstyled virtual list component you can drop into projects without modification. ```tsx repl import { render } from "@solidjs/web"; import { createSignal } from "solid-js"; import { VirtualList } from "@solid-primitives/virtual"; function Demo() { const [count, setCount] = createSignal(1_000); const items = () => Array.from({ length: count() }, (_, i) => i + 1); return ( <> No items

}> {item =>
Item #{item()}
}
); } render(() => , document.getElementById("app")!); ``` ```tsx No items} // an optional class applied to the element wrapping the rendered rows, useful for styling row layout (e.g. flex/grid) class="my-list" // the number of elements to render both before and after the visible section of the list, so passing 5 will render 5 items before the list, and 5 items after. Defaults to 1, cannot be set to zero. This is necessary to hide the blank space around list items when scrolling overscanCount={5} // the height of the root element of the virtualizedList itself rootHeight={20} // the height of individual rows in the virtualizedList rowHeight={10} > { // the flowComponent that will be used to transform the items into rows in the list // item is an Accessor — call it to get the value item =>
{item()}
}
``` The tests describe the exact behavior and how overscanCount handles the start/end of the list in more detail. Note that the component only handles vertical lists where the number of items is known. Row heights can be fixed, given by a function, or measured (see above). #### Styling the rows with `class` The rendered rows are wrapped in an absolutely positioned element that `` manages internally (for offsetting the visible window as you scroll). Pass `class` to have it applied to that wrapper, which is useful for laying out rows with flexbox or grid instead of relying on each row's own styles: ```tsx {item =>
{item()}
}
``` ```css .row-list { display: flex; flex-flow: column; width: 100%; } ``` ## Changelog See [CHANGELOG.md](./CHANGELOG.md)