Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add a `DVirtualList` windowing primitive to the ui-kit (#42382)

Sérgio Saquetimf5e04de2c896
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index 3f25ccf8f33..c4fff83a856 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -25,6 +25,7 @@
@import "d-filter-controls";
@import "docked-composer";
@import "d-toggle-switch";
+@import "d-virtual-list";
@import "date-input";
@import "date-picker";
@import "date-range-picker";
diff --git a/app/assets/stylesheets/common/components/d-virtual-list.scss b/app/assets/stylesheets/common/components/d-virtual-list.scss
new file mode 100644
index 00000000000..50dcb68a2a9
--- /dev/null
+++ b/app/assets/stylesheets/common/components/d-virtual-list.scss
@@ -0,0 +1,31 @@
+.d-virtual-list {
+ /* This element is the scroll viewport the virtualizer measures and drives. Its
+ height belongs to the consumer: a zero-height element yields an empty window
+ and silently renders nothing. Box spacing here would offset the engine's
+ measured total from the DOM scroll height permanently, so put padding and
+ borders on a wrapper or on the rows.
+
+ Vertical only: rows are absolutely positioned and stretched across the inline
+ axis, so they offer no intrinsic width for an inline scrollbar to act on.
+ Content wider than the viewport has to scroll inside its own row. */
+ overflow: hidden auto;
+ overscroll-behavior: contain;
+
+ /* Rows are absolutely positioned to approximate offsets, so the browser must not
+ pick the list as a scroll anchor — its correction would fight the virtualizer's
+ own scroll compensation and produce a jump. */
+ overflow-anchor: none;
+
+ &__sizer {
+ margin: 0;
+ padding: 0;
+
+ /* Removing the marker also removes the implicit list semantics in some
+ screen readers, so only do it once the element is carrying an explicit
+ role of its own. */
+
+ &[role] {
+ list-style: none;
+ }
+ }
+}
diff --git a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md b/docs/developer-guides/docs/03-code-internals/02-ui-kit.md
index 80cd199ca14..85b6e5b1b18 100644
--- a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md
+++ b/docs/developer-guides/docs/03-code-internals/02-ui-kit.md
@@ -97,6 +97,7 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under
| `DBreadcrumbsContainer`, `DBreadcrumbsItem` | Breadcrumb trails registered from routes. | [Breadcrumbs](https://meta.discourse.org/styleguide/molecules/bread-crumbs) |
| `DNavItem`, `DNavigationItem`, `DHorizontalOverflowNav` | Navigation bars, including ones that scroll horizontally when they overflow. | [Navigation bar](https://meta.discourse.org/styleguide/molecules/navigation-bar) |
| `DResponsiveTable`, `DTableHeaderToggle` | Tables that stay usable on narrow viewports, with sortable column headers. | |
+| `DVirtualList` | Long lists that render only the rows in view. | [Virtual list](https://meta.discourse.org/styleguide/molecules/virtual-list) |
| `DStatTiles` | Rows of headline numbers. | |
| `DTapTileGrid`, `DTapTile` | Grids of tappable choices. | |
| `DPostAccordion`, `DPostAccordionItem` | Collapsible sections. | |
diff --git a/frontend/discourse/app/ui-kit/-internals/windowing/virtualizer.js b/frontend/discourse/app/ui-kit/-internals/windowing/virtualizer.js
new file mode 100644
index 00000000000..deed17b121c
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/-internals/windowing/virtualizer.js
@@ -0,0 +1,313 @@
+/*
+ * This is the only module in the app that imports the windowing engine. Plugins,
+ * themes, and other core code go through `DVirtualList` and this module so the
+ * engine stays swappable behind this boundary.
+ *
+ * The dependency is pinned to an exact version because the adapter relies on
+ * framework hooks that can shift between minor releases. Gate upgrades on the
+ * ui-kit virtualizer test suite.
+ */
+import {
+ defaultRangeExtractor,
+ elementScroll,
+ measureElement,
+ observeElementOffset,
+ observeElementRect,
+ Virtualizer,
+} from "@tanstack/virtual-core";
+
+let VIRTUALIZATION_ENABLED = true;
+
+/**
+ * Test hook: render every item instead of a window. A `setupRenderingTest`
+ * container has no real scroll/layout height, so the virtualizer would compute an
+ * empty window and rows would never render. Toggling this off makes `DVirtualList`
+ * yield all items in normal flow. Mirrors `disableLoadMoreObserver()`.
+ *
+ * `tests/setup-tests.js` disables virtualization for EVERY test and re-enables it
+ * in teardown, so the render-all fallback is the default a test sees. A test that
+ * needs the real engine opts in with {@link enableVirtualization}.
+ *
+ * Opting out is opting out of coverage: the fallback is a genuinely different code
+ * path, in which the row index and the item can never disagree. Any consumer whose
+ * behaviour depends on windowing needs its own companion module that opts back in,
+ * or its suite proves nothing about what ships.
+ *
+ * The flag is read at render time and is not reactive, so it must be set before the
+ * first render of a `DVirtualList`; flipping it afterwards does not re-render one
+ * that already mounted.
+ */
+export function disableVirtualization() {
+ VIRTUALIZATION_ENABLED = false;
+}
+
+/** Restore real windowing after {@link disableVirtualization}. */
+export function enableVirtualization() {
+ VIRTUALIZATION_ENABLED = true;
+}
+
+/**
+ * Whether rows are windowed. False means the render-all fallback is active.
+ *
+ * @returns {boolean}
+ */
+export function isVirtualizationEnabled() {
+ return VIRTUALIZATION_ENABLED;
+}
+
+const STABLE_KEYS = new WeakMap();
+
+/**
+ * Keys for symbol items. A strong map, unlike the object one, so a symbol used as
+ * an item is retained for the life of the tab. Acceptable because symbols are
+ * sentinel values a consumer defines a fixed number of, not per-row data — but it
+ * is the one entry here that does not release.
+ */
+const STABLE_SYMBOL_KEYS = new Map();
+
+const KEY_NAMESPACE = "d-virtual-list:key:";
+let stableKeyCounter = 0;
+
+/**
+ * An immutable per-object identity key for virtual rows — the DEFAULT keying,
+ * used when a consumer does not pass a `@key` field.
+ *
+ * By default we do NOT key on a domain id: a consumer can mutate an item's id in
+ * place (e.g. an optimistic row created with a temporary id, then reconciled to a
+ * server id on confirmation), which would orphan the row's measured height and
+ * snap it back to its estimate. Object identity is stable across such a mutation.
+ *
+ * A consumer whose ids are immutable AND who rebuilds its item objects each render
+ * (so object identity is NOT stable) should instead pass `@key` — see {@link keyFor}.
+ *
+ * @param {unknown} item
+ * @returns {number | string | bigint}
+ */
+export function stableKeyFor(item) {
+ const type = typeof item;
+
+ if (type === "string") {
+ return item.startsWith(KEY_NAMESPACE) ? `${KEY_NAMESPACE}${item}` : item;
+ }
+
+ if (type === "number" || type === "bigint") {
+ return item;
+ }
+
+ if (type === "boolean" || item === null || type === "undefined") {
+ return `${KEY_NAMESPACE}${type}:${String(item)}`;
+ }
+
+ if (type === "symbol") {
+ let key = STABLE_SYMBOL_KEYS.get(item);
+ if (key === undefined) {
+ key = `${KEY_NAMESPACE}symbol:${++stableKeyCounter}`;
+ STABLE_SYMBOL_KEYS.set(item, key);
+ }
+ return key;
+ }
+
+ let key = STABLE_KEYS.get(item);
+ if (key === undefined) {
+ key = `${KEY_NAMESPACE}object:${++stableKeyCounter}`;
+ STABLE_KEYS.set(item, key);
+ }
+ return key;
+}
+
+/**
+ * The row key for an item, given an optional `@key` FIELD NAME. Field values are
+ * routed through {@link stableKeyFor} so a domain value inherits its namespace
+ * escaping and can never collide with a generated object key.
+ *
+ * The field value must be UNIQUE per logical row: two rows sharing one value
+ * alias to one key (a duplicate `{{#each}}` key and shared measurement), exactly
+ * as two `===` items would. A row whose field is ABSENT is not treated that way —
+ * it falls back to identity keying, because otherwise every such row would
+ * collapse onto the single key that a nullish value normalizes to, which is a
+ * collision the consumer never asked for and cannot see.
+ *
+ * The single source of truth for both keying paths (the modifier's `getItemKey`
+ * and the component's render-all fallback), so the two can never drift.
+ *
+ * @param {unknown} item
+ * @param {string} [field]
+ * @returns {number | string | bigint}
+ */
+export function keyFor(item, field) {
+ if (field != null && item != null && typeof item === "object") {
+ const value = item[field];
+ return value == null ? stableKeyFor(item) : stableKeyFor(value);
+ }
+ return stableKeyFor(item);
+}
+
+/**
+ * The engine's viewport-rect callbacks, keyed by engine.
+ *
+ * The engine reads its viewport once as it mounts and then only from a ResizeObserver, whose
+ * delivery is the browser's to schedule. A consumer that changes the viewport's size itself —
+ * an overlay being positioned, say — knows the recorded rect is stale immediately, and holding
+ * the callback lets it say so. `measure()` is not that lever: it clears the item-size cache and
+ * never re-reads the viewport.
+ */
+const RECT_CALLBACKS = new WeakMap();
+
+function observeElementRectWithHandle(instance, callback) {
+ RECT_CALLBACKS.set(instance, callback);
+ return observeElementRect(instance, callback);
+}
+
+/**
+ * The engine's scroll-offset callbacks, keyed by engine.
+ *
+ * Held for the same reason as the viewport callbacks: the engine learns the
+ * offset only from a real `scroll` event, which the browser delivers
+ * asynchronously even for a programmatic scroll. Holding the callback lets a
+ * caller state the new offset directly instead of counterfeiting a DOM event —
+ * which would reach the engine flagged as user scrolling and latch its
+ * `isScrolling` for the reset delay, suppressing synchronous row measurement
+ * for that whole window.
+ */
+const OFFSET_CALLBACKS = new WeakMap();
+
+function observeElementOffsetWithHandle(instance, callback) {
+ OFFSET_CALLBACKS.set(instance, callback);
+ return observeElementOffset(instance, callback);
+}
+
+/**
+ * Tell the engine the viewport's current scroll offset, without pretending a
+ * user scrolled. A no-op before the engine has mounted or once it has torn down.
+ *
+ * @param {{ scrollElement?: HTMLElement | null }} virtualizer
+ */
+export function pushScrollOffset(virtualizer) {
+ const callback = OFFSET_CALLBACKS.get(virtualizer);
+ const element = virtualizer?.scrollElement;
+
+ if (!callback || !element) {
+ return;
+ }
+
+ callback(element.scrollTop, false);
+}
+
+/**
+ * Re-reads the viewport and pushes the measurement into the engine, which republishes its
+ * window from it. A no-op before the engine has mounted or once it has torn down.
+ *
+ * Measured the way the engine measures it — `offsetWidth`/`offsetHeight`, rounded — so a
+ * pushed rect and an observed one are the same value and cannot disagree.
+ *
+ * @param {{ scrollElement?: HTMLElement | null }} virtualizer
+ */
+export function remeasureViewport(virtualizer) {
+ const callback = RECT_CALLBACKS.get(virtualizer);
+ const element = virtualizer?.scrollElement;
+
+ if (!callback || !element) {
+ return;
+ }
+
+ callback({
+ width: Math.round(element.offsetWidth),
+ height: Math.round(element.offsetHeight),
+ });
+}
+
+/**
+ * The element-adapter plumbing every element-backed virtualizer needs.
+ * `scrollToFn` and the two element observers are required with no engine
+ * default, and `setOptions` replaces the whole options object rather than
+ * merging into the previous one — so they must be re-supplied on every update,
+ * not just at construction. Dropping them leaves the engine unable to scroll
+ * (`scrollToFn is not a function`) the moment anything asks it to move, which
+ * includes prepend anchoring and every `scrollTo*` API call.
+ */
+const ELEMENT_ADAPTER = {
+ scrollToFn: elementScroll,
+ observeElementRect: observeElementRectWithHandle,
+ observeElementOffset: observeElementOffsetWithHandle,
+ measureElement,
+};
+
+/**
+ * A `rangeExtractor` extended with consumer-selected, otherwise-out-of-window
+ * indices.
+ *
+ * Full-set deduplication is unconditional at this library wall because the engine
+ * publishes one measurement per index with zero deduplication of its own. A
+ * surviving duplicate becomes a duplicate `{{#each}}` key and a hard Glimmer
+ * assertion.
+ *
+ * Ascending order is load-bearing, not cosmetic: `DVirtualList` positions rows by
+ * absolute `translateY`, so appended extras would paint in the visually correct
+ * spot while leaving the DOM sequence non-monotonic. DOM order === visual order;
+ * `aria-posinset` order, screen-reader browse order, and the roving-focus NodeList
+ * all depend on it.
+ *
+ * The callback is contained here because this is the one consumer callback the
+ * engine invokes from inside its own memoized computation. Letting it throw
+ * would leave that memo holding committed dependencies with no result, so every
+ * later call short-circuits to `undefined` and the render crashes on it from
+ * then on. Degrading to the unextended window keeps the list alive instead.
+ *
+ * Recovery is NOT automatic: the degraded result is a successful one as far as
+ * the engine is concerned, so it is cached against the extractor identity and
+ * the range. A callback that merely stops throwing is not consulted again until
+ * one of those changes — which, for a consumer following the documented
+ * reactivity contract, happens on the next input change.
+ *
+ * @param {(indices: readonly number[], range: { startIndex: number, endIndex: number, overscan: number, count: number }) => readonly number[] | null | undefined} pins Returns extra indices to keep mounted.
+ * @returns {(range: { startIndex: number, endIndex: number, overscan: number, count: number }) => number[]}
+ */
+export function rangeExtractorWithPins(pins) {
+ return (range) => {
+ const indices = defaultRangeExtractor(range);
+ const merged = new Set(indices);
+
+ let extra;
+ try {
+ extra = pins(indices, range) ?? [];
+ } catch (e) {
+ // eslint-disable-next-line no-console
+ console.error("[d-virtual-list] pinnedIndices threw: ", e);
+ extra = [];
+ }
+
+ for (const index of extra) {
+ if (Number.isInteger(index) && index >= 0 && index < range.count) {
+ merged.add(index);
+ }
+ }
+
+ return [...merged].sort((a, b) => a - b);
+ };
+}
+
+/**
+ * Construct an element-backed virtualizer, filling in the element-observer
+ * plumbing the caller does not supply. See {@link ELEMENT_ADAPTER}.
+ *
+ * @param {object} options
+ * @returns {object} An element-backed virtualizer instance.
+ */
+export function createElementVirtualizer(options) {
+ return new Virtualizer({ ...ELEMENT_ADAPTER, ...options });
+}
+
+/**
+ * Re-sync options on an existing element virtualizer, preserving the adapter
+ * plumbing. Always use this instead of calling `setOptions` directly.
+ *
+ * Typed structurally rather than as the engine's own class: callers hold their
+ * own narrow view of the instance, and naming the engine type here would leak it
+ * back across the wall this module exists to be.
+ *
+ * @param {{ setOptions: (options: object) => void }} virtualizer
+ * @param {object} options
+ */
+export function updateElementVirtualizer(virtualizer, options) {
+ virtualizer.setOptions({ ...ELEMENT_ADAPTER, ...options });
+}
diff --git a/frontend/discourse/app/ui-kit/d-virtual-list.gts b/frontend/discourse/app/ui-kit/d-virtual-list.gts
new file mode 100644
index 00000000000..57472d4944c
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-virtual-list.gts
@@ -0,0 +1,716 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { assert } from "@ember/debug";
+import { action } from "@ember/object";
+import { next } from "@ember/runloop";
+import type { ModifierLike } from "@glint/template";
+import { modifier } from "ember-modifier";
+import {
+ isVirtualizationEnabled,
+ keyFor,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dElement from "discourse/ui-kit/helpers/d-element";
+import dVirtualizer from "discourse/ui-kit/modifiers/d-virtualizer";
+
+/** A single measured/positioned row as published by the engine. */
+interface VirtualItem {
+ key: number | string | bigint;
+ index: number;
+ start: number;
+ size: number;
+}
+
+/**
+ * The positioning modifier, applied as `{{row.place row.start row.index}}`. Its
+ * positional args carry the row's offset and absolute index.
+ *
+ * One stable definition shared by every row, so a row that survives a re-render
+ * re-runs its existing instance instead of being destroyed and reinstalled —
+ * where the destroy could run after the replacement wrote its styles and strip
+ * them off the reused element.
+ */
+type PlaceModifier = ModifierLike<{
+ Element: HTMLElement;
+ Args: { Positional: [start: number, index: number] };
+}>;
+
+/**
+ * The per-row context yielded as the block's second parameter. In `@ownedRow`
+ * mode the consumer renders the row element itself and applies `{{row.place}}`
+ * (positioning) and `{{row.measure}}` (measurement); simple consumers can ignore
+ * it and let the primitive wrap their content.
+ */
+interface RowContext<T> {
+ item: T;
+ index: number;
+ key: number | string | bigint;
+ start: number;
+ size: number;
+ /**
+ * Positions the row (absolute + `translateY`) when windowing; inert in the
+ * render-all fallback. Apply with the row's offset and index:
+ * `{{row.place row.start row.index}}`.
+ *
+ * Apply it BEFORE {@link measure}. It stamps the `data-index` that measurement
+ * identifies the row by, and modifiers run in template order.
+ */
+ place: PlaceModifier;
+ /**
+ * Registers the row for height measurement. Arg-less and stable; apply once per row,
+ * AFTER {@link place} — a row reached before its `data-index` is stamped cannot be
+ * identified, so it is skipped and keeps rendering at `@estimateSize`.
+ */
+ measure: ModifierLike<HTMLElement>;
+ /**
+ * The row's `aria-posinset`, or undefined when `@itemRole` is not a role that
+ * defines it. Meaningful only when every entry in `@items` is a real row: a
+ * list that also carries headers, dividers, or placeholders has to derive its
+ * own logical positions, because this counts physical rows.
+ */
+ posinset: number | undefined;
+ /** The matching `aria-setsize`. Carries the same homogeneity caveat as {@link posinset}. */
+ setSize: number | undefined;
+}
+
+/** The imperative handle registered via `@onRegisterApi`. */
+export interface DVirtualListApi {
+ /**
+ * Scroll a row into view.
+ *
+ * @param index - Absolute index in `@items`.
+ * @param opts - Placement within the viewport, and how to animate getting there.
+ */
+ scrollToIndex(
+ index: number,
+ opts?: {
+ align?: "start" | "center" | "end" | "auto";
+ behavior?: ScrollBehavior;
+ }
+ ): void;
+
+ /**
+ * Scroll to an absolute pixel offset in the list's coordinate space.
+ *
+ * @param offset - Offset in px from the start of the list.
+ * @param opts - How to animate getting there.
+ */
+ scrollToOffset(offset: number, opts?: { behavior?: ScrollBehavior }): void;
+
+ /**
+ * Scroll to the first or last row. A no-op on an empty list.
+ *
+ * @param edge - Which end to travel to.
+ */
+ scrollToEdge(edge: "start" | "end"): void;
+
+ /**
+ * Let an edge callback fire again.
+ *
+ * An edge callback fires once and then latches, and re-arms on its own only when the reader
+ * retreats from the band or a boundary row changes. A consumer whose fetch FAILED has
+ * neither: the item set is byte-for-byte what it was, so nothing re-arms and the callback
+ * never fires again. On a list short enough that the range never leaves the band, that is
+ * permanent. This is the lever for that case.
+ *
+ * Arming is not firing. The callback runs on the next evaluation, and only if the range is
+ * still inside the band.
+ *
+ * @param edge - Which edge to re-arm. The other is left alone.
+ */
+ armEdge(edge: "start" | "end"): void;
+
+ /**
+ * Discard every cached row measurement so the next window re-measures from
+ * `@estimateSize`. Leaves the viewport measurement untouched.
+ */
+ measure(): void;
+
+ /**
+ * Re-reads the viewport's size and republishes the window from it.
+ *
+ * For a consumer that changes the viewport's size itself and would otherwise wait on a
+ * resize being observed, which the browser schedules and may not deliver promptly. Distinct
+ * from `measure`, which clears the item-size cache and leaves the viewport untouched.
+ */
+ remeasureViewport(): void;
+ /**
+ * Registers one row element for height measurement.
+ *
+ * Internal plumbing for the row `measure` modifier, exposed because that modifier is
+ * yielded to consumers. The element must carry the `data-index` that `place` stamps;
+ * anything else is ignored rather than measured under a key that does not exist.
+ */
+ measureElement(element: HTMLElement): void;
+
+ /**
+ * The visible index range, or undefined before the first measurement.
+ *
+ * A frozen snapshot, never the engine's own range object: the committed value of that
+ * object is what the engine's change memo compares against, so a consumer writing
+ * through it could silently stop the window updating. Every call builds a new
+ * object, so compare the indices rather than the identity.
+ */
+ visibleRange():
+ | Readonly<{ startIndex: number; endIndex: number }>
+ | undefined;
+
+ /** Whether the viewport is mid-scroll. */
+ readonly isScrolling: boolean;
+}
+
+interface VisibleRange {
+ startIndex: number;
+ endIndex: number;
+}
+
+interface VirtualRange extends VisibleRange {
+ overscan: number;
+ count: number;
+}
+
+/** The visible range plus the total item count, passed to an edge callback. */
+interface EdgeInfo extends VisibleRange {
+ count: number;
+}
+
+/**
+ * Roles for which `aria-setsize`/`aria-posinset` are defined. On anything else
+ * assistive tech discards them.
+ */
+const POSITION_AWARE_ROLES = new Set([
+ "article",
+ "listitem",
+ "menuitem",
+ "menuitemcheckbox",
+ "menuitemradio",
+ "option",
+ "radio",
+ "row",
+ "tab",
+ "treeitem",
+]);
+
+interface DVirtualListSignature<T> {
+ Args: {
+ /**
+ * The full backing array. Only a window is rendered; it is never sliced.
+ *
+ * The sizer is one element as tall as the whole list, so browsers cap the
+ * reachable range at their maximum element height (on the order of 33 million
+ * px). Beyond `ceiling / @estimateSize` rows the tail cannot be scrolled to,
+ * and `@initialIndex` past it lands short.
+ */
+ items: readonly T[];
+ /** Estimated px size for a not-yet-measured row. A good estimate reduces jump. */
+ estimateSize: (item: T, index: number) => number;
+ /**
+ * Field name whose value is a row's STABLE key. Omit it and rows key by object
+ * identity — fine when `@items` holds the same objects across renders, but a
+ * consumer that rebuilds its item objects each render (same logical rows, fresh
+ * objects) would orphan every measured height and remount the whole window.
+ * Point `@key` at a stable id/key field to tie a row to its logical identity.
+ * The field must be present and unique per logical row (a missing/duplicate
+ * value aliases two rows to one key); nullish/primitive rows fall back to
+ * identity keying.
+ */
+ key?: string;
+ /** Extra rows rendered above/below the viewport to cut mount churn (default 5). */
+ overscan?: number;
+ /**
+ * Tag name for the inner container that carries `@role`, `...attributes`, and
+ * the rows (the semantic element — e.g. `"ul"` for a listbox). Resolved once
+ * at mount, with an omitted or empty value falling back to `"div"`.
+ *
+ * A container with a content model, such as `ul` or `ol`, requires
+ * `@ownedRow`: the wrapped path emits `div` rows, which those elements do not
+ * permit as children.
+ *
+ * A list container keeps its native markers unless it also carries a `@role`,
+ * since suppressing them costs the implicit list semantics some screen readers
+ * derive from the marker. The container's own box spacing is zeroed either
+ * way, so a consumer that wants visible markers owns both `list-style` and the
+ * indent they need.
+ */
+ as?: string;
+ /** Gives consumers a stable hook for sizing and styling the scroll viewport. */
+ viewportClass?: string;
+ /**
+ * Names a scroll region whose non-interactive role offers no other naming path.
+ * Naming it also makes it a `region`, since a role-less element cannot be named.
+ */
+ viewportLabel?: string;
+ /** Names the scroll viewport from existing descriptive content, as `@viewportLabel` does. */
+ viewportLabelledBy?: string;
+ /**
+ * Whether the scroll viewport may take sequential focus. Defaults to `true`, which leaves
+ * the decision to the browser.
+ *
+ * A browser with keyboard-focusable scrollers adopts a scroll container as a tab stop when
+ * it holds no focusable descendants, so that a list which can only be read by scrolling is
+ * still reachable from the keyboard. Pass `false` when the rows are already reachable some
+ * other way and that tab stop would be a dead end — a listbox whose cursor is driven by
+ * `aria-activedescendant`, for instance, leaves its options without a tabindex but is fully
+ * navigable with the arrow keys from its controller.
+ *
+ * Opt out only with such a route in hand: without one this removes the sole keyboard access
+ * to the list's content.
+ */
+ viewportTabbable?: boolean;
+ /**
+ * When set, the default block yields `[item, rowContext]` and the CONSUMER
+ * renders the row element, applying `{{rowContext.place}}` + `{{rowContext.measure}}`
+ * (no wrapper, native semantic rows). When omitted, the primitive wraps the
+ * yielded content in its own measured, `@itemRole`-stamped row element.
+ */
+ ownedRow?: boolean;
+ /**
+ * `"bottom"` rests at the end on mount and then follows appended rows, so a
+ * live-updating list stays on its newest content. Following is bounded by
+ * `@scrollEndThreshold`: a reader who has scrolled away from the end keeps
+ * their position and is never pulled down by arriving rows. Default `"top"`.
+ */
+ anchor?: "top" | "bottom";
+ /**
+ * Distance from the end, in px, that still counts as resting at the end.
+ * Governs whether `@anchor="bottom"` follows an append, and whether a row
+ * resize preserves the at-end position.
+ *
+ * Defaults to the engine's own 1px, which means "exactly at the end". A
+ * bottom-anchored list almost always wants this higher, so that a reader
+ * sitting a few px short of the end still counts as following.
+ */
+ scrollEndThreshold?: number;
+ /**
+ * On the FIRST render only, scroll so this absolute index is revealed (per
+ * `@initialAlign`). Applied once at mount; a later `@items` change never
+ * re-scrolls, so it cannot fight the user. Takes precedence over
+ * `@anchor="bottom"`.
+ *
+ * The scroll is applied a tick after the first render, because the sizer must
+ * take its height before the viewport can scroll past its initially-empty
+ * content. A deep index is therefore reached on the frame after the first
+ * paint rather than before it.
+ */
+ initialIndex?: number;
+ /** Alignment for `@initialIndex` within the viewport. Default `"start"`. */
+ initialAlign?: "start" | "center" | "end" | "auto";
+ /**
+ * Extends the default window with extra absolute indices to keep mounted.
+ *
+ * REACTIVITY CONTRACT: pass a NEW function whenever any closed-over input
+ * changes (normally by invoking a template helper). Function identity is what
+ * re-triggers the modifier and updates the engine options.
+ *
+ * PURITY CONTRACT: the engine invokes this during its own flush, outside any
+ * tracking frame, and memoizes by extractor identity plus range. Tracked state
+ * read inside the callback is silently non-reactive; it must be pure over its
+ * arguments and a closed-over snapshot. A callback that throws degrades to the
+ * unextended window and is not consulted again until its identity or the range
+ * changes.
+ *
+ * This is also the mechanism for keeping a row mounted that must not be
+ * destroyed while scrolled out of the window. A consumer managing focus or a
+ * roving tabindex has to pin the active index, or scrolling past it unmounts
+ * the focused element and focus falls back to the document.
+ */
+ pinnedIndices?: (
+ indices: readonly number[],
+ range: VirtualRange
+ ) => readonly number[];
+ /**
+ * Role for the inner container (the semantic element), e.g. `"listbox"` or
+ * `"feed"`. Omitted by default: a role is a promise about keyboard behaviour
+ * the primitive does not implement on the consumer's behalf, so the consumer
+ * opts in.
+ *
+ * With a non-interactive role, nothing inside the list is focusable. Use
+ * `@viewportClass` as the hook for making the viewport focusable, and name
+ * it with `@viewportLabel` or `@viewportLabelledBy`, so the region can be
+ * scrolled without a pointer.
+ */
+ role?: string;
+ /**
+ * The role each row carries, e.g. `"listitem"` or `"option"`.
+ *
+ * Without `@ownedRow` it is stamped on the row the primitive renders. With
+ * `@ownedRow` the consumer stamps the role itself and this only declares what
+ * that role will be, which is what lets `row.posinset` and `row.setSize` be
+ * computed — they are defined for a handful of roles and are omitted for the
+ * rest, so the primitive has to be told.
+ *
+ * The wrapped row exposes no `id` and no attribute pass-through, so a role
+ * needing `aria-selected`, `aria-checked`, or an id to be pointed at by
+ * `aria-activedescendant` — `option`, `radio`, `tab`, `treeitem` — cannot be
+ * fully expressed there and needs `@ownedRow`.
+ */
+ itemRole?: string;
+ /**
+ * Overrides `aria-setsize`, for when `@items` is a loaded prefix of a
+ * larger known set.
+ *
+ * Omit it when the total is unknown: ARIA's `-1` sentinel is handled
+ * inconsistently by screen readers, so negative values are refused and the
+ * loaded count is published instead.
+ */
+ setSize?: number;
+ /** Receives the imperative handle once mounted. */
+ onRegisterApi?: (api: DVirtualListApi) => void;
+ /** Fires when the visible index range changes. */
+ onVisibleRangeChange?: (range: VisibleRange) => void;
+ /**
+ * Fires once when the window enters the START band (within `@edgeThreshold`
+ * rows of the first row), re-arming after it retreats. Mount at the top is
+ * suppressed. A start-edge consumer loads rows ABOVE the anchor.
+ */
+ onReachStart?: (info: EdgeInfo) => void;
+ /**
+ * Fires once when the window enters the END band (within `@edgeThreshold`
+ * rows of the last row), re-arming after retreat. Fires on mount when the
+ * first page already reaches the end. An end-edge consumer loads more rows.
+ */
+ onReachEnd?: (info: EdgeInfo) => void;
+ /** Rows from an edge at which its reach callback arms (default 8). */
+ edgeThreshold?: number;
+ };
+ Blocks: {
+ /** Renders each item in the active window. */
+ default: [
+ /** The backing-array item. */
+ item: T,
+ /** Its measured position and row modifiers. */
+ row: RowContext<T>,
+ ];
+ /** Renders when the backing array is empty. */
+ empty: [];
+ };
+ Element: HTMLElement;
+}
+
+/**
+ * Renders only a window of a large list while keeping the DOM bounded. The
+ * windowing engine remains behind the ui-kit library boundary.
+ *
+ * Structure: an outer role-less `.d-virtual-list` scroll VIEWPORT (the element the
+ * `dVirtualizer` modifier drives) wraps an inner `@as` CONTAINER — the semantic
+ * element that carries `@role`/`...attributes` and is the sizer (`height` = the
+ * full total) — whose rows are direct children, each absolutely positioned to its
+ * virtual offset. The component owns the tracked window (`_virtualItems`); the
+ * modifier owns the engine and pushes state in through `onState`.
+ *
+ * The consumer must give the outer viewport a nonzero height. Without one,
+ * windowing has no visible area and renders no rows.
+ *
+ * Simple consumers yield content and let the primitive wrap it in a measured,
+ * `@itemRole`-stamped row. A consumer that needs native row elements passes
+ * `@ownedRow` and renders the element itself, applying both
+ * `{{row.place row.start row.index}}` (positioning; also stamps `data-index`) and
+ * `{{row.measure}}` (height measurement). Neither requires the consumer to set
+ * `data-index`.
+ *
+ * @example
+ * ```gjs
+ * <DVirtualList @items={{this.rows}} @estimateSize={{this.estimate}} as |row|>
+ * <MyRow @row={{row}} />
+ * </DVirtualList>
+ *
+ * <DVirtualList @items={{this.rows}} @estimateSize={{this.estimate}}
+ * @as="ul" @role="listbox" @key="id" @ownedRow={{true}} as |item row|>
+ * <li role="option" {{row.place row.start row.index}} {{row.measure}}>
+ * {{item.label}}
+ * </li>
+ * </DVirtualList>
+ * ```
+ */
+export default class DVirtualList<T> extends Component<
+ DVirtualListSignature<T>
+> {
+ container = dElement(this.args.as || "div");
+ emptyContainer = dElement(
+ ["menu", "ol", "ul"].includes(this.args.as?.toLowerCase() ?? "")
+ ? "li"
+ : "div"
+ );
+
+ /**
+ * Makes the inner container a containing block for the absolutely positioned
+ * rows. Cleared in the render-all fallback so rows flow normally.
+ *
+ * Deliberately does NOT set the height. The modifier owns that, because it has
+ * to raise it before the engine scrolls and this runs afterwards in the same
+ * commit — Glimmer installs a parent's modifier update before a child's, so a
+ * height written from tracked state here would land second and overwrite the
+ * modifier's with the PREVIOUS flush's total. One writer avoids the collision
+ * entirely.
+ *
+ * This lands as an individual inline property rather than a `style` attribute,
+ * so a consumer's own `style` survives. Note the converse is not guaranteed: a
+ * consumer passing a DYNAMIC `style` through `...attributes` replaces the whole
+ * attribute when it updates, which drops it until the next resize.
+ */
+ sizeContainer = modifier((element: HTMLElement) => {
+ if (!isVirtualizationEnabled()) {
+ element.style.removeProperty("position");
+ element.style.removeProperty("height");
+ return;
+ }
+ element.style.position = "relative";
+ });
+ /**
+ * Registers a row for height measurement. Runs on insert and re-runs only when
+ * the api handle arrives — NOT per-render, so it does not re-measure on every
+ * window move, which would fight the engine's prepend-anchor settlement.
+ *
+ * `measureElement` identifies the row by its `data-index`, which
+ * {@link placeRow} stamps, so apply place before measure.
+ */
+ measureRow = modifier((element: HTMLElement) => {
+ this._api?.measureElement(element);
+ });
+ /**
+ * Positions one row: stamps `data-index` (the engine reads it to identify the
+ * row) and, while windowing, positions the row absolutely at its virtual
+ * offset. Positioning is inert in the render-all fallback, so rows stay in
+ * normal flow rather than stacking at `translateY(0)`.
+ *
+ * One stable modifier DEFINITION shared by every row, applied as
+ * `{{row.place row.start row.index}}`. A row that persists across a re-render
+ * re-runs its existing instance with new args, where a definition created per
+ * row would instead be destroyed and reinstalled — and the destroy can run
+ * AFTER the replacement wrote its styles, stripping them off the reused element.
+ */
+ placeRow = modifier(
+ (element: HTMLElement, [start, index]: [start: number, index: number]) => {
+ element.dataset.index = String(index);
+ if (!isVirtualizationEnabled()) {
+ element.style.removeProperty("position");
+ element.style.removeProperty("top");
+ element.style.removeProperty("inset-inline");
+ element.style.removeProperty("transform");
+ return;
+ }
+ element.style.position = "absolute";
+ // `top: 0` pins the translate base to the container origin; without it the
+ // row translates from its browser-computed static position (nonzero for a
+ // later absolute sibling), which silently mis-places every row.
+ element.style.top = "0";
+ element.style.insetInline = "0";
+ element.style.transform = `translateY(${start}px)`;
+ }
+ );
+ @tracked _api: DVirtualListApi | null = null;
+
+ @tracked _virtualItems: readonly VirtualItem[] = [];
+
+ /**
+ * Whether rows are windowed. Reads a module-level flag rather than tracked
+ * state, so it is fixed for the lifetime of a mounted list — flipping it
+ * afterwards does not re-render one that already exists.
+ */
+ get virtualizationActive() {
+ return isVirtualizationEnabled();
+ }
+
+ get rows(): Array<RowContext<T>> {
+ if (!this.virtualizationActive) {
+ // Test / fallback path: render every item in normal flow, no windowing.
+ // `keyFor` is the SAME helper the modifier's `getItemKey` uses, so a row keys
+ // identically here and in the windowed path.
+ return this.args.items.map((item, index) => {
+ const key = keyFor(item, this.args.key);
+ return this.#rowContext(item, index, key, 0, 0);
+ });
+ }
+
+ // The window is published from the modifier's after-render flush, so during
+ // the render in which `@items` shrank it still describes the PREVIOUS list.
+ // Dropping the rows that no longer exist keeps `items[index]` from handing a
+ // consumer `undefined` for the one pass before the next flush lands.
+ return this._virtualItems
+ .filter((vi) => vi.index < this.args.items.length)
+ .map((vi) =>
+ this.#rowContext(
+ this.args.items[vi.index],
+ vi.index,
+ vi.key,
+ vi.start,
+ vi.size
+ )
+ );
+ }
+
+ #rowContext(
+ item: T,
+ index: number,
+ key: number | string | bigint,
+ start: number,
+ size: number
+ ): RowContext<T> {
+ return {
+ item,
+ index,
+ key,
+ start,
+ size,
+ // Absolute position in the full backing array, never the window offset.
+ posinset: this.positionAwareItems ? index + 1 : undefined,
+ setSize: this.setSize,
+ place: this.placeRow,
+ measure: this.measureRow,
+ };
+ }
+
+ /** Whether `@itemRole` is one of the roles that defines position attributes. */
+ get positionAwareItems() {
+ return POSITION_AWARE_ROLES.has(this.args.itemRole ?? "");
+ }
+
+ /**
+ * `"region"` once the viewport carries a name, and otherwise absent.
+ *
+ * A `div` maps to the `generic` role, which ARIA forbids from carrying a name, so the
+ * naming arguments are inert without a role. An unnamed viewport is left alone: an
+ * unnamed region is skipped anyway, and a landmark per list would clutter the document.
+ */
+ get viewportRole() {
+ return this.args.viewportLabel || this.args.viewportLabelledBy
+ ? "region"
+ : undefined;
+ }
+
+ /**
+ * `-1` once a consumer has opted the viewport out of the tab order, and otherwise absent so
+ * the browser keeps its own judgement. Written as an explicit attribute rather than left off,
+ * because a scroller a browser has adopted reports `tabIndex === -1` either way — the
+ * attribute is what actually suppresses the adoption.
+ */
+ get viewportTabIndex() {
+ return this.args.viewportTabbable === false ? "-1" : undefined;
+ }
+
+ /**
+ * The published total: `@setSize` when given, floored at the loaded count
+ * so no `aria-posinset` can exceed it. The ARIA `-1` sentinel has no
+ * consistent screen reader implementation, so it is refused.
+ */
+ get setSize() {
+ if (!this.positionAwareItems) {
+ return undefined;
+ }
+
+ assert(
+ 'DVirtualList: `aria-setsize="-1"` has no consistent screen reader ' +
+ "implementation; omit `@setSize` when the total is unknown and let " +
+ "the loaded count stand",
+ (this.args.setSize ?? 0) >= 0
+ );
+
+ const loaded = this.args.items.length;
+ return Math.max(this.args.setSize ?? loaded, loaded);
+ }
+
+ @action
+ onState(state: {
+ virtualItems: readonly VirtualItem[];
+ totalSize: number;
+ range: VisibleRange | null;
+ }) {
+ this._virtualItems = state.virtualItems;
+ }
+
+ @action
+ onRegisterApi(api: DVirtualListApi) {
+ this._api = api;
+
+ // Registration happens once (first-run only), so an initial scroll set up
+ // here is inherently applied a single time and never re-fights the user on a
+ // later `@items` change. It is deferred a tick because the first flush must
+ // size the sizer before the viewport can scroll past its initially empty
+ // content.
+ //
+ // Scheduled before the consumer is handed the API, so a consumer that throws
+ // does not take the list's own opening position down with it.
+ if (this.args.initialIndex != null) {
+ const index = this.args.initialIndex;
+ const align = this.args.initialAlign ?? "start";
+ next(() => api.scrollToIndex(index, { align }));
+ } else if (this.args.anchor === "bottom") {
+ // Only the initial rest position. Following subsequent appends is the
+ // engine's job, configured by the modifier.
+ next(() => api.scrollToEdge("end"));
+ }
+
+ this.args.onRegisterApi?.(api);
+ }
+
+ <template>
+ {{! The outer viewport is the scroll element; the modifier drives it. The
+ consumer's role and splattributes go on the inner container, so the
+ semantic element owns them. This element takes a role only to carry its own
+ name. Size this viewport from CSS. }}
+ <div
+ class={{dConcatClass "d-virtual-list" @viewportClass}}
+ role={{this.viewportRole}}
+ aria-label={{if @viewportLabel @viewportLabel}}
+ aria-labelledby={{if @viewportLabelledBy @viewportLabelledBy}}
+ tabindex={{this.viewportTabIndex}}
+ {{dVirtualizer
+ items=@items
+ estimateSize=@estimateSize
+ key=@key
+ overscan=@overscan
+ anchor=@anchor
+ scrollEndThreshold=@scrollEndThreshold
+ pinnedIndices=@pinnedIndices
+ onState=this.onState
+ onRegisterApi=this.onRegisterApi
+ onVisibleRangeChange=@onVisibleRangeChange
+ onReachStart=@onReachStart
+ onReachEnd=@onReachEnd
+ edgeThreshold=@edgeThreshold
+ }}
+ >
+ {{! The container always renders, even when empty: a consumer's id and role
+ must stay resolvable for anything referencing them from outside. The
+ splattributes come first so the role and the sizer win a collision, and
+ the sizer writes individual properties rather than a style attribute so a
+ consumer's own styling survives. }}
+ {{#let this.container this.emptyContainer as |Container EmptyContainer|}}
+
+ <Container
+ class="d-virtual-list__sizer"
+ ...attributes
+ role={{@role}}
+ {{this.sizeContainer}}
+ >
+ {{#if @items.length}}
+ {{#each this.rows key="key" as |row|}}
+ {{#if @ownedRow}}
+ {{yield row.item row}}
+ {{else}}
+ {{! The role is dynamic, so the linter only sees a bare div and
+ assumes the generic role. Both position attributes are gated at
+ runtime on the roles that define them, and omitted otherwise. }}
+ {{! eslint-disable-next-line ember/template-no-unsupported-role-attributes }}
+ <div
+ class="d-virtual-list__item"
+ role={{@itemRole}}
+ aria-setsize={{row.setSize}}
+ aria-posinset={{row.posinset}}
+ {{row.place row.start row.index}}
+ {{row.measure}}
+ >
+ {{yield row.item row}}
+ </div>
+ {{/if}}
+ {{/each}}
+ {{else}}
+ <EmptyContainer class="d-virtual-list__empty" role="presentation">
+ {{yield to="empty"}}
+ </EmptyContainer>
+ {{/if}}
+ </Container>
+ {{/let}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/ui-kit/helpers/d-element.gts b/frontend/discourse/app/ui-kit/helpers/d-element.gts
index cf3a168e1ec..47ac1eef3c6 100644
--- a/frontend/discourse/app/ui-kit/helpers/d-element.gts
+++ b/frontend/discourse/app/ui-kit/helpers/d-element.gts
@@ -4,7 +4,16 @@ import type { TemplateOnlyComponent } from "@ember/component/template-only";
import type { ComponentLike } from "@glint/template";
/** The tag names that have a dedicated, higher-performance shortcut wrapper. */
-type ShortcutTag = "div" | "span" | "form" | "a" | "button" | "td" | "aside";
+type ShortcutTag =
+ | "div"
+ | "span"
+ | "form"
+ | "a"
+ | "button"
+ | "td"
+ | "aside"
+ | "ul"
+ | "li";
/**
* A wrapper component for a single known tag, typed with the matching element so
@@ -46,8 +55,22 @@ const shortcuts: { [K in ShortcutTag]: ElementWrapper<K> } = {
aside: <template>
<aside ...attributes>{{yield}}</aside>
</template>,
+ ul: <template>
+ <ul ...attributes>{{yield}}</ul>
+ </template>,
+ li: <template>
+ <li ...attributes>{{yield}}</li>
+ </template>,
};
+/**
+ * Wrappers built for tags outside the shortcut table, kept so a given tag always
+ * resolves to the same component. A caller that picks its tag at runtime would
+ * otherwise get a new component identity on every call, and rendering it would
+ * tear down and rebuild the whole subtree instead of updating it.
+ */
+const fallbacks = new Map<string, unknown>();
+
/**
* Returns a wrapper component that renders the given tag name, or an empty
* pass-through wrapper for an empty string. Modeled on the reference
@@ -116,16 +139,25 @@ export default function dElement(
if (tagName === "") {
wrapper = empty;
- } else if (shortcuts[tagName as ShortcutTag]) {
+ // `hasOwn`, not a bare read: the table is a plain object, so a tag named after
+ // an inherited member would otherwise resolve to that member.
+ } else if (Object.hasOwn(shortcuts, tagName)) {
wrapper = shortcuts[tagName as ShortcutTag];
} else {
- wrapper = <template>
- {{! @glint-nocheck: @ember/component (ClassicComponent) is not glint-typed }}
- <ClassicComponent
- @tagName={{tagName}}
- ...attributes
- >{{yield}}</ClassicComponent>
- </template>;
+ const cached = fallbacks.get(tagName);
+ if (cached) {
+ wrapper = cached;
+ } else {
+ const fallback = <template>
+ {{! @glint-nocheck: @ember/component (ClassicComponent) is not glint-typed }}
+ <ClassicComponent
+ @tagName={{tagName}}
+ ...attributes
+ >{{yield}}</ClassicComponent>
+ </template>;
+ fallbacks.set(tagName, fallback);
+ wrapper = fallback;
+ }
}
return wrapper as ComponentLike<{
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-virtualizer.ts b/frontend/discourse/app/ui-kit/modifiers/d-virtualizer.ts
new file mode 100644
index 00000000000..44e03c4712f
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-virtualizer.ts
@@ -0,0 +1,1053 @@
+import { DEBUG } from "@glimmer/env";
+import { isDestroying, registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import { cancel, schedule } from "@ember/runloop";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import { prefersReducedMotion } from "discourse/lib/utilities";
+import {
+ createElementVirtualizer,
+ isVirtualizationEnabled,
+ keyFor,
+ pushScrollOffset,
+ rangeExtractorWithPins,
+ remeasureViewport,
+ updateElementVirtualizer,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import type { DVirtualListApi } from "discourse/ui-kit/d-virtual-list";
+
+type VirtualKey = number | string | bigint;
+
+/**
+ * How close (in rows) the visible range must come to an edge before its reach
+ * callback arms. A few rows of lead time lets a fetch land before the reader
+ * reaches the true edge.
+ */
+const DEFAULT_EDGE_THRESHOLD = 8;
+
+/**
+ * Once an edge has fired, the range must retreat this many rows PAST the band
+ * before the edge re-arms. Without the gap, a range hovering on the band
+ * boundary would re-fire on every jitter.
+ */
+const EDGE_HYSTERESIS = 4;
+
+/**
+ * The engine's own tolerance for treating a computed offset and the element's
+ * snapped `scrollTop` as the same position. Its offsets come from arithmetic over
+ * estimates and alignment halving, while `scrollTop` is snapped to the browser's
+ * layout grid, so exact equality is the wrong comparison and would leave the two
+ * permanently "disagreeing" for a fractional row size.
+ */
+const SCROLL_EPSILON = 1.5;
+
+interface VisibleRange {
+ startIndex: number;
+ endIndex: number;
+}
+
+interface VirtualRange extends VisibleRange {
+ overscan: number;
+ count: number;
+}
+
+type PinnedIndices = (
+ indices: readonly number[],
+ range: VirtualRange
+) => readonly number[];
+
+/** The visible range plus the total item count, handed to an edge callback. */
+interface EdgeInfo extends VisibleRange {
+ count: number;
+}
+
+interface VirtualItem {
+ key: VirtualKey;
+ index: number;
+ start: number;
+ end: number;
+ size: number;
+ lane: number;
+}
+
+interface PublishedState {
+ /**
+ * The rendered window. Frozen, and a copy of the engine's own array rather than
+ * the array itself, so a consumer cannot write into the memoized result the
+ * engine hands back on every later read. Only the array is frozen: the items in
+ * it are reconstructed per computation, so a write to one cannot outlive the
+ * next window change.
+ */
+ virtualItems: readonly VirtualItem[];
+ totalSize: number;
+ range: VisibleRange | null;
+}
+
+interface StateSignature {
+ totalSize: number;
+ startIndex: number | undefined;
+ endIndex: number | undefined;
+ virtualItems: Array<
+ readonly [VirtualKey, number, number, number, number, number]
+ >;
+}
+
+interface VirtualizerOptions {
+ anchorTo: "start" | "end";
+ count: number;
+ getScrollElement: () => HTMLDivElement | null;
+ estimateSize: (index: number) => number;
+ getItemKey: (index: number) => VirtualKey;
+ overscan: number;
+ onChange: () => void;
+ followOnAppend: boolean;
+ scrollEndThreshold?: number;
+ rangeExtractor?: (range: VirtualRange) => number[];
+}
+
+interface VirtualizerApi {
+ range: VisibleRange | null;
+ isScrolling: boolean;
+ /** The viewport the engine measures and scrolls. Null until it mounts. */
+ scrollElement: HTMLElement | null;
+
+ /**
+ * The engine's cached scroll offset (px). Null until the first measure. The
+ * element's real `scrollTop` is the source of truth; this can drift from it
+ * when the browser clamps a scroll the engine never observed.
+ */
+ scrollOffset: number | null;
+ _didMount(): () => void;
+ _willUpdate(): void;
+ getTotalSize(): number;
+ getVirtualItems(): VirtualItem[];
+ measure(): void;
+ measureElement(element: HTMLElement | null): void;
+ scrollToIndex(
+ index: number,
+ options?: Parameters<DVirtualListApi["scrollToIndex"]>[1]
+ ): void;
+ scrollToOffset(
+ offset: number,
+ options?: Parameters<DVirtualListApi["scrollToOffset"]>[1]
+ ): void;
+ setOptions(options: VirtualizerOptions): void;
+}
+
+interface DVirtualizerSignature<T> {
+ Element: HTMLDivElement;
+ Args: {
+ Named: {
+ /** The complete list whose visible window is rendered. */
+ items: readonly T[];
+
+ /** Returns the estimated pixel size of an unmeasured item. */
+ estimateSize: (item: T, index: number) => number;
+
+ /**
+ * Field name whose value is the row's STABLE key (see {@link keyFor}). Without
+ * it rows key by object identity, so a consumer that rebuilds its item objects
+ * each render (fresh objects, same logical rows) orphans every measurement and
+ * remounts the whole window. The field must be present and unique per row;
+ * nullish/primitive rows fall back to identity keying.
+ */
+ key?: string;
+
+ /** The number of extra items rendered outside the visible range. */
+ overscan?: number;
+
+ /**
+ * The edge the list rests at. `"bottom"` additionally makes the engine
+ * follow appends while the reader is within `scrollEndThreshold` of the
+ * end; the initial rest position is applied by the component, not here.
+ */
+ anchor?: "top" | "bottom";
+
+ /**
+ * Distance from the end, in px, that still counts as "at the end". Governs
+ * both the follow-on-append gate and the engine's at-end row-resize branch.
+ * Defaults to the engine's own value, which is 1px.
+ */
+ scrollEndThreshold?: number;
+
+ /**
+ * Extends the default window with extra absolute indices to keep mounted.
+ * Invalid and duplicate extras are discarded, and the result stays in
+ * ascending index order. See {@link rangeExtractorWithPins}.
+ */
+ pinnedIndices?: PinnedIndices;
+
+ /** Receives newly published virtualizer state. */
+ onState?: (state: PublishedState) => void;
+
+ /**
+ * Receives the imperative virtual-list API after initialization.
+ *
+ * Delivered synchronously during the first `modify()`, unlike the other
+ * callbacks here, which are delivered from the after-render flush. The
+ * phase is load-bearing: a consumer that positions the list and then calls
+ * back into the API needs the handle before that positioning runs. The
+ * cost is that writing tracked state already consumed in this render pass
+ * will trip a backtracking assertion — do that work in a later phase.
+ */
+ onRegisterApi?: (api: DVirtualListApi) => void;
+
+ /** Runs when the visible item range changes. */
+ onVisibleRangeChange?: (range: VisibleRange) => void;
+
+ /**
+ * Runs once when the visible range enters the START band (within
+ * `edgeThreshold` rows of index 0), re-arming only after it retreats past
+ * the band plus hysteresis. Mount at the start is suppressed (the start
+ * latch begins satisfied) so a list that opens at the top does not fire.
+ */
+ onReachStart?: (info: EdgeInfo) => void;
+
+ /**
+ * Runs once when the visible range enters the END band (within
+ * `edgeThreshold` rows of the last index), re-arming after retreat past
+ * hysteresis. Unlike the start edge, the end latch begins UNsatisfied, so
+ * a list whose first page already reaches the end fires on mount.
+ */
+ onReachEnd?: (info: EdgeInfo) => void;
+
+ /** Rows from an edge at which its reach callback arms (default 8). */
+ edgeThreshold?: number;
+ };
+ Positional: [];
+ };
+}
+
+/**
+ * Bridges the windowing engine to Glimmer's reactivity.
+ *
+ * Applied to the scroll element by `DVirtualList`. It owns the imperative
+ * virtualizer instance and is the single reactive site for it:
+ *
+ * - `modify()` re-runs whenever its tracked named args change. On the first run
+ * it constructs and mounts the virtualizer; on later runs it calls
+ * `setOptions`.
+ * - Engine changes enqueue one `schedule("afterRender")` flush. The flush only
+ * publishes when the total, range, or any virtual item field changes, avoiding
+ * the render loop caused by assigning an equivalent fresh array to tracked
+ * state.
+ * - Teardown calls the cleanup returned by `_didMount()` and cancels any pending
+ * flush; every path that could write is fenced by destruction state.
+ */
+export default class DVirtualizer<T> extends Modifier<
+ DVirtualizerSignature<T>
+> {
+ #cleanup: (() => void) | null = null;
+ #element: HTMLDivElement | null = null;
+ #flushScheduled = false;
+ #flushTimer: ReturnType<typeof schedule> | null = null;
+ #getItemKey: ((index: number) => VirtualKey) | null = null;
+ #getItemKeyEstimate: ((item: T, index: number) => number) | null = null;
+ #getItemKeyField: string | undefined;
+ #getItemKeyItems: readonly T[] | null = null;
+ #lastSignature: StateSignature | null = null;
+ #lastEmittedRange: VisibleRange | null = null;
+ #named: DVirtualizerSignature<T>["Args"]["Named"] | null = null;
+ #virtualizer: VirtualizerApi | null = null;
+ #warnedZeroHeight = false;
+
+ /**
+ * The start latch begins satisfied (mount at the top is not a "reached start"
+ * event); the end latch begins unsatisfied so a list whose first page already
+ * fills to the end fires its end callback on mount. `count === 0` resets both.
+ */
+ #startLatched = true;
+ #endLatched = false;
+
+ /**
+ * True while an edge callback is running. `armEdge` is inert then: the callback
+ * would be clearing the latch this evaluation has just set, and the flush it
+ * schedules would fire the same callback again, with no yield in between.
+ */
+ #inEdgeCallback = false;
+
+ /**
+ * The edge keys the latches were last evaluated against. A latch can only be
+ * re-armed by a range retreat, which an `@items` change never produces: rows
+ * arriving beyond the viewport move the BAND, not the range. Watching the keys
+ * instead re-arms the edge the change actually touched. Null until the first
+ * non-empty evaluation seeds them, which is what keeps mount suppression
+ * intact across the initial transition from zero to a populated list.
+ */
+ #lastFirstKey: VirtualKey | null = null;
+ #lastLastKey: VirtualKey | null = null;
+
+ /**
+ * The item count the edges were last evaluated against. A latch may only be
+ * re-armed by a list that actually changed length, so that an in-place refresh
+ * cannot be mistaken for rows arriving at an edge.
+ */
+ #lastCount = 0;
+
+ /** Reentrancy guard for the synchronous offset push (see `#syncScrollOffset`). */
+ #syncingScroll = false;
+
+ /**
+ * Snapshotted from the named arg in `modify()` (not read live at flush time)
+ * so that CHANGING it re-invokes `modify()` — which schedules a flush that
+ * re-arms the latches against the new band. Reading it only inside `#flush`
+ * would leave a threshold change without a flush, so the latches would never
+ * re-arm until the next unrelated scroll.
+ */
+ #edgeThreshold = DEFAULT_EDGE_THRESHOLD;
+
+ constructor(owner: Owner, args: ArgsFor<DVirtualizerSignature<T>>) {
+ super(owner, args);
+ registerDestructor(this, () => this.#teardown());
+ }
+
+ modify(
+ element: HTMLDivElement,
+ _positional: [],
+ named: DVirtualizerSignature<T>["Args"]["Named"]
+ ) {
+ this.#element = element;
+ this.#named = named;
+
+ // When virtualization is globally disabled (the test render-all fallback), the
+ // modifier is fully inert: the component renders every row in normal flow, so there
+ // is no window to drive. Building the engine anyway would still fire edge/range
+ // callbacks off a zero-height container — e.g. trip onReachEnd on mount — driving a
+ // consumer's edge fetch against a list that is fully mounted. Tear down any engine a
+ // prior enabled run built, so "disabled ⇒ no live virtualizer" holds and a stale
+ // engine cannot keep scheduling flushes after the flag flips (a fresh mount has none).
+ if (!isVirtualizationEnabled()) {
+ if (this.#virtualizer) {
+ this.#teardown();
+ }
+ return;
+ }
+
+ // A non-finite threshold makes every band comparison false, and a negative one
+ // puts the band out of reach, so the edge would silently never fire again.
+ const threshold = named.edgeThreshold;
+ this.#edgeThreshold = Number.isFinite(threshold)
+ ? Math.max(0, Math.floor(threshold!))
+ : DEFAULT_EDGE_THRESHOLD;
+
+ const options = this.#buildOptions(named);
+
+ if (!this.#virtualizer) {
+ // Build into locals and only adopt once mounting has fully succeeded.
+ //
+ // `_willUpdate()` is not inert on a first run: it attaches the observers,
+ // and the rect observer reports eagerly, which measures every index through
+ // the consumer's `estimateSize`. If that throws mid-way while `#virtualizer`
+ // is already assigned, every later `modify()` takes the update branch and
+ // the API is never registered — so `measureRow` stays a no-op and NO row is
+ // ever measured, silently, for the life of the list.
+ //
+ // TODO(devxp-typescript-pending): Remove once the JavaScript adapter
+ // preserves the engine's element and option types.
+ const virtualizer = createElementVirtualizer(
+ options
+ ) as unknown as VirtualizerApi;
+
+ let cleanup: (() => void) | null = null;
+ try {
+ cleanup = virtualizer._didMount();
+ virtualizer._willUpdate();
+ } catch (e) {
+ cleanup?.();
+ throw e;
+ }
+
+ this.#virtualizer = virtualizer;
+ this.#cleanup = cleanup;
+ named.onRegisterApi?.(this.#buildApi());
+ } else {
+ updateElementVirtualizer(this.#virtualizer, options);
+ this.#growSizerToTotal();
+ this.#virtualizer._willUpdate();
+ this.#resyncScrollOffset();
+ }
+
+ this.#scheduleFlush();
+ }
+
+ /** The element whose height stands in for the whole list. */
+ #sizer() {
+ return (
+ this.#element?.querySelector<HTMLElement>(
+ ":scope > .d-virtual-list__sizer"
+ ) ?? null
+ );
+ }
+
+ /**
+ * Sets the sizer to the engine's current total, so the scrollbar spans the whole
+ * list while only a window is mounted.
+ *
+ * This modifier is the ONLY writer of that height. Sharing it with the component
+ * would not merely be untidy: Glimmer installs a parent's modifier update before
+ * its children's, so a height the component derived from tracked state would land
+ * after this one and carry the PREVIOUS flush's total — reverting the raise below
+ * within the same commit, and leaving the engine to reconcile a scroll target it
+ * captured against a height that no longer exists.
+ *
+ * An empty list gets no height at all: the `empty` block renders inside this
+ * element, and a self-centering empty state would collapse into a zero-height box.
+ *
+ * @param options - `grow` raises the height but never lowers it.
+ */
+ #applySizerHeight({ grow = false } = {}) {
+ const sizer = this.#sizer();
+ if (!sizer || !this.#virtualizer) {
+ return;
+ }
+
+ if (!(this.#named?.items.length ?? 0)) {
+ sizer.style.removeProperty("height");
+ return;
+ }
+
+ const total = this.#virtualizer.getTotalSize();
+ if (grow && total <= sizer.offsetHeight) {
+ return;
+ }
+
+ sizer.style.height = `${total}px`;
+ }
+
+ /**
+ * Raise the sizer to the engine's new total BEFORE the engine acts on the options
+ * it was just given.
+ *
+ * `setOptions` resolves the keyed scroll anchor and stashes it; `_willUpdate` then
+ * writes that offset to the element. At this instant the element is still as tall
+ * as the OLD list, and the browser clamps a scroll past the end of it — so a
+ * prepend larger than the reader's remaining distance to the bottom lands short,
+ * losing the very anchor that exists to hold their position.
+ *
+ * Raise only. Lowering here would clamp in the other direction while the engine
+ * is still deciding where to go; the flush sets the exact height afterwards.
+ */
+ #growSizerToTotal() {
+ this.#applySizerHeight({ grow: true });
+ }
+
+ /**
+ * After an `@items` change the engine can hold a scroll offset the element no
+ * longer has: shrinking the sizer makes the browser clamp `scrollTop`, but that
+ * clamp does not reach the engine's offset observer, so it keeps computing the
+ * window from a stale, now out-of-range offset. On its own that only mis-scrolls
+ * the window; combined with pinned indices it surfaces as a visible gap — the
+ * pinned row renders at its true offset while the window sits far below it, and
+ * the rows between are absent. Adopt the element's real `scrollTop` whenever the
+ * two disagree so the window tracks the actual position.
+ *
+ * Compared with a tolerance rather than exactly, because the engine's offset is
+ * arithmetic over estimates while `scrollTop` is snapped to the layout grid. A
+ * no-op when they already agree, which is the common case now that
+ * `#growSizerToTotal` keeps a grown list's anchored scroll reachable.
+ */
+ #resyncScrollOffset() {
+ const element = this.#element;
+ if (this.#syncingScroll || !element?.isConnected || isDestroying(this)) {
+ return;
+ }
+ const engineOffset = this.#virtualizer?.scrollOffset ?? null;
+ if (
+ engineOffset === null ||
+ Math.abs(engineOffset - element.scrollTop) < SCROLL_EPSILON
+ ) {
+ return;
+ }
+
+ // Only correct an offset that is genuinely out of range. A mere disagreement
+ // is normal mid-update — the engine may have just issued a programmatic scroll
+ // whose target it has not observed yet — and adopting the element's position
+ // there would overwrite that intent and settle the window somewhere stale.
+ //
+ // Measured against the ENGINE's new total rather than the element's height,
+ // which may still describe the outgoing list during the update-time call.
+ // The flush calls again after settling the height so a shrink's forced layout
+ // exposes the browser-clamped position before the window is read.
+ const maxOffset = Math.max(
+ this.#virtualizer.getTotalSize() - element.clientHeight,
+ 0
+ );
+ if (engineOffset <= maxOffset + SCROLL_EPSILON) {
+ return;
+ }
+
+ this.#syncingScroll = true;
+ try {
+ pushScrollOffset(this.#virtualizer);
+ } finally {
+ this.#syncingScroll = false;
+ }
+ }
+
+ /**
+ * Strip an animated scroll when the reader has asked for reduced motion, so a
+ * consumer does not have to check for it at every call site.
+ *
+ * @param options - The caller's scroll options.
+ * @returns The options, with any animation removed if motion is unwelcome.
+ */
+ #respectMotionPreference<O extends { behavior?: ScrollBehavior }>(
+ options: O | undefined
+ ): O | undefined {
+ if (options?.behavior === "smooth" && prefersReducedMotion()) {
+ return { ...options, behavior: "auto" };
+ }
+ return options;
+ }
+
+ #buildApi(): DVirtualListApi {
+ const isScrolling = () => this.#virtualizer?.isScrolling ?? false;
+
+ return {
+ scrollToIndex: (index, options) => {
+ const before = this.#element?.scrollTop;
+ this.#virtualizer?.scrollToIndex(
+ index,
+ this.#respectMotionPreference(options)
+ );
+ this.#syncScrollOffset(before);
+ },
+ scrollToOffset: (offset, options) => {
+ const before = this.#element?.scrollTop;
+ this.#virtualizer?.scrollToOffset(
+ offset,
+ this.#respectMotionPreference(options)
+ );
+ this.#syncScrollOffset(before);
+ },
+ scrollToEdge: (edge) => {
+ const count = this.#named?.items.length ?? 0;
+ if (!count) {
+ return;
+ }
+ const before = this.#element?.scrollTop;
+ this.#virtualizer?.scrollToIndex(edge === "end" ? count - 1 : 0, {
+ align: edge === "end" ? "end" : "start",
+ });
+ this.#syncScrollOffset(before);
+ },
+ armEdge: (edge) => {
+ if (!this.#virtualizer || this.#inEdgeCallback || isDestroying(this)) {
+ return;
+ }
+ if (edge === "end") {
+ this.#endLatched = false;
+ } else {
+ this.#startLatched = false;
+ }
+ // Clearing the latch is all this does. The callback fires from the next
+ // flush's edge evaluation, and only if the range is still in the band, so
+ // a consumer cannot drive its own callback by calling this.
+ this.#scheduleFlush();
+ },
+ measure: () => this.#virtualizer?.measure(),
+ remeasureViewport: () => {
+ if (this.#virtualizer) {
+ remeasureViewport(this.#virtualizer);
+ }
+ },
+ measureElement: (element) => {
+ // The engine resolves the row from the `data-index` that `place` stamps. Given
+ // anything it cannot resolve it warns, then observes the element under a key no
+ // row has, for the life of the list. Refuse it here rather than poison the cache.
+ // Checked against the item count rather than just parsed, because an index past
+ // the end resolves to no row just as surely as a missing one.
+ if (!(element instanceof HTMLElement)) {
+ return;
+ }
+ // Read the raw attribute first: `Number("")` is 0, so an empty `data-index`
+ // would otherwise pass as a valid index into the first row.
+ const raw = element.dataset.index;
+ if (raw === undefined || raw.trim() === "") {
+ return;
+ }
+ const index = Number(raw);
+ if (
+ !Number.isInteger(index) ||
+ index < 0 ||
+ index >= (this.#named?.items.length ?? 0)
+ ) {
+ return;
+ }
+ this.#virtualizer?.measureElement(element);
+ },
+ visibleRange: () =>
+ this.#freezeRange(this.#virtualizer?.range ?? null) ?? undefined,
+ get isScrolling() {
+ return isScrolling();
+ },
+ };
+ }
+
+ /**
+ * The engine reads the scroll offset only from the element's `scroll` event,
+ * which `element.scrollTo` (used by every programmatic scroll) fires
+ * ASYNCHRONOUSLY. Left to that, the window would not reflect an imperative
+ * scroll until a later tick — imperceptible in a browser, but a race that
+ * leaves a rendering test unsettled at the old window. Pushing the offset
+ * straight into the engine makes a programmatic scroll immediately consistent;
+ * the real async event that follows is a no-op (the engine short-circuits when
+ * the offset already matches).
+ *
+ * Guarded so it only pushes when the scroll actually moved, never on a
+ * detached/destroyed element, and never re-enters.
+ *
+ * A `behavior: "smooth"` scroll does not move `scrollTop` synchronously, so it
+ * takes the no-op branch and settles through the engine's own reconcile loop
+ * instead.
+ *
+ * @param previousScrollTop - The offset before the scroll was requested.
+ */
+ #syncScrollOffset(previousScrollTop: number | undefined) {
+ const element = this.#element;
+ if (
+ this.#syncingScroll ||
+ !element?.isConnected ||
+ isDestroying(this) ||
+ element.scrollTop === previousScrollTop
+ ) {
+ return;
+ }
+ this.#syncingScroll = true;
+ try {
+ pushScrollOffset(this.#virtualizer);
+ } finally {
+ this.#syncingScroll = false;
+ }
+ }
+
+ #buildOptions(
+ named: DVirtualizerSignature<T>["Args"]["Named"]
+ ): VirtualizerOptions {
+ const { items, estimateSize, overscan, key, pinnedIndices } = named;
+ // Fractional and non-finite ranges can permanently poison engine memoization;
+ // negative ranges leave viewport gaps.
+ const normalizedOverscan =
+ overscan === undefined || !Number.isFinite(overscan)
+ ? 5
+ : Math.max(0, Math.floor(overscan));
+
+ if (
+ !this.#getItemKey ||
+ this.#getItemKeyItems !== items ||
+ this.#getItemKeyField !== key ||
+ this.#getItemKeyEstimate !== estimateSize
+ ) {
+ // Count is insufficient: a same-length replacement must key the incoming
+ // items rather than keep reading the outgoing array.
+ //
+ // The estimate belongs in this condition even though it is not part of the
+ // key. This function's identity is the only input to the engine's
+ // measurement memo that we control, and the engine does not watch its own
+ // `estimateSize`. Holding the function stable across an estimate change
+ // therefore leaves every unmeasured row at the old size. Measured rows are
+ // unaffected: the size cache is keyed by row key and survives the rebuild.
+ this.#getItemKey = (index) => keyFor(items[index], key);
+ this.#getItemKeyItems = items;
+ this.#getItemKeyField = key;
+ this.#getItemKeyEstimate = estimateSize;
+ }
+
+ const options: VirtualizerOptions = {
+ // Despite the name, this does NOT set where the list rests — the component
+ // applies the initial position. Unconditional because it gates key-based
+ // prepend anchoring, which we always want: inserting older rows above the
+ // viewport otherwise shifts everything the reader is looking at by the
+ // height of what arrived. The engine's other uses of it are additionally
+ // bounded by `scrollEndThreshold`.
+ anchorTo: "end",
+ count: items.length,
+ getScrollElement: () => this.#element,
+ estimateSize: (index) => estimateSize(items[index]!, index),
+ getItemKey: this.#getItemKey,
+ overscan: normalizedOverscan,
+ onChange: () => this.#scheduleFlush(),
+ // Only a bottom-anchored list tracks the live edge. The engine gates this
+ // on the reader having been within `scrollEndThreshold` of the end BEFORE
+ // the append, so a reader who has scrolled up to read history is never
+ // yanked down by arriving rows.
+ followOnAppend: named.anchor === "bottom",
+ };
+
+ // Left unset the engine keeps its own 1px default. `setOptions` skips
+ // undefined values, so passing it through unconditionally would be harmless
+ // but would misrepresent "unset" as an explicit choice.
+ if (named.scrollEndThreshold != null) {
+ options.scrollEndThreshold = named.scrollEndThreshold;
+ }
+
+ // Set the extractor only when there is something to pin, so the engine keeps
+ // its own default path when there isn't — and so dropping `@pinnedIndices`
+ // reverts cleanly rather than installing a pass-through.
+ if (pinnedIndices != null) {
+ options.rangeExtractor = rangeExtractorWithPins(pinnedIndices);
+ }
+
+ return options;
+ }
+
+ #flush() {
+ this.#flushScheduled = false;
+ if (!this.#virtualizer || isDestroying(this)) {
+ return;
+ }
+
+ const count = this.#named?.items.length ?? 0;
+ if (
+ DEBUG &&
+ count > 0 &&
+ !this.#warnedZeroHeight &&
+ this.#element?.clientHeight === 0
+ ) {
+ this.#warnedZeroHeight = true;
+ // eslint-disable-next-line no-console
+ console.warn(
+ "[d-virtual-list] The scroll viewport has zero height; give it a height so virtualized rows can render."
+ );
+ }
+
+ // Sweep disconnected rows out of the engine's ResizeObserver. A ResizeObserver
+ // does not fire on removal, and the engine only self-heals opportunistically,
+ // so without this the element cache grows with every row ever scrolled past.
+ // The sweep contract is pinned in the virtualizer unit suite.
+ this.#virtualizer.measureElement(null);
+
+ // Settle a shrink before reading the window. Reading `scrollTop` during the
+ // resync forces the browser to apply the height clamp, and pushes that
+ // position into the engine before anything can be published.
+ this.#applySizerHeight();
+ this.#resyncScrollOffset();
+
+ const virtualItems = this.#virtualizer.getVirtualItems();
+ const totalSize = this.#virtualizer.getTotalSize();
+ const range = this.#virtualizer.range;
+
+ const signature = this.#stateSignature(virtualItems, totalSize, range);
+
+ // Hand out frozen copies, never the engine's own objects. `range` stays
+ // attached to the engine between computations and its committed value is what
+ // the engine's change memo compares against, and `getVirtualItems()` returns a
+ // memoized array the engine keeps handing back — so a consumer that wrote
+ // through either could silently stop the window from updating.
+ const publishedRange = this.#freezeRange(range);
+ const publishedItems = Object.freeze([...virtualItems]);
+
+ // Publish BEFORE any edge callback runs. The window is what the component
+ // needs to render at all, so it must not sit behind a consumer callback that
+ // could throw — the engine's own change memo has already committed by the
+ // time this runs, so a flush lost to an exception is never re-driven and the
+ // list would stay blank for good.
+ if (!this.#signaturesMatch(signature, this.#lastSignature)) {
+ this.#lastSignature = signature;
+
+ const published = this.#safely("onState", () =>
+ this.#named?.onState?.({
+ virtualItems: publishedItems,
+ totalSize,
+ range: publishedRange,
+ })
+ );
+
+ // Drop the memo when the publish did not happen. Unlike the edge callbacks,
+ // this one carries the window the component renders from, so remembering a
+ // publish that threw would match forever and strand the list on whatever it
+ // last drew — for a mounted list nobody scrolls, that is permanent.
+ if (!published) {
+ this.#lastSignature = null;
+ }
+
+ // A row remeasurement changes the signature (sizes/offsets shift) without
+ // moving the visible indices. Gate the range callback on a real start/end
+ // change so a size-only remeasure does not publish a spurious range event.
+ if (range && this.#rangeIndicesChanged(range)) {
+ this.#lastEmittedRange = {
+ startIndex: range.startIndex,
+ endIndex: range.endIndex,
+ };
+ this.#safely("onVisibleRangeChange", () =>
+ this.#named?.onVisibleRangeChange?.(publishedRange!)
+ );
+ }
+ }
+
+ // Deliberately outside the signature gate: the edge inputs (range, count,
+ // threshold) are not all captured by the rendering signature, so a
+ // threshold-only change — which leaves the rendered window identical — must
+ // still re-arm the latches.
+ this.#evaluateEdges(range, count);
+ }
+
+ /**
+ * Runs a callback so that throwing cannot abort the flush around it.
+ *
+ * A latch or cache the caller owns is committed BEFORE the call, so a callback
+ * that throws every time is not retried on every subsequent flush. That trade
+ * only makes sense for a callback whose loss costs the consumer an event; where
+ * the loss would instead desync the rendered window, the caller must undo its
+ * commit on a false return rather than memoize a publish that never happened.
+ *
+ * @param label - Callback name, used to attribute the error.
+ * @param run - The callback to invoke.
+ * @returns Whether it completed without throwing.
+ */
+ #safely(label: string, run: () => void): boolean {
+ try {
+ run();
+ return true;
+ } catch (e) {
+ // eslint-disable-next-line no-console
+ console.error(`[d-virtual-list] ${label} threw: `, e);
+ return false;
+ }
+ }
+
+ /**
+ * Re-arms the edge whose boundary row changed identity, so a consumer that
+ * answers an edge callback by growing the list can reach that edge again.
+ *
+ * Direction matters: an append moves the end band away from a range that has
+ * not moved, so the retreat rule alone would re-arm only for a page bigger than
+ * the band plus hysteresis, and a smaller page would stall the edge forever.
+ * Keying off the boundary rows instead re-arms exactly the edge that gained
+ * rows, which is why a tail change must not disturb the start latch.
+ *
+ * @param count - The total number of items, known to be non-zero.
+ */
+ #rearmEdgesForItemChange(count: number) {
+ const named = this.#named;
+ if (!named) {
+ return;
+ }
+
+ const firstKey = keyFor(named.items[0], named.key);
+ const lastKey = keyFor(named.items[count - 1], named.key);
+ const previousCount = this.#lastCount;
+
+ this.#lastCount = count;
+
+ // Seed only: the first non-empty evaluation must not unlatch, or a list that
+ // mounts non-empty would lose the deliberate start-edge suppression.
+ if (this.#lastFirstKey === null && this.#lastLastKey === null) {
+ this.#lastFirstKey = firstKey;
+ this.#lastLastKey = lastKey;
+ return;
+ }
+
+ const previousFirstKey = this.#lastFirstKey;
+ const previousLastKey = this.#lastLastKey;
+ this.#lastFirstKey = firstKey;
+ this.#lastLastKey = lastKey;
+
+ // Whether a changed boundary key means anything depends on how rows are keyed.
+ //
+ // With an explicit `@key` the key IS the row's logical identity, so a changed
+ // boundary is a genuinely different row and re-arming is right even at a
+ // constant length — which is exactly a capped stream, appending at the tail
+ // while dropping from the head.
+ //
+ // Without one, rows key by object identity, and a consumer that rebuilds its
+ // items in place hands over brand new boundary keys for the very same rows.
+ // Re-arming there would answer an edge callback with an edge callback: the
+ // consumer refreshes, the boundary key changes, the range is still in the
+ // band, and it fires again. So an unkeyed list additionally has to have
+ // changed length before a boundary is believed.
+ if (!named.key && count === previousCount) {
+ return;
+ }
+
+ const headChanged = firstKey !== previousFirstKey;
+ const tailChanged = lastKey !== previousLastKey;
+
+ if (!headChanged && !tailChanged && count === previousCount) {
+ return;
+ }
+
+ // Neither boundary moved yet the list changed length, so rows were inserted
+ // between them — which is what a list carrying a stable trailing sentinel
+ // looks like, a loading skeleton or placeholder that outlives the page it
+ // announces. The side cannot be told apart, so arm both rather than let an
+ // edge stall forever behind a row whose key never changes.
+ if (!headChanged && !tailChanged) {
+ this.#startLatched = false;
+ this.#endLatched = false;
+ return;
+ }
+
+ if (headChanged) {
+ this.#startLatched = false;
+ }
+ if (tailChanged) {
+ this.#endLatched = false;
+ }
+ }
+
+ #rangeIndicesChanged(range: VisibleRange): boolean {
+ const last = this.#lastEmittedRange;
+ return (
+ !last ||
+ last.startIndex !== range.startIndex ||
+ last.endIndex !== range.endIndex
+ );
+ }
+
+ /**
+ * Fires `onReachStart`/`onReachEnd` once per entry into an edge band, re-arming
+ * after the range retreats past the band plus hysteresis OR when the list gains
+ * a new edge (see `#rearmEdgesForItemChange`). An empty list returns both
+ * latches to their MOUNT state, so a refill behaves like a fresh mount: the end
+ * edge can fire again and the start edge stays suppressed. A null range holds
+ * the current state (nothing measured yet) but still tracks the edges.
+ *
+ * @param range - The visible range, or null before anything has been measured.
+ * @param count - The total number of items.
+ */
+ #evaluateEdges(range: VisibleRange | null, count: number) {
+ if (count === 0) {
+ this.#startLatched = true;
+ this.#endLatched = false;
+ // Dropping the emitted range alongside the latches keeps an empty->refill
+ // cycle from swallowing the new list's first range event when it happens to
+ // land on the same indices.
+ this.#lastEmittedRange = null;
+ this.#lastFirstKey = null;
+ this.#lastLastKey = null;
+ this.#lastCount = 0;
+ return;
+ }
+
+ this.#rearmEdgesForItemChange(count);
+
+ if (!range) {
+ return;
+ }
+
+ const threshold = this.#edgeThreshold;
+ const startBand = threshold;
+ const endBand = count - 1 - threshold;
+
+ if (range.startIndex <= startBand) {
+ if (!this.#startLatched) {
+ this.#startLatched = true;
+ this.#inEdgeCallback = true;
+ try {
+ this.#safely("onReachStart", () =>
+ this.#named?.onReachStart?.({ ...range, count })
+ );
+ } finally {
+ this.#inEdgeCallback = false;
+ }
+ }
+ } else if (range.startIndex > startBand + EDGE_HYSTERESIS) {
+ this.#startLatched = false;
+ }
+
+ if (range.endIndex >= endBand) {
+ if (!this.#endLatched) {
+ this.#endLatched = true;
+ this.#inEdgeCallback = true;
+ try {
+ this.#safely("onReachEnd", () =>
+ this.#named?.onReachEnd?.({ ...range, count })
+ );
+ } finally {
+ this.#inEdgeCallback = false;
+ }
+ }
+ } else if (range.endIndex < endBand - EDGE_HYSTERESIS) {
+ this.#endLatched = false;
+ }
+ }
+
+ /**
+ * A frozen copy of a range. Hand these out, never the engine's own object: `range`
+ * stays attached to the engine between computations, and its committed value is what
+ * the engine's change memo compares against.
+ */
+ #freezeRange(range: VisibleRange | null): Readonly<VisibleRange> | null {
+ return range
+ ? Object.freeze({
+ startIndex: range.startIndex,
+ endIndex: range.endIndex,
+ })
+ : null;
+ }
+
+ #scheduleFlush() {
+ if (this.#flushScheduled || isDestroying(this)) {
+ return;
+ }
+ this.#flushScheduled = true;
+ this.#flushTimer = schedule("afterRender", this, this.#flush);
+ }
+
+ #signaturesMatch(
+ current: StateSignature,
+ previous: StateSignature | null
+ ): boolean {
+ if (
+ !previous ||
+ current.totalSize !== previous.totalSize ||
+ current.startIndex !== previous.startIndex ||
+ current.endIndex !== previous.endIndex ||
+ current.virtualItems.length !== previous.virtualItems.length
+ ) {
+ return false;
+ }
+
+ return current.virtualItems.every((item, index) =>
+ item.every(
+ (value, field) => value === previous.virtualItems[index]![field]
+ )
+ );
+ }
+
+ #stateSignature(
+ virtualItems: VirtualItem[],
+ totalSize: number,
+ range: VisibleRange | null
+ ): StateSignature {
+ return {
+ totalSize,
+ startIndex: range?.startIndex,
+ endIndex: range?.endIndex,
+ virtualItems: virtualItems.map(
+ ({ key, index, start, end, size, lane }) => [
+ key,
+ index,
+ start,
+ end,
+ size,
+ lane,
+ ]
+ ),
+ };
+ }
+
+ #teardown() {
+ if (this.#flushTimer) {
+ cancel(this.#flushTimer);
+ }
+ this.#flushScheduled = false;
+ this.#cleanup?.();
+ this.#cleanup = null;
+ this.#virtualizer = null;
+ // Drop the publish and edge bookkeeping with the engine that produced it.
+ // This path is not only destruction: the disabled-virtualization branch tears
+ // down a live modifier, and a later re-enable builds a FRESH engine that must
+ // not inherit the previous one's de-dup memo or latch state.
+ this.#lastSignature = null;
+ this.#lastEmittedRange = null;
+ this.#lastFirstKey = null;
+ this.#lastLastKey = null;
+ this.#lastCount = 0;
+ this.#startLatched = true;
+ this.#endLatched = false;
+ // Drop the element too: a retained API handle or a pending `next()` scroll
+ // must not dispatch a synthetic event onto a detached node after teardown.
+ this.#element = null;
+ }
+}
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index 66c175dec5d..0df5bf0cd79 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -130,6 +130,7 @@
"@glimmer/component": "^2.0.0",
"@rolldown/pluginutils": "1.0.1",
"@rollup/plugin-babel": "^7.1.0",
+ "@tanstack/virtual-core": "3.17.5",
"@types/jquery": "^3.5.33",
"@types/picomatch": "^4.0.3",
"@types/qunit": "^2.19.13",
diff --git a/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs
new file mode 100644
index 00000000000..1d4d852b27d
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-element-test.gjs
@@ -0,0 +1,60 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import dElement from "discourse/ui-kit/helpers/d-element";
+
+module("Integration | ui-kit | dElement", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("a shortcut tag resolves to its dedicated wrapper", async function (assert) {
+ const Tag = dElement("ul");
+
+ await render(
+ <template>
+ <Tag class="probe">item</Tag>
+ </template>
+ );
+
+ assert.dom(".probe").hasTagName("ul");
+ });
+
+ test("an unlisted tag falls back to a wrapper for that tag", async function (assert) {
+ const Tag = dElement("section");
+
+ await render(
+ <template>
+ <Tag class="probe">item</Tag>
+ </template>
+ );
+
+ assert.dom(".probe").hasTagName("section");
+ });
+
+ // The shortcut table is a plain object, so a bare property read reaches
+ // `Object.prototype`. A tag name that collides with an inherited member must
+ // still take the fallback path rather than resolving to that member.
+ //
+ // Asserted on the resolved value rather than by rendering it: an inherited
+ // member is not a component, so rendering one throws past the test and takes
+ // the rest of the run with it.
+ test("a tag named after an inherited Object member takes the fallback", function (assert) {
+ for (const tagName of [
+ "constructor",
+ "toString",
+ "valueOf",
+ "hasOwnProperty",
+ ]) {
+ assert.notStrictEqual(
+ dElement(tagName),
+ Object.prototype[tagName],
+ `dElement("${tagName}") does not resolve to the inherited member`
+ );
+ }
+
+ assert.strictEqual(
+ dElement("constructor"),
+ dElement("constructor"),
+ "and the fallback for it is still cached by tag name"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/anchoring-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/anchoring-test.gjs
new file mode 100644
index 00000000000..af40435fd8b
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/anchoring-test.gjs
@@ -0,0 +1,300 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ findAll,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+function renderedIndices() {
+ return findAll(".d-virtual-list__item").map((element) =>
+ Number(element.dataset.index)
+ );
+}
+
+function renderedPositions() {
+ return findAll(".d-virtual-list__item").map((element) =>
+ Number(element.getAttribute("aria-posinset"))
+ );
+}
+
+function isStrictlyAscending(values) {
+ return values.every(
+ (value, index) => index === 0 || values[index - 1] < value
+ );
+}
+
+module("Integration | ui-kit | DVirtualList | anchoring", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("initialIndex defaults to start alignment", async function (assert) {
+ const items = buildRows(1000);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @initialIndex={{500}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ renderedIndices()[0],
+ 500,
+ "the initial index is the first rendered row"
+ );
+ });
+
+ for (const [align, expectedScrollTop] of [
+ ["start", 20_000],
+ ["center", 19_820],
+ ["end", 19_640],
+ ["auto", 19_640],
+ ]) {
+ test(`initialAlign=${align} positions the initial row`, async function (assert) {
+ const items = buildRows(1000);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @initialIndex={{500}}
+ @initialAlign={{align}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ find(".d-virtual-list").scrollTop,
+ expectedScrollTop,
+ `row 500 uses ${align} alignment in the 400px viewport`
+ );
+ });
+ }
+
+ test("initial positioning runs only once", async function (assert) {
+ const state = new State(buildRows(1000));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @initialIndex={{500}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ renderedIndices()[0],
+ 500,
+ "the initial positioning starts the window at row 500"
+ );
+
+ await scrollTo(0);
+ state.items = buildRows(1000);
+ await settled();
+
+ assert
+ .dom(".d-virtual-list__item[data-index='0']")
+ .exists("a fresh item array leaves the user at the top");
+ assert
+ .dom(".d-virtual-list__item[data-index='500']")
+ .doesNotExist(
+ "a fresh item array does not re-apply the initial position"
+ );
+ });
+
+ test("an off-window pinned row stays mounted in ascending DOM order", async function (assert) {
+ const items = buildRows(100);
+ const pinFirst = () => [0];
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @itemRole="option"
+ @pinnedIndices={{pinFirst}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 100);
+
+ const indices = renderedIndices();
+ const positions = renderedPositions();
+
+ assert
+ .dom(".d-virtual-list__item[data-index='0']")
+ .exists("the pinned row remains mounted outside the visible window");
+ assert.strictEqual(
+ indices[0],
+ 0,
+ "the pinned row precedes the bottom window in DOM order"
+ );
+ assert.true(
+ isStrictlyAscending(indices),
+ `rendered data-index values are strictly ascending (${indices.join(", ")})`
+ );
+ assert.true(
+ isStrictlyAscending(positions),
+ `rendered aria-posinset values are strictly ascending (${positions.join(", ")})`
+ );
+ });
+
+ test("a pinned row inside the visible window is not duplicated", async function (assert) {
+ const items = buildRows(100);
+ const pinFifth = () => [5];
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @pinnedIndices={{pinFifth}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item[data-index='5']")
+ .exists(
+ { count: 1 },
+ "the visible pinned row has exactly one DOM instance"
+ );
+ });
+
+ test("a null pinnedIndices callback renders no extra off-window row", async function (assert) {
+ const items = buildRows(100);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @pinnedIndices={{null}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 100);
+
+ assert
+ .dom(".d-virtual-list__item[data-index='0']")
+ .doesNotExist("no off-window row is added when pinnedIndices is null");
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/api-surface-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/api-surface-test.gjs
new file mode 100644
index 00000000000..4fe3e981abd
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/api-surface-test.gjs
@@ -0,0 +1,415 @@
+import { find, findAll, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+function scroller() {
+ return find(".d-virtual-list");
+}
+
+function renderedIndices() {
+ return findAll(".d-virtual-list__item").map((element) =>
+ Number(element.dataset.index)
+ );
+}
+
+async function renderList(items, onRegisterApi) {
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+}
+
+module("Integration | ui-kit | DVirtualList | API surface", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("API surface pin: visibleRange is undefined before an empty list is measured", async function (assert) {
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList([], onRegisterApi);
+
+ assert.strictEqual(
+ api.visibleRange(),
+ undefined,
+ "an empty list has no visible range before measurement"
+ );
+ });
+
+ for (const [label, dataIndex] of [
+ ["an empty data-index", ""],
+ ["a malformed data-index", "not-an-index"],
+ ["an out-of-range data-index", "100"],
+ ]) {
+ test(`API surface pin: measureElement ignores ${label}`, async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const rangeBeforeMeasurement = { ...api.visibleRange() };
+ const windowBeforeMeasurement = renderedIndices();
+ const warn = sinon.stub(console, "warn");
+ const foreignElement = document.createElement("div");
+ foreignElement.dataset.index = dataIndex;
+ foreignElement.style.height = `${ROW_PX * 2}px`;
+ scroller().append(foreignElement);
+ let thrown;
+
+ try {
+ api.measureElement(foreignElement);
+ } catch (error) {
+ thrown = error;
+ }
+ await settled();
+
+ assert.strictEqual(thrown, undefined, `${label} does not throw`);
+ assert.false(
+ warn.called,
+ `${label} is rejected without an engine warning`
+ );
+ assert.deepEqual(
+ api.visibleRange(),
+ rangeBeforeMeasurement,
+ `${label} does not disturb the visible range`
+ );
+ assert.deepEqual(
+ renderedIndices(),
+ windowBeforeMeasurement,
+ `${label} does not disturb the rendered window`
+ );
+ });
+ }
+
+ test("API surface pin: measureElement ignores an untyped non-HTMLElement", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const rangeBeforeMeasurement = { ...api.visibleRange() };
+ const windowBeforeMeasurement = renderedIndices();
+ const warn = sinon.stub(console, "warn");
+ let thrown;
+
+ try {
+ api.measureElement({});
+ } catch (error) {
+ thrown = error;
+ }
+ await settled();
+
+ assert.strictEqual(
+ thrown,
+ undefined,
+ "an untyped non-HTMLElement does not throw"
+ );
+ assert.false(
+ warn.called,
+ "an untyped non-HTMLElement is rejected without an engine warning"
+ );
+ assert.deepEqual(
+ api.visibleRange(),
+ rangeBeforeMeasurement,
+ "an untyped non-HTMLElement does not disturb the visible range"
+ );
+ assert.deepEqual(
+ renderedIndices(),
+ windowBeforeMeasurement,
+ "an untyped non-HTMLElement does not disturb the rendered window"
+ );
+ });
+
+ test("API surface pin: measureElement forwards an unregistered valid row", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const unregisteredIndex = api.visibleRange().endIndex + 1;
+ const totalBeforeMeasurement = parseFloat(
+ find(".d-virtual-list__sizer").style.height
+ );
+ const unregisteredRow = document.createElement("div");
+ unregisteredRow.dataset.index = String(unregisteredIndex);
+ unregisteredRow.style.height = `${ROW_PX * 2}px`;
+ scroller().append(unregisteredRow);
+
+ assert.false(
+ renderedIndices().includes(unregisteredIndex),
+ "precondition: the valid row was not registered by the row modifier"
+ );
+
+ api.measureElement(unregisteredRow);
+ await settled();
+
+ assert.strictEqual(
+ parseFloat(find(".d-virtual-list__sizer").style.height),
+ totalBeforeMeasurement + ROW_PX,
+ "the public method forwards the row's measured growth to the engine"
+ );
+ });
+
+ test("API surface pin: visibleRange is an immutable snapshot", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const exposedRange = api.visibleRange();
+ const rangeBeforeMutation = { ...exposedRange };
+ const windowBeforeMutation = renderedIndices();
+ const replacementStart = exposedRange.endIndex + 1;
+
+ assert.true(
+ Object.isFrozen(exposedRange),
+ "the public range object is frozen"
+ );
+ assert.throws(
+ () => (exposedRange.startIndex = replacementStart),
+ TypeError,
+ "attempting to mutate the range is rejected"
+ );
+ assert.deepEqual(
+ renderedIndices(),
+ windowBeforeMutation,
+ "the mutation attempt does not change the rendered window"
+ );
+ assert.deepEqual(
+ api.visibleRange(),
+ rangeBeforeMutation,
+ "a later range read retains the committed indices"
+ );
+ });
+
+ test("API surface pin: measureElement ignores an element without data-index", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const rangeBeforeMeasurement = { ...api.visibleRange() };
+ const windowBeforeMeasurement = renderedIndices();
+ const warn = sinon.stub(console, "warn");
+ const foreignElement = document.createElement("div");
+ foreignElement.style.position = "absolute";
+ foreignElement.style.height = `${ROW_PX * 2}px`;
+ scroller().append(foreignElement);
+
+ api.measureElement(foreignElement);
+ await settled();
+
+ assert.false(
+ warn.called,
+ "an unindexed element is rejected before reaching the engine"
+ );
+ assert.deepEqual(
+ api.visibleRange(),
+ rangeBeforeMeasurement,
+ "the foreign element does not disturb the visible range"
+ );
+ assert.deepEqual(
+ renderedIndices(),
+ windowBeforeMeasurement,
+ "the foreign element does not disturb the rendered window"
+ );
+
+ const measuredRow = find(".d-virtual-list__item");
+ const rowContent = measuredRow.querySelector(".row");
+ const heightBeforeResize = measuredRow.offsetHeight;
+ const totalBeforeResize = parseFloat(
+ find(".d-virtual-list__sizer").style.height
+ );
+ const resizeDelivered = new Promise((resolve) => {
+ const observer = new ResizeObserver(() => {
+ observer.disconnect();
+ resolve();
+ });
+ observer.observe(measuredRow, { box: "border-box" });
+ });
+ rowContent.style.height = `${heightBeforeResize + ROW_PX / 2}px`;
+ await resizeDelivered;
+ await settled();
+
+ const measuredGrowth = measuredRow.offsetHeight - heightBeforeResize;
+ assert.strictEqual(
+ parseFloat(find(".d-virtual-list__sizer").style.height),
+ totalBeforeResize + measuredGrowth,
+ "a real row still updates the measurement cache afterwards"
+ );
+ });
+
+ test("API surface pin: scrollToOffset moves the rendered window", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const measuredRowHeight = find(".d-virtual-list__item").offsetHeight;
+ const targetIndex = api.visibleRange().endIndex + 5;
+ const targetOffset = targetIndex * measuredRowHeight;
+
+ api.scrollToOffset(targetOffset);
+ await settled();
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ targetOffset,
+ "the viewport moves to the requested measured offset"
+ );
+ assert.strictEqual(
+ api.visibleRange().startIndex,
+ targetIndex,
+ "the visible range starts with the row at that offset"
+ );
+ assert.true(
+ renderedIndices().includes(targetIndex),
+ "the row at the requested offset is mounted"
+ );
+ });
+
+ test("API surface pin: scrollToEdge start returns a scrolled list to the top", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ api.scrollToEdge("end");
+ await settled();
+
+ assert.true(
+ api.visibleRange().startIndex > 0,
+ "precondition: the list is scrolled away from the start"
+ );
+
+ api.scrollToEdge("start");
+ await settled();
+
+ assert.strictEqual(scroller().scrollTop, 0, "the viewport returns to zero");
+ assert.strictEqual(
+ api.visibleRange().startIndex,
+ 0,
+ "the visible range returns to the first row"
+ );
+ assert.true(
+ renderedIndices().includes(0),
+ "the first row is mounted again"
+ );
+ });
+
+ test("API surface pin: remeasureViewport immediately adopts a new height", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const viewport = scroller();
+ const measuredRowHeight = find(".d-virtual-list__item").offsetHeight;
+ const newViewportHeight = viewport.offsetHeight + measuredRowHeight * 3;
+ viewport.style.height = `${newViewportHeight}px`;
+
+ assert.strictEqual(
+ viewport.offsetHeight,
+ newViewportHeight,
+ "precondition: layout exposes the new viewport height"
+ );
+
+ api.remeasureViewport();
+ await settled();
+
+ const expectedVisibleRows = Math.ceil(
+ newViewportHeight / measuredRowHeight
+ );
+ assert.strictEqual(
+ api.visibleRange().endIndex - api.visibleRange().startIndex + 1,
+ expectedVisibleRows,
+ "the visible range uses the new viewport height"
+ );
+ assert.strictEqual(
+ renderedIndices().length,
+ expectedVisibleRows,
+ "the list mounts exactly the rows implied by the new height"
+ );
+ });
+
+ test("API surface pin: isScrolling is false at rest", async function (assert) {
+ const items = buildRows(100);
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ assert.strictEqual(
+ typeof api.isScrolling,
+ "boolean",
+ "isScrolling exposes a boolean"
+ );
+ assert.false(api.isScrolling, "the list reports that it is idle at rest");
+ });
+
+ test("API surface pin: scrollToEdge is inert for an empty list", async function (assert) {
+ const items = [];
+ let api;
+ const onRegisterApi = (value) => (api = value);
+
+ await renderList(items, onRegisterApi);
+
+ const scrollTopBefore = scroller().scrollTop;
+ api.scrollToEdge("start");
+ api.scrollToEdge("end");
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ scrollTopBefore,
+ "both edge requests remain harmless no-ops"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/container-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/container-test.gjs
new file mode 100644
index 00000000000..78286891223
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/container-test.gjs
@@ -0,0 +1,181 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const COUNT = 100;
+
+const estimate = () => ROW_PX;
+const emptyItems = [];
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+class State {
+ @tracked as = "div";
+}
+
+function sizerHeight() {
+ const sizer = find(".d-virtual-list__sizer");
+ return sizer ? parseFloat(sizer.style.height) : null;
+}
+
+module("Integration | ui-kit | DVirtualList | container", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // `dElement` treats an empty tag name as a pass-through that renders no element
+ // at all. The sizer is that element, so an empty `@as` leaves the modifier with
+ // nothing to size, no scroll range, and rows resolving their offsets against
+ // whatever positioned ancestor happens to exist. Silent, total layout failure.
+ test("container fallback: an empty @as still renders a sizer", async function (assert) {
+ const items = buildRows(COUNT);
+ const blank = "";
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @as={{blank}}
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__sizer")
+ .exists("the sizer element is rendered");
+ assert.true(
+ sizerHeight() > 0,
+ `the sizer carries the engine's height (${sizerHeight()}px)`
+ );
+ });
+
+ // `@as` is not an argument to the modifier, so changing it swaps the sizer for a
+ // fresh element that no flush is scheduled to size. Treating it as mount-time
+ // keeps the engine's geometry on an element that cannot be swapped underneath it.
+ test("container fallback: changing @as after mount keeps the sized container", async function (assert) {
+ const items = buildRows(COUNT);
+ const state = new State();
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @as={{state.as}}
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const heightBefore = sizerHeight();
+ assert.true(heightBefore > 0, "precondition: the sizer starts sized");
+
+ state.as = "ul";
+ await settled();
+
+ assert.true(
+ sizerHeight() > 0,
+ `the sizer is still sized after @as changes (${sizerHeight()}px)`
+ );
+ });
+
+ // A roled container has a content model. `listbox` owns options, `list` owns
+ // listitems; arbitrary empty-state markup as a direct child is neither, and with
+ // `@as="ul"` it is invalid HTML as well.
+ test("container fallback: the empty block is not a direct child of the roled container", async function (assert) {
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{emptyItems}}
+ @as="ul"
+ @role="list"
+ @estimateSize={{estimate}}
+ >
+ <:default as |item|><div class="row">{{item.text}}</div></:default>
+ <:empty><p class="empty-message">Nothing here yet</p></:empty>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.dom(".empty-message").exists("the empty block renders");
+ assert
+ .dom(".d-virtual-list__sizer > .empty-message")
+ .doesNotExist(
+ "the consumer's empty markup is not an owned child of the roled container"
+ );
+ });
+
+ // The most likely first-run mistake, and silent: the viewport's height belongs to
+ // the consumer, and without one the window computes to nothing and the list draws
+ // no rows, with no error to explain it.
+ test("container fallback: a zero-height viewport warns in development", async function (assert) {
+ const items = buildRows(COUNT);
+ const warn = sinon.stub(console, "warn");
+
+ await render(
+ <template>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ warn.calledWithMatch(/d-virtual-list/i),
+ "a zero-height viewport is reported rather than silently rendering nothing"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/deep-scroll-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/deep-scroll-test.gjs
new file mode 100644
index 00000000000..9a90d836149
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/deep-scroll-test.gjs
@@ -0,0 +1,101 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 44;
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `Row ${index}`,
+ }));
+}
+
+function styledCount() {
+ return [...document.querySelectorAll(".d-virtual-list__item")].filter(
+ (el) => el.style.transform && el.style.position === "absolute"
+ ).length;
+}
+
+function unstyled() {
+ return [...document.querySelectorAll(".d-virtual-list__item")]
+ .filter((el) => !el.style.transform || el.style.position !== "absolute")
+ .map((el) => el.dataset.index);
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | deep scroll", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("rows keep their absolute positioning across a keyed re-render", async function (assert) {
+ const state = new State(buildRows(10000));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @role="list"
+ @itemRole="listitem"
+ as |row|
+ >
+ <div style="height: 44px">{{row.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(1500 * ROW_PX);
+ assert.true(styledCount() > 0, "rows are positioned after scrolling deep");
+
+ // A keyed re-render (same ids, fresh objects) reuses the row elements but
+ // churns the per-row positioning modifier: destroy old + install new on the
+ // SAME element. If the destroy runs last, its cleanup strips the styles the
+ // new modifier just wrote.
+ for (let i = 0; i < 5; i++) {
+ state.items = state.items.map((row) => ({ ...row }));
+ await settled();
+ }
+
+ assert.strictEqual(
+ unstyled().length,
+ 0,
+ `every mounted row keeps its absolute translate (lost: ${unstyled().join(", ")})`
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-arm-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-arm-test.gjs
new file mode 100644
index 00000000000..8e336d845c6
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-arm-test.gjs
@@ -0,0 +1,257 @@
+import { clearRender, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, id) => ({
+ id,
+ text: `row ${id}`,
+ }));
+}
+
+module("Integration | ui-kit | DVirtualList | edge arm", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("edge-arm API retries a failed end fetch without changing items", async function (assert) {
+ const items = buildRows(5);
+ let api;
+ let endFires = 0;
+ let fetchAttempts = 0;
+ const onRegisterApi = (value) => (api = value);
+ const fetchNextPage = async () => {
+ fetchAttempts++;
+ throw new Error("the page fetch failed");
+ };
+ const onReachEnd = () => {
+ endFires++;
+ void fetchNextPage().catch(() => {});
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachEnd={{onReachEnd}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.deepEqual(
+ api.visibleRange(),
+ { startIndex: 0, endIndex: items.length - 1 },
+ "precondition: the whole short list remains in the end band"
+ );
+ assert.strictEqual(endFires, 1, "the end edge fires once on mount");
+ assert.strictEqual(fetchAttempts, 1, "the first edge fire starts a fetch");
+
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ 1,
+ "the failed fetch leaves identical items and does not re-arm automatically"
+ );
+
+ api.armEdge("end");
+
+ assert.strictEqual(endFires, 1, "arming does not fire synchronously");
+
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ 2,
+ "the next edge evaluation retries while the range is still in the band"
+ );
+ assert.strictEqual(fetchAttempts, 2, "the retry starts a second fetch");
+ });
+
+ test("edge-arm API re-arms only the requested edge", async function (assert) {
+ const items = buildRows(5);
+ let api;
+ let endFires = 0;
+ let startFires = 0;
+ const onRegisterApi = (value) => (api = value);
+ const onReachEnd = () => endFires++;
+ const onReachStart = () => startFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachEnd={{onReachEnd}}
+ @onReachStart={{onReachStart}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.deepEqual(
+ api.visibleRange(),
+ { startIndex: 0, endIndex: items.length - 1 },
+ "precondition: the range overlaps both edge bands"
+ );
+ assert.strictEqual(endFires, 1, "the end latch is satisfied on mount");
+ assert.strictEqual(
+ startFires,
+ 0,
+ "the start callback is suppressed on mount"
+ );
+
+ api.armEdge("start");
+
+ assert.strictEqual(startFires, 0, "arming does not fire synchronously");
+
+ await settled();
+
+ assert.strictEqual(
+ startFires,
+ 1,
+ "the armed start edge fires on evaluation"
+ );
+ assert.strictEqual(
+ endFires,
+ 1,
+ "arming the start edge does not re-arm the end edge"
+ );
+ });
+
+ test("edge-arm API is safe before initial evaluation and after destruction", async function (assert) {
+ const items = buildRows(5);
+ let api;
+ let endFires = 0;
+ const onReachEnd = () => endFires++;
+ const onRegisterApi = (value) => {
+ api = value;
+ api.armEdge("end");
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachEnd={{onReachEnd}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ endFires,
+ 1,
+ "arming before the initial evaluation does not duplicate its edge fire"
+ );
+
+ await clearRender();
+
+ api.armEdge("start");
+ api.armEdge("end");
+ });
+
+ test("edge-arm API ignores synchronous self-rearming", async function (assert) {
+ const items = buildRows(5);
+ let api;
+ let endFires = 0;
+ const onRegisterApi = (value) => (api = value);
+ const onReachEnd = () => {
+ endFires++;
+
+ if (endFires < 3) {
+ api.armEdge("end");
+ }
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachEnd={{onReachEnd}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.deepEqual(
+ api.visibleRange(),
+ { startIndex: 0, endIndex: items.length - 1 },
+ "precondition: the whole short list remains in the end band"
+ );
+
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ 1,
+ "synchronously re-arming an executing edge callback is ignored"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-hysteresis-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-hysteresis-test.gjs
new file mode 100644
index 00000000000..88f32fc223f
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-hysteresis-test.gjs
@@ -0,0 +1,112 @@
+import { find, render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+const COUNT = 100;
+const THRESHOLD = 8;
+
+// endBand is the first index inside the end band, and the latch only re-arms once
+// the range retreats a further EDGE_HYSTERESIS rows past it. Both are derived so
+// the fixture states the arithmetic it depends on.
+const END_BAND = COUNT - 1 - THRESHOLD;
+const VISIBLE_ROWS = VIEWPORT_PX / ROW_PX;
+
+// The scrollTop whose last visible row is `index`.
+function scrollTopForEndIndex(index) {
+ return (index + 1 - VISIBLE_ROWS) * ROW_PX;
+}
+
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+// Supplemental coverage for the anti-jitter gap, which the oracle in
+// edges-test.gjs does not pin: every retreat there overshoots the gap, so the
+// whole suite passes with EDGE_HYSTERESIS set to 0.
+module(
+ "Integration | ui-kit | DVirtualList | edge hysteresis",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a retreat inside the gap does not re-arm the end edge", async function (assert) {
+ const items = buildRows(COUNT);
+ const calls = [];
+ const onReachEnd = () => calls.push(true);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @edgeThreshold={{THRESHOLD}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(calls.length, 0, "the top of the list is not the end");
+
+ await scrollTo(scrollTopForEndIndex(COUNT - 1));
+ assert.strictEqual(calls.length, 1, "reaching the end fires once");
+
+ // One row back from the band. Inside the gap, so the latch must hold: this
+ // is the jitter case, where a reader nudging the scrollbar at the boundary
+ // would otherwise re-fire the consumer's fetch on every wobble.
+ await scrollTo(scrollTopForEndIndex(END_BAND - 1));
+ await scrollTo(scrollTopForEndIndex(COUNT - 1));
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "a retreat that stays inside the gap does not re-arm"
+ );
+
+ // Past the gap now, so the latch clears and the next arrival fires again.
+ await scrollTo(scrollTopForEndIndex(END_BAND - THRESHOLD));
+ await scrollTo(scrollTopForEndIndex(COUNT - 1));
+
+ assert.strictEqual(
+ calls.length,
+ 2,
+ "a retreat beyond the gap re-arms, and returning fires again"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-rearm-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-rearm-test.gjs
new file mode 100644
index 00000000000..97fdc497157
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-rearm-test.gjs
@@ -0,0 +1,331 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+
+// The default edge threshold is 8 rows and the hysteresis is 4, so an append
+// smaller than 13 rows never retreats the range past the re-arm band. A page of
+// 10 is the realistic case a paging consumer ships.
+const PAGE = 10;
+
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+
+ append(count) {
+ const from = this.items.length;
+ this.items = [...this.items, ...buildRows(count, from)];
+ }
+
+ prepend(count) {
+ this.items = [...buildRows(count, -count), ...this.items];
+ }
+
+ replaceWith(count) {
+ this.items = buildRows(count, 10_000);
+ }
+}
+
+function buildRows(count, from = 0) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: from + index,
+ text: `row ${from + index}`,
+ }));
+}
+
+function scroller() {
+ return find(".d-virtual-list");
+}
+
+async function scrollTo(top) {
+ const element = scroller();
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | edge re-arm", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("onReachEnd fires again after a page smaller than the hysteresis band", async function (assert) {
+ const state = new State(buildRows(100));
+ let endFires = 0;
+ const onReachEnd = () => endFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ assert.strictEqual(endFires, 1, "precondition: the end edge fired once");
+
+ state.append(PAGE);
+ await settled();
+ await scrollTo(110 * ROW_PX - VIEWPORT_PX);
+
+ assert.strictEqual(
+ endFires,
+ 2,
+ "reaching the new end after a 10-row page fires the end edge again"
+ );
+ });
+
+ test("an append does not re-arm the start edge", async function (assert) {
+ const state = new State(buildRows(100));
+ let startFires = 0;
+ const onReachStart = () => startFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachStart={{onReachStart}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ startFires,
+ 0,
+ "precondition: mount at the top is suppressed"
+ );
+
+ state.append(PAGE);
+ await settled();
+
+ assert.strictEqual(
+ startFires,
+ 0,
+ "a tail-only change must not unlatch the start edge"
+ );
+ });
+
+ test("a wholesale replacement re-arms the end edge for the new list", async function (assert) {
+ const state = new State(buildRows(100));
+ let endFires = 0;
+ const onReachEnd = () => endFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ assert.strictEqual(endFires, 1, "precondition: the end edge fired once");
+
+ // A short replacement list whose window already reaches its end: the latch
+ // from the previous list must not suppress the new list's first fire.
+ state.replaceWith(12);
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ 2,
+ "a replaced list fires its own end edge rather than inheriting the old latch"
+ );
+ });
+
+ test("an in-place refresh of the same rows does not re-arm either edge", async function (assert) {
+ // No `@key`, so rows key by object identity and a refresh hands both
+ // boundaries brand new keys for the very same rows. Re-arming on that turns
+ // one edge callback into an endless chain: the consumer answers by
+ // refreshing, the boundary key changes, the range is still in the band.
+ const state = new State(buildRows(100));
+ let endFires = 0;
+ let startFires = 0;
+ const onReachEnd = () => endFires++;
+ const onReachStart = () => startFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ @onReachStart={{onReachStart}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ assert.strictEqual(endFires, 1, "precondition: the end edge fired once");
+
+ // Same length, same logical rows, fresh objects.
+ state.items = buildRows(100);
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ 1,
+ "a same-length refresh does not re-fire the end edge"
+ );
+ assert.strictEqual(startFires, 0, "and does not arm the start edge either");
+ });
+
+ test("replacing the only row of a single-item list arms nothing", async function (assert) {
+ const state = new State(buildRows(1));
+ let endFires = 0;
+ let startFires = 0;
+ const onReachEnd = () => endFires++;
+ const onReachStart = () => startFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ @onReachStart={{onReachStart}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const endAfterMount = endFires;
+ state.items = buildRows(1);
+ await settled();
+
+ assert.strictEqual(
+ endFires,
+ endAfterMount,
+ "the one row is both boundaries, so replacing it must not fire the end edge"
+ );
+ assert.strictEqual(startFires, 0, "nor the start edge");
+ });
+
+ test("a prepend re-arms the start edge", async function (assert) {
+ const state = new State(buildRows(100));
+ let startFires = 0;
+ const onReachStart = () => startFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachStart={{onReachStart}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // Move away from the start band so the latch is genuinely re-armed by the
+ // head change rather than by a retreat.
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ assert.strictEqual(
+ startFires,
+ 0,
+ "precondition: never entered the start band"
+ );
+
+ state.prepend(PAGE);
+ await settled();
+ await scrollTo(0);
+
+ assert.strictEqual(
+ startFires,
+ 1,
+ "returning to the head of a prepended list fires the start edge"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-threshold-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-threshold-test.gjs
new file mode 100644
index 00000000000..6ef1dd55506
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edge-threshold-test.gjs
@@ -0,0 +1,186 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+class Config {
+ @tracked threshold;
+
+ constructor(threshold) {
+ this.threshold = threshold;
+ }
+}
+
+// Supplemental regression coverage for a review finding NOT pinned by the
+// decorrelated oracle (edges-test.gjs): a runtime change to
+// @edgeThreshold must re-arm the edge latches. Kept in a separate file so the
+// oracle stays the untouched spec.
+module(
+ "Integration | ui-kit | DVirtualList | edge threshold reactivity",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("narrowing @edgeThreshold at runtime re-arms the end edge", async function (assert) {
+ const items = buildRows(100);
+ const calls = [];
+ const onReachEnd = (range) => calls.push(range);
+ // A wide threshold makes the top of the list already sit in the end band
+ // (endBand = 99 - 90 = 9), so mount fires once and latches the end edge.
+ const config = new Config(90);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @edgeThreshold={{config.threshold}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "a threshold spanning the whole list reaches the end on mount"
+ );
+
+ // The visible range does not move, but the end band narrows to the last
+ // eight rows. The narrowed threshold must re-arm the latch even though no
+ // scroll (and so no rendering-signature change) accompanies it.
+ config.threshold = 8;
+ await settled();
+
+ // Jump straight to the true end, past any range that would have re-armed
+ // the latch incidentally. With the latch correctly re-armed by the
+ // threshold change, entering the narrow end band fires again.
+ await scrollTo(ROW_PX * 100);
+
+ assert.strictEqual(
+ calls.length,
+ 2,
+ "after narrowing the threshold, reaching the true end re-fires"
+ );
+ });
+
+ // A threshold is arithmetic on an index, so a non-finite one makes every band
+ // comparison false and the edge silently never fires again. The sibling
+ // numeric argument @overscan is normalized for the same reason.
+ test("a non-finite @edgeThreshold falls back to the default", async function (assert) {
+ const items = buildRows(100);
+ const calls = [];
+ const onReachEnd = (range) => calls.push(range);
+ const config = new Config(NaN);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @edgeThreshold={{config.threshold}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ calls.length,
+ 0,
+ "the end is not reached from the top of a 100 row list"
+ );
+
+ await scrollTo(ROW_PX * 100);
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "reaching the end still fires, so the threshold fell back to a usable one"
+ );
+ });
+
+ test("a negative @edgeThreshold falls back to a reachable band", async function (assert) {
+ const items = buildRows(100);
+ const calls = [];
+ const onReachEnd = (range) => calls.push(range);
+ const config = new Config(-5);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @edgeThreshold={{config.threshold}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 100);
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "a negative threshold cannot push the band out of reach"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edges-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edges-test.gjs
new file mode 100644
index 00000000000..cf0d66d025c
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/edges-test.gjs
@@ -0,0 +1,260 @@
+import { find, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | edges", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("visible-range changes ignore size-only remeasurement", async function (assert) {
+ const items = buildRows(100);
+ const ranges = [];
+ let api;
+ const onRegisterApi = (value) => (api = value);
+ const onVisibleRangeChange = (range) => ranges.push({ ...range });
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onVisibleRangeChange={{onVisibleRangeChange}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 20 + 10);
+
+ const countBeforeResize = ranges.length;
+ const rangeBeforeResize = api.visibleRange();
+ const measuredRow = find(
+ `.d-virtual-list__item[data-index='${rangeBeforeResize.startIndex + 2}']`
+ );
+ // Resolve on ANY delivery rather than on an exact height, then assert the
+ // height separately. Waiting for a specific number here turns a mismatch —
+ // adding padding to the row wrapper would be enough — into a test-timeout with
+ // no diagnostic, instead of a failed assertion that says what it measured.
+ const resizeDelivered = new Promise((resolve) => {
+ const observer = new ResizeObserver(() => {
+ observer.disconnect();
+ resolve();
+ });
+ observer.observe(measuredRow, { box: "border-box" });
+ });
+ measuredRow.querySelector(".row").style.height = "41px";
+ await resizeDelivered;
+ await settled();
+
+ assert.strictEqual(
+ measuredRow.offsetHeight,
+ 41,
+ "the row wrapper reports the height set on its content"
+ );
+
+ assert.deepEqual(
+ api.visibleRange(),
+ rangeBeforeResize,
+ "the resize leaves the visible start and end indices unchanged"
+ );
+ assert.strictEqual(
+ ranges.length,
+ countBeforeResize,
+ "a size-only remeasurement does not publish a visible-range change"
+ );
+
+ const countBeforeScroll = ranges.length;
+ await scrollTo(ROW_PX * 30 + 10);
+
+ assert.strictEqual(
+ ranges.length,
+ countBeforeScroll + 1,
+ "a scroll that changes the visible indices publishes once"
+ );
+ });
+
+ test("end edge fires once per entry and re-arms after retreat", async function (assert) {
+ const items = buildRows(100);
+ const calls = [];
+ let api;
+ const onRegisterApi = (value) => (api = value);
+ const onReachEnd = (range) => calls.push(range);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 81);
+ assert.strictEqual(
+ calls.length,
+ 0,
+ "the default threshold waits until the last eight rows"
+ );
+
+ await scrollTo(ROW_PX * 82);
+
+ assert.strictEqual(calls.length, 1, "entering the end band fires once");
+ assert.deepEqual(
+ calls[0],
+ { ...api.visibleRange(), count: items.length },
+ "the callback receives the visible range and item count"
+ );
+
+ await scrollTo(ROW_PX * 82 + 20);
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "continued scrolling within the end band does not re-fire"
+ );
+
+ await scrollTo(ROW_PX * 60);
+ await scrollTo(ROW_PX * 82);
+
+ assert.strictEqual(
+ calls.length,
+ 2,
+ "retreating beyond hysteresis re-arms the end edge"
+ );
+ });
+
+ test("start edge suppresses mount and fires after leaving and returning", async function (assert) {
+ const items = buildRows(100);
+ const calls = [];
+ let api;
+ const onRegisterApi = (value) => (api = value);
+ const onReachStart = (range) => calls.push(range);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @onRegisterApi={{onRegisterApi}}
+ @onReachStart={{onReachStart}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ calls.length,
+ 0,
+ "initial mount at offset zero is suppressed"
+ );
+
+ await scrollTo(ROW_PX * items.length);
+ await scrollTo(0);
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "returning to the start band fires once"
+ );
+ assert.deepEqual(
+ calls[0],
+ { ...api.visibleRange(), count: items.length },
+ "the callback receives the visible range and item count"
+ );
+ });
+
+ test("end edge fires on mount when the whole list fits", async function (assert) {
+ const items = buildRows(5);
+ const calls = [];
+ const onReachEnd = (range) => calls.push(range);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ calls.length,
+ 1,
+ "a fully visible list reaches the end on mount"
+ );
+ assert.deepEqual(
+ calls[0],
+ { startIndex: 0, endIndex: 4, count: 5 },
+ "the initial-fill callback describes the complete list"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/estimate-reactivity-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/estimate-reactivity-test.gjs
new file mode 100644
index 00000000000..4172fb7aa9c
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/estimate-reactivity-test.gjs
@@ -0,0 +1,118 @@
+import { tracked } from "@glimmer/tracking";
+import { find, findAll, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const COUNT = 500;
+const ROW_PX = 40;
+const FIRST_ESTIMATE = 40;
+const SECOND_ESTIMATE = 80;
+
+// Two distinct STABLE identities. An inline arrow would change identity on every
+// render, which busts the engine's memo for an unrelated reason and would hide
+// the defect under test.
+const estimateSmall = () => FIRST_ESTIMATE;
+const estimateLarge = () => SECOND_ESTIMATE;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+class State {
+ @tracked estimate = estimateSmall;
+}
+
+function sizerHeight() {
+ const sizer = find(".d-virtual-list__sizer");
+ return sizer ? parseFloat(sizer.style.height) : null;
+}
+
+function mountedRows() {
+ return findAll(".d-virtual-list__item");
+}
+
+module(
+ "Integration | ui-kit | DVirtualList | estimate reactivity",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a changed @estimateSize re-estimates unmeasured rows", async function (assert) {
+ // The SAME array instance across the change: the engine keys its measurement
+ // memo on the item-key function, which the modifier caches per items array.
+ // A fresh array would rebuild that function and invalidate the memo for a
+ // reason other than the estimate, so the defect would not surface.
+ const items = buildRows(COUNT);
+ const state = new State();
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ .row {
+ height: 40px;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{state.estimate}}
+ as |item|
+ >
+ <div class="row">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const before = sizerHeight();
+ assert.strictEqual(
+ before,
+ COUNT * FIRST_ESTIMATE,
+ `every row starts at the first estimate (${COUNT * FIRST_ESTIMATE}px)`
+ );
+
+ // Rows that mounted have a real measured height and keep it; only the rest
+ // fall back to the estimate. Derived here rather than hardcoded so the
+ // expectation survives a change in viewport height or overscan.
+ const measured = mountedRows().length;
+ const expected = measured * ROW_PX + (COUNT - measured) * SECOND_ESTIMATE;
+
+ state.estimate = estimateLarge;
+ await settled();
+
+ const after = sizerHeight();
+
+ assert.notStrictEqual(
+ after,
+ before,
+ "the total moves when the estimate changes"
+ );
+ assert.strictEqual(
+ after,
+ expected,
+ `unmeasured rows take the new estimate (${measured} measured at ${ROW_PX}px, ${
+ COUNT - measured
+ } estimated at ${SECOND_ESTIMATE}px)`
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/follow-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/follow-test.gjs
new file mode 100644
index 00000000000..34d00178d85
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/follow-test.gjs
@@ -0,0 +1,341 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ render,
+ settled,
+ triggerEvent,
+ waitUntil,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+const INITIAL_ROWS = 1000;
+const APPENDED_ROWS = 10;
+
+// Resting at the end of the initial list: the sizer is 1000 rows tall and the
+// viewport shows 400px of it.
+const INITIAL_END = INITIAL_ROWS * ROW_PX - VIEWPORT_PX;
+// Resting at the end once the appended page has been measured.
+const APPENDED_END = (INITIAL_ROWS + APPENDED_ROWS) * ROW_PX - VIEWPORT_PX;
+
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+
+ append(count) {
+ const from = this.items.length;
+ this.items = [
+ ...this.items,
+ ...Array.from({ length: count }, (_, offset) => ({
+ id: from + offset,
+ text: `row ${from + offset}`,
+ })),
+ ];
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+function scroller() {
+ return find(".d-virtual-list");
+}
+
+async function scrollTo(top) {
+ const element = scroller();
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+/**
+ * Waits for a scroll to come to rest.
+ *
+ * Order matters. The Ember commit is what STARTS the engine's reconcile loop, and
+ * that loop runs on `requestAnimationFrame`, outside the runloop, so `settled()`
+ * does not cover it. Waiting on frames first and settling afterwards is therefore
+ * backwards: the trailing settle can kick off the very reconciliation the frames
+ * were supposed to await, and the assertion samples an offset still in flight.
+ *
+ * @param expectedTop When given, the offset to wait for before checking stability.
+ */
+async function settleScroll(expectedTop) {
+ await settled();
+
+ if (expectedTop != null) {
+ await waitUntil(() => scroller().scrollTop === expectedTop, {
+ timeout: 2000,
+ });
+ }
+
+ // One stable frame lets the engine observe the position and drop its scroll state.
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ await settled();
+}
+
+module("Integration | ui-kit | DVirtualList | follow", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("anchor=bottom rests at the end on mount", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @anchor="bottom"
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll(INITIAL_END);
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ INITIAL_END,
+ "the list opens resting at the live edge"
+ );
+ });
+
+ test("anchor=bottom follows an append while resting at the end", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @anchor="bottom"
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll(INITIAL_END);
+ assert.strictEqual(
+ scroller().scrollTop,
+ INITIAL_END,
+ "precondition: resting at the live edge"
+ );
+
+ state.append(APPENDED_ROWS);
+ await settleScroll(APPENDED_END);
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ APPENDED_END,
+ "the viewport tracks the new live edge after the append"
+ );
+ assert
+ .dom(
+ `.d-virtual-list__item[data-index='${INITIAL_ROWS + APPENDED_ROWS - 1}']`
+ )
+ .exists("the newest row is mounted");
+ });
+
+ test("anchor=bottom does not follow an append while scrolled up", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+ const readingAt = 20_000;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @anchor="bottom"
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll();
+ await scrollTo(readingAt);
+ await settleScroll();
+
+ state.append(APPENDED_ROWS);
+ await settleScroll();
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ readingAt,
+ "a reader scrolled away from the end is not yanked to the new edge"
+ );
+ });
+
+ test("scrollEndThreshold widens the band that counts as following", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+ const nearEnd = INITIAL_END - 20;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @anchor="bottom"
+ @scrollEndThreshold={{50}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll();
+ await scrollTo(nearEnd);
+ await settleScroll();
+
+ state.append(APPENDED_ROWS);
+ await settleScroll(APPENDED_END);
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ APPENDED_END,
+ "a reader within the threshold of the end still follows"
+ );
+ });
+
+ test("without scrollEndThreshold the same near-end offset does not follow", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+ const nearEnd = INITIAL_END - 20;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @anchor="bottom"
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll();
+ await scrollTo(nearEnd);
+ await settleScroll();
+
+ state.append(APPENDED_ROWS);
+ await settleScroll();
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ nearEnd,
+ "the engine's 1px default keeps a 20px gap outside the follow band"
+ );
+ });
+
+ test("a top-anchored list never follows an append", async function (assert) {
+ const state = new State(buildRows(INITIAL_ROWS));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await settleScroll();
+ await scrollTo(INITIAL_END);
+ await settleScroll();
+
+ state.append(APPENDED_ROWS);
+ await settleScroll();
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ INITIAL_END,
+ "omitting @anchor leaves the viewport where the reader left it"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/index-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/index-test.gjs
new file mode 100644
index 00000000000..d822f70cda1
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/index-test.gjs
@@ -0,0 +1,479 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ findAll,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const estimate = () => 40;
+
+module("Integration | ui-kit | DVirtualList", function (hooks) {
+ setupRenderingTest(hooks);
+
+ // A rendering container has no real scroll height, so exercise the render-all
+ // fallback. Windowing-with-geometry is covered by the windowing module below.
+ hooks.beforeEach(function () {
+ disableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ enableVirtualization();
+ });
+
+ test("renders each item and wraps it in a measured row", async function (assert) {
+ const items = [
+ { id: 1, text: "one" },
+ { id: 2, text: "two" },
+ { id: 3, text: "three" },
+ ];
+
+ await render(
+ <template>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}} as |item|>
+ <span class="row">{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item")
+ .exists({ count: 3 }, "renders every item");
+ assert.dom(".row").exists({ count: 3 }, "all row content is rendered");
+ assert
+ .dom(".d-virtual-list__item:last-child .row")
+ .hasText("three", "items retain their backing-array order");
+ });
+
+ test("emits no ARIA position attributes without a row role", async function (assert) {
+ // aria-setsize/posinset are undefined on a bare div, so AT discards them.
+ // Emitting them unconditionally is noise, not accessibility.
+ const items = [{ id: 1, text: "one" }];
+
+ await render(
+ <template>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}} as |item|>
+ <span class="row">{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute("role", "the viewport has no implicit role");
+ assert
+ .dom(".d-virtual-list__item")
+ .doesNotHaveAttribute("role", "rows have no implicit role");
+ assert
+ .dom(".d-virtual-list__item")
+ .doesNotHaveAttribute(
+ "aria-setsize",
+ "set size is omitted without a role"
+ );
+ assert
+ .dom(".d-virtual-list__item")
+ .doesNotHaveAttribute(
+ "aria-posinset",
+ "position is omitted without a role"
+ );
+ });
+
+ test("threads listbox roles through with a true set size", async function (assert) {
+ // The listbox shape a select consumer needs. @role lands on the inner sizer
+ // container (the semantic element), and wrapped rows carry role=option as its
+ // direct children — no intervening presentation wrappers to break the required
+ // listbox->option ownership. The outer .d-virtual-list viewport stays role-less.
+ const items = [
+ { id: 1, text: "one" },
+ { id: 2, text: "two" },
+ { id: 3, text: "three" },
+ ];
+
+ await render(
+ <template>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @role="listbox"
+ @itemRole="option"
+ as |item|
+ >
+ <span class="row">{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute("role", "the viewport remains role-less");
+ assert
+ .dom(".d-virtual-list__sizer")
+ .hasAttribute("role", "listbox", "the inner container is the listbox");
+ assert
+ .dom(".d-virtual-list__item:first-child")
+ .hasAttribute("role", "option", "wrapped rows receive the item role");
+ assert
+ .dom(".d-virtual-list__item:first-child")
+ .hasAttribute("aria-posinset", "1", "position is absolute, not windowed");
+ assert
+ .dom(".d-virtual-list__item:first-child")
+ .hasAttribute("aria-setsize", "3", "set size is the true total");
+ });
+
+ test("yields the empty block when there are no items", async function (assert) {
+ const items = [];
+
+ await render(
+ <template>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}}>
+ <:default as |item|><span>{{item.text}}</span></:default>
+ <:empty><span class="empty">Nothing here</span></:empty>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.dom(".empty").hasText("Nothing here", "the empty block is yielded");
+ assert
+ .dom(".d-virtual-list__item")
+ .doesNotExist("no row wrapper is rendered");
+ });
+});
+
+const ROW_PX = 40;
+
+// Consumers hand DVirtualList a new array reference on change; this is the
+// smallest tracked holder that lets a test do the same.
+class State {
+ @tracked value;
+
+ constructor(value) {
+ this.value = value;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, i) => ({ id: i, text: `row ${i}` }));
+}
+
+function scroller() {
+ return find(".d-virtual-list");
+}
+
+// Setting scrollTop dispatches `scroll` asynchronously, and the bridge modifier
+// then schedules an afterRender flush. triggerEvent fires the event and awaits
+// settled(), collapsing both hops deterministically.
+async function scrollTo(top) {
+ const el = scroller();
+ el.scrollTop = top;
+ await triggerEvent(el, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | windowing", function (hooks) {
+ setupRenderingTest(hooks);
+
+ // Inverts the suite default: these tests need the real engine driving a real
+ // scroll container. Geometry comes from browser layout rather than stubs; the
+ // 0.5 scale on #ember-testing does not distort offsetHeight/borderBoxSize,
+ // which is all the windowing engine reads. The scroll viewport is the outer
+ // .d-virtual-list; it is sized via CSS, not `...attributes` (which route to the
+ // inner container).
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("renders only a window of a large list", async function (assert) {
+ const items = buildRows(1000);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}} as |item|>
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const rendered = findAll(".d-virtual-list__item").length;
+
+ assert.true(rendered > 0, "renders some rows");
+ assert.true(
+ rendered < 40,
+ `windows a small slice of 1000 rows (rendered ${rendered})`
+ );
+ assert
+ .dom(".d-virtual-list__sizer")
+ .hasStyle(
+ { height: `${ROW_PX * 1000}px` },
+ "the sizer spans the full list so the scrollbar is honest"
+ );
+ assert
+ .dom(".d-virtual-list__item:first-child")
+ .hasAttribute("data-index", "0", "window starts at the first row");
+ });
+
+ test("owned rows are stamped with data-index for measurement", async function (assert) {
+ // Row measurement identifies an item by its data-index, so an owned
+ // consumer that applies {{row.place}}/{{row.measure}} but does NOT set data-index
+ // itself must still get it — otherwise every row measures at index -1 and shares
+ // one bogus cache key. The modifiers stamp it; this pins that.
+ const items = buildRows(1000);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @as="ul"
+ @role="listbox"
+ @ownedRow={{true}}
+ as |item row|
+ >
+ {{! deliberately NO data-index attribute — the modifiers must supply it.
+ The listbox role is on the dElement-rendered container, which the
+ linter can't see through, so the option-in-listbox rule is disabled. }}
+ {{! eslint-disable ember/template-require-context-role }}
+ <li
+ class="row"
+ role="option"
+ style="height: 40px"
+ {{row.place row.start row.index}}
+ {{row.measure}}
+ >
+ {{item.text}}
+ </li>
+ </DVirtualList>
+ </template>
+ );
+
+ const owned = findAll(".row");
+ assert.true(owned.length > 0, "mounts a window of owned rows");
+ assert.true(
+ owned.every((el) => el.hasAttribute("data-index")),
+ "every owned row is stamped with data-index"
+ );
+ assert
+ .dom(".row")
+ .hasAttribute("data-index", "0", "first owned row is index 0");
+ });
+
+ test("scrolling advances the window and unmounts rows above it", async function (assert) {
+ const items = buildRows(1000);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}} as |item|>
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 500);
+
+ assert
+ .dom(".d-virtual-list__item[data-index='0']")
+ .doesNotExist("the first row is unmounted once scrolled away");
+
+ const first = find(".d-virtual-list__item");
+ const firstIndex = Number(first.getAttribute("data-index"));
+
+ assert.true(
+ firstIndex > 480,
+ `window advanced with the scroll (first mounted index ${firstIndex})`
+ );
+ assert.true(
+ firstIndex <= 500,
+ `window did not overshoot the scroll position (first mounted index ${firstIndex})`
+ );
+ });
+
+ test("re-syncing options with unchanged geometry does not republish state", async function (assert) {
+ // Guards the equality signature gate in d-virtualizer's #flush. Without it,
+ // getVirtualItems() returning a fresh array each call plus unconditional
+ // @tracked invalidation is itself a render loop.
+ //
+ // This must force a real modify() -> setOptions -> scheduled flush. Merely
+ // awaiting settled() after render proves nothing: render has already settled,
+ // so no engine callback fires and the assertion holds even with the gate removed.
+ const items = buildRows(200);
+ const state = new State(() => 40);
+ let ranges = 0;
+ const onVisibleRangeChange = () => ranges++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{state.value}}
+ @onVisibleRangeChange={{onVisibleRangeChange}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const baseline = ranges;
+
+ // A fresh function identity re-runs modify() and busts the engine's
+ // measurement memo, but every size is identical, so the published window is
+ // byte-for-byte the same and the gate must swallow it.
+ state.value = () => 40;
+ await settled();
+
+ assert.strictEqual(
+ ranges,
+ baseline,
+ "an options re-sync that changes no geometry publishes nothing"
+ );
+ });
+
+ test("prepending preserves the viewport position on a top-resting list", async function (assert) {
+ // Cursor-paginated sources have no total, so loading older content means
+ // genuinely inserting above the viewport. Without anchoring, every row the
+ // user is reading jumps down by the height of whatever arrived.
+ //
+ // The engine anchors by key across a count change, but gates that on
+ // anchorTo:"end" — which does NOT control resting position (it is consulted
+ // only at the prepend-anchor gate and the wasAtEnd resize branch), so a
+ // top-resting list can opt in without becoming bottom-anchored.
+ const state = new State(buildRows(200));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.value}}
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 50);
+
+ // Identify the row actually being read, and where it sits on screen.
+ // Asserting only that scrollTop moved by the prepended height proves
+ // arithmetic, not preservation: a broken key-to-item mapping could satisfy
+ // the number while swapping the content under the reader.
+ const anchorRow = find(".d-virtual-list__item");
+ const anchorText = anchorRow.querySelector(".row").textContent.trim();
+ const anchorTop = anchorRow.getBoundingClientRect().top;
+
+ const older = Array.from({ length: 100 }, (_, i) => ({
+ id: -100 + i,
+ text: `older ${i}`,
+ }));
+ state.value = [...older, ...state.value];
+ await settled();
+
+ const movedRow = findAll(".d-virtual-list__item").find(
+ (el) => el.querySelector(".row")?.textContent.trim() === anchorText
+ );
+
+ assert.strictEqual(
+ movedRow?.textContent.trim(),
+ anchorText,
+ "the row being read is still rendered after the prepend"
+ );
+ assert.strictEqual(
+ Math.round(movedRow.getBoundingClientRect().top),
+ Math.round(anchorTop),
+ "it holds its exact viewport position"
+ );
+ });
+
+ test("replacing an interior item republishes its key", async function (assert) {
+ // The published window pairs each virtual key with items[index]. Replacing an
+ // object strictly inside the window must change that row's key, or keyed row
+ // state stays attached to the previous object.
+ const state = new State(buildRows(1000));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.value}}
+ @estimateSize={{estimate}}
+ as |item row|
+ >
+ <div class="row" style="height: 40px" data-key={{row.key}}>
+ {{item.text}}
+ </div>
+ </DVirtualList>
+ </template>
+ );
+
+ const keyBefore = find(
+ ".d-virtual-list__item[data-index='5'] .row"
+ ).getAttribute("data-key");
+
+ const next = state.value.slice();
+ next[5] = { id: 5, text: "replaced" };
+ state.value = next;
+ await settled();
+
+ const keyAfter = find(
+ ".d-virtual-list__item[data-index='5'] .row"
+ ).getAttribute("data-key");
+
+ assert.notStrictEqual(
+ keyAfter,
+ keyBefore,
+ "a new object at an interior index publishes a new virtual key"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/inert-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/inert-test.gjs
new file mode 100644
index 00000000000..09fa38fcbbe
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/inert-test.gjs
@@ -0,0 +1,89 @@
+// Disabling virtualization must leave the render-all fallback active while making
+// every virtualizer callback inert.
+import { tracked } from "@glimmer/tracking";
+import { render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { disableVirtualization } from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const estimateSize = () => 40;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, id) => ({
+ id,
+ text: `row ${id}`,
+ }));
+}
+
+module("Integration | ui-kit | DVirtualList | inert", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("disabled virtualization renders all rows without invoking callbacks", async function (assert) {
+ disableVirtualization();
+
+ const state = new State(buildRows(5));
+ const calls = {
+ registerApi: 0,
+ reachEnd: 0,
+ reachStart: 0,
+ visibleRangeChange: 0,
+ };
+ const onRegisterApi = () => calls.registerApi++;
+ const onReachEnd = () => calls.reachEnd++;
+ const onReachStart = () => calls.reachStart++;
+ const onVisibleRangeChange = () => calls.visibleRangeChange++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimateSize}}
+ @onRegisterApi={{onRegisterApi}}
+ @onVisibleRangeChange={{onVisibleRangeChange}}
+ @onReachStart={{onReachStart}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ state.items = state.items.map((item) => ({
+ ...item,
+ text: `${item.text} replaced`,
+ }));
+ await settled();
+
+ assert.dom(".row").exists({ count: 5 }, "renders every fallback row");
+ assert.strictEqual(
+ calls.visibleRangeChange,
+ 0,
+ "does not publish a visible range"
+ );
+ assert.strictEqual(calls.reachEnd, 0, "does not report the end edge");
+ assert.strictEqual(calls.reachStart, 0, "does not report the start edge");
+ assert.strictEqual(calls.registerApi, 0, "does not register an API");
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/lifecycle-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/lifecycle-test.gjs
new file mode 100644
index 00000000000..3fa98b33d5e
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/lifecycle-test.gjs
@@ -0,0 +1,326 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ render,
+ resetOnerror,
+ settled,
+ setupOnerror,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+import dVirtualizer from "discourse/ui-kit/modifiers/d-virtualizer";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+class State {
+ @tracked items = buildRows(100);
+ @tracked estimate = estimate;
+ @tracked edgeThreshold = 8;
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | lifecycle", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // Emptying a list mid-scroll takes two engine-live branches nothing else
+ // reaches: the sizer's height is dropped entirely, and the edge latches plus
+ // the remembered boundary keys return to their mount state, so a refill can
+ // fire its end edge again.
+ test("lifecycle pin: emptying and refilling a list clears its height and re-arms its edges", async function (assert) {
+ const state = new State();
+ let endFires = 0;
+ const onReachEnd = () => endFires++;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ assert.true(
+ endFires > 0,
+ "precondition: the end edge fired while populated"
+ );
+ const firesWhilePopulated = endFires;
+
+ state.items = [];
+ await settled();
+
+ assert.dom(".d-virtual-list__item").doesNotExist("no rows remain");
+ assert.strictEqual(
+ find(".d-virtual-list__sizer").style.height,
+ "",
+ "the sizer drops its height rather than keeping the outgoing list's scroll range"
+ );
+
+ state.items = buildRows(12);
+ await settled();
+
+ assert.true(
+ endFires > firesWhilePopulated,
+ "the refilled list can fire its end edge again"
+ );
+ });
+
+ // NOT COVERED: the mount-rollback invariant (a mount whose `@estimateSize` throws
+ // must not be adopted, so a later update re-enters the mount branch and still
+ // registers the api). A test for it is possible to write but not to ship: the
+ // throw escapes from the after-render flush rather than from `render()`, so it
+ // cannot be caught at the call site and surfaces as a global error that aborts
+ // the rest of the suite. Pinning it needs a way to scope a global-error handler
+ // to one test, which this suite does not have today.
+
+ // The window memo is committed before the publish runs. If the publish throws,
+ // the memo has to be dropped: keeping it would match every later identical
+ // window and strand a mounted list on whatever it last drew.
+ test("lifecycle pin: a publish that throws does not strand the window", async function (assert) {
+ const state = new State();
+ const payloads = [];
+ let shouldThrow = true;
+ const onState = (payload) => {
+ if (shouldThrow) {
+ shouldThrow = false;
+ throw new Error("onState failed");
+ }
+ payloads.push(payload);
+ };
+
+ await render(
+ <template>
+ <div
+ class="viewport"
+ style="height: 400px; overflow-y: auto"
+ {{dVirtualizer
+ items=state.items
+ estimateSize=estimate
+ key="id"
+ edgeThreshold=state.edgeThreshold
+ onState=onState
+ }}
+ >
+ <div class="d-virtual-list__sizer"></div>
+ </div>
+ </template>
+ );
+
+ assert.strictEqual(
+ payloads.length,
+ 0,
+ "precondition: the first publish threw and delivered nothing"
+ );
+
+ // Re-run the modifier without moving the window, so the republish depends on
+ // the failed memo having been dropped rather than on the signature changing.
+ state.edgeThreshold = 4;
+ await settled();
+
+ assert.true(
+ payloads.length > 0,
+ "a later flush publishes the window despite the identical signature"
+ );
+ assert.true(
+ payloads.at(-1).virtualItems.length > 0,
+ "the recovered publish carries a real window"
+ );
+ });
+
+ // `@setSize` exists for a backing array that is a loaded prefix of a larger
+ // known set, where the array length undercounts the real total.
+ test("lifecycle pin: an explicit setSize overrides the item count", async function (assert) {
+ const items = buildRows(3);
+ const total = 500;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @role="listbox"
+ @itemRole="option"
+ @setSize={{total}}
+ as |item|
+ >
+ <span>{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item")
+ .hasAttribute(
+ "aria-setsize",
+ "500",
+ "the consumer's declared total wins over the backing array length"
+ );
+ });
+
+ test("lifecycle pin: setSize is omitted for a role that does not define it", async function (assert) {
+ const items = buildRows(3);
+ const total = 500;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @setSize={{total}}
+ as |item|
+ >
+ <span>{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item")
+ .doesNotHaveAttribute(
+ "aria-setsize",
+ "a row with no position-aware role carries no set size"
+ );
+ });
+
+ // ARIA's "unknown total" sentinel has no consistent screen reader support,
+ // so the primitive refuses it rather than letting it reach AT.
+ test("lifecycle pin: a negative setSize is refused rather than published", async function (assert) {
+ const consoleError = sinon.stub(console, "error");
+ const items = buildRows(3);
+ const unbounded = -1;
+ let errors = 0;
+
+ setupOnerror((error) => {
+ assert.true(
+ error.message.includes("omit `@setSize`"),
+ "the assertion tells the consumer what to do instead"
+ );
+ errors++;
+ });
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @role="listbox"
+ @itemRole="option"
+ @setSize={{unbounded}}
+ as |item|
+ >
+ <span>{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(errors, 1, "the sentinel is reported once");
+
+ resetOnerror();
+ consoleError.restore();
+ });
+
+ test("lifecycle pin: a setSize below the loaded count is floored to it", async function (assert) {
+ // A declared total the loaded rows already exceed would push aria-posinset
+ // past aria-setsize, so the loaded count wins.
+ const items = buildRows(3);
+ const staleTotal = 2;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @role="listbox"
+ @itemRole="option"
+ @setSize={{staleTotal}}
+ as |item|
+ >
+ <span>{{item.text}}</span>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item")
+ .hasAttribute(
+ "aria-setsize",
+ "3",
+ "no position can exceed the published set size"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/measurement-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/measurement-test.gjs
new file mode 100644
index 00000000000..6e464d7131a
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/measurement-test.gjs
@@ -0,0 +1,212 @@
+import { findAll, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ESTIMATE_PX = 40;
+const COUNT = 100;
+
+// Rows cycle through four DIFFERENT heights, none of them the estimate. Uniform
+// rows would let an implementation that reports one hardcoded height, or that
+// attributes a measurement to the wrong row, satisfy every assertion here.
+const HEIGHTS = [40, 65, 90, 115];
+
+const estimate = () => ESTIMATE_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ sizeClass: `row--h${index % HEIGHTS.length}`,
+ }));
+}
+
+function mountedRows() {
+ return findAll(".d-virtual-list__item").sort(
+ (a, b) => Number(a.dataset.index) - Number(b.dataset.index)
+ );
+}
+
+module("Integration | ui-kit | DVirtualList | measurement", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("measured rows grow the total beyond the estimated one", async function (assert) {
+ const items = buildRows(COUNT);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ .row--h0 {
+ height: 40px;
+ }
+ .row--h1 {
+ height: 65px;
+ }
+ .row--h2 {
+ height: 90px;
+ }
+ .row--h3 {
+ height: 115px;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row {{item.sizeClass}}">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const sizer = document.querySelector(".d-virtual-list__sizer");
+ const total = parseFloat(sizer.style.height);
+
+ assert.true(
+ total > COUNT * ESTIMATE_PX,
+ `the sizer total (${total}px) exceeds the all-estimates total (${
+ COUNT * ESTIMATE_PX
+ }px), so measured heights reached the engine`
+ );
+ });
+
+ test("measured rows are stacked contiguously at their measured heights", async function (assert) {
+ const items = buildRows(COUNT);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ .row--h0 {
+ height: 40px;
+ }
+ .row--h1 {
+ height: 65px;
+ }
+ .row--h2 {
+ height: 90px;
+ }
+ .row--h3 {
+ height: 115px;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row {{item.sizeClass}}">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const rows = mountedRows();
+ assert.true(rows.length > 1, "precondition: several rows are mounted");
+ assert.strictEqual(
+ getComputedStyle(rows[0]).position,
+ "absolute",
+ "precondition: rows sit at their virtual offset, not in normal flow"
+ );
+
+ // Contiguity, not merely non-overlap. Each row sits exactly where the
+ // measured heights of its predecessors put it, so a height attributed to the
+ // wrong row, or one uniform guess, shows up as a gap or an overlap.
+ const misplaced = [];
+ for (let i = 1; i < rows.length; i++) {
+ const previous = rows[i - 1].getBoundingClientRect();
+ const current = rows[i].getBoundingClientRect();
+ const drift = current.top - previous.bottom;
+ if (Math.abs(drift) > 1.5) {
+ misplaced.push(
+ `row ${rows[i].dataset.index} sits ${Math.round(drift)}px from the bottom of row ${rows[i - 1].dataset.index}`
+ );
+ }
+ }
+
+ assert.deepEqual(
+ misplaced,
+ [],
+ "every mounted row starts where its predecessor ends"
+ );
+ });
+
+ test("estimateSize receives the item and its index together", async function (assert) {
+ const items = buildRows(COUNT);
+ const seenIndices = [];
+ const mismatches = [];
+ const recordingEstimate = (item, index) => {
+ seenIndices.push(index);
+ if (items[index] !== item) {
+ mismatches.push(`index ${index} got ${item?.text ?? String(item)}`);
+ }
+ return ESTIMATE_PX;
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ .row--h0 {
+ height: 40px;
+ }
+ .row--h1 {
+ height: 65px;
+ }
+ .row--h2 {
+ height: 90px;
+ }
+ .row--h3 {
+ height: 115px;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{recordingEstimate}}
+ as |item|
+ >
+ <div class="row {{item.sizeClass}}">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // Without this the test is vacuous: an implementation that ignores
+ // `@estimateSize` entirely records no calls and so records no mismatches.
+ assert.true(
+ seenIndices.length > 0,
+ "precondition: the estimate callback was actually consulted"
+ );
+ assert.deepEqual(
+ mismatches,
+ [],
+ "every estimateSize call paired an item with its own index"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/mount-order-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/mount-order-test.gjs
new file mode 100644
index 00000000000..bfdda3adad1
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/mount-order-test.gjs
@@ -0,0 +1,117 @@
+import { find, render, resetOnerror, setupOnerror } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const INITIAL_INDEX = 100;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+module("Integration | ui-kit | DVirtualList | mount order", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ resetOnerror();
+ disableVirtualization();
+ });
+
+ // The list's own mount positioning must not depend on consumer code
+ // succeeding. `@onRegisterApi` hands out a handle, and a consumer is free to
+ // do something that throws with it.
+ test("a throwing @onRegisterApi still leaves the list at @initialIndex", async function (assert) {
+ const items = buildRows(300);
+ const caught = [];
+ setupOnerror((error) => caught.push(error));
+
+ const onRegisterApi = () => {
+ throw new Error("consumer boom");
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @initialIndex={{INITIAL_INDEX}}
+ @onRegisterApi={{onRegisterApi}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ caught.length,
+ 1,
+ "the consumer's throw surfaces rather than being swallowed"
+ );
+ assert.strictEqual(
+ find(".d-virtual-list").scrollTop,
+ INITIAL_INDEX * ROW_PX,
+ "and the list still opens at the requested index"
+ );
+ });
+
+ test("@initialIndex is applied when the consumer callback succeeds", async function (assert) {
+ const items = buildRows(300);
+ let handle;
+ const onRegisterApi = (api) => (handle = api);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @initialIndex={{INITIAL_INDEX}}
+ @onRegisterApi={{onRegisterApi}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(
+ typeof handle?.scrollToIndex,
+ "function",
+ "the consumer receives a usable API handle"
+ );
+ assert.strictEqual(
+ find(".d-virtual-list").scrollTop,
+ INITIAL_INDEX * ROW_PX,
+ "and the list opens at the requested index"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/options-reuse-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/options-reuse-test.gjs
new file mode 100644
index 00000000000..baf8b9e556c
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/options-reuse-test.gjs
@@ -0,0 +1,138 @@
+import { tracked } from "@glimmer/tracking";
+import { findAll, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const COUNT = 1000;
+
+function buildRows(count, from = 0) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: from + index,
+ text: `row ${from + index}`,
+ }));
+}
+
+class State {
+ @tracked items = buildRows(COUNT);
+ @tracked edgeThreshold = 8;
+}
+
+module("Integration | ui-kit | DVirtualList | options reuse", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // The engine memoizes its measurements on the identity of the key function among
+ // other things. Rebuilding that function on every update busts the memo, so an
+ // arg change that moves nothing still walks every index in the list. The cost is
+ // proportional to the whole list rather than the window.
+ test("options reuse: an unrelated arg change does not re-estimate the whole list", async function (assert) {
+ const state = new State();
+ let estimateCalls = 0;
+ const countingEstimate = () => {
+ estimateCalls++;
+ return ROW_PX;
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{countingEstimate}}
+ @edgeThreshold={{state.edgeThreshold}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ estimateCalls > 0,
+ "precondition: the mount estimated the list"
+ );
+ estimateCalls = 0;
+
+ // Changes nothing about geometry, keys, or the window. It exists only to force
+ // the modifier to rebuild its engine options.
+ state.edgeThreshold = 4;
+ await settled();
+
+ assert.true(
+ estimateCalls < COUNT,
+ `an arg change that moves nothing re-estimates a window, not the list (${estimateCalls} calls for ${COUNT} rows)`
+ );
+ });
+
+ // The guard against fixing the above the wrong way. Caching the key function on
+ // the item COUNT rather than on the items themselves would survive this suite's
+ // happy paths and quietly key a new list by the outgoing list's rows.
+ test("options reuse: replacing items with a same-length set still keys the new rows", async function (assert) {
+ const state = new State();
+ state.items = buildRows(20);
+ const estimate = () => ROW_PX;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__item .row")
+ .hasText("row 0", "precondition: the first list is rendered");
+
+ // Same length, entirely different keys.
+ state.items = buildRows(20, 500);
+ await settled();
+
+ const texts = findAll(".d-virtual-list__item .row").map((row) =>
+ row.textContent.trim()
+ );
+
+ assert.true(
+ texts.every((text) => text.startsWith("row 5")),
+ `every mounted row belongs to the incoming list (${texts[0]} … ${texts.at(-1)})`
+ );
+ assert.strictEqual(
+ texts[0],
+ "row 500",
+ "the window starts at the incoming list's first row"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-input-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-input-test.gjs
new file mode 100644
index 00000000000..125780495b4
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-input-test.gjs
@@ -0,0 +1,138 @@
+import { findAll, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+const COUNT = 100;
+
+// The window must always cover the viewport, whatever `@overscan` arrives.
+const MIN_MOUNTED = VIEWPORT_PX / ROW_PX;
+
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+module(
+ "Integration | ui-kit | DVirtualList | overscan input",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // A fractional overscan reaches the engine's range extractor, where
+ // `new Array(end - start + 1)` gets a fractional length and throws. The
+ // engine's memo commits its dependencies before calling the producer, so the
+ // throw is cached: every later read short-circuits and the list stays blank
+ // for good rather than recovering on the next scroll.
+ test("a fractional overscan still mounts a window", async function (assert) {
+ const items = buildRows(COUNT);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0.5}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ findAll(".d-virtual-list__item").length >= MIN_MOUNTED,
+ "a fractional overscan still mounts enough rows to fill the viewport"
+ );
+ });
+
+ test("a NaN overscan still mounts a window", async function (assert) {
+ const items = buildRows(COUNT);
+ const notANumber = Number.NaN;
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{notANumber}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ findAll(".d-virtual-list__item").length >= MIN_MOUNTED,
+ "a NaN overscan still mounts enough rows to fill the viewport"
+ );
+ });
+
+ // Negative overscan does not throw. It shrinks the extracted range from both
+ // ends, so the list quietly renders fewer rows than the viewport shows and
+ // leaves a strip of blank space instead.
+ test("a negative overscan still mounts a window", async function (assert) {
+ const items = buildRows(COUNT);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{-1}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ findAll(".d-virtual-list__item").length >= MIN_MOUNTED,
+ "a negative overscan still mounts enough rows to fill the viewport"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-window-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-window-test.gjs
new file mode 100644
index 00000000000..f6f7d127977
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/overscan-window-test.gjs
@@ -0,0 +1,112 @@
+import { findAll, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const OVERSCAN = 5;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+function mountedIndices() {
+ return findAll(".d-virtual-list__item")
+ .map((row) => Number(row.dataset.index))
+ .sort((a, b) => a - b);
+}
+
+// Supplemental coverage: every explicit @overscan in the suite is 0 or a value
+// that normalizes to 0, and the counts elsewhere are inequalities that hold at 0,
+// so the whole suite passes with the overscan hardcoded to 0.
+module(
+ "Integration | ui-kit | DVirtualList | overscan window",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a positive @overscan mounts that many rows beyond the viewport", async function (assert) {
+ const items = buildRows(200);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const withoutOverscan = mountedIndices();
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{OVERSCAN}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ const withOverscan = mountedIndices();
+
+ // At the top of the list there is nothing to overscan above, so the extra
+ // rows all land below. Derived from the measured window rather than a
+ // literal, so the assertion survives a viewport or row-height change.
+ assert.strictEqual(
+ withOverscan.length,
+ withoutOverscan.length + OVERSCAN,
+ `@overscan={{${OVERSCAN}}} mounts ${OVERSCAN} rows more than @overscan={{0}}`
+ );
+ assert.strictEqual(
+ withOverscan.at(-1),
+ withoutOverscan.at(-1) + OVERSCAN,
+ "and they extend the window past the last visible row"
+ );
+ assert.strictEqual(
+ withOverscan[0],
+ withoutOverscan[0],
+ "without moving its start, since the list is scrolled to the top"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/pinned-guard-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/pinned-guard-test.gjs
new file mode 100644
index 00000000000..3bc093245bb
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/pinned-guard-test.gjs
@@ -0,0 +1,240 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 320;
+
+// Derived from the geometry, never from the rendered array's own length: an oracle
+// built out of that length accepts a single row as "contiguous from the pinned
+// index", which is the exact gap these tests exist to catch.
+const MIN_MOUNTED_ROWS = Math.ceil(VIEWPORT_PX / ROW_PX);
+
+const estimate = () => ROW_PX;
+
+/**
+ * Asserts that the mounted rows are the pinned index followed by an unbroken run
+ * tall enough to fill the viewport.
+ *
+ * Three assertions rather than one `deepEqual`, so a failure names which property
+ * broke: too few rows, the wrong starting index, or a hole.
+ *
+ * @param assert The QUnit assert object for the running test.
+ * @param indices The mounted row indices, ascending.
+ * @param label Prefix identifying which stage of the test is being checked.
+ */
+function assertCoversViewportFromZero(assert, indices, label) {
+ assert.true(
+ indices.length >= MIN_MOUNTED_ROWS,
+ `${label}: at least ${MIN_MOUNTED_ROWS} rows mounted to fill the viewport (got ${indices.length}: [${indices}])`
+ );
+ assert.strictEqual(
+ indices[0],
+ 0,
+ `${label}: the run starts at the pinned row`
+ );
+ assert.deepEqual(
+ indices,
+ Array.from({ length: indices.length }, (_, i) => i),
+ `${label}: the run has no holes (got [${indices}])`
+ );
+}
+
+class Harness {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+function renderedIndices() {
+ return [...document.querySelectorAll(".d-virtual-list__item")]
+ .map((el) => Number(el.dataset.index))
+ .sort((a, b) => a - b);
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+// Guards the wall around @pinnedIndices callback output: garbage extras must be
+// inert rather than indexing the engine's measurements with a fractional/NaN key
+// (which pushes `undefined` and crashes the state signature), and a stale engine
+// scroll offset must not open holes between forced indices and the window.
+module(
+ "Integration | ui-kit | DVirtualList | pinned index guard",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("garbage callback output is inert and does not crash", async function (assert) {
+ const items = buildRows(100);
+ const garbagePins = () => [1.5, -2, 1000, Number.NaN];
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @pinnedIndices={{garbagePins}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 100);
+
+ assert
+ .dom(".d-virtual-list__item")
+ .exists("the list renders without crashing on garbage extras");
+ assert
+ .dom(".d-virtual-list__item[data-index='1']")
+ .doesNotExist("a fractional index pins nothing");
+ assert
+ .dom(".d-virtual-list__item[data-index='0']")
+ .doesNotExist("no valid extra means no off-window row");
+ });
+
+ // Regression for a reported gap: filtering a large list down to a single match
+ // and then widening the filter (e.g. "1356" → backspace → "135") left a visible
+ // hole right after the active row. The active row is pinned, and the engine had
+ // kept the scroll offset from before the filter shrank the list, so it computed
+ // a window far down while the pin force-rendered the active row at the top —
+ // the rows between were never mounted. The window must track the element's
+ // real (browser-clamped) offset after the set changes, leaving no gap.
+ test("a pinned row leaves no gap after the item set shrinks then grows", async function (assert) {
+ const h = new Harness(buildRows(30));
+ const pinFirst = () => [0];
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 320px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{h.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @pinnedIndices={{pinFirst}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // Scroll away from the pinned row, then filter down to a single match and
+ // widen it again — the sequence that stranded the stale offset.
+ await scrollTo(ROW_PX * 8);
+ h.items = buildRows(1);
+ await settled();
+ h.items = buildRows(15);
+ await settled();
+
+ assertCoversViewportFromZero(
+ assert,
+ renderedIndices(),
+ "after the shrink and regrow"
+ );
+ });
+
+ // A callback can force SEVERAL off-window indices at once, so a stale offset
+ // has more than one forced row to open holes against. The pins must all stay
+ // mounted while scrolled away, and a shrink→grow must leave no hole between
+ // any pin and the window.
+ test("multiple pinned rows stay mounted and leave no gaps after shrink then grow", async function (assert) {
+ const h = new Harness(buildRows(60));
+ const pinPair = () => [0, 3];
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 320px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{h.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @pinnedIndices={{pinPair}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(ROW_PX * 40);
+
+ const indices = renderedIndices();
+ assert.true(
+ indices.includes(0),
+ `the first pinned row stays mounted outside the window (got [${indices}])`
+ );
+ assert.true(
+ indices.includes(3),
+ `the second pinned row stays mounted outside the window (got [${indices}])`
+ );
+ assert.false(
+ indices.includes(1),
+ "the first row between the pins is not dragged along"
+ );
+ assert.false(
+ indices.includes(2),
+ "the second row between the pins is not dragged along"
+ );
+
+ h.items = buildRows(1);
+ await settled();
+ h.items = buildRows(15);
+ await settled();
+
+ assertCoversViewportFromZero(
+ assert,
+ renderedIndices(),
+ "across both pins after the shrink and regrow"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/published-state-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/published-state-test.gjs
new file mode 100644
index 00000000000..2c7a250d66c
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/published-state-test.gjs
@@ -0,0 +1,188 @@
+import { tracked } from "@glimmer/tracking";
+import { render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import dVirtualizer from "discourse/ui-kit/modifiers/d-virtualizer";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+class ReSyncState {
+ @tracked estimate = estimate;
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+// Drives the modifier directly rather than through DVirtualList: the published
+// payload is what the component consumes, so nothing above it can observe the
+// engine objects it hands out.
+module(
+ "Integration | ui-kit | DVirtualList | published state",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ // The modifier publishes nothing while the render-all fallback is active, and
+ // the global harness turns it off for every test.
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // The existing "re-syncing options does not republish" test counts
+ // onVisibleRangeChange, which a SECOND gate suppresses whenever the indices are
+ // unchanged, so deleting the signature gate leaves it green. Counting onState
+ // publishes on ONE mounted instance observes the signature gate and nothing else.
+ test("an identity-only options re-sync does not republish the window", async function (assert) {
+ const publishes = [];
+ const onState = (state) => publishes.push(state);
+ const items = buildRows(100);
+ const state = new ReSyncState();
+
+ await render(
+ <template>
+ <div
+ class="resync-viewport"
+ style="height: 400px; overflow-y: auto"
+ {{dVirtualizer
+ items=items
+ estimateSize=state.estimate
+ key="id"
+ onState=onState
+ }}
+ >
+ <div class="d-virtual-list__sizer"></div>
+ </div>
+ </template>
+ );
+
+ const publishesAfterMount = publishes.length;
+ assert.true(publishesAfterMount > 0, "precondition: the mount published");
+
+ // A different closure with identical behaviour, on the SAME instance: the
+ // options object changes identity while the rendered window does not.
+ state.estimate = () => ROW_PX;
+ await settled();
+
+ assert.strictEqual(
+ publishes.length,
+ publishesAfterMount,
+ "an options change that moves nothing republishes nothing"
+ );
+ });
+
+ test("the published range is an exact frozen snapshot or null", async function (assert) {
+ const populatedStates = [];
+ const emptyStates = [];
+ const onPopulatedState = (state) => populatedStates.push(state);
+ const onEmptyState = (state) => emptyStates.push(state);
+ const populatedItems = buildRows(100);
+ const emptyItems = [];
+
+ await render(
+ <template>
+ <div
+ class="populated-viewport"
+ style="height: 400px; overflow-y: auto"
+ {{dVirtualizer
+ items=populatedItems
+ estimateSize=estimate
+ key="id"
+ onState=onPopulatedState
+ }}
+ >
+ <div class="d-virtual-list__sizer"></div>
+ </div>
+ <div
+ class="empty-viewport"
+ style="height: 400px; overflow-y: auto"
+ {{dVirtualizer
+ items=emptyItems
+ estimateSize=estimate
+ key="id"
+ onState=onEmptyState
+ }}
+ >
+ <div class="d-virtual-list__sizer"></div>
+ </div>
+ </template>
+ );
+
+ assert.true(
+ populatedStates.length > 0,
+ "precondition: the populated modifier published state"
+ );
+ assert.true(
+ emptyStates.length > 0,
+ "precondition: the empty modifier published state"
+ );
+
+ const populatedRange = populatedStates.at(-1).range;
+ assert.deepEqual(
+ populatedRange,
+ { startIndex: 0, endIndex: 9 },
+ "the range carries exactly the visible start and end indices"
+ );
+ assert.true(Object.isFrozen(populatedRange), "the range is frozen");
+ assert.strictEqual(
+ emptyStates.at(-1).range,
+ null,
+ "state publishes null when there is no range"
+ );
+ });
+
+ test("the published window is frozen and detached from the engine's array", async function (assert) {
+ const items = buildRows(100);
+ const published = [];
+ const onState = (state) => published.push(state);
+
+ await render(
+ <template>
+ <div
+ class="viewport"
+ style="height: 400px; overflow-y: auto"
+ {{dVirtualizer
+ items=items
+ estimateSize=estimate
+ key="id"
+ onState=onState
+ }}
+ >
+ <div class="d-virtual-list__sizer"></div>
+ </div>
+ </template>
+ );
+
+ assert.true(
+ published.length > 0,
+ "precondition: the modifier published a window"
+ );
+
+ const { virtualItems } = published.at(-1);
+ assert.true(
+ virtualItems.length > 0,
+ `precondition: the window is not empty (got ${virtualItems.length})`
+ );
+ assert.true(
+ Object.isFrozen(virtualItems),
+ "the published window is frozen"
+ );
+ assert.throws(
+ () => virtualItems.push({ index: 999 }),
+ /TypeError/,
+ "a consumer cannot extend the array the engine memoized"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/rendering-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/rendering-test.gjs
new file mode 100644
index 00000000000..5d6cb0ed2a9
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/rendering-test.gjs
@@ -0,0 +1,235 @@
+import { findAll, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+const items = Array.from({ length: 100 }, (_, index) => ({
+ id: index,
+ text: `Row ${index}`,
+}));
+
+module("Integration | ui-kit | DVirtualList | rendering", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ disableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ enableVirtualization();
+ });
+
+ test("uses the semantic inner container and absolutely positioned owned rows when windowing", async function (assert) {
+ enableVirtualization();
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @as="ul"
+ @role="listbox"
+ @ownedRow={{true}}
+ as |item row|
+ >
+ {{! eslint-disable ember/template-require-context-role }}
+ <li
+ class="row"
+ role="option"
+ data-index={{row.index}}
+ style="height: 40px"
+ {{row.place row.start row.index}}
+ >
+ {{item.text}}
+ </li>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom("ul[role='listbox']")
+ .exists("the semantic inner container exists");
+ assert
+ .dom("ul[role='listbox'] .row[role='option']")
+ .exists("the semantic inner container carries the owned options");
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute(
+ "role",
+ "the primitive-owned viewport is role-less"
+ );
+
+ const rows = findAll(".row");
+ assert.true(rows.length > 0, "mounts some rows");
+ assert.true(rows.length < items.length, "mounts a bounded window");
+
+ for (const row of rows) {
+ assert.strictEqual(
+ getComputedStyle(row).position,
+ "absolute",
+ `row ${row.dataset.index} is absolutely positioned`
+ );
+ // Asserted against the row's OWN index rather than merely being non-"none",
+ // which every row sharing translateY(0) would also satisfy.
+ assert.strictEqual(
+ row.style.transform,
+ `translateY(${Number(row.dataset.index) * ROW_PX}px)`,
+ `row ${row.dataset.index} is translated to its own virtual offset`
+ );
+ assert.strictEqual(
+ row.textContent.trim(),
+ items[Number(row.dataset.index)].text,
+ "the yielded index identifies the matching item"
+ );
+ }
+ });
+
+ test("keeps owned rows in normal flow when virtualization is disabled", async function (assert) {
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @as="ul"
+ @role="listbox"
+ @ownedRow={{true}}
+ as |item row|
+ >
+ {{! eslint-disable ember/template-require-context-role }}
+ <li
+ class="row"
+ role="option"
+ data-index={{row.index}}
+ style="height: 40px"
+ {{row.place row.start row.index}}
+ >
+ {{item.text}}
+ </li>
+ </DVirtualList>
+ </template>
+ );
+
+ const rows = findAll(".row");
+ assert.strictEqual(rows.length, items.length, "renders every fallback row");
+
+ let previousTop = -Infinity;
+ for (const row of rows) {
+ assert.strictEqual(
+ getComputedStyle(row).position,
+ "static",
+ `row ${row.dataset.index} remains in normal flow`
+ );
+ assert.strictEqual(
+ getComputedStyle(row).transform,
+ "none",
+ `row ${row.dataset.index} is not translated`
+ );
+ assert.true(
+ row.getBoundingClientRect().top > previousTop,
+ `row ${row.dataset.index} is below its predecessor`
+ );
+ previousTop = row.getBoundingClientRect().top;
+ }
+ });
+
+ test("puts role and splatted attributes on the semantic inner container", async function (assert) {
+ await render(
+ <template>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @as="ul"
+ @role="listbox"
+ @ownedRow={{true}}
+ id="my-listbox"
+ as |item row|
+ >
+
+ <li
+ class="row"
+ role="option"
+ data-index={{row.index}}
+ {{row.place row.start row.index}}
+ >
+ {{item.text}}
+ </li>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom("ul")
+ .hasAttribute("role", "listbox", "the inner container owns the role");
+ assert
+ .dom("ul")
+ .hasAttribute(
+ "id",
+ "my-listbox",
+ "the inner container receives attributes"
+ );
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute("role", "the viewport has no consumer role");
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute("id", "the viewport has no consumer id");
+ });
+
+ // A browser with keyboard-focusable scrollers puts a scroll container into the tab sequence
+ // when it holds nothing focusable, and does so without marking the element: adopted or not, it
+ // reports `tabIndex === -1` and matches no focusable selector. An explicit attribute is
+ // therefore both the only way to suppress the adoption and the only part of it a test can read.
+ test("leaves the viewport's tab behaviour to the browser by default", async function (assert) {
+ await render(
+ <template>
+ <DVirtualList @items={{items}} @estimateSize={{estimate}} as |item|>
+ {{item.text}}
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute(
+ "tabindex",
+ "a list read by scrolling keeps whatever access the browser gives it"
+ );
+ });
+
+ test("opts the viewport out of the tab sequence on request", async function (assert) {
+ await render(
+ <template>
+ <DVirtualList
+ @items={{items}}
+ @estimateSize={{estimate}}
+ @viewportTabbable={{false}}
+ as |item|
+ >
+ {{item.text}}
+ </DVirtualList>
+ </template>
+ );
+
+ assert.dom(".d-virtual-list").hasAttribute("tabindex", "-1");
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/resilience-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/resilience-test.gjs
new file mode 100644
index 00000000000..cc55d23257f
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/resilience-test.gjs
@@ -0,0 +1,257 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ findAll,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+
+ prepend(count) {
+ this.items = [...buildRows(count, -count), ...this.items];
+ }
+}
+
+function buildRows(count, from = 0) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: from + index,
+ text: `row ${from + index}`,
+ }));
+}
+
+function scroller() {
+ return find(".d-virtual-list");
+}
+
+function renderedIndices() {
+ return findAll(".d-virtual-list__item").map((element) =>
+ Number(element.dataset.index)
+ );
+}
+
+async function scrollTo(top) {
+ const element = scroller();
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | resilience", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ // These tests drive consumer callbacks that throw on purpose; the primitive
+ // reports them rather than rethrowing, so silence the report itself.
+ this.consoleError = sinon.stub(console, "error");
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a throwing onReachEnd still leaves the window published", async function (assert) {
+ // Short enough that the end band is reached on mount, which is when a
+ // throwing callback would abort the very first publish.
+ const items = buildRows(12);
+ const explode = () => {
+ throw new Error("consumer blew up");
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachEnd={{explode}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.true(
+ renderedIndices().length > 0,
+ "rows still render after the edge callback threw"
+ );
+ assert.true(
+ find(".d-virtual-list__sizer").offsetHeight > 0,
+ "the sizer still took the list's height"
+ );
+
+ // The stub is not just noise suppression: this path exists to REPORT, and
+ // without asserting it the reporting could be deleted with the suite still green.
+ assert.true(
+ this.consoleError.calledWithMatch(/\[d-virtual-list\] onReachEnd/),
+ "the swallowed onReachEnd error is reported"
+ );
+ });
+
+ test("a throwing pinnedIndices degrades to the unextended window", async function (assert) {
+ const items = buildRows(100);
+ const explode = () => {
+ throw new Error("pins blew up");
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @pinnedIndices={{explode}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+
+ const indices = renderedIndices();
+ assert.true(
+ indices.length > 0,
+ "the list keeps rendering its default window"
+ );
+ assert.false(
+ indices.includes(0),
+ "no pin is applied, rather than the render crashing on a poisoned window"
+ );
+
+ // The stub is not just noise suppression: this path exists to REPORT, and
+ // without asserting it the reporting could be deleted with the suite still green.
+ assert.true(
+ this.consoleError.calledWithMatch(/\[d-virtual-list\] pinnedIndices/),
+ "the swallowed pinnedIndices error is reported"
+ );
+ });
+
+ test("a shrink never yields a row without a backing item", async function (assert) {
+ // Mirrors the pass in which `@items` has shrunk but the window published by
+ // the after-render flush still describes the previous, longer list.
+ const state = new State(buildRows(100));
+ const seen = [];
+ const record = (item) => {
+ seen.push(item);
+ return "";
+ };
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{record item}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(100 * ROW_PX - VIEWPORT_PX);
+ seen.length = 0;
+
+ state.items = buildRows(3);
+ await settled();
+
+ assert.true(
+ seen.length > 0,
+ "precondition: rows re-rendered on the shrink"
+ );
+ assert.true(
+ seen.every((item) => item != null),
+ "every yielded row had a real item behind it"
+ );
+ });
+
+ test("prepending more than the remaining scroll distance holds the reader's row", async function (assert) {
+ const state = new State(buildRows(30));
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // Rest at the top: the whole list is 1200px against a 400px viewport, so a
+ // 30-row prepend is far taller than the 800px left below the reader. That
+ // is what makes the engine's anchored offset unreachable under the old
+ // sizer height, which is the condition the anchor has to survive.
+ await scrollTo(0);
+ const anchorIndex = renderedIndices()[0];
+
+ state.prepend(30);
+ await settled();
+
+ assert.strictEqual(
+ scroller().scrollTop,
+ 30 * ROW_PX,
+ "the viewport moved down by exactly the height that arrived above it"
+ );
+ assert.true(
+ renderedIndices().includes(anchorIndex + 30),
+ "the row the reader was looking at is still the one in view"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/sentinel-rearm-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/sentinel-rearm-test.gjs
new file mode 100644
index 00000000000..77baf657df5
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/sentinel-rearm-test.gjs
@@ -0,0 +1,143 @@
+import { tracked } from "@glimmer/tracking";
+import { render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+const SENTINEL = { id: "sentinel", text: "loading" };
+
+function rowsThenSentinel(count) {
+ return [
+ ...Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ })),
+ SENTINEL,
+ ];
+}
+
+class State {
+ @tracked items = rowsThenSentinel(6);
+}
+
+// Supplemental coverage for the branch that arms both latches when the count
+// moved but neither boundary key did. A list that keeps a persistent sentinel
+// row at one end holds both boundary keys stable across a refresh, so nothing
+// else re-arms it and its edge callbacks stop for good.
+//
+// The list SHRINKS here rather than grows. Growing moves the end band away from
+// a stationary range, which re-arms through the ordinary retreat path and hides
+// the branch under test.
+module(
+ "Integration | ui-kit | DVirtualList | sentinel re-arm",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a count change between stable boundary keys re-arms both edges", async function (assert) {
+ const state = new State();
+ const ends = [];
+ const starts = [];
+ const onReachEnd = () => ends.push(true);
+ const onReachStart = () => starts.push(true);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ @onReachStart={{onReachStart}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // The whole list fits, so the end band is already on screen and fires once.
+ // The start edge is suppressed at mount by design, so nothing has fired it.
+ assert.strictEqual(ends.length, 1, "the end fires once on mount");
+ assert.strictEqual(starts.length, 0, "the start is suppressed at mount");
+
+ // Same first row, same sentinel last row, fewer rows between them. The
+ // window never leaves either band, so the retreat path cannot account for
+ // any callback that follows.
+ state.items = rowsThenSentinel(1);
+ await settled();
+
+ assert.strictEqual(
+ ends.length,
+ 2,
+ "the end re-arms and fires again for the new list"
+ );
+ assert.strictEqual(
+ starts.length,
+ 1,
+ "and the start re-arms too, since both boundaries are new content"
+ );
+ });
+
+ test("a refresh that moves neither the count nor the keys arms nothing", async function (assert) {
+ const state = new State();
+ const ends = [];
+ const onReachEnd = () => ends.push(true);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @onReachEnd={{onReachEnd}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert.strictEqual(ends.length, 1, "the end fires once on mount");
+
+ // A fresh array of equivalent rows: same keys, same count. Re-arming here
+ // would answer an edge callback with another edge callback.
+ state.items = rowsThenSentinel(6);
+ await settled();
+
+ assert.strictEqual(
+ ends.length,
+ 1,
+ "an in-place refresh does not re-fire the end"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/shrink-window-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/shrink-window-test.gjs
new file mode 100644
index 00000000000..c3610034ef8
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/shrink-window-test.gjs
@@ -0,0 +1,171 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ find,
+ findAll,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const VIEWPORT_PX = 400;
+const LONG_COUNT = 100;
+const SHORT_COUNT = 10;
+
+const estimate = () => ROW_PX;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+/**
+ * Ids start at `from` so a shrink can hand over rows the outgoing list never
+ * contained. The engine resolves its scroll anchor by key, so reusing ids would
+ * let it find the anchor and correct the offset on its own, hiding the defect.
+ */
+function buildRows(count, from = 0) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: from + index,
+ text: `row ${from + index}`,
+ }));
+}
+
+async function scrollTo(top) {
+ const element = find(".d-virtual-list");
+ element.scrollTop = top;
+ await triggerEvent(element, "scroll");
+}
+
+module("Integration | ui-kit | DVirtualList | shrink window", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("a deep shrink never publishes a window past the new end", async function (assert) {
+ // The flush reads the window from the engine before it settles the sizer to
+ // the shrunk total. Until that height lands the browser has not clamped
+ // `scrollTop`, so the engine still answers from the outgoing list's offset
+ // and the published range collapses onto the last row of the new list.
+ const state = new State(buildRows(LONG_COUNT));
+ const ranges = [];
+ // Recorded as strings so a failure names the offending window rather than
+ // printing `[object Object]`.
+ const onVisibleRangeChange = (range) =>
+ ranges.push(`${range.startIndex}-${range.endIndex}`);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ @onVisibleRangeChange={{onVisibleRangeChange}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(LONG_COUNT * ROW_PX - VIEWPORT_PX);
+
+ assert.true(
+ ranges.length > 0,
+ "precondition: scrolling to the end published a range"
+ );
+
+ // Drop the pre-shrink windows. Those legitimately sit at the end of the long
+ // list; only what is published from the shrink onwards is under test.
+ ranges.length = 0;
+
+ state.items = buildRows(SHORT_COUNT, 1000);
+ await settled();
+
+ assert.true(
+ ranges.length > 0,
+ "precondition: the shrink published at least one range"
+ );
+
+ // The whole shrunk list fits the viewport, so every window it can legitimately
+ // occupy starts at row 0. One that starts later was computed against the
+ // outgoing list's scroll offset.
+ assert.deepEqual(
+ ranges.filter((range) => !range.startsWith("0-")),
+ [],
+ "no window published from the shrink starts past the first row of a list that fits the viewport"
+ );
+ });
+
+ test("a deep shrink publishes a window covering the whole shorter list", async function (assert) {
+ // The positive half. This one can also pass on the defective ordering once
+ // the browser's clamp fires its scroll event and a corrected flush lands, so
+ // it guards the settled result rather than discriminating the bug.
+ const state = new State(buildRows(LONG_COUNT));
+ const ranges = [];
+ const onVisibleRangeChange = (range) =>
+ ranges.push(`${range.startIndex}-${range.endIndex}`);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @overscan={{0}}
+ @onVisibleRangeChange={{onVisibleRangeChange}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ await scrollTo(LONG_COUNT * ROW_PX - VIEWPORT_PX);
+
+ state.items = buildRows(SHORT_COUNT, 1000);
+ await settled();
+
+ assert.strictEqual(
+ ranges.at(-1),
+ `0-${SHORT_COUNT - 1}`,
+ "the last published range spans the shrunk list"
+ );
+ assert.strictEqual(
+ findAll(".d-virtual-list__item").length,
+ SHORT_COUNT,
+ "every row of the shrunk list is mounted"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/stable-key-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/stable-key-test.gjs
new file mode 100644
index 00000000000..ac30041965b
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/stable-key-test.gjs
@@ -0,0 +1,109 @@
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { findAll, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_HEIGHT = 40;
+const estimateSize = () => ROW_HEIGHT;
+
+class State {
+ @tracked items;
+
+ constructor(items) {
+ this.items = items;
+ }
+}
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, id) => ({
+ id: String(id),
+ text: `row ${id}`,
+ }));
+}
+
+module("Integration | ui-kit | DVirtualList | stable key", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ test("stable @key reuses row DOM across an item-array replacement", async function (assert) {
+ const state = new State(buildRows(1000));
+ const insertCounts = new Map();
+ const recordInsert = (id) => {
+ insertCounts.set(id, (insertCounts.get(id) ?? 0) + 1);
+ };
+
+ await render(
+ <template>
+ {{! Size the scroll viewport via CSS: `...attributes` route to the inner
+ container, so an inline `style` would size that, not the viewport. }}
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{state.items}}
+ @key="id"
+ @estimateSize={{estimateSize}}
+ as |item|
+ >
+ <div
+ class="row"
+ data-row-id={{item.id}}
+ style="height: 40px"
+ {{didInsert (fn recordInsert item.id)}}
+ >
+ {{item.text}}
+ </div>
+ </DVirtualList>
+ </template>
+ );
+
+ const rowsBefore = new Map(
+ findAll(".row").map((element) => [element.dataset.rowId, element])
+ );
+ const insertsBefore = new Map(insertCounts);
+
+ assert.true(rowsBefore.size > 0, "a real window mounts some rows");
+ assert.true(
+ rowsBefore.size < 40,
+ `a real window mounts fewer than 40 rows (${rowsBefore.size} rows)`
+ );
+
+ state.items = state.items.map((row) => ({ ...row }));
+ await settled();
+
+ const rowsAfter = new Map(
+ findAll(".row").map((element) => [element.dataset.rowId, element])
+ );
+
+ for (const [id, elementBefore] of rowsBefore) {
+ assert.strictEqual(
+ insertCounts.get(id),
+ insertsBefore.get(id),
+ `row ${id} is not inserted again after the replacement`
+ );
+ assert.strictEqual(
+ rowsAfter.get(id),
+ elementBefore,
+ `row ${id} keeps its DOM element after fresh objects replace the item array`
+ );
+ }
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-virtual-list/viewport-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/viewport-test.gjs
new file mode 100644
index 00000000000..bc07865f4c8
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/d-virtual-list/viewport-test.gjs
@@ -0,0 +1,223 @@
+import { find, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_PX = 40;
+const estimate = () => ROW_PX;
+
+function buildRows(count) {
+ return Array.from({ length: count }, (_, index) => ({
+ id: index,
+ text: `row ${index}`,
+ }));
+}
+
+module("Integration | ui-kit | DVirtualList | viewport", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ enableVirtualization();
+ });
+
+ hooks.afterEach(function () {
+ disableVirtualization();
+ });
+
+ // Splattributes go to the inner semantic container, so the scroll viewport is
+ // unreachable: the element whose height the consumer owns, and which a browser
+ // may adopt as a tab stop, can carry neither a hook nor a name. Every consumer
+ // in the repo reaches through the internal class name from an ancestor instead.
+ test("viewport hooks: @viewportClass lands on the scroll viewport", async function (assert) {
+ const items = buildRows(50);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @viewportClass="my-scroller"
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list.my-scroller")
+ .exists("the consumer's class joins the viewport's own");
+ assert
+ .dom(".d-virtual-list__sizer.my-scroller")
+ .doesNotExist("it does not land on the inner container instead");
+ });
+
+ // A non-interactive role leaves nothing inside focusable, so the component's own
+ // documentation tells the consumer to make the viewport focusable and name it.
+ // Until now the API could express neither half of that instruction.
+ test("viewport hooks: @viewportLabel names the scroll viewport", async function (assert) {
+ const items = buildRows(50);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @viewportLabel="Search results"
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list")
+ .hasAttribute(
+ "aria-label",
+ "Search results",
+ "the scrollable region carries an accessible name"
+ );
+ // A name on a role-less div is prohibited by ARIA: the implicit `generic`
+ // role cannot be named, so the attribute is decorative without a role that
+ // permits naming.
+ assert
+ .dom(".d-virtual-list")
+ .hasAttribute(
+ "role",
+ "region",
+ "and a role that is allowed to carry that name"
+ );
+ });
+
+ test("viewport hooks: an unnamed viewport stays role-less", async function (assert) {
+ const items = buildRows(50);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ // The role exists to make a name legal, so a viewport with no name must not
+ // gain one: a landmark per list would clutter the document's structure.
+ assert
+ .dom(".d-virtual-list")
+ .doesNotHaveAttribute(
+ "role",
+ "an unnamed viewport adds no landmark to the page"
+ );
+ });
+
+ test("viewport hooks: @viewportLabelledBy names it from existing markup", async function (assert) {
+ const items = buildRows(50);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <h2 id="results-heading">Results</h2>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @viewportLabelledBy="results-heading"
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list")
+ .hasAttribute("aria-labelledby", "results-heading");
+ assert
+ .dom(".d-virtual-list")
+ .hasAttribute(
+ "role",
+ "region",
+ "either naming argument earns the role that permits a name"
+ );
+ });
+
+ // The existing split is deliberate and must survive: the semantic element owns
+ // the role and the consumer's own attributes.
+ test("viewport hooks: splattributes still reach the inner container", async function (assert) {
+ const items = buildRows(50);
+
+ await render(
+ <template>
+ {{! eslint-disable-next-line ember/template-no-forbidden-elements }}
+ <style>
+ .d-virtual-list {
+ height: 400px;
+ overflow-y: auto;
+ }
+ </style>
+ <DVirtualList
+ @items={{items}}
+ @key="id"
+ @estimateSize={{estimate}}
+ @viewportClass="my-scroller"
+ data-container="yes"
+ as |item|
+ >
+ <div class="row" style="height: 40px">{{item.text}}</div>
+ </DVirtualList>
+ </template>
+ );
+
+ assert
+ .dom(".d-virtual-list__sizer")
+ .hasAttribute(
+ "data-container",
+ "yes",
+ "consumer attributes still land on the semantic container"
+ );
+ assert.strictEqual(
+ find(".d-virtual-list").getAttribute("data-container"),
+ null,
+ "and not on the viewport"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/setup-tests.js b/frontend/discourse/tests/setup-tests.js
index b8b8fe9514d..e2a2e54b1b2 100644
--- a/frontend/discourse/tests/setup-tests.js
+++ b/frontend/discourse/tests/setup-tests.js
@@ -51,6 +51,10 @@ import {
disableLoadMoreObserver,
enableLoadMoreObserver,
} from "discourse/ui-kit/d-load-more";
+import {
+ disableVirtualization,
+ enableVirtualization,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
const REPORT_MEMORY = false;
let cancelled = false;
@@ -304,6 +308,15 @@ export default async function setupTests(config) {
sinon.stub(scrollManager, "unbindScrolling");
disableLoadMoreObserver();
+
+ // Rendering tests mount in a zero-height container, so a virtualizer would compute an
+ // empty window and render nothing. Disable it globally (opt back in per-test with
+ // enableVirtualization) so tests mount every row; mirrors disableLoadMoreObserver.
+ //
+ // The fallback is a different code path, in which a row's index and its item can
+ // never disagree. A consumer whose behaviour depends on windowing therefore needs
+ // its own module that opts back in, or its suite says nothing about what ships.
+ disableVirtualization();
});
QUnit.testDone(function () {
@@ -338,6 +351,7 @@ export default async function setupTests(config) {
window.MessageBus.unsubscribe("*");
localStorage.clear();
enableLoadMoreObserver();
+ enableVirtualization();
// Release the app reference so the destroyed app isn't retained
// by this closure until the next test creates a new one.
diff --git a/frontend/discourse/tests/unit/ui-kit/virtualizer-test.js b/frontend/discourse/tests/unit/ui-kit/virtualizer-test.js
new file mode 100644
index 00000000000..8005ea5d97f
--- /dev/null
+++ b/frontend/discourse/tests/unit/ui-kit/virtualizer-test.js
@@ -0,0 +1,396 @@
+import { module, test } from "qunit";
+import {
+ createElementVirtualizer,
+ keyFor,
+ pushScrollOffset,
+ rangeExtractorWithPins,
+ stableKeyFor,
+} from "discourse/ui-kit/-internals/windowing/virtualizer";
+
+// A deterministic virtualizer over a fake 500px-tall viewport with fixed-height
+// rows, so the windowing math can be asserted without a real layout.
+function buildVirtualizer(overrides = {}) {
+ const scrollElement = {};
+ let scrollOffset = overrides.initialOffset ?? 0;
+
+ const virtualizer = createElementVirtualizer({
+ count: 1000,
+ getScrollElement: () => scrollElement,
+ estimateSize: () => 50,
+ overscan: 2,
+ // Feed fixed geometry synchronously instead of a real ResizeObserver / scroll.
+ observeElementRect: (instance, cb) => {
+ cb({ width: 300, height: 500 });
+ return () => {};
+ },
+ observeElementOffset: (instance, cb) => {
+ cb(scrollOffset, false);
+ return () => {};
+ },
+ scrollToFn: (offset) => {
+ scrollOffset = offset;
+ },
+ ...overrides,
+ });
+
+ const cleanup = virtualizer._didMount();
+ virtualizer._willUpdate();
+ return { virtualizer, cleanup, setOffset: (o) => (scrollOffset = o) };
+}
+
+module("Unit | ui-kit | virtualizer", function () {
+ test("a pushed offset survives the engine's settle", async function (assert) {
+ // The engine learns the offset from a closure only its own scroll handler
+ // writes, and its debounced settle re-reports that captured value once
+ // scrolling stops. `pushScrollOffset` calls the retained callback directly and
+ // cannot reach that closure, so the settle looks able to hand the engine back
+ // a pre-push offset. It cannot: a push only ever carries the element's own
+ // `scrollTop`, and every change to `scrollTop` emits a scroll event that
+ // refreshes the closure long before the settle delay elapses. Pinned here
+ // because that safety is the ENGINE's behaviour, not ours, so a version bump
+ // could remove it. Uses the real adapter, since the shared harness stubs
+ // `observeElementOffset` and would bypass the debounce under test.
+ const scrollElement = document.createElement("div");
+ scrollElement.style.cssText = "height: 500px; overflow-y: auto";
+ const inner = document.createElement("div");
+ inner.style.height = "50000px";
+ scrollElement.appendChild(inner);
+ document.body.appendChild(scrollElement);
+
+ try {
+ const virtualizer = createElementVirtualizer({
+ count: 1000,
+ getScrollElement: () => scrollElement,
+ estimateSize: () => 50,
+ overscan: 2,
+ });
+ const cleanup = virtualizer._didMount();
+ virtualizer._willUpdate();
+
+ // A real scroll, so the engine captures this offset and arms its settle.
+ scrollElement.scrollTop = 2000;
+ scrollElement.dispatchEvent(new Event("scroll"));
+ assert.strictEqual(
+ virtualizer.scrollOffset,
+ 2000,
+ "precondition: the engine adopted the scrolled offset"
+ );
+
+ // Correct the engine the way the modifier does for an out-of-range offset.
+ scrollElement.scrollTop = 1000;
+ pushScrollOffset(virtualizer);
+ assert.strictEqual(
+ virtualizer.scrollOffset,
+ 1000,
+ "precondition: the push was adopted"
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 250));
+
+ // Without this the assertion below can pass by arriving BEFORE the settle it
+ // exists to outlast: a longer debounce in a future engine version would make
+ // it vacuous rather than failing, which is the opposite of what it guards.
+ assert.false(
+ virtualizer.isScrolling,
+ "precondition: the scroll settle actually ran inside the wait"
+ );
+ assert.strictEqual(
+ virtualizer.scrollOffset,
+ 1000,
+ "the settle did not re-adopt the pre-push offset"
+ );
+ cleanup();
+ } finally {
+ scrollElement.remove();
+ }
+ });
+
+ test("getTotalSize reflects the full count, not the window", function (assert) {
+ const { virtualizer, cleanup } = buildVirtualizer();
+ assert.strictEqual(
+ virtualizer.getTotalSize(),
+ 50 * 1000,
+ "total size spans all 1000 rows"
+ );
+ cleanup();
+ });
+
+ test("getVirtualItems returns a bounded window at the top", function (assert) {
+ const { virtualizer, cleanup } = buildVirtualizer();
+ const items = virtualizer.getVirtualItems();
+
+ assert.true(items.length > 0, "renders some rows");
+ assert.true(
+ items.length < 30,
+ `windows a small slice of 1000 rows (got ${items.length})`
+ );
+ assert.strictEqual(items[0].index, 0, "starts at the first row");
+ assert.strictEqual(items[0].start, 0, "first row is at offset 0");
+ cleanup();
+ });
+
+ test("measureElement(null) sweeps disconnected rows from the element cache", function (assert) {
+ // The modifier calls measureElement(null) on every flush to evict rows the DOM
+ // has removed: a ResizeObserver never fires on removal, so without the sweep the
+ // cache — and the observer — would retain every row ever scrolled past. The
+ // dependency is version-pinned because this sweep semantics could shift between
+ // releases, so pin it here.
+ const { virtualizer, cleanup } = buildVirtualizer();
+
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const rows = [0, 1, 2].map((index) => {
+ const row = document.createElement("div");
+ row.setAttribute("data-index", String(index));
+ container.appendChild(row);
+ virtualizer.measureElement(row);
+ return row;
+ });
+
+ assert.strictEqual(
+ virtualizer.elementsCache.size,
+ 3,
+ "every measured row is cached"
+ );
+
+ // Detach one row as an unmount would, then run the sweep.
+ rows[1].remove();
+ virtualizer.measureElement(null);
+
+ const cached = [...virtualizer.elementsCache.values()];
+ assert.strictEqual(
+ virtualizer.elementsCache.size,
+ 2,
+ "the sweep evicts the disconnected row"
+ );
+ assert.false(cached.includes(rows[1]), "the detached node is gone");
+ assert.true(
+ cached.includes(rows[0]),
+ "the first connected row stays cached"
+ );
+ assert.true(
+ cached.includes(rows[2]),
+ "the last connected row stays cached"
+ );
+
+ container.remove();
+ cleanup();
+ });
+
+ test("stableKeyFor is stable across an in-place id mutation", function (assert) {
+ // Reproduces optimistic insertion: a row created with a temporary client id,
+ // then reconciled to the server's id on the SAME object. Keying on `id` would
+ // orphan the measured height; object identity must not.
+ const row = { id: "staged-guid-abc" };
+ const before = stableKeyFor(row);
+
+ row.id = 4213; // server confirmation mutates in place
+
+ assert.strictEqual(
+ stableKeyFor(row),
+ before,
+ "same object keeps its key across id mutation"
+ );
+ });
+
+ test("stableKeyFor does not collide across objects and primitive items", function (assert) {
+ // Generated object keys live in a reserved namespace, and a string item that
+ // looks like one is escaped, so a primitive item can never resolve to a live
+ // object's key. Keys drive BOTH the engine's measurement cache (keyed by
+ // getItemKey) and {{#each key=}}, so a collision would alias row heights and
+ // row identity at once.
+ const object = {};
+ const objectKey = stableKeyFor(object);
+
+ assert.notStrictEqual(
+ stableKeyFor(objectKey),
+ objectKey,
+ "a primitive item equal to an object's key must not resolve to that same key"
+ );
+ });
+
+ test("stableKeyFor returns an engine-valid key type", function (assert) {
+ // The engine's Key contract is number | string | bigint, so every other item
+ // shape has to be normalized into one of them.
+ const key = stableKeyFor(true);
+
+ assert.true(
+ ["number", "string", "bigint"].includes(typeof key),
+ `key type must be engine-valid (got ${typeof key})`
+ );
+ });
+
+ test("stableKeyFor distinguishes different objects and passes primitives through", function (assert) {
+ const a = { id: 1 };
+ const b = { id: 1 };
+ assert.notStrictEqual(
+ stableKeyFor(a),
+ stableKeyFor(b),
+ "distinct objects get distinct keys even with equal ids"
+ );
+ assert.strictEqual(
+ stableKeyFor("row-7"),
+ "row-7",
+ "primitive is its own key"
+ );
+ assert.strictEqual(stableKeyFor(42), 42, "number is its own key");
+ });
+
+ module("rangeExtractorWithPins", function () {
+ // The window this range yields from the engine's default extractor is exactly
+ // [10..15]: overscan 0 keeps the expected arrays literal.
+ const RANGE = { startIndex: 10, endIndex: 15, overscan: 0, count: 100 };
+ const WINDOW = [10, 11, 12, 13, 14, 15];
+
+ test("extras merge into the window in ascending index order", function (assert) {
+ const extract = rangeExtractorWithPins(() => [20, 3]);
+
+ assert.deepEqual(
+ extract(RANGE),
+ [3, ...WINDOW, 20],
+ "unsorted extras land sorted around the window"
+ );
+ });
+
+ test("the callback receives the default window indices and the range", function (assert) {
+ let received;
+ const extract = rangeExtractorWithPins((indices, range) => {
+ received = { indices, range };
+ return [];
+ });
+
+ extract(RANGE);
+
+ assert.deepEqual(
+ [...received.indices],
+ WINDOW,
+ "the callback sees the overscan-expanded window"
+ );
+ assert.strictEqual(
+ received.range.count,
+ RANGE.count,
+ "the callback sees the range it is extending"
+ );
+ });
+
+ test("duplicate extras and window collisions never yield a duplicate index", function (assert) {
+ // The engine publishes one measurement per index with zero dedup of its own,
+ // so a surviving duplicate becomes a duplicate {{#each}} key downstream. The
+ // wall dedupes unconditionally: within the extras and against the window.
+ const extract = rangeExtractorWithPins(() => [3, 3, 12, 20, 20]);
+
+ assert.deepEqual(
+ extract(RANGE),
+ [3, ...WINDOW, 20],
+ "each index appears exactly once"
+ );
+ });
+
+ test("invalid extras are dropped, not merged", function (assert) {
+ const extract = rangeExtractorWithPins(() => [
+ 1.5,
+ -1,
+ 100,
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ "7",
+ null,
+ undefined,
+ 3,
+ ]);
+
+ assert.deepEqual(
+ extract(RANGE),
+ [3, ...WINDOW],
+ "only the integer in [0, count) survives"
+ );
+ });
+
+ test("an empty or nullish extras result leaves the window unchanged", function (assert) {
+ assert.deepEqual(
+ rangeExtractorWithPins(() => [])(RANGE),
+ WINDOW,
+ "no extras → the default window"
+ );
+ assert.deepEqual(
+ rangeExtractorWithPins(() => null)(RANGE),
+ WINDOW,
+ "a nullish result is treated as no extras"
+ );
+ });
+ });
+
+ module("keyFor (@key field)", function () {
+ test("keys by the field value when given a field on an object row", function (assert) {
+ // Distinct objects with the SAME field value must resolve to the SAME key —
+ // that is the whole point: a rebuilt object with a stable id keeps its row.
+ assert.strictEqual(
+ keyFor({ id: "u-5", n: 1 }, "id"),
+ keyFor({ id: "u-5", n: 2 }, "id"),
+ "same field value → same key across distinct objects"
+ );
+ assert.notStrictEqual(
+ keyFor({ id: "u-5" }, "id"),
+ keyFor({ id: "u-6" }, "id"),
+ "different field values → different keys"
+ );
+ });
+
+ test("with no field, falls back to identity keying", function (assert) {
+ const item = { id: "u-5" };
+ assert.strictEqual(
+ keyFor(item, undefined),
+ stableKeyFor(item),
+ "no field → same as stableKeyFor(item)"
+ );
+ });
+
+ test("a nullish or primitive row falls back to identity keying, never throws", function (assert) {
+ // The guard: a field name plus a null/primitive row must not attempt property
+ // access. It falls back to stableKeyFor, which supports every item shape.
+ assert.strictEqual(keyFor(null, "id"), stableKeyFor(null), "null row");
+ assert.strictEqual(
+ keyFor(undefined, "id"),
+ stableKeyFor(undefined),
+ "undefined row"
+ );
+ assert.strictEqual(keyFor(7, "id"), 7, "primitive row keys as itself");
+ });
+
+ test("rows whose field value is absent key by identity, not onto one shared key", function (assert) {
+ // Normalizing a nullish field value would send every such row to the SAME
+ // constant, aliasing their measurements and duplicating their iteration key.
+ // Only a DUPLICATE value is the consumer's contract to keep; a MISSING one
+ // has to degrade to the identity keying that works for any item shape.
+ const a = { name: "first" };
+ const b = { name: "second" };
+
+ assert.notStrictEqual(
+ keyFor(a, "id"),
+ keyFor(b, "id"),
+ "two rows both missing the field stay distinct"
+ );
+ assert.strictEqual(
+ keyFor(a, "id"),
+ stableKeyFor(a),
+ "a missing field falls back to the row's own identity"
+ );
+ assert.notStrictEqual(
+ keyFor({ id: null }, "id"),
+ keyFor({ id: null }, "id"),
+ "an explicitly null field value is treated the same way"
+ );
+ });
+
+ test("routes the field value through stableKeyFor so a domain value can't collide with a generated key", function (assert) {
+ // A field value that looks like a generated object key must be escaped, not
+ // taken verbatim, or it could alias a real object's key.
+ const objectKey = stableKeyFor({});
+ assert.notStrictEqual(
+ keyFor({ id: objectKey }, "id"),
+ objectKey,
+ "a field value equal to a generated object key is escaped, not aliased"
+ );
+ });
+ });
+});
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list-variable.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list-variable.gjs
new file mode 100644
index 00000000000..bb544e2c19e
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list-variable.gjs
@@ -0,0 +1,51 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_COUNT = 5000;
+
+export default class VirtualListVariableExample extends Component {
+ /**
+ * A single guess for rows whose real heights differ; each is measured on entry.
+ * Deliberately near the MEAN rather than above every row, so measurements correct
+ * the total in both directions. An estimate above the tallest row would only ever
+ * shrink it, and 5000 rows of one-way drift reads as the primitive mis-measuring
+ * rather than as an estimate settling.
+ */
+ estimateSize = () => 60;
+
+ @cached
+ get rows() {
+ return Array.from({ length: ROW_COUNT }, (_, index) => ({
+ id: index,
+ label: `Row ${index + 1}`,
+ body: "lorem ipsum dolor sit amet ".repeat(((index * 7) % 6) + 1).trim(),
+ }));
+ }
+
+ <template>
+ <DVirtualList
+ @items={{this.rows}}
+ @key="id"
+ @as="ul"
+ @role="list"
+ @itemRole="listitem"
+ @ownedRow={{true}}
+ @estimateSize={{this.estimateSize}}
+ aria-label="Variable height virtual list"
+ as |item row|
+ >
+ <li
+ class="styleguide-virtual-list__vrow"
+ aria-posinset={{row.posinset}}
+ aria-setsize={{row.setSize}}
+ {{row.place row.start row.index}}
+ {{row.measure}}
+ >
+ <strong>{{item.label}}</strong>
+ —
+ {{item.body}}
+ </li>
+ </DVirtualList>
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list.gjs
new file mode 100644
index 00000000000..c6f7baf902f
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/virtual-list.gjs
@@ -0,0 +1,148 @@
+/* The listbox that contains these options is rendered by DVirtualList from
+ `@role`, so the rule cannot see it from inside this block. */
+/* eslint-disable ember/template-require-context-role */
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DVirtualList from "discourse/ui-kit/d-virtual-list";
+
+const ROW_COUNT = 5000;
+const ROW_HEIGHT = 44;
+
+export default class VirtualListExample extends Component {
+ @tracked selectedIndex = 2500;
+ @tracked visibleRange = null;
+
+ estimateSize = () => ROW_HEIGHT;
+ api = null;
+
+ @cached
+ get rows() {
+ return Array.from({ length: ROW_COUNT }, (_, index) => ({
+ id: index,
+ label: `Row ${index + 1}`,
+ }));
+ }
+
+ /**
+ * A fresh function whenever the selection changes, because function identity is
+ * what re-triggers the window, and pure over that captured value, because the
+ * engine calls it outside any tracking frame. Cached so that identity tracks the
+ * selection rather than changing on every read, which is the point being shown.
+ */
+ @cached
+ get selectedPins() {
+ const selectedIndex = this.selectedIndex;
+ return () => (selectedIndex == null ? [] : [selectedIndex]);
+ }
+
+ /**
+ * Whether the selected row falls inside the VISIBLE range. Outside it the row
+ * may still be mounted because of overscan; only beyond that does keeping it
+ * mounted demonstrate `@pinnedIndices`.
+ *
+ * Undefined until the first window is published. Collapsing that into "outside"
+ * would state a positive fact about pinning from an absence of measurement.
+ */
+ get selectionInVisibleRange() {
+ const range = this.visibleRange;
+ if (range == null) {
+ return undefined;
+ }
+ return (
+ this.selectedIndex >= range.startIndex &&
+ this.selectedIndex <= range.endIndex
+ );
+ }
+
+ /** The selected row's 1-based label, so the readout and the rows agree. */
+ get selectedLabel() {
+ return this.rows[this.selectedIndex]?.label ?? "none";
+ }
+
+ @action
+ registerApi(api) {
+ this.api = api;
+ }
+
+ @action
+ trackRange(range) {
+ this.visibleRange = range;
+ }
+
+ @action
+ reselect() {
+ this.selectedIndex = Math.floor(Math.random() * ROW_COUNT);
+ }
+
+ @action
+ scrollToSelection() {
+ this.api?.scrollToIndex(this.selectedIndex, { align: "center" });
+ }
+
+ <template>
+ <div class="styleguide-virtual-list__controls">
+ <DButton
+ @action={{this.reselect}}
+ @translatedLabel="Re-select a random row"
+ />
+ <DButton
+ @action={{this.scrollToSelection}}
+ @translatedLabel="Scroll to selection"
+ />
+ <span class="styleguide-virtual-list__status">
+ {{this.selectedLabel}}
+ —
+ {{#if this.visibleRange}}
+ {{#if this.selectionInVisibleRange}}
+ inside the visible range
+ {{else}}
+ outside the visible range, still mounted
+ {{/if}}
+ (rendering rows
+ {{this.visibleRange.startIndex}}–{{this.visibleRange.endIndex}}
+ of
+ {{this.rows.length}})
+ {{else}}
+ measuring
+ {{/if}}
+ </span>
+ </div>
+
+ <DVirtualList
+ @items={{this.rows}}
+ @key="id"
+ @as="ul"
+ @role="listbox"
+ @itemRole="option"
+ @ownedRow={{true}}
+ @estimateSize={{this.estimateSize}}
+ @initialIndex={{this.selectedIndex}}
+ @initialAlign="center"
+ @pinnedIndices={{this.selectedPins}}
+ @onVisibleRangeChange={{this.trackRange}}
+ @onRegisterApi={{this.registerApi}}
+ aria-label="Virtual list"
+ as |item row|
+ >
+
+ <li
+ class="styleguide-virtual-list__row
+ {{if
+ (eq row.index this.selectedIndex)
+ 'styleguide-virtual-list__row--selected'
+ }}"
+ role="option"
+ aria-selected={{if (eq row.index this.selectedIndex) "true" "false"}}
+ aria-posinset={{row.posinset}}
+ aria-setsize={{row.setSize}}
+ {{row.place row.start row.index}}
+ {{row.measure}}
+ >
+ {{item.label}}
+ </li>
+ </DVirtualList>
+ </template>
+}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/virtual-list.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/virtual-list.gjs
new file mode 100644
index 00000000000..a115f7c6e40
--- /dev/null
+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/virtual-list.gjs
@@ -0,0 +1,35 @@
+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";
+import VirtualListExample from "../../examples/molecules/virtual-list";
+import virtualListSource from "../../examples/molecules/virtual-list?source=file";
+import VirtualListVariableExample from "../../examples/molecules/virtual-list-variable";
+import virtualListVariableSource from "../../examples/molecules/virtual-list-variable?source=file";
+
+export default <template>
+ <StyleguideExample
+ @title="<DVirtualList> — pinned rows and an initial selection"
+ @code={{virtualListSource}}
+ @description="Thousands of rows, of which only the visible window plus overscan is in the DOM. The list opens already scrolled to the selected row."
+ >
+ <:tryThis>
+ Scroll far away from the selection and inspect the DOM: the selected row
+ keeps its
+ <code>[data-index]</code>
+ element mounted, so a cursor pointing at it never dangles.
+ </:tryThis>
+ <:default>
+ <div class="styleguide-virtual-list">
+ <VirtualListExample />
+ </div>
+ </:default>
+ </StyleguideExample>
+
+ <StyleguideExample
+ @title="<DVirtualList> — variable-height rows"
+ @code={{virtualListVariableSource}}
+ @description="Rows whose real heights differ against a single estimate, so each re-measures as it enters the window and the total settles as you scroll. Rows are placed individually rather than laid out in flow, so a correction moves one row instead of reflowing the rest."
+ >
+ <div class="styleguide-virtual-list styleguide-virtual-list--tall">
+ <VirtualListVariableExample />
+ </div>
+ </StyleguideExample>
+</template>
diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
index ccd8afdf67e..76a8b750feb 100644
--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js
@@ -30,6 +30,7 @@ import tooltips from "../components/sections/molecules/tooltips";
import topicListItem from "../components/sections/molecules/topic-list-item";
import topicNotifications from "../components/sections/molecules/topic-notifications";
import topicTimerInfo from "../components/sections/molecules/topic-timer-info";
+import virtualList from "../components/sections/molecules/virtual-list";
import post from "../components/sections/organisms/00-post";
import postList from "../components/sections/organisms/01-post-list";
import postOneboxes from "../components/sections/organisms/02-post-oneboxes";
@@ -101,6 +102,7 @@ const SECTIONS = [
id: "topic-notifications",
},
{ component: topicTimerInfo, category: "molecules", id: "topic-timer-info" },
+ { component: virtualList, category: "molecules", id: "virtual-list" },
{ component: post, category: "organisms", id: "post", priority: 0 },
{ component: postList, category: "organisms", id: "post-list", priority: 1 },
{
diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scss
index 25195282c15..fffd5a2b5eb 100644
--- a/plugins/styleguide/assets/stylesheets/styleguide.scss
+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss
@@ -962,3 +962,54 @@
padding: var(--space-1) var(--space-4) var(--space-1) 0;
}
}
+
+.styleguide-virtual-list {
+ /* The border goes on a wrapper, never on the scroll element: box spacing there
+ offsets the engine's measured total from the DOM scroll height. */
+ border: 1px solid var(--primary-low);
+
+ .d-virtual-list {
+ height: 400px;
+ }
+
+ &--tall .d-virtual-list {
+ height: 600px;
+ }
+
+ &__controls {
+ display: flex;
+ gap: 0.5em;
+ align-items: center;
+ margin-bottom: 0.5em;
+ }
+
+ &__status {
+ color: var(--primary-medium);
+ }
+
+ &__row {
+ /* Border-box so the declared height IS the measured height. Under the default
+ content-box the border makes each row a pixel taller than the estimate, and
+ the total drifts upward as rows are measured. */
+ box-sizing: border-box;
+ display: flex;
+ align-items: center;
+ height: 44px;
+ padding: 0 1em;
+ border-bottom: 1px solid var(--primary-very-low);
+
+ &--selected {
+ background: var(--tertiary-low);
+ font-weight: bold;
+ }
+ }
+
+ &__vrow {
+ /* Intrinsic height rather than a fixed one, so wrapped text of varying length
+ gives each row a different height and forces re-measurement. */
+ box-sizing: border-box;
+ padding: 0.5em 1em;
+ border-bottom: 1px solid var(--primary-very-low);
+ line-height: 1.4;
+ }
+}
diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.yml
index 6f868006dd9..c9042341946 100644
--- a/plugins/styleguide/config/locales/client.en.yml
+++ b/plugins/styleguide/config/locales/client.en.yml
@@ -421,3 +421,5 @@ en:
title: "Combo Button"
segmented_control:
title: "Segmented Control (Button toggle group)"
+ virtual_list:
+ title: "Virtual list"
diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rb
index 636cf7a7aa5..05b7e5076f0 100644
--- a/plugins/styleguide/spec/system/smoke_test_spec.rb
+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb
@@ -45,6 +45,7 @@ RSpec.describe "Styleguide Smoke Test" do
{ href: "/molecules/topic-list-item", title: "Topic List Item" },
{ href: "/molecules/topic-notifications", title: "Topic Notifications" },
{ href: "/molecules/topic-timer-info", title: "Topic Timers" },
+ { href: "/molecules/virtual-list", title: "Virtual list" },
],
"organisms" => [
{ href: "/organisms/post", title: "Post" },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9d3e8834b29..ab1006e2511 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -511,6 +511,9 @@ importers:
'@rollup/plugin-babel':
specifier: ^7.1.0
version: 7.1.0(@babel/[email protected])
+ '@tanstack/virtual-core':
+ specifier: 3.17.5
+ version: 3.17.5
'@types/jquery':
specifier: ^3.5.33
version: 3.5.33
@@ -2920,6 +2923,9 @@ packages:
'@standard-schema/[email protected]':
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-AXfBC3sq6PuYSwyxYORqqgHCNjPGAvKJvZuBBJ1klhztWBB5cgqgwsq8+fNfaQJG7/K4xYBja9S90QFn2zmQAg==}
+
'@transloadit/[email protected]':
resolution: {integrity: sha512-8/SnIF9Q2k52mbjRVAYLranwkaDTLb+O9r4Z/uo8uNw//SjygKvvbF4BHSOuReufaAyum1q13602VcNud25Dfg==}
@@ -10878,6 +10884,8 @@ snapshots:
'@standard-schema/[email protected]': {}
+ '@tanstack/[email protected]': {}
+
'@transloadit/[email protected]': {}
'@tufjs/[email protected]': {}