Skip to content
Source
Sign inSign up
TanStack/virtual

packages/marko-virtual

README.md

TanStack Marko Virtual
# @tanstack/marko-virtual

Headless UI for virtualizing scrollable elements in Marko 6, built on top of @tanstack/virtual-core.

Part of the TanStack Virtual family. Full documentation: tanstack.com/virtual β€” Marko.

Installation

npm install @tanstack/marko-virtual
# or
pnpm add @tanstack/marko-virtual

Peer dependency: marko ^6.0.0

Setup

The tags are discovered automatically by the Marko compiler when the package is installed β€” no imports are needed in your .marko files. If your build setup does not pick them up (monorepo links, unusual resolution), add the taglib explicitly to your project's marko.json:

{
  "taglib-imports": ["@tanstack/marko-virtual/marko.json"]
}

Usage

Each tag is used self-closing and exposes a tag variable (<virtualizer/v .../>). You own the markup: read v.virtualItems and v.totalSize to render the visible rows. Declare the virtualizer before the markup that reads it, and pass getScrollElement as an arrow thunk (() => scrollEl()) so the element ref resolves at call time.

<virtualizer> β€” scrollable container

Use when you control the scroll element (a div with overflow: auto).

<div/scrollEl
  style="height: 400px; width: 400px; overflow-y: auto; position: relative;"
>
  <virtualizer/v
    count=10000
    estimateSize=() => 35
    getScrollElement=() => scrollEl()
  />
  <div style=`height: ${v.totalSize}px; width: 100%; position: relative`>
    <for|item| of=v.virtualItems>
      <div
        style=`
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: ${item.size}px;
          transform: translateY(${item.start}px);
        `
      >
        Row ${item.index}
      </div>
    </for>
  </div>
</div>

No mount guard is needed: the tag renders a deterministic initial state on the server (see SSR) and the live, observing instance takes over on mount.

For columns, set horizontal=true and swap the width/height and translateX accordingly. For grids, compose two <virtualizer> tags (rows + columns) sharing the same scroll element β€” each with its own tag variable and its own () => scrollEl() thunk.

<window-virtualizer> β€” full-page scrolling

Use when the page itself is the scroll container.

<window-virtualizer/v
  count=10000
  estimateSize=() => 35
/>
<div style=`height: ${v.totalSize}px; position: relative`>
  <for|item| of=v.virtualItems>
    <div
      style=`
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: ${item.size}px;
        transform: translateY(${item.start}px);
      `
    >
      Row ${item.index}
    </div>
  </for>
</div>

If content sits above the list (it almost always does on a real page), measure the list's offsetTop on mount and pass it as scrollMargin, then subtract it from item.start when positioning β€” see the window example.

SSR: server-rendered slices

Server rendering is opt-in per virtualizer via initialRect (a viewport size hint). When set, the server paints the initial visible rows directly into the HTML; without it the server renders an empty container and the client fills it on mount β€” byte-for-byte identical to a client-only build. Pair with initialOffset (a number) to server-render at a scroll position (deep links, restore):

<virtualizer/v
  count=10000
  estimateSize=() => 35
  getScrollElement=() => scrollEl()
  initialRect=({ width: 800, height: 400 })
  initialOffset=3500
/>

Nothing live is serialized β€” the slice is computed as plain data at render time and recomputes identically on resume. See the five ssr* examples for the full patterns, including measurement-cache restore.

Streaming SSR: the tag inside <await>

The tags compose with Marko's streaming out of the box β€” put a virtualizer inside an <await> and the whole pattern above still holds, per streamed chunk:

<try>
  <@placeholder>
    <p>Loading people…</p>
  </@placeholder>
  <@catch|err|>
    <p>Failed to load: ${(err as Error).message}</p>
  </@catch>

  <await|people| value=fetchPeople()>
    <div/scrollEl class="scroll-container">
      <virtualizer/v
        count=people.length
        estimateSize=() => 48
        getScrollElement=() => scrollEl()
        initialRect=({ width: 800, height: 400 })
      />
      <!-- sizer + rows exactly as usual -->
    </div>
  </await>
</try>

What happens on the wire: the server flushes the page shell (with the placeholder) immediately, keeps streaming, and when fetchPeople() resolves it flushes the awaited subtree as a later chunk β€” including the server-painted rows when initialRect is set. Each streamed chunk resumes independently on the client: the live virtualizer instance for this list mounts when its chunk arrives, without waiting for the rest of the page. Nothing extra to configure β€” the seed is computed inside the awaited subtree from the resolved data, so server and resumed client agree by construction.

Two things to know:

  • Marko streams awaited content out of order: the chunk arrives at the end of the byte stream and an inline script swaps it into place. With JavaScript disabled that swap never runs, so an <await>-wrapped list renders blank without JS even though the row HTML is present in the source. If no-JS visibility matters, fetch before render (await the data in the route) instead of streaming.
  • The ssr-fetch example shows the streamed pattern with client-rendered rows; the ssr-slice example shows it with server-painted rows (initialRect) β€” its test suite includes a wire-level assertion that the placeholder flushes first and the painted rows arrive in a later chunk.

Dynamic / variable item sizes

For items with unknown heights, drive measureElement from a per-row <script>:

<div/scrollEl style="height: 400px; overflow-y: auto">
  <virtualizer/v
    count=data.length
    estimateSize=() => 50
    getScrollElement=() => scrollEl()
  />
  <div style=`height: ${v.totalSize}px; position: relative`>
    <for|item| of=v.virtualItems>
      <div/el
        data-index=item.index
        style=`position: absolute; top: 0; width: 100%; transform: translateY(${item.start}px)`>
        <script() {
          // re-run when the item changes; measureElement reads the rendered
          // height and feeds it back to the virtualizer
          const _key = item.key
          if (el() && v.measureElement) v.measureElement(el())
        }/>
        ${data[item.index].text}
      </div>
    </for>
  </div>
</div>

data-index is required on measured elements β€” the virtualizer uses it to map measurements back to items. Measuring under a different attribute name requires passing that name as indexAttribute.

Tag variable reference

Both tags expose the same shape. Capture it with <virtualizer/v .../> and read v.property:

PropertyTypeDescription
virtualItemsVirtualItem[]The currently visible virtual items (index, start, size, key, lane)
totalSizenumberTotal scrollable size in px β€” set as the inner container's height (or width for columns). Margin-free: scrollMargin is already subtracted
range{ startIndex: number; endIndex: number } | nullThe visible index window (excludes overscan). null until there is a window
measureElement(el: Element | null) => voidRef callback for dynamic item sizing
scrollToIndex(index: number, options?: ScrollToOptions) => voidScroll to an item by index. Default align: 'auto' scrolls the minimum
scrollToOffset(offset: number, options?: ScrollToOptions) => voidScroll to a pixel offset
measure() => voidDrop all measured sizes and re-measure everything (after a width/font change)
resizeItem(index: number, size: number) => voidSet one item's size directly, without a DOM measure
scrollToEnd(options?: { behavior?: ScrollBehavior }) => voidScroll to the very end of the list
isAtEnd(threshold?: number) => booleanWhether the scroll position is at (or within threshold px of) the end. false before mount
getDistanceFromEnd() => numberPixels between the current scroll position and the end. Infinity before mount

Inside your own onScroll handler, compute end-proximity from the element (el.scrollHeight - el.scrollTop - el.clientHeight) rather than calling v.isAtEnd() β€” your handler runs before the virtualizer's listener during the same event, so the virtualizer's numbers are one event stale there. Everywhere else they are current.

<virtualizer> input reference

PropTypeDefaultDescription
countnumberrequiredNumber of items
getScrollElement() => Element | nullrequiredReturns the scroll container
estimateSize(index: number) => number() => 50Estimated item size in px
overscannumber5Items to render beyond the visible area
horizontalbooleanfalseVirtualise horizontally (columns)
paddingStartnumberβ€”Padding before first item
paddingEndnumberβ€”Padding after last item
scrollPaddingStartnumberβ€”Scroll padding for scrollToIndex
scrollPaddingEndnumberβ€”Scroll padding for scrollToIndex
gapnumberβ€”Gap between items in px
lanesnumber1Lanes for masonry layouts
initialOffsetnumber | (() => number)β€”Scroll offset (px) for the server slice β€” server-render at a scroll position (deep link / restore)
initialRect{ width: number; height: number }β€”Viewport hint for a server-rendered slice (SSR). When set, the server paints the initial visible rows; omit for client-only fill
getItemKey(index: number) => number | string | bigintthe indexStable per-item identity so cached measurements survive reorder
rangeExtractor(range: Range) => number[]defaultRangeExtractorHook over the visible range: force extra indexes (e.g. a pinned sticky header) into the rendered window. Compose with defaultRangeExtractor from @tanstack/virtual-core
indexAttributestring'data-index'DOM attribute carrying the item index for measureElement. Give two instances measuring the same element (a grid cell) distinct attributes
initialMeasurementsCacheVirtualItem[]β€”Pre-measured items (plain data) to seed the measurement cache
anchorTo'start' | 'end''start'Anchor the window to the list end (a chat pinned to newest). Client-behavioral: it does not position the server slice β€” use initialOffset for that
followOnAppendboolean | ScrollBehaviorfalseWith anchorTo="end": stay pinned to the end as items append
scrollEndThresholdnumber1How close (px) to the end still counts as "at the end"
scrollMarginnumber0The list's offset (px) from the top of its scroll area, when other content sits above it in the same scroller. item.start values then INCLUDE this margin β€” subtract it when positioning items relative to the list (see the window example)
enabledbooleantrueDisable switch. false is not a freeze: the virtualizer unobserves, clears its measurements, and renders an empty window until re-enabled
isRtlbooleanfalseRight-to-left horizontal lists
isScrollingResetDelaynumber150ms after the last scroll event before "user is scrolling" ends
useScrollendEventbooleanfalseUse the native scrollend event instead of the isScrollingResetDelay timer
useAnimationFrameWithResizeObserverbooleanfalseBatch ResizeObserver measurements into animation frames (avoids "ResizeObserver loop" console errors under heavy resize load)
laneAssignmentMode'estimate' | 'measured''estimate'Masonry/multi-lane: assign items to lanes by estimated or measured sizes
useCachedMeasurementsbooleanfalseMake the default measurer return the cached (or estimated) size instead of reading the DOM β€” freezes item sizes when they are already known
debugbooleanfalseVerbose engine logging
measureElement(element, entry, instance) => numberborder-box measurerReplace HOW an item's size is read from its element (e.g. include margins, or measure a child)

<window-virtualizer> input reference

Same as <virtualizer> except getScrollElement is not accepted β€” the scroll element is always window. Two notes:

  • horizontal is accepted (the page scrolls sideways) and defaults to false.
  • initialOffset defaults to the live window scroll position (window.scrollY, or window.scrollX when horizontal) on the client and 0 on the server. Pass a number to override it β€” e.g. to server-render a slice at a scroll position, paired with initialRect.

scrollMargin is the signature window-virtualizer option: pass the list's offset from the top of the document and subtract it from item.start when positioning.

Examples

All examples use @marko/run. Run any with:

pnpm --filter tanstack-marko-virtual-example-<name> dev
ExampleDescription
fixedFixed-size rows, columns, and grid
variableVariable sizes via estimateSize
dynamicUnknown sizes measured via measureElement
gridTwo virtualizers sharing one scroll element
pretextCalculated text heights via @chenglou/pretext (no estimate error)
paddingpaddingStart / paddingEnd
scroll-paddingscrollPaddingStart with scrollToIndex
stickySticky group headers via rangeExtractor
infinite-scrollLazy data loading with a fixed total count
chatEnd-anchored messaging (anchorTo="end", followOnAppend), history prepends, a real server-streamed reply
chat-pretextChat rebuilt on calculated heights: zero-correction prepends, streamed reply growing via resizeItem
smooth-scrollscrollToIndex with smooth behavior
tableVirtualized table rows
windowFull-page scrolling with scrollMargin measured on mount
ssrSSR: no fetch, rows render on client
ssr-fetchSSR: fetch on server, rows render on client
ssr-sliceSSR: fetch on server, rows render on server (initialRect)
ssr-restoreSSR: server slice at an offset + measurement-cache restore
window-ssr-sliceSSR window: rows render on server

TypeScript

The tags are fully typed. Each tag ships a committed index.d.marko (a types-only twin, like a .d.ts for a Marko template) that editors and @marko/type-check prefer over the implementation file. Both tags also export a named handle interface β€” VirtualizerHandle / WindowVirtualizerHandle β€” describing the tag-variable shape, which you can use to type your own variables and functions.

Verification (CI)

pnpm test:types runs mtc (marko-type-check) over the package: the .ts sources, the .marko tags and test fixtures, the tests, and the committed .d.marko files. This is what CI runs β€” CI only ever verifies, it never generates. If a tag's surface changes and the .d.marko files were not regenerated, this check fails instead of letting the types drift silently. The project file is tsconfig.typecheck.json.

Generating .d.marko (manual, on demand)

The .d.marko files are generated, committed artifacts β€” regenerate them whenever a tag's Input or return surface changes:

pnpm types:generate

The script (scripts/generate-d-marko.mjs) verifies the sources type-check, deletes the old .d.marko (mtc prefers them as input when present), emits fresh ones via tsconfig.emit.json, copies them back beside the sources, and re-verifies. Review the diff and commit. Two notes: TS6059 rootDir warnings during the emit step are a known benign artifact of the cross-package virtual-core paths mapping (the script accounts for them), and generation relies on the tags' named return interfaces β€” mtc's emitter truncates wide anonymous inline types, so keep returns cast to the exported handle types.

Running all e2e Tests

To run all the e2e tests under each of examples/marko/<example-name>/e2e use the command

pnpm -r --workspace-concurrency=1 --filter "./examples/marko/*" run test:e2e

Note: This has to be run sequentially as they all start the same port.

Note: All suites run against dev servers; production builds are not exercised by any test. After bumping marko (or other build-path dependencies) or changing the package's build/packaging config, sanity-check production builds manually: pnpm --filter <example> build then preview β€” and check both kinds of example: fixed (render-only β€” rows must appear; this is the case production tree-shaking can silently break) and chat (interactive β€” click through Stream reply).

Running all unit tests

To run all the unit tests specifically for marko-virtual/tests use the command

pnpm --filter @tanstack/marko-virtual exec vitest run --reporter=verbose

Pre-requisite before running tests

pnpm install
pnpm --filter @tanstack/virtual-core build
pnpm --filter @tanstack/marko-virtual build

Author & license

Authored and maintained as part of TanStack Virtual by Tanner Linsley and contributors; Marko adapter contributed by defunkt-dev (@DSz340). If this library helps you, consider sponsoring TanStack.

MIT Β© Tanner Linsley