Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

Virtual list

A build log of 10,000 lines that keeps a couple of dozen rows in the page at a time, jumps to any line, and still answers find in page.

Goal

A log, a long table or a feed with thousands of rows: rendering every row makes the page slow to build and to scroll, so only the rows in view are elements, and the rest are space. Rows that wrap are measured, so each sits right under the one before, and a line out of view can still be reached by its number or by the browser's find.

Primitives

  • VirtualizerController works out which rows are in view. On each scroll it reports the range to render through onRange, with every row's offset and the total height; measure(index, element) replaces the estimated height of a row with its real one, and scrollToIndex scrolls a line to the top. With findable, it keeps a hidden="until-found" stand-in holding the text of each row that is not rendered, and scrolls a row into view when find in page matches its stand-in.

Left to the recipe: rendering the rows of the range at their offsets, the spacer sized to total, and the ARIA. The rows in the page are not the whole list, so each row carries aria-setsize (the 10,000) and aria-posinset (its line number), and a screen reader reads "line 5,000 of 10,000" rather than the count of the rows that happen to be rendered.

Example

Scroll the log, type a line number and press Go, or search the page for a line such as Line 6001 with the browser's find. The caption shows how many rows are in the page. Pick an authoring pattern below; they behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element, which finds its parts with @query.

    import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
    import { createVirtualizerController, type VirtualRange } from '@ecopages/radiant-ui/controllers';
    import { LINE_COUNT, LINE_ESTIMATE, lineText } from './virtual-list.data';
    
    @customElement('virtual-list-element')
    export class VirtualListElement extends RadiantElement {
    	@query('[data-scroller]') private scroller!: HTMLElement;
    	@query('[data-spacer]') private spacer!: HTMLElement;
    	@query('[data-spacer] ul') private list!: HTMLUListElement;
    	@query('[data-findable]') private findableLayer!: HTMLElement;
    	@query('input') private input!: HTMLInputElement;
    	@query('[data-status]') private status!: HTMLElement;
    
    	private readonly virtualizer = createVirtualizerController(this, {
    		getScroller: () => this.scroller,
    		getCount: () => LINE_COUNT,
    		estimate: () => LINE_ESTIMATE,
    		onRange: (range) => this.showRange(range),
    		findable: { text: lineText, getLayer: () => this.findableLayer },
    	});
    
    	@onEvent({ selector: 'form', type: 'submit' })
    	goToLine(event: SubmitEvent): void {
    		event.preventDefault();
    		this.virtualizer.scrollToIndex(this.input.valueAsNumber - 1, { align: 'start' });
    	}
    
    	private showRange({ items, total }: VirtualRange): void {
    		this.spacer.style.height = `${total}px`;
    		const rows = items.map(({ index, start }) => {
    			const row = document.createElement('li');
    			row.textContent = lineText(index);
    			row.setAttribute('aria-setsize', String(LINE_COUNT));
    			row.setAttribute('aria-posinset', String(index + 1));
    			row.style.transform = `translateY(${start}px)`;
    			return row;
    		});
    		this.list.replaceChildren(...rows);
    		rows.forEach((row, position) => this.virtualizer.measure(items[position]!.index, row));
    		this.status.textContent = `${rows.length} of ${LINE_COUNT.toLocaleString('en')} lines in the page`;
    	}
    }

    createVirtualizerController(this, ...) attaches when the element connects, which reports the first range and adds the stand-ins, and destroys the controller when the element disconnects, which removes them. The method that draws the range is not called render, because a RadiantElement keeps that name for the markup it draws itself.

    What the Radiant form removes: the mount function and its registration, the listener to remove, and the cleanup to return and call.

    Styles

    The stylesheet is the virtual-list.css tab in the files above. The scroller has a fixed height, the spacer inside it is position: relative and gets its height from total, and each row is absolutely positioned and moved to its offset with transform, so a new range moves no other row. The stand-in layer is an absolutely positioned sibling of the list, at the same origin, so a stand-in the browser reveals sits where its row will be. The selectors are scoped to the example on this site; drop the scope in your own project.

    Accessibility

    • Each row carries aria-setsize and aria-posinset, so a screen reader announces its place in the whole list, not among the rendered rows.
    • The scroller has role="region", a name and tabindex="0", so the keyboard can reach it and scroll it; nothing inside it is focusable.
    • The stand-in layer has aria-hidden="true". A stand-in that find in page reveals shows until the next frame, and a screen reader should not read it beside its row.
    • The controller writes no ARIA; the recipe sets all of the above.

    What to watch for

    • Measure every rendered row, on every range. A row of the estimated height needs no measuring, but a row that wraps does, and only measuring tells which. When the scroller changes width the controller reports the range again, so the rows are drawn and measured again at their new heights.
    • Rows render from the range, not from the DOM. Replacing the rows on each range is the simplest correct render. A recipe that keeps row elements and reuses them for other lines must measure each one again for its new line.
    • Keep the stand-ins displayed. A rule such as [hidden] { display: none } that reaches a stand-in hides it from find in page, so the stylesheet gives [hidden='until-found'] in the layer display: block; the docs frame around this example has such a rule.
    • Find in page costs one element per line. The stand-ins are cheap, since a hidden element is not laid out, but they are elements: fine for thousands of lines, not for millions. Leave findable out where the browser's find does not matter.
    • Offsets start at the scroller's edge. Put nothing before the spacer inside the scroller, and give the scroller no padding along the axis, or the offsets the controller reports are off by that much.