Architecture
This page follows one update through the grid, in the order the data flows. It is for contributors and for users who need to know why the grid behaves the way it does. You do not need it to use the grid.
The code lives in core/src. Grid.vue creates the inputs and renders the result. pipeline.ts holds the RxJS pipeline between them. utilites.ts and composables/ hold the helpers that turn props, resizes and scrolls into streams.
props ─────────────┐
grid + probe size ─┼─> measurement ─┐
scroll parents ────┘ ├─> buffer window ─> page numbers ─> pageProvider
│ │
│ loaded pages
│ │
└────────────> items in the DOM <────────┘
Inputs
pipeline() takes nine streams. Three kinds feed it.
Props. fromProp(props, "length") in utilites.ts creates an RxJS Observable from a prop. It emits the current value at once and again whenever a Vue watchEffect sees the prop change. The grid does this for length, pageProvider, pageProviderDebounceTime, pageSize, scrollTo and respectScrollToOnResize.
Sizes. fromResizeObserver wraps VueUse's useResizeObserver and delivers entries on an animation frame. The grid observes two elements. The grid element yields the element itself, and the probe element yields its contentRect. On the server fromResizeObserver returns an empty stream, because there is no window.
Scrolling. fromScrollParent in composables/useFromScrollParent.ts calls getElementScrollParents to find the nearest ancestor with overflow-y of auto or scroll, and the nearest with overflow-x of auto or scroll. If none exists, it falls back to the page. It then adds a passive scroll listener to each, with capture on, and emits the grid element on every scroll event. A fixed-position grid scrolls against document.body.
Measurement
The grid combines the latest grid element and the latest probe size into one ResizeMeasurement in getResizeMeasurement.
- From the grid's computed style it reads
row-gap,column-gap,grid-auto-flow, and the number of tracks ingrid-template-columnsandgrid-template-rows. - From the probe's
contentRectit reads the item width and height. - It adds the gap to each size, giving
itemWidthWithGapanditemHeightWithGap.
Because the column count is the number of tracks in the computed grid-template-columns, a repeat(auto-fill, ...) grid reports the number of columns that fit at that moment.
The measurement passes through distinctUntilChanged, which compares the fields, and shareReplay, so every consumer reads one measurement, and nothing downstream runs when a resize leaves it unchanged. The same stream is exposed as measurement, and a change to it emits layout-change.
The buffer window
The grid renders more items than the screen shows, so a fast scroll does not reveal empty space. computeBufferMeta works in lines. A line is a row in row flow and a column in column flow.
- It measures how far the grid's top (or left) edge has moved above the browser window with
getBoundingClientRect. The result is the space scrolled past. - It divides that space by the item size plus gap, which gives the number of lines before the viewport. Multiplying by the tracks across gives the index of the first visible item.
- It counts the lines that fit in
window.innerHeight(orinnerWidth), adds one, and multiplies by the tracks across. This is the visible count. - The buffer starts half a visible count before the first visible item, and never before index 0.
- The buffer is twice the visible count long.
The window comes from index arithmetic only. The grid keeps no per-item state and reads no item's size, which is why all items must share the probe's size.
Page requests
getObservableOfVisiblePageNumbers turns the buffer window into page numbers. It divides the window's start and end by pageSize, which gives a range of pages.
- With a non-zero
pageProviderDebounceTime, the stream of page ranges is debounced, so pages skimmed past during a fast scroll are never requested. - Each page number goes to a memoized
pageProvider. The memo key is the length, the page number, the page size and a version counter. A page already requested is not requested again, and a change oflength,pageSizeor the provider function starts a fresh memo. - The
recomputefunction in the pipeline bumps the version counter to drop the memo on demand. callPageProviderwraps the result inPromise.resolve, so a provider can return an array or a promise.accumulateItemStorekeeps each page in a map under its page number, so memory grows with the pages loaded and not withlength. A change ofpageSizeempties the map.
The map is internal. An item whose page is not in the map is undefined, and the grid renders it through the placeholder slot.
Rendering
createVisibleItemsGetter takes the buffer window, the measurement and the loaded pages, and returns one InternalItem per index in the window. An item holds its index, its value and a style.
- The
styleisgrid-area: 1/1and atranslate(x, y)transform. The grid computesxandyfrom the index, the measurement and the flow: row flow usesindex % columnsandfloor(index / columns), column flow uses the rows. - The getter reuses the previous items whose value and position did not change. It returns the same array when nothing changed.
accumulateBuffergoes one step further. An item that left the window gives its slot to an item that entered it, so the list of rendered elements keeps its length. A loaded item is never replaced by a placeholder when a staleundefinedarrives.
All items sit in grid cell 1/1, and the transform moves each to its position. The browser does not lay out the items on scroll. The grid element's height (or width in column flow) is set to the size of the whole list, computed in getContentSize as the line count times the item size plus gap, minus the last gap. That height is what gives the scroll parent its scrollbar.
The grid keys items with <keyPrefix>.<index> when you do not provide getKey. keyPrefix changes when pageProvider changes, so elements are recreated for a new provider.
scrollTo takes the same arithmetic. getItemOffsetByIndex converts the index to an offset, and the pipeline adds the grid's padding, border and distance from its scroll parent, then scrolls that parent.
Server rendering
pipeline() is asynchronous, and Grid.vue awaits it in <script setup>. Before it builds any stream, the pipeline calls pageProvider(0, pageSize) once. The result is the first buffer, with no style, so the server renders the first page with no positions.
The probe also moves. While ready is false, the probe is rendered after the items, with no grid-area. Once the first measurement produces items, ready becomes true and the probe renders first, in cell 1/1.
The client builds the same first buffer, so hydration matches the server HTML. After mount, the observers measure the probe, the pipeline emits real items with positions, and the grid replaces the first buffer.
Exposed refs and events
ready and measurement are shallowRef values created before the await and passed to defineExpose. A template ref binds to the component when it mounts. If the component exposes values only after the await, the parent's ref points at the instance from before the await and sees no exposed values until the parent renders again. Exposing the refs before the await means they exist on the first render.
Grid.vue emits render, viewport-scroll and layout-change from the buffer, scroll and measurement streams. The VirtualGrid events table says when each one fires and what to do in a handler.
Where the primitives fit
vvirtual-grid/primitives is separate from the grid. primitives.ts imports only the ResizeMeasurement type, and nothing in Grid.vue or pipeline.ts imports it. The primitives are pure functions of a measurement and an index, so the same formulas that place items in the DOM place items that are not rendered.
You pass the exposed measurement to them as layout. Primitives lists each function.