VirtualList unstable
A list that renders only the items near the visible part of its scroll container, and leaves room for the others so the scrollbar covers the whole list.
VirtualList is a headless component: it keeps the rendered range, the
measured item sizes, the focused item and the scroll position, and a mount on
list follows scrolling, resizing and focus. Your view draws the scroll
container, the list and one element for each index in items.
Anatomy
| Part | Element |
|---|---|
viewport |
<div>, <ul> or <ol>: the element that scrolls. Leave it out and the list scrolls with scrollContainer or the page |
table |
<table>, for a list that is a <tbody>, or a <div> with role="grid" or role="table": aria-rowcount |
list |
<div>, <ul>, <ol> or <tbody>, role="list" unless another role is set or it's a <tbody> |
item |
<div>, <li> or <tr>, role="listitem" unless another role is set or it's a <tr> |
item takes { element, index }. Draw one for each index in items, in
order, as children of list, and key each element by the item's own id.
viewport and list may be one element. Only a <tbody> list adds
markup: empty <tr> rows that stand in for the rows left out.
Data attributes
item:data-index, the item's index, anddata-key, its key whenkeysis given.list:data-virtual-list-spaceron each row a<tbody>list adds.
Keyboard
Every item says where it is in the whole set with aria-posinset and
aria-setsize, or a <tr> or role="row" item with aria-rowindex and
the table part with aria-rowcount. They count from firstPosition out
of setSize, so a page of a longer set or one whose size isn't known says
so. In a table, the header row takes a row index too: pass
firstPosition: 2 for one header row, and count it in setSize. The item
that has the focus, or holds the element that has it, stays rendered with
the rows next to it wherever the list scrolls, so Tab and Shift+Tab go where
they would if every item were rendered.
viewport sets tabindex="0" while its content overflows and
tabindex="-1" otherwise, allowing keyboard scrolling even without
focusable items. Removing the focused item moves focus to the item now at
its index, or the previous item if it was last. Focus goes to the item
itself or its first focusable descendant. If neither can receive focus,
including when the list is empty, focus moves to viewport or, without
that part, to the list.
Layout
Nothing about the layout is passed in: the mount reads it from the boxes of
the rendered items. The list is taken to be rows of items. Every item takes
one cell, each row has as many items as the others but the last, and the
items of one lane share a left edge. A row is as tall as its tallest item,
and the space between two rows is the same everywhere. A block, a flex
column and a CSS grid with equal columns are such lists, and a grid needs no
column count: the lanes follow its breakpoints. Items that span cells and
masonry are not supported. Use gap for the space between items, since a
margin can collapse with the one the list writes.
With horizontal: true the list scrolls along the inline axis, from the
right edge in a right-to-left direction. Sizes are widths and lanes are
rows. Make the list as wide as its items, such as a flex row with
inline-size: max-content, or the items shrink to fit. For rows and
columns that both scroll, use VirtualGrid.
With layout: "absolute" the items are taken out of the flow and each is
placed with a transform in a single lane, the full width of the list, so
an item can animate and rendering more of them rewrites no padding. When
an item is measured and the size estimated for the items above changes,
every rendered item moves and the list scrolls by as much, so a
transition on transform shows that move too: pass sizes for the
items you can size up front.
Sizes
An item is itemSize tall (wide when horizontal), or sizes[index] when
sizes is given, until it's measured. An item that hasn't been measured
takes the average of the ones that have, when no sizes entry covers it.
With measure: false those numbers are exact, items aren't measured, and
each item writes its block-size (inline-size when horizontal) with
box-sizing: border-box, so its padding, border and content can't make it
taller. A CSS min-height above the size still
wins. Sizes are kept by index, or by key when keys is given, and dropped
when the list's width or its number of lanes changes, or when dataset
does.
Scrolling
When the rows above the visible ones change size, or keys puts items
before them, the mount scrolls by the difference before the browser paints,
so what the user sees stays in place. Content before the list that changes
size does the same once the list's top has scrolled past the viewport's,
and pushes the list down while it hasn't, as the browser's own scroll
anchoring does. scrollTo scrolls to an index, a
key, an offset or the end once it's rendered, and keeps it there as the
items around it are measured, until anything else scrolls the list. A
request waits for its target, such as the items of a list that is still
empty or the item with its key, even when the prop is dropped meanwhile,
until it's applied, a newer request replaces it, or the user scrolls.
End(), atEnd and followEnd use the viewport part's scroll limit,
including padding and content after the list. With scrollContainer or
page scrolling, they use the list's end instead.
followEnd keeps the end in view while the user is there, without pulling
an external scroller back if the user has scrolled past the list. With
behavior: "smooth" it glides as the end grows, such as a streamed reply, and
a wheel, a touch, a new scrollTo or any other scroll stops it. A
scrollTo targeting the end with behavior: "smooth" glides the same
way, even without followEnd.
Both jump on initial placement, a dataset change or reduced motion.
contentAlignment: "end" places a list shorter than its viewport at the
bottom, as a chat does. These options preserve element order.
A browser that scrolls off the main thread, as Safari and Firefox do, can
show the rows past the rendered ones before the list renders again. So
after each scroll the list also renders ahead in the direction it moved, as
far as it moved, up to the viewport's height. A jump further than that, or
a scrollTo, renders only the rows around the new position.
To load earlier items, such as older messages, as the user scrolls up,
pass reserveStart, space held above the first item while there are more,
and load a page when Scrolled reports a first near the start. Add the
page to the start of keys and the rows on screen stay put, and drop
reserveStart once the first item is the first of the set.
Sticky items
sticky lists item indices, such as section headers, to keep mounted.
The last one at or above the viewport's top stays at its own offset even
when surrounding items are unmounted. The prop does not pin the item;
positioning is up to the consumer's styles.
Styling
viewport and list disable native scroll anchoring with inline
overflow-anchor: none. list also writes padding-block-start and
padding-block-end, and the first item of a range kept apart from the
others writes margin-block-start: the padding and margin stand in for the
items left out, so pad an element around the list instead. A <tbody> list
writes neither and adds spacer rows instead, and with layout: "absolute"
the list writes position: relative and each item position, inset-inline,
top and transform. A horizontal list writes the inline padding and
margin in place of the block ones. A viewport needs a bounded height
(width when horizontal) and an overflow that scrolls.
Limits
listcarries the component's mount, so it can't take a mount of your own.- A list scrolls with its
viewport, the elementscrollContainernames, or the page, and not with another scrolling element around it. - Without
keys, items are known by index, so items added before the visible ones push them down. - A
<tbody>list is a single lane and can't uselayout: "absolute", andlayout: "absolute"is a single lane whatever the CSS. Neither can be horizontal. - The mount watches content before the list for size changes and changes
to
class,style,hiddenandopen, and ancestors for child changes. Inside the list'sviewportpart, it also watches content after the list. Other layout changes, such as a stylesheet loading, take effect at the next scroll or resize. - On the server, and on a host that doesn't run mounts, the first
initialCountitems are rendered, or those around ascrollTotarget.
Example A list of a thousand rows in a scroll container
import { Html, HtmlServer } from "effect/ui/html"import { VirtualList } from "effect/ui/kit"import { Effect, Schema } from "effect"
const rows = Array.from({ length: 1000 }, (_, i) => ({ id: "row-" + i, label: "Row " + i }))
const Rows = Html.component({ name: "Rows", model: Schema.Struct({}), message: Schema.Never}).make({ init: () => ({}), update: ($) => $.model, view: (h) => VirtualList(h, { props: { count: rows.length, itemSize: 32, initialCount: 20 }, view: (virtualList) => virtualList.viewport(h.div.class("scroller")).children( virtualList.list(h.ul.class("rows")).children( virtualList.items.map((index) => virtualList.item({ element: h.li.key(rows[index]!.id), index }).children(rows[index]!.label) ) ) ) })})
const { html } = await Effect.runPromise(HtmlServer.renderToHtml(Rows, {}))if (!html.includes("Row 19") || html.includes("Row 20<") || !html.includes('aria-setsize="1000"')) { throw new Error("expected the first 20 rows of 1000")}Components
VirtualList
unstableA headless virtual list. Call it with the consumer's h, its props, and
a view closure that draws an optional viewport, the list, and an item
for each index in items.
Details
The parts object also carries items, the indices to render in order,
count, atStart and atEnd, whether the list is scrolled to its
start and to its end, for a button that jumps back to the end, and
scrolling, whether it's scrolling, for rows that skip costly content
meanwhile.
item({ element, index }) returns element. list and item write
role only when no other role is set on the element, so a role="feed"
or another kit part's role stays. item owns aria-posinset,
aria-setsize, aria-rowindex, data-index and data-key, and
viewport owns tabindex. The list's padding and an
item's top margin are added after the consumer's inline style.
It emits Scrolled when the visible items, an edge or scrolling
changes, so a parent can load more items near either end, react when it
reaches one, or save the position once a scroll ends. With trackScroll
it also emits it for each change of the scroll offset.
History restore keeps the measured sizes and the position, so the list is as tall as before when the page's scroll position comes back, and not the focused item.
Signature
declare const VirtualList: Headless<{ readonly contentAlignment?: "start" | "end"; readonly count?: number; readonly dataset?: string; readonly firstPosition?: number; readonly followEnd?: boolean | { readonly behavior?: "instant" | "smooth"; readonly threshold?: number; }; readonly horizontal?: boolean; readonly initialCount?: number; readonly itemSize: number; readonly keys?: readonly Array<string>; readonly layout?: "flow" | "absolute"; readonly measure?: boolean; readonly overscan?: number; readonly reserveStart?: number; readonly scrollContainer?: "nearest" | { readonly selector: string; }; readonly scrollTo?: { readonly align?: "start" | "end" | "center" | "nearest"; readonly behavior?: "instant" | "smooth"; readonly id?: string | number; readonly target: { readonly _tag: "Offset"; readonly offset: number; } | { readonly _tag: "End"; } | { readonly _tag: "Index"; readonly index: number; } | { readonly _tag: "Key"; readonly key: string; }; }; readonly setSize?: number; readonly sizes?: readonly Array<number>; readonly sticky?: readonly Array<number>; readonly trackScroll?: boolean;}, { readonly _tag: "Scrolled"; readonly atEnd: boolean; readonly atStart: boolean; readonly first: number; readonly height: number; readonly last: number; readonly length: number; readonly offset: number; readonly scrolling: boolean;}, { atEnd: boolean; atStart: boolean; count: number; item: <B extends PartTarget<"div" | "li" | "tr">>(__namedParameters: { readonly element: B; readonly index: number; }) => ReturnType<B["attr"]> & Pick<Part<"div" | "li" | "tr", [index: number], never>, "~R">; items: Array<number>; list: Part<"div" | "ol" | "tbody" | "ul", [], never>; scrolling: boolean; table: Part<"table" | "div", [], never>; viewport: Part<"div" | "ol" | "ul", [], never>;}, never, never, never, never, never, never, { readonly announced: { readonly atEnd: boolean; readonly atStart: boolean; readonly first: number; readonly height: number; readonly last: number; readonly length: number; readonly offset: number; readonly scrolling: boolean; } | null; readonly atEnd: boolean; readonly atStart: boolean; readonly dataset: string | null; readonly epoch: number; readonly focused: { readonly index: number; readonly key: string | null; } | null; readonly gap: number; readonly height: number; readonly lanes: number; readonly lead: number; readonly length: number; readonly offset: number; readonly overflowing: boolean; readonly position: { readonly index: number; readonly key: string | null; readonly offset: number; } | null; readonly scroll: { readonly done: boolean; readonly scrollTo: { readonly align?: "start" | "end" | "center" | "nearest"; readonly behavior?: "instant" | "smooth"; readonly id?: string | number; readonly target: { readonly _tag: "Offset"; readonly offset: number; } | { readonly _tag: "End"; } | { readonly _tag: "Index"; readonly index: number; } | { readonly _tag: "Key"; readonly key: string; }; }; } | null; readonly scrolling: boolean; readonly sizes: { [key: string]: number; }; readonly width: number;}, { readonly _tag: "MovedViewport"; readonly anchor: { readonly index: number; readonly key: string | null; readonly offset: number; } | null; readonly atEnd: boolean; readonly atStart: boolean; readonly height: number; readonly length: number; readonly overflowing: boolean; readonly scrolled: { readonly align?: "start" | "end" | "center" | "nearest"; readonly behavior?: "instant" | "smooth"; readonly id?: string | number; readonly target: { readonly _tag: "Offset"; readonly offset: number; } | { readonly _tag: "End"; } | { readonly _tag: "Index"; readonly index: number; } | { readonly _tag: "Key"; readonly key: string; }; } | null; readonly start: number;} | { readonly _tag: "RequestedScroll"; readonly scrollTo: { readonly align?: "start" | "end" | "center" | "nearest"; readonly behavior?: "instant" | "smooth"; readonly id?: string | number; readonly target: { readonly _tag: "Offset"; readonly offset: number; } | { readonly _tag: "End"; } | { readonly _tag: "Index"; readonly index: number; } | { readonly _tag: "Key"; readonly key: string; }; };} | { readonly _tag: "ScrolledByUser";} | { readonly _tag: "MeasuredItems"; readonly epoch: number; readonly items: readonly Array<{ readonly index: number; readonly key: string | null; readonly left: number; readonly size: number; readonly top: number; }>; readonly width: number;} | { readonly _tag: "BlurredItems";} | { readonly _tag: "ScrolledViewport"; readonly height: number; readonly length: number; readonly offset: number; readonly scrolling: boolean;} | { readonly _tag: "FocusedItem"; readonly index: number; readonly key: string | null;}, QueryEntries<{}, {}>>Models
VirtualListAlign
unstableWhere an item scrollTo goes to ends up in the viewport. "nearest"
leaves an item that is in full view where it is, and otherwise brings in its
nearest edge.
Signature
declare const VirtualListAlign: Literals<readonly ["start", "center", "end", "nearest"]>Where an item scrollTo goes to ends up in the viewport.
Signature
type VirtualListAlign = Virtualizer.AlignVirtualListEvents
unstableThe events of a VirtualList.
Details
Scrolled reports first and last, the first and last visible items,
atStart and atEnd, whether the start and end boundaries are reached,
and scrolling, whether it's scrolling. The end boundary is the
viewport part's scroll limit, or the list's end with scrollContainer
or page scrolling. atEnd uses the followEnd threshold as its tolerance,
or 1px by default. It stays true past the end or during an end-following glide.
offset measures how far the viewport's top is past the first item's top,
in the units of an Offset scroll target. height is the viewport's
height, and length is the list's height from its first item's top.
It's emitted when first, last, atStart, atEnd or scrolling
changes, and with trackScroll also when offset, height or length
does. scrolling turns true at the first scroll event, from the user,
a scrollTo or the list keeping its rows in place, and false once the
scroll has ended and the list has stayed still for 100ms, so a burst of
wheel ticks reports one start and one end.
Signature
declare const VirtualListEvents: TaggedEnum<{ Scrolled: TaggedStruct<"Scrolled", { readonly atEnd: Boolean; readonly atStart: Boolean; readonly first: Number; readonly height: Number; readonly last: Number; readonly length: Number; readonly offset: Number; readonly scrolling: Boolean; }>;}>The events of a VirtualList.
Signature
type VirtualListEvents = Virtualizer.EventsVirtualListProps
unstableSchema for VirtualListProps.
Details
The props of Virtualizer.Props, with sizes and offsets in pixels and
overscan 3 when omitted. initialCount is also what the server renders.
layout: "absolute" positions each item with a transform.
Signature
declare const VirtualListProps: Struct<{ readonly contentAlignment: optional<Literals<readonly ["start", "end"]>>; readonly count: optional<Number>; readonly dataset: optional<String>; readonly firstPosition: optional<Number>; readonly followEnd: optional<Union<readonly [Boolean, Struct<{ readonly behavior: optional<Literals<readonly ["instant", "smooth"]>>; readonly threshold: optional<Number>; }>]>>; readonly horizontal: optional<Boolean>; readonly initialCount: optional<Number>; readonly itemSize: Number; readonly keys: optional<$Array<String>>; readonly layout: optional<Literals<readonly ["flow", "absolute"]>>; readonly measure: optional<Boolean>; readonly overscan: optional<Number>; readonly reserveStart: optional<Number>; readonly scrollContainer: optional<Union<readonly [Literal<"nearest">, Struct<{ readonly selector: String; }>]>>; readonly scrollTo: optional<Struct<{ readonly align: optional<Literals<readonly ["start", "center", "end", "nearest"]>>; readonly behavior: optional<Literals<readonly ["instant", "smooth"]>>; readonly id: optional<Union<readonly [String, Number]>>; readonly target: TaggedEnum<{ End: TaggedStruct<"End", {}>; Index: TaggedStruct<"Index", { readonly index: Number; }>; Key: TaggedStruct<"Key", { readonly key: String; }>; Offset: TaggedStruct<"Offset", { readonly offset: Number; }>; }>; }>>; readonly setSize: optional<Number>; readonly sizes: optional<$Array<Number>>; readonly sticky: optional<$Array<Number>>; readonly trackScroll: optional<Boolean>;}>The props of a VirtualList.
Signature
type VirtualListProps = typeof VirtualListProps.TypeVirtualListScrollContainer
unstableThe element that scrolls the list when no viewport part is applied:
"nearest", the closest ancestor whose overflow-y (overflow-x when
horizontal) scrolls, or the closest ancestor that selector matches. The list looks for it again each time it
renders, the window resizes, or the class, style, hidden or open
of an ancestor changes, so a shell that starts or stops scrolling takes or
gives back the list.
Signature
declare const VirtualListScrollContainer: Union<readonly [Literal<"nearest">, Struct<{ readonly selector: String;}>]>The element that scrolls the list when no viewport part is applied.
Signature
type VirtualListScrollContainer = typeof VirtualListScrollContainer.TypeVirtualListScrollTarget
unstableWhere scrollTo goes: an item by index or by key, a distance in pixels
from the top of the list, or the end of the list.
Signature
declare const VirtualListScrollTarget: TaggedEnum<{ End: TaggedStruct<"End", {}>; Index: TaggedStruct<"Index", { readonly index: Number; }>; Key: TaggedStruct<"Key", { readonly key: String; }>; Offset: TaggedStruct<"Offset", { readonly offset: Number; }>;}>Where scrollTo goes.
Signature
type VirtualListScrollTarget = Virtualizer.ScrollTargetVirtualListScrollTo
unstableA scroll request. The list scrolls once for each request that differs from
the last one it received, so change id to go to the same target again.
Signature
declare const VirtualListScrollTo: Struct<{ readonly align: optional<Literals<readonly ["start", "center", "end", "nearest"]>>; readonly behavior: optional<Literals<readonly ["instant", "smooth"]>>; readonly id: optional<Union<readonly [String, Number]>>; readonly target: TaggedEnum<{ End: TaggedStruct<"End", {}>; Index: TaggedStruct<"Index", { readonly index: Number; }>; Key: TaggedStruct<"Key", { readonly key: String; }>; Offset: TaggedStruct<"Offset", { readonly offset: Number; }>; }>;}>A scroll request.
Signature
type VirtualListScrollTo = Virtualizer.ScrollTo