Repository navigation
feat(lab): experimental ChatVirtualizer - #5461
Conversation
… story Adds a windowing participant for ChatMessageList children: ChatLayout keeps the scroller, ChatMessageList keeps its shell semantics, and the lab ChatVirtualizer renders only the rows near the viewport between two document-flow spacers. It owns follow-at-end (displacement-based disengage, position-based re-engage, declarative jumps) and read-position stability (identity anchoring while scrolled up), with per-type running size estimates behind hysteresis. The story pairs a virtualized and an unvirtualized arm over the same corpus and controls: streaming a reply with 3000 messages mounted measures ~8fps unvirtualized vs the machine's full frame rate virtualized with ~17 rows in the DOM (the status pill shows both live). Related: meta#4102, meta#2282, meta#3942. Co-Authored-By: Claude Fable 5 <[email protected]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
PR Analysis Report🔎 Preview ·
|
| Component | Size | LoC | Visual · A11y · RTL |
|---|---|---|---|
| lab/ChatVirtualizer | 54.0 kB (not measured) · 144 B CSS (not measured) | — | — · ✓ · ✗ |
| lab/Chat | — | — | — · ✓ · — |
| lab/ChatEmojiPicker | 101.0 kB (not measured) · 773 B CSS (not measured) | — | — · ✓ · ✓ |
3 more components
| Component | Size | LoC | Visual · A11y · RTL |
|---|---|---|---|
| lab/ChatReactionBar | 102.2 kB (not measured) · 1.1 kB CSS (not measured) | — | — · ✓ · ✓ |
| lab/ChatTypingIndicator | 25.1 kB (not measured) · 612 B CSS (not measured) | — | — · ✓ · ✓ |
| lab/ChatUnreadDivider | 3.7 kB (not measured) · 348 B CSS (not measured) | — | — · ✓ · ✓ |
Package size: measured; main has no measurement of the merge base to compare yet.
API changes: cli +14 · ~5 · −0 (against the merge base's committed report); core +15 · ~10 · −0 (against the merge base's committed report)
Committed API report behind this build: cli 19 rows, core 25 rows; run pnpm api:report.
44 API changes (advisory)
| Package | Where | Signature | Usage | |
|---|---|---|---|---|
| + | cli |
./api · Types · type SearchResultEntry |
deprecated?: ComponentDeprecation | undefined |
import type {SearchResultEntry} from '@astryxdesign/cli/api'; const x: SearchResultEntry = {deprecated: …} |
| + | cli |
./authoring · Types · interface ComponentDeprecation |
interface ComponentDeprecation |
import type {ComponentDeprecation} from '@astryxdesign/cli/authoring' |
| + | cli |
./authoring · Types · interface ComponentIconSlotDoc |
interface ComponentIconSlotDoc |
import type {ComponentIconSlotDoc} from '@astryxdesign/cli/authoring' |
| + | cli |
./authoring · Types · interface ComponentIconSlotStateDoc |
interface ComponentIconSlotStateDoc |
import type {ComponentIconSlotStateDoc} from '@astryxdesign/cli/authoring' |
| + | cli |
./authoring · Types · interface MultiComponentDoc |
deprecated?: ComponentDeprecation |
import type {MultiComponentDoc} from '@astryxdesign/cli/authoring'; const x: MultiComponentDoc = {deprecated: …} |
| + | cli |
./authoring · Types · interface SingleComponentDoc |
deprecated?: ComponentDeprecation |
import type {SingleComponentDoc} from '@astryxdesign/cli/authoring'; const x: SingleComponentDoc = {deprecated: …} |
| + | cli |
./doc · Types · interface ComponentBaseDoc |
deprecated?: ComponentDeprecation |
import type {ComponentBaseDoc} from '@astryxdesign/cli/doc'; const x: ComponentBaseDoc = {deprecated: …} |
| + | cli |
./doc · Types · interface SubComponentDoc |
deprecated?: ComponentDeprecation |
import type {SubComponentDoc} from '@astryxdesign/cli/doc'; const x: SubComponentDoc = {deprecated: …} |
| + | cli |
./doc · Also exported from an earlier entry point · ComponentDeprecation |
ComponentDeprecation (./authoring) |
import {ComponentDeprecation} from '@astryxdesign/cli/doc' |
| + | cli |
./doc · Also exported from an earlier entry point · ComponentIconSlotDoc |
ComponentIconSlotDoc (./authoring) |
import {ComponentIconSlotDoc} from '@astryxdesign/cli/doc' |
| + | cli |
./doc · Also exported from an earlier entry point · ComponentIconSlotStateDoc |
ComponentIconSlotStateDoc (./authoring) |
import {ComponentIconSlotStateDoc} from '@astryxdesign/cli/doc' |
| + | cli |
./template · Also exported from an earlier entry point · ComponentDeprecation |
ComponentDeprecation (./authoring) |
import {ComponentDeprecation} from '@astryxdesign/cli/template' |
| + | cli |
./template · Also exported from an earlier entry point · ComponentIconSlotDoc |
ComponentIconSlotDoc (./authoring) |
import {ComponentIconSlotDoc} from '@astryxdesign/cli/template' |
| + | cli |
./template · Also exported from an earlier entry point · ComponentIconSlotStateDoc |
ComponentIconSlotStateDoc (./authoring) |
import {ComponentIconSlotStateDoc} from '@astryxdesign/cli/template' |
| ~ | cli |
./api · Functions · function search |
function search: (query: string, options?: { cwd?: string | undefined; type?: "template" | "component" | "hook" | "theme" | "doc" | undefined; limit?: number | undefined }) => Promise<SearchResponse> → function search: (query: string, options?: { cwd?: string | undefined; type?: "template" | "component" | "doc" | "theme" | "hook" | undefined; limit?: number | undefined }) => Promise<SearchResponse> |
import {search} from '@astryxdesign/cli/api'; search(…) |
| ~ | cli |
./authoring · Types · interface MultiComponentDoc |
theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] } → theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[]; componentIcons?: ComponentIconSlotDoc[] } |
import type {MultiComponentDoc} from '@astryxdesign/cli/authoring'; const x: MultiComponentDoc = {theming: …} |
| ~ | cli |
./authoring · Types · interface SingleComponentDoc |
theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] } → theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[]; componentIcons?: ComponentIconSlotDoc[] } |
import type {SingleComponentDoc} from '@astryxdesign/cli/authoring'; const x: SingleComponentDoc = {theming: …} |
| ~ | cli |
./doc · Types · interface ComponentBaseDoc |
theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] } → theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[]; componentIcons?: ComponentIconSlotDoc[] } |
import type {ComponentBaseDoc} from '@astryxdesign/cli/doc'; const x: ComponentBaseDoc = {theming: …} |
| ~ | cli |
./doc · Types · interface SubComponentDoc |
theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] } → theming?: { container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[]; componentIcons?: ComponentIconSlotDoc[] } |
import type {SubComponentDoc} from '@astryxdesign/cli/doc'; const x: SubComponentDoc = {theming: …} |
| + | core |
. · Types · type ComponentIconMap |
type ComponentIconMap<Variant extends string = IconVariant> = { [Slot in ComponentIconSlotName]?: ComponentIconSlotMap[Slot] extends true ? IconName | null | ComponentIconRequest<Variant> : ComponentIconValue<ComponentIconSlotMap[Slot], Variant> } |
import type {ComponentIconMap} from '@astryxdesign/core' |
| + | core |
. · Types · type ComponentIconRequest |
type ComponentIconRequest<Variant extends string = IconVariant> = Readonly<{ icon?: IconName | null; variant?: Variant; size?: IconSize }> |
import type {ComponentIconRequest} from '@astryxdesign/core' |
| + | core |
. · Types · interface ComponentIconSlotMap |
interface ComponentIconSlotMap |
import type {ComponentIconSlotMap} from '@astryxdesign/core' |
| + | core |
. · Types · type ComponentIconSlotName |
type ComponentIconSlotName = keyof ComponentIconSlotMap & string |
import type {ComponentIconSlotName} from '@astryxdesign/core' |
| + | core |
. · Types · type ComponentIconStaticMap |
type ComponentIconStaticMap = Partial<Record<ComponentIconSlotName, IconName | null | ComponentIconRequest<string>>> |
import type {ComponentIconStaticMap} from '@astryxdesign/core' |
| + | core |
. · Types · type ComponentIconValue |
type ComponentIconValue<State, Variant extends string = IconVariant> = IconName | null | ComponentIconRequest<Variant> | ((state: Readonly<State>) => ComponentIconRequest<Variant> | null | undefined) |
import type {ComponentIconValue} from '@astryxdesign/core' |
| + | core |
. · Types · interface DefineThemeInput |
componentIcons?: ComponentIconMap<ThemeIconEntryVariant<IconVariants, Base>> |
import type {DefineThemeInput} from '@astryxdesign/core'; const x: DefineThemeInput = {componentIcons: …} |
| + | core |
. · Types · interface DefinedTheme |
__componentIcons?: Partial<Record<string, StoredComponentIconValue>> @internal |
import type {DefinedTheme} from '@astryxdesign/core'; const x: DefinedTheme = {__componentIcons: …} |
| + | core |
. · Types · interface DefinedTheme |
componentIcons?: ComponentIconStaticMap |
import type {DefinedTheme} from '@astryxdesign/core'; const x: DefinedTheme = {componentIcons: …} |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconMap |
ComponentIconMap (.) |
import {ComponentIconMap} from '@astryxdesign/core/Icon' |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconRequest |
ComponentIconRequest (.) |
import {ComponentIconRequest} from '@astryxdesign/core/Icon' |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconSlotMap |
ComponentIconSlotMap (.) |
import {ComponentIconSlotMap} from '@astryxdesign/core/Icon' |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconSlotName |
ComponentIconSlotName (.) |
import {ComponentIconSlotName} from '@astryxdesign/core/Icon' |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconStaticMap |
ComponentIconStaticMap (.) |
import {ComponentIconStaticMap} from '@astryxdesign/core/Icon' |
| + | core |
./Icon · Also exported from an earlier entry point · ComponentIconValue |
ComponentIconValue (.) |
import {ComponentIconValue} from '@astryxdesign/core/Icon' |
| ~ | core |
. · Components · component DateInput |
prop value?: ISODateString → prop value?: ISODateString | undefined |
<DateInput value={…} /> |
| ~ | core |
. · Components · component DateTimeInput |
prop value?: ISODateTimeString → prop value?: ISODateTimeString | undefined |
<DateTimeInput value={…} /> |
| ~ | core |
. · Components · component TimeInput |
prop value?: ISOTimeString → prop value?: ISOTimeString | undefined |
<TimeInput value={…} /> |
| ~ | core |
. · Hooks · hook useScrollOverflow |
hook useScrollOverflow: () => { overflowStart: boolean; overflowEnd: boolean; hasOverflow: boolean; scrollRef: (el: HTMLElement | null) => void } → hook useScrollOverflow: () => { scrollRef: (el: HTMLElement | null) => void; overflowStart: boolean; overflowEnd: boolean; hasOverflow: boolean } |
import {useScrollOverflow} from '@astryxdesign/core'; useScrollOverflow(…) |
| ~ | core |
Theme targets · target code (Code) |
target code (Code) props [color] → target code (Code) props [color, size] |
defineTheme({components: {'code': {…}}}) |
| ~ | core |
Theme targets · target item (Item) |
target item (Item) props [align, density] → target item (Item) props [align, density] states [disabled, highlighted, selected] |
defineTheme({components: {'item': {…}}}) |
| ~ | core |
Public attributes · attr data-disabled |
attr data-disabled (theme reflection on 30 targets) → attr data-disabled (theme reflection on 31 targets) |
[data-disabled] { … } |
| ~ | core |
Public attributes · attr data-highlighted |
attr data-highlighted (theme reflection on 1 target) → attr data-highlighted (theme reflection on 2 targets) |
[data-highlighted] { … } |
| ~ | core |
Public attributes · attr data-selected |
attr data-selected (theme reflection on 14 targets) → attr data-selected (theme reflection on 15 targets) |
[data-selected] { … } |
| ~ | core |
Public attributes · attr data-size |
attr data-size (theme reflection on 55 targets) → attr data-size (theme reflection on 56 targets) |
[data-size] { … } |
Touched components checked; add ci:run-visual or ci:run-rtl to run the full suites.
Generated by PR Enrichment workflow | View full report
The re-engage threshold maps directly to the follow-semantics discussion in the PR: at 1px (TanStack Virtual's default) stopping visually at the bottom often leaves follow silently disengaged while a stream grows below; the control makes that reproducible in 30 seconds. Co-Authored-By: Claude Fable 5 <[email protected]>
Fast chunk cadence is the stress case for follow ownership — disengage mid-stream, scroll back, re-engage — so make it a control instead of a fixed 25ms. Co-Authored-By: Claude Fable 5 <[email protected]>
'Show code' defaults to the dynamic snippet, which serializes the rendered element tree — at messageCount=3000 that walk freezes the docs panel. docs.source.type='code' renders the story source instead (4KB, instant). Co-Authored-By: Claude Fable 5 <[email protected]>
The virtualized/unvirtualized comparison becomes a story switch instead of a control that turns the subject off: "Thousands of Messages" keeps the virtualizer controls, "Unvirtualized Baseline" carries only the shared corpus/stream controls. startAtTop demos the anchorToKey half of the imperative API (log-reading mode: open at the first row, stream grows below without moving the viewport).
36b86dc to
435d6f3
Compare
435d6f3 to
046a6e7
Compare
…n the spacer The follow and anchoring machinery was measured against wheel gestures and programmatic scrolls. Touch produces scroll events with no wheel event anywhere, and that input class had three defects living in it, found by hand-testing the preview on a phone. Slow drags off the bottom deadlocked: re-engage is a position test, disengage a displacement test, and per-event restores erased the displacement faster than a slow drag could accumulate it — 599 of 600 frames reverted, 8px of 4800 travelled, identical in Blink and WebKit. Where momentum belongs to the scroll view (iOS WebKit, Android) a programmatic write also cancels the fling, so a flick stopped after about two messages. And with writes withheld, rows mounting above the viewport landed their (real − estimate) delta in the geometry and the content crawled under the finger. So while a touch gesture owns the viewport — finger down, plus the settle window after lift-off — the machinery writes no scrollTop at all. The correction it would have written goes into the top spacer instead, and paintOrigin() converts between painted space and model space so the two can never be mixed. Rows in normal document flow are what make that possible: the spacer is a second knob, where a transform-positioned virtualizer has only scrollTop, which is exactly the thing a gesture forbids. Nothing is deferred into a ledger, so nothing stale can replay — the flush is one ordinary sync from the re-stated mode. That restatement is unconditional, because it also hands the adjustment back: anchorAt reads through paintOrigin, so the carried adjustment folds into the stored viewportOffset and zeroing it leaves a single balancing write in the same task. Whether the gesture moved decides only the semantics — a real scroll re-judges follow against the bottom edge, a plain tap keeps the mode it had, and "moved" counts only non-echo scrolls so a browser clamp cannot masquerade as intent. No platform sniffing: where momentum survives a write there are touch events to gate on, and where it does not (a macOS trackpad, whose momentum arrives as wheel events) this path never runs. Settling is scroll silence plus an elastic-overscroll guard, polled; only the last finger off the glass starts it. Measured on this story, 40000px of touch travel: 0 pushbacks, 0 drift events, 1px flush shift, 0px on a tap. Four tests pin the state machine (both the gate and the multi-touch guard fail the suite when reverted). The story's wrapper moves to dvh, which mobile Safari needs to stop the page rubber-banding under the list.
…n a head change Two defects found by hand-testing the preview on a phone. Releasing the finger moved the page. paintOrigin() — and so anchorAt, targetFor and computeWindow — assume painted == model + gestureAdj. At the very top there is nothing above to absorb a negative adjustment into, so the spacer stops at 0 while gestureAdj keeps its full value, and the flush then restates the frame from a map the screen no longer shares. anchorFromPaint reads viewportOffset off a rendered row's rect instead; anchorAt already computes that same quantity (offsets[idx] - y IS the painted top), so this only stops assuming the map holds. A drag ending at the top moved 182px on release before and 0px after, while mid-history the scroll still travels (435px, 1218px) with the picture at 0-1px. Loading older history hijacked the anchor. The live-anchor refresh fired in the middle of an unfinished correction and froze the intermediate position, after which the list held the wrong row faithfully — 7 runs in 12, permanently. A page of history is a correction the size of the page, paid over several passes as those rows measure in; converging is already the state for "a correction is in flight, do not re-derive", it was simply never set for a data change. 7/12 -> 0/12, and every gesture path already clears converging so it cannot wedge. Adds the contract halves jsdom can hold: a prepend re-indexes rows without renumbering their keys, and a gesture that ends with nothing rendered falls back rather than throwing.
|
/approve-spec 5f1c510 |
There was a problem hiding this comment.
Changes are still needed. An engineering owner approved the record at this head, and a batch appended while the list follows now mounts one window (53 rows instead of 2,051 in Chromium).
- A later batch, or a run of single arrivals, while the reader stays in history still mounts every row from the first arrival to the end (a second 2,000-message batch mounted 2,054 rows and took about 390 ms to the next frame in Chromium), because the cap at
ChatVirtualizer.tsx:1437-1446limits only the new run while earlier arrivals stay and the tail run mounts from the first of them; cap the whole arrived set at one window, and add a test that appends two batches while the reader is in history. - Miss: a thread loaded into an empty list, or one that replaces the rows, mounts its first window with no
aria-busy(70 rows in Chromium), so the log can read old messages out as new against the record's AR2, because the news walk atChatVirtualizer.tsx:951-961counts every row as news when no key of the previous data matches; count rows as news, and as arrivals, only when the walk stops at the previous data's last row, and add busy tests for both cases.
Non-blocking: an inline getItemType or estimatedItemSize function now runs the correction pass on every parent render, so both props' docs should ask for a stable function. The failing lint job flags a commit message that reached this branch from main, not one of this pull request's own commits.
[Automated review]
| const sizing = [ | ||
| overscanTop, | ||
| overscanBottom, | ||
| estimatedItemSize, | ||
| getItemType, | ||
| ]; |
There was a problem hiding this comment.
Non-blocking: estimatedItemSize and getItemType are compared by identity, so an inline getItemType={m => m.kind} runs the pass, with its O(n) recompute, on every parent render. Consider asking for a stable function in both props' docs.
The cap on mounted arrivals now applies to the whole set after every change, not only to the newest batch, so a second batch or a run of single arrivals while the reader stays in history keeps one window of the newest rows mounted. The test appends a second 2,000-row batch and three single rows in history.
|
/approve-spec aa7c75a |
There was a problem hiding this comment.
Changes are still needed. An engineering owner approved the record at this head, and the rows that arrive while the reader is in history now stay one window of the newest messages across every batch and single arrival.
- Miss: a thread loaded into a list that mounted empty, or one that replaces the rows, still mounts its first window with no
aria-busy(ChatVirtualizer.tsx:951-961), so the log reads old messages out as new against the record's AR2; count rows as news only when the walk stops at a key the previous data held, and add busy tests for both cases.
Two smaller points, not blocking: say in the estimatedItemSize and getItemType docs to pass a stable function, since an inline one runs the correction pass on every parent render, and trim the file header and the comments that narrate history or other libraries' designs.
[Automated review]
… log Rows count as news only for a tail append, when the walk stops at a row the previous data held. A thread loaded into an empty list, or one that replaces the rows, mounts as history, so the block is busy for that commit and the log does not read old messages out as new. Test and the AR2 verification row cover both.
|
/approve-spec 62e8bf2 |
There was a problem hiding this comment.
Changes are still needed. A thread loaded into an empty list, or one that replaces the rows, now mounts as history for the log, and an engineering owner approved the record at this head.
- The first message that arrives in an empty transcript now mounts inside
aria-busy="true"(ChatVirtualizer.tsx:955-967), so the log does not deliver it, against the record's AR2 ("A message appended at the tail mounts unmarked, and the log delivers it"); count a single row that arrives into an empty list as news, add that state to AR2's verification row, and add a busy test for it. - Miss: the required lint job fails "Check Changeset coverage" because
packages/cli/assets/discover/official-packages.jsonchanges what@astryxdesign/cliships and no Changeset names that package; add one withpnpm changeset:new --packages @astryxdesign/cli --category experimental.
Two smaller points, not blocking: ask for a stable function in the estimatedItemSize and getItemType docs, and trim the file header and the comments that narrate history or other libraries' designs.
[Automated review]
One row arriving into an empty list counts as news, so the opening message of a new conversation mounts unmarked and the log delivers it; a larger load into an empty list stays history. Adds a test and the AR2 verification state, a CLI Changeset for the discover package list, stable-function notes on estimatedItemSize and getItemType, and trims the file header and a history comment.
|
/approve-spec aedf5cb |
|
Some context on AR2 that may help: how two shipped chat UIs deliver new messages. Neither ties announcement to row mounting. What they do
Compared with AR2
Suggestion Most of the remaining complexity (arrival state, a tail run outside the window, the news walk, per-commit busy marking, and the regressions of the last rounds) exists because delivery is tied to mounting inside
This needs an owner decision, because it moves delivery ownership: AST-086 FR4 gives content added inside a live container to that container, and this record names ChatMessageList's Trade-off: the channel speaks plain text, so code blocks and lists lose their structure in the announcement; the full message stays readable in browse mode (AST-086 FR7). |
There was a problem hiding this comment.
Approved pending CI: the CI workflow (unit tests, typecheck and builds) had not finished on this head when this review ran.
The opening message of a new conversation now reaches the transcript's log, the CLI Changeset clears the required lint check, and an engineering owner approved the record at this head.
Non-blocking, worth a follow-up:
- A conversation that opens with two messages in one update still mounts as history (
ChatVirtualizer.tsx:941-944); stating that one-row rule in AR2, or taking a caller signal, would let the record decide the case. - The
.doc.mjsdescriptions ofestimatedItemSizeandgetItemTypecould carry the stable-function note the JSDoc now has. - Two comments still narrate a past bug and other libraries' designs (
ChatVirtualizer.tsx:243-244,:374-377); keeping only the reason would match INV29.
[Automated review]
| // The first message of a new conversation (one row into an empty list) | ||
| // is news too; a larger load into an empty list stays history. | ||
| const isFirstMessage = previous.size === 0 && appended.size === 1; | ||
| newsKeysRef.current = isTailAppend || isFirstMessage ? appended : new Set(); |
There was a problem hiding this comment.
Non-blocking: with this rule, a conversation that opens with two messages in one update (a two-part greeting, or a prompt and its reply appended together) mounts under aria-busy="true" like a loaded thread, so the log does not deliver it. AR2's prose ("A message appended at the tail mounts unmarked") and the record's End-user impact row do not state the one-row rule; consider writing it into AR2, or taking a caller signal instead of a row count.
| name: 'estimatedItemSize', | ||
| type: 'number | ((item: T, index: number) => number)', | ||
| description: | ||
| 'Height assumed for rows that have not been measured yet; a function is authoritative and is never overridden by the running averages. Bias it LOW — an estimate that is too small lets content grow below you and leaves your position valid, while one that is too large shrinks the scroll range and the browser clamps your position into it.', |
There was a problem hiding this comment.
Non-blocking: the JSDoc now asks for a stable function (ChatVirtualizer.tsx:126, :136). The docsite and the CLI read this description, so it could carry the same sentence: "Pass a stable function: a new one each render reprices every row." The same goes for getItemType at line 52.
| // closure. A violation froze attach mode for a memoized consumer on the | ||
| // first render's null scroller (geometry stuck on estimates forever). |
There was a problem hiding this comment.
Non-blocking (INV29): this sentence narrates a past bug. The lines above already state the rule, so it can go.
| // to the pass that just landed. (LegendList snapshots the averages for the | ||
| // duration of a programmatic scroll; virtua reprices once and returns the | ||
| // displacement for the caller to apply as a jump. The invariant all of them | ||
| // hold is that a price move and its position correction are one step.) |
There was a problem hiding this comment.
Non-blocking (INV29): the parenthesis describes other libraries' designs. Suggest keeping only the invariant: "A price move and its position correction are one step."
…check Not for merge. A standalone sandbox page (no Storybook frame) with the contributor's transcript demo: ?mode=virtualized (default, the list's own scroller), ?mode=baseline (unvirtualized ChatLayout) and ?mode=native (messages in the document, scrolled by the page itself). Co-authored-by: yyq1025 <[email protected]>
|
/approve-spec aedf5cb |
What
An experimental
ChatVirtualizerfor@astryxdesign/lab— a windowing participant forChatMessageListchildren — plus two storybook stories (Lab/ChatVirtualizer) that run a virtualized and an unvirtualized arm over the same corpus and controls.The integration formula the component is built around:
ChatMessageList's column (bounded without a percentage). It can instead attach to a scroller the host already owns (scrollElement) and render its content block into it — but not toChatLayout's:ChatLayoutruns its own follow (useChatStreamScroll) on that element with no way to hand it off, and a position with two writers is a position nobody owns. The story builds its own shell (list + dock) for the virtualized arm and keepsChatLayoutfor the baseline; see question 2;ChatMessageListkeeps the shell —role="log",aria-busystreaming semantics, padding — withgap=0(row spacing moves inside the rows, sinceoffsetHeightcannot see flex gap);Why
An unvirtualized transcript degrades with history length, and the cost center is updates, not passive scrolling: streaming a reply re-renders every mounted row. Measured in this story on a 144Hz machine,
messageCount=3000:The story's status pill shows both numbers live, so this reproduces in any checkout: send a message at 3000 messages in “Thousands of Messages”, then do the same in “Unvirtualized Baseline”.
Interaction quality is the part that usually blocks virtualizing chat, so it is the focus: the corrections run pre-paint in the commit's layout effect (no compensation deltas — position is re-derived from a stored reference frame each pass, so misses self-heal), and the follow/anchor semantics were tuned against a CDP-driven painted-frame benchmark (per-frame screenshot sampling of pin error and scroll-up jitter, 8-profile matrix at 0% painted artifacts on the scroll-up axes; happy to share the harness).
Why not an existing virtualization library
Two deliberate differences, neither a knock on the libraries themselves:
anchorTo: 'end'), and it works. This component goes further where chat needs it: disengage judged on the user's own displacement from the position the list last wrote (a live distance read during a stream carries movement the user didn't make, and a wheel that lands between two writes coalesces with the next write into one event — against the previous event it can read as "moved down"; against the write it reads as the reader), a continuous identity anchor while reading history (TanStack anchors identity across data edits like prepends, but re-measures while scrolled up go through delta compensation), and declarative jumps that render the destination before the position lands.ChatMessageListshell work unchanged, a row growing mid-stream moves its neighbors atomically in the browser's own layout, and a correction can go into the top spacer instead ofscrollTop— a lever an absolute scheme does not have (see "Touch input"). It also dissolves the absolute scheme's documented backward-scroll dilemma (compensate above-fold re-measures and cascade jumps, or skip and let the estimate error land in the viewport): the browser moves the neighbors, the anchor re-derives.Touch input
Hand-testing this preview on a phone found three defects that no wheel-driven measurement can reach, because touch produces scroll events with no wheel event anywhere:
scrollTopwrite cancels it; a flick stopped after about two messages.The fix leans on the flow scheme. While a gesture owns the viewport the component writes no
scrollTopat all, and the correction it would have written goes into the top spacer instead — a knob a transform-positioned virtualizer doesn't have, since there the only lever is the one a gesture forbids. Nothing is deferred into a ledger, so nothing stale can replay: the gesture ends with one ordinary sync from the re-stated reference frame. No UA sniffing either — where momentum survives a write there are touch events to gate on, and where it doesn't (a trackpad, whose momentum arrives as wheel events) the path never runs.Measured in this story, 40000px of touch travel: 0 pushbacks, 0 drift events, 1px settle shift, 0px on a tap.
Checked on all three engines (Blink, WebKit, Gecko) against the same corpus and probe: the gate behaves identically, and no engine-specific difference showed up in the scroll or measurement pipeline.
Two more turned up the same way, on the same phone, after that first round.
model + adjustment— but at the very top of the list there is nothing above to absorb into, so the spacer clamps at 0 while the adjustment keeps its full value and every derived position is wrong by the difference. The flush now reads the anchored row's offset off its rect instead of deriving it, which is the same quantity the derived path computes (offsets[idx] - yIS the painted top) with one assumption removed. A drag ending at the top moved 182px on release before and 0px after; mid-history the scroll still travels (435px, 1218px) with the picture holding at 0-1px.convergingis already the state for "a correction is in flight, do not re-derive", it was simply never set for a data change. 7/12 → 0/12, and every gesture path already clears it, so it cannot wedge.Known residual, measured through the new story control: loading a page at the very top holds the anchored row to within 40-60px rather than to 0 (four runs: 39, 58, 42, 42). These rows measure in later than the compensation pass that reads them, so a lighter corpus reads 0 on the same case and this one does not. Smaller than a row, and visible if you are looking for it.
One setting that can make it look broken
estimatedItemSizeshould be biased LOW, and the prop now documents why. The two directions are not symmetric: an estimate that is too small makes content grow as it measures, which extends the scroll range below you and leaves your position valid, while one that is too large makes it shrink and the browser then clamps scrollTop into a range that just got smaller — a position loss nothing can undo. The default errs small on purpose; raising it past typical row height is the one configuration that turns a normal drag into a blank viewport.Questions for maintainers (draft on purpose)
Naming/scope:
ChatVirtualizerfollows the labChat/family convention, but the mechanism is not chat-specific —LogStreamdocuments "no virtualization" as a known limit and could reuse it. Prefer a genericVirtualizer(broader claim, broader review surface) or keep it chat-scoped?Follow ownership and
ChatLayout: the virtualizer is the only writer of its scroller's position — that is what lets "the reader moved" be measured rather than inferred.ChatLayoutcannot host it today because it runsuseChatStreamScrollon its own scroller unconditionally, and the hook already publishes anenabledoption thatChatLayoutdoes not forward. A production consumer carries exactly that seam as a vendored patch (refactor(ui): make the transcript the only writer of its scroll position apache/maka#4105:autoScroll?: booleanonChatLayout, forwarded toenabled; off, the layout installs no scroll listeners and never writesscrollTop). Two consumers wantingChatLayout's chrome with a host-owned position suggests the seam is the long-term shape and the story's own shell is the interim; I'll open that as its own small issue rather than fold it in here. (An earlier revision attached toChatLayout's scroller and measured the consequence: a consumerscrollTo({behavior: 'smooth'})moved 0px of 3000 with both writers live.).doc.mjs: happy to add the docsite entry if lab canary components should ship one from day one.The component deliberately ships no RTL, horizontal, or sections support — it is a primitive under evaluation. Is lab the right staging ground, or would you rather see this stay story-only until the API settles?
Workloads wanted: the follow/anchor machinery was tuned against a chat corpus under a painted-frame benchmark, and this class of component hardens with workload diversity more than with review. If you have a transcript shape or interaction that has broken virtualized lists for you — late-loading images, tool-call expansion, RTL, page zoom, nested sticky content — I'd like to fold it into the story and the regression suite as a named case. Rows whose unmount reads layout (a layout-effect cleanup or ref callback that measures) are the first such case, from this round's review.
Related: #4102, #2282 (story precedent for scroll-behavior issues), #3942 (anchoring policy).
Test plan
pnpm vitest run packages/lab/src/Chat/ChatVirtualizer.test.tsx— 20 contract tests (rendering shape, key coercion, attach mode, imperative handle, identity stability, the touch write-gate state machine: gate suppression, last-finger-lifts settling, touchcancel release, no timer surviving unmount; and who moved the scroller: a wheel by itself does not disengage, a scroll-up the next write outruns still does, a clamp onto a smaller bottom is not displacement, native anchoring is switched off through an attribute and never the element's inline style; and from this round's review: a row removed by a commit still reads the previous extent as the floor from its layout cleanup, and a list switched from attach mode back to its own scroller lands its follow target at its own bottom — both red on the previous revision).Thousands of Messagesat 3000 rows: 15–23 rows mounted throughout; a streamed reply followed at 0px from the bottom whilescrollHeightgrew 359k → 383k; a 300px scroll-up mid-stream released and held (760px from the bottom as the stream continued); the scroll button re-engaged to 0px; 144 fps on the status pill.Lab/ChatVirtualizer— Load 300 older prepends a page of history at whatever position you are reading (the case this had no way to demonstrate before); send/stream/follow, scroll up mid-stream (disengage + anchored reading), scroll button (declarative re-engage),startAtTopfor the anchorToKey/log-reading mode, and the “Unvirtualized Baseline” story at 3000 for the comparison.pnpm --filter @astryxdesign/lab typecheck— clean.Carried over from #5678
The review of #5678 settled, for
useChatStreamScroll, what may move a following container other than the reader; the same four answers apply here and are in the latest revision:overscroll-behavior: contain, an overscroll at the bottom — moves nothing here. Whether the container moved is what the scroll handler measures.progTarget), not from the last event seen, so a wheel the next write outruns still reads as the reader — the comparison use-stick-to-bottom makes againstignoreScrollToTop.data-astryx-chat-virtualizedand one injected!importantrule (thehighlightRangespattern), never through the element's inline style, so in attach mode a host's ownoverflow-anchor— set before or during the list's tenure — is neither read, written nor restored.Carried over from review
The automated review asked for two fixes; both are in the latest revision, each with a regression test.
useInsertionEffectincluded — run only after its whole subtree has mutated. The previous revision's pre-mutation spacer write therefore ran too late: a row whose unmount reads layout (a layout-effect cleanup, a ref callback) sees the extent without the removed rows, the browser clampsscrollTopon the spot, and the live-anchor refresh adopts the clamp as the reader's position. Author-measured, identical in Chromium and Firefox: a jump from mid-history to 100–300px above the bottom landed 2,381–2,617px short. The spacers and rows now live in one content block whosemin-heightis the modelled extent, written only by the correction pass and never through React's style, so from the first removal until the pass re-derives the geometry the floor is the previous extent; the insertion effect is gone. After: 0px in both directions, including with a layout read forced after every single DOM insertion and removal of the commit.scrollElementback to the own scroller kept both, so every follow target aimed past the end of the list and was clamped. Own-container mode now states both as 0 on every pass.One visible consequence: attach mode now renders one content block (
display: flow-root) instead of a bare fragment, so a host's flexgapno longer reaches between rows.Merge main (conflict only)
Merged
mainat a228d96. The only conflict wasinternal/shadcn-registry/routes.lock.json, resolved as the union of both sides' entries in generator format. This pull request's own diff is byte-identical in every file it changes.Review round (maintainer commits on top)
Behavior module: ChatVirtualizer
Two commits on top of yyq1025's work; his commits are unchanged.
groupnamed by a newlabelprop (default: the translated "Messages"), through Core'suseScrollableArea(spec:AST-025FR12).aria-busy="true"until the frame after it. The transcript'srole="log"stays the one owner of delivery.useFingerScrolland its newonEnd) instead of the list's own touch listeners and 150 ms settle clock. It gates from a finger's first scroll until that scroll ends, momentum included, and folds the held correction when it ends.apiRefis nowhandleRef, as in Core components.docs/specs/components/Chat/ChatVirtualizer.spec.mdholds the ownership lines and the verification map. Evidence gap: whetheraria-busykeeps history from being spoken varies by screen reader, so it stays unchecked until a VoiceOver and an NVDA check.getRowKey, as in Core's table row hooks.Depends on two Core changes: the
useFingerScrollend signal and the scroll-anchoring writer (open as separate pull requests). This branch builds once both are onmain.Real Chrome keyboard check (Storybook
Thousands of messages, Chromium):role="group", name "Messages",tabindex="0")ChatVirtualizer unit tests pass (23, including the new finger-scroll, keyboard, focused-row and busy tests), and so does the whole Lab Chat folder (69). Lab tsc for Chat, strict lint and check-knowledge pass too.