An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): experimental ChatVirtualizer (#5461)
Yueqian Yangdaa239e98189
diff --git a/.changeset/chat-virtualizer-cli-discover.md b/.changeset/chat-virtualizer-cli-discover.mdnew file mode 100644index 0000000000..ad2abd6816--- /dev/null+++ b/.changeset/chat-virtualizer-cli-discover.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[experimental] `discover` lists the Lab ChatVirtualizer among the official `@astryxdesign/lab` components.++@cixzhangdiff --git a/.changeset/chat-virtualizer-label.md b/.changeset/chat-virtualizer-label.mdnew file mode 100644index 0000000000..d7ffc37271--- /dev/null+++ b/.changeset/chat-virtualizer-label.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[experimental] Adds the English default name of the Lab ChatVirtualizer's own scroll container (`@astryx.chatVirtualizer.label`, "Messages"). It is a Lab string shipped in Core's locale file; it adds no public API to `@astryxdesign/core`.++@cixzhangdiff --git a/docs/specs/components/Chat/ChatVirtualizer.spec.md b/docs/specs/components/Chat/ChatVirtualizer.spec.mdnew file mode 100644index 0000000000..97b1b817bf--- /dev/null+++ b/docs/specs/components/Chat/ChatVirtualizer.spec.md@@ -0,0 +1,133 @@+---+schema_version: 3+template_version: 7+kind: component+id: component:ChatVirtualizer+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [yyq1025]+review_triggers: [behavior, accessibility, interaction, testing]+verified_by:+ [packages/lab/src/Chat/ChatVirtualizer.test.tsx, scripts/check-knowledge.mjs]+modules: []+families: []+design_specs: []+architecture:+ [architecture:public-component-api, architecture:react-component-runtime]+contributing: []+system_specs: [spec:AST-025, spec:AST-086, spec:AST-094]+---++# ChatVirtualizer component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `@astryxdesign/lab` exports `ChatVirtualizer`, its props and its handle. This record holds only what the list owns beside the transcript it windows; consumer usage is in its `.doc.mjs`. |+| Behavior | The list keeps the rows near the viewport mounted, follows the newest message, and keeps the row a reader is on still while rows above it measure in. |+| End-user impact | People reading a long chat transcript get the same scrolling, keyboard access and screen reader news as an unwindowed one. |+| Builder impact | Callers render it inside `ChatMessageList`, or attach it to a scroller they own. |+| Compatibility/readiness | Additive experimental Lab component; draft until owner review and real-device evidence settle it. |+| Review checks | Reject a second anchoring rule or touch listener set beside Core's, a focused row that unmounts under keyboard focus, and history rows announced as new messages. |+| Governing rules | `architecture:public-component-api` INV23, `architecture:react-component-runtime`, `spec:AST-025` FR12, `spec:AST-086` FR1, and `spec:AST-094`. |++This table is a review projection; the body below is authoritative.++## Intent++ChatVirtualizer lets a chat transcript of thousands of messages cost about one+viewport of DOM. It owns windowing and its position. Delivery of new messages+to assistive technology, the browser's scroll anchoring rule, and the finger+scroll watch stay with their owners.++## Compatibility and migration++- Released default preserved: `yes` (new Lab component)+- Compatibility class: additive experimental+- Controlled/uncontrolled behavior: not applicable+- Migration decision: none++## Ownership boundary++**Owns**++- Which rows are mounted, the spacers that stand for the rest, and the scroll+ position it restores (follow-at-end or a row identity).+- Keeping a row that holds focus mounted while the window moves away from it.+- Its own scroll container's keyboard access, through Core's+ `useScrollableArea`.++**Does not own / non-goals**++- The browser's scroll anchoring rule: the list turns anchoring off only+ through Core's scroll-anchoring writer, the rule's one owner.+- Telling a finger's scroll from the program's, and when it ends: Core's+ `useFingerScroll` decides both; the list holds its scrollTop writes while+ that scroll lasts.+- Delivering new messages to assistive technology: `ChatMessageList`'s+ `role="log"` delivers them (`spec:AST-086` FR1).++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default |+| -------------- | ------------------------------ | ------------------------------------------------------------ | ----------------------------------------- | ------------- |+| Container mode | own container, attach | Whether the list renders its scroller or uses the caller's | `scrollElement` absent, or an element | own container |+| Scroller name | caller `label`, or the default | The accessible name of the list's own scroll container (AR1) | Own-container mode only | "Messages" |++## Behavioral and layout contract++| ID | Requirement | Basis |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |+| FR1 | While its scroller is mounted, the list turns the browser's scroll anchoring off on it through Core's scroll-anchoring writer, and hands it back on unmount; the caller's own `overflow-anchor` is never read or written. | Current source and tests |+| FR2 | While a finger scrolls the list (from its first scroll until it ends, momentum included, as `useFingerScroll` reports), the list writes no scrollTop; position corrections go to the top spacer, and settle when that scroll ends. | Current source and tests |+| FR3 | A row that holds focus stays mounted while the window moves away from it, with a spacer between it and the window, so the scroll geometry does not change. | Current source and tests |+| FR4 | While the reader scrolls, the list reads the scroller's scroll position and size in one batched pass per scroll event, before any write, because the rows it mounts depend on them; the scroll handler writes nothing to the DOM, so it forces no layout. A correction pass runs only when the content changes (an append, a row's measured size, or the window mounting other rows), the scroller's size changes, a sizing prop changes (overscan, the estimated row size, the row-type reader), a caller declares a position, or a finger's scroll ends; a pass whose scroll write the browser clamped runs once more on the next frame, and a history load's pass releases its hold on the next frame. It never runs for a scroll event alone or for a commit that changes none of these, such as a parent re-render with the same rows. Each pass writes its spacers, reads in one batch, writes its spacers and the scroll position, and reads the scroll position once more to claim any move the browser made itself, so it forces at most two layouts (`architecture:react-component-runtime` INV18). | `architecture:react-component-runtime` INV18 |++## Accessibility contract++- **AR1 — Keyboard access.** In own-container mode the scroll container is a+ `group` named by the list's `label`, else the translated "Messages", and+ keyboard users can focus and scroll it (`spec:AST-025` FR12). In attach mode+ the caller's scroller owns this.+- **AR2 — History is not news.** A commit that mounts rows that are not new+ messages (the window moving over history, or history loading above) marks+ the content block `aria-busy="true"` until the frame after it, so the log+ does not read those rows out as new. A message appended at the tail mounts+ unmarked, and the log delivers it.++## Design relationships++None beyond the Chat family's own records.++## Family and system relationships++- `component:ChatMessageList` owns the transcript's log and its delivery.+- `component:ChatLayout` runs its own follow on its scroller, so the list does+ not attach to it.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |+| FR1 | `ChatVirtualizer.test.tsx` anchoring test | attach mode with a caller inline `overflow-anchor` | Anchoring left on, the caller's inline value changed, or the attribute kept after unmount fails. | `audit:ChatVirtualizer/behavior` |+| FR2 | `ChatVirtualizer.test.tsx` finger-scroll tests | finger down, momentum after the lift, scroll end, no finger | A scrollTop write during a finger scroll, or a gate still held after it ends, fails. | `audit:ChatVirtualizer/interaction` |+| FR3, AR1 | `ChatVirtualizer.test.tsx` keyboard tests | default and caller label; a focused row scrolled away | A missing group name, or a focused row that unmounts, fails. | `audit:ChatVirtualizer/a11y` |+| AR2 | `ChatVirtualizer.test.tsx` busy test, thread-load busy test, first-message test, history-arrival test and thread-switch test | window moving over history; a tail append while following; a tail append while the reader is in history, then streamed; another thread replacing the rows while the reader is in history; a 2,000-row batch appended while following and while in history; a thread loaded into an empty list, and one replacing the rows; the first message of an empty transcript | History mounted without `aria-busy` (a loaded or replacing thread included), a tail append (the first message of an empty transcript included) marked busy or left unmounted while the reader is in history, or a replaced thread or an appended batch mounting more than a window of rows, fails. Evidence gap: whether `aria-busy` keeps history from being spoken varies by screen reader; spoken behavior is unchecked until a VoiceOver and an NVDA check. | `audit:ChatVirtualizer/a11y` |+| FR4 | `ChatVirtualizer.test.tsx` layout trace: reads of scroll geometry, rects and row sizes, and writes to spacers and scrollTop | an append while following; scrolling up over history; an append in history; a fling of scroll events; a parent re-render with the same rows | A correction pass with more than two write-then-read turns (two forced layouts), a scroll event that writes to the DOM or reads the scroller's size more than once, or a pass for a commit that changes nothing it reads, fails. | `audit:ChatVirtualizer/behavior` |++## Decision log++None recorded.++## Open questions++None.++## Content boundary++This file does not duplicate consumer prop tables/examples, current audit+results, implementation steps, or family/system rules. It links to their owners.diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex bb8b0ad950..f01c2537df 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -567,6 +567,11 @@"path": "components/lab/chat-unread-divider","aliases": []},+ {+ "name": "component-lab-chat-virtualizer",+ "path": "components/lab/chat-virtualizer",+ "aliases": []+ },{"name": "component-lab-circle-check-indicator","path": "components/lab/circle-check-indicator",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex 82b1d14d9e..910381263e 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -100,6 +100,10 @@"kind": "component","name": "ChatUnreadDivider"},+ {+ "kind": "component",+ "name": "ChatVirtualizer"+ },{"kind": "component","name": "CircleCheckIndicator"diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 0d878863cd..36963c0d8b 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -1447,6 +1447,10 @@"defaultMessage": "New messages","description": "Text on a floating pill at the bottom of a chat viewport when unseen messages arrive below the fold; clicking scrolls to bottom. Keep short — narrow pill."},+ "@astryx.chatVirtualizer.label": {+ "defaultMessage": "Messages",+ "description": "Accessible name of a lab ChatVirtualizer's own scroll container, which keyboard users can focus and scroll, when the caller gives no label."+ },"@astryx.chatLayoutScrollButton.scrollToBottom": {"defaultMessage": "Scroll to bottom","description": "Visible tooltip AND screen-reader label for a small down-arrow button that scrolls the chat viewport to its latest message."diff --git a/packages/lab/src/Chat/ChatVirtualizer.doc.mjs b/packages/lab/src/Chat/ChatVirtualizer.doc.mjsnew file mode 100644index 0000000000..d683111c38--- /dev/null+++ b/packages/lab/src/Chat/ChatVirtualizer.doc.mjs@@ -0,0 +1,161 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'ChatVirtualizer',+ subComponentOf: 'Chat',+ group: 'Chat',+ category: 'Chat',+ displayName: 'Chat Virtualizer',+ description:+ 'Windowed message list for long transcripts: only the rows near the viewport are rendered, and the rest is represented by two spacer elements, so a thread of thousands of messages costs a viewport of DOM. Rows stay in normal document flow. While a finger scrolls the list, position corrections are written as spacer height rather than a scrollTop jump, so nothing moves under the finger; they settle when that scroll ends. Outside a touch gesture the list writes scrollTop. Follows the newest message by default, re-engaging that follow when a user scroll lands within endThreshold of the bottom. Renders its own scroll container, or nests inside one the caller already owns (see scrollElement).',+ props: [+ {+ name: 'data',+ type: 'readonly T[]',+ description:+ 'Rows to render, oldest first. Changes are detected by REFERENCE, so replace the array instead of mutating it — a mutation leaves the geometry stale.',+ required: true,+ },+ {+ name: 'getRowKey',+ type: '(item: T, index: number) => string',+ description:+ 'Stable identity per row, coerced with String(). The size cache and the running size averages are keyed by it, so deriving a key from the index discards every measurement whenever the list shifts.',+ required: true,+ },+ {+ name: 'renderItem',+ type: '(info: {item: T; index: number}) => ReactNode',+ description:+ 'Renders one row. Row spacing must live inside what this returns (padding) — container gap and margins are invisible to measurement, so the geometry would drift by one gap per row.',+ required: true,+ },+ {+ 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.',+ default: '120',+ },+ {+ name: 'handleRef',+ type: 'Ref<ChatVirtualizerHandle>',+ description:+ 'Imperative handle exposing scrollToDistanceFromBottomPx and anchorToKey. Both DECLARE a reference frame rather than performing one scroll: the list keeps restoring the declared position as rows measure in, so a landing is not lost to content that arrives after it.',+ },+ {+ name: 'getItemType',+ type: '(item: T, index: number) => string',+ description:+ 'Classifies a row so measured sizes feed a running average per type. A transcript mixing one-line tool stubs with long markdown then converges to an honest price per shape instead of one blended number.',+ },+ {+ name: 'scrollElement',+ type: 'HTMLElement | null',+ description:+ "Attach mode: the scroll container the caller already owns, into which spacers and rows render as one content block instead of the list creating its own scroller. Pass the ELEMENT, not a ref: a parent's ref attaches after its children's layout effects, so a ref still reads null on the commit that first needs the scroller, and a ref mutation is invisible to React — nothing re-renders and no effect re-runs when it lands, while an element in state makes its arrival a render and a real dependency (scroll listeners, observation, and the gesture state machine are rebuilt when the container changes). Read it in a passive effect and hold it in state. Pass null (not undefined) while it is still pending: undefined means own-container mode, and one commit of that inside an unbounded parent mounts every row.",+ },+ {+ name: 'endThreshold',+ type: 'number',+ description:+ 'How close to the bottom, in px, a user scroll must land to re-engage following the newest message; disengaging is any upward movement past it. Too tight and a user who stops visually at the bottom (trackpad inertia, fractional row heights, page zoom) silently stops following while output grows below them.',+ default: '24',+ },+ {+ name: 'overscanTop',+ type: 'number',+ description:+ 'Extra px of rows kept mounted above the viewport, absorbing upward scrolls before a new window has to be computed.',+ default: '1600',+ },+ {+ name: 'overscanBottom',+ type: 'number',+ description: 'Extra px of rows kept mounted below the viewport.',+ default: '600',+ },+ {+ name: 'label',+ type: 'string',+ description:+ 'Accessible name of the scroll container the list creates, which keyboard users can focus and scroll. Own-container mode only; in attach mode the caller names its own scroller.',+ default: "'Messages' (translated)",+ },+ {+ name: 'style',+ type: 'CSSProperties',+ description:+ 'Applied to the scroll container the list creates. Own-container mode only.',+ },+ {+ name: 'className',+ type: 'string',+ description:+ 'Applied to the scroll container the list creates. Own-container mode only.',+ },+ ],+};++export const docsZh = {+ name: 'ChatVirtualizer',+ displayName: 'Chat Virtualizer',+ description:+ '面向长会话的窗口化消息列表:只渲染视口附近的行,其余用两个占位元素表示,因此上千条消息的线程只消耗一个视口的 DOM。行保持在正常文档流中。手指滚动列表期间,位置修正写入占位高度而非跳写 scrollTop,所以手指下的内容不会移动;该次滚动结束后修正落定。触摸手势之外,列表直接写入 scrollTop。默认跟随最新消息,用户滚动落在距底部 endThreshold 以内时重新接管跟随。可自建滚动容器,也可嵌入调用方已有的容器(见 scrollElement)。',+ propDescriptions: {+ data: '要渲染的行,按时间正序。变更通过引用比较检测,所以请替换数组而不要原地修改。',+ getRowKey:+ '每行的稳定标识(内部用 String() 转换)。尺寸缓存与运行时均值都以它为键,用下标派生会在列表位移时丢弃全部测量结果。',+ renderItem:+ '渲染单行。行间距必须放在返回内容内部(padding)——容器的 gap 和 margin 测量不到,会让几何每行漂移一个间距。',+ estimatedItemSize:+ '未测量行的假定高度;传函数则以函数为准,不受运行时均值覆盖。要往小估:估小了内容向下生长、位置依然有效;估大了滚动范围收缩,浏览器会把位置钳进新范围,无法挽回。',+ handleRef:+ '暴露 scrollToDistanceFromBottomPx 与 anchorToKey 的命令式句柄。两者都是“声明参考系”而非执行一次滚动:行陆续测量进来时列表会持续恢复所声明的位置。',+ getItemType:+ '为行分类,使测量结果按类型累积均值。工具调用短行与长 markdown 混排的会话因此能收敛出各自诚实的价格,而非一个混合数字。',+ scrollElement:+ '接管模式:调用方已有的滚动容器,占位与行包在一个内容块里渲染进去,列表不再自建滚动容器。传元素本身而非 ref:父的 ref 在子的 layout effect 之后才装配,所以最先需要滚动容器的那次提交里 ref 仍读到 null;而且 ref 赋值对 React 不可见,落地时既不重渲染也不重跑 effect,元素存进 state 才让“到达”成为一次渲染和真正的依赖(换容器时滚动监听、观察和手势状态机都要重建)。请在 passive effect 里读出并存进 state。尚未就绪时传 null 而不是 undefined:undefined 表示自建容器模式,在不限高的父容器里哪怕只有一次提交也会挂载全部行。',+ endThreshold:+ '用户滚动落点距底部多少 px 才重新接管跟随;脱离则是任何越过该范围的向上移动。设得太紧,视觉上停在底部的用户(触控板惯性、小数行高、页面缩放)会在内容持续产出时悄悄停止跟随。',+ overscanTop:+ '视口上方额外保持挂载的行数(按 px),用于在需要重算窗口前吸收向上滚动。',+ overscanBottom: '视口下方额外保持挂载的行数(按 px)。',+ label:+ '列表自建滚动容器的无障碍名称,键盘用户可聚焦并滚动它。仅自建容器模式有效;接管模式下由调用方为自己的滚动容器命名。',+ style: '应用在列表自建的滚动容器上。仅自建容器模式有效。',+ className: '应用在列表自建的滚动容器上。仅自建容器模式有效。',+ },+};++export const docsDense = {+ name: 'ChatVirtualizer',+ displayName: 'Chat Virtualizer',+ description:+ 'windowed msg list; rows near viewport + 2 spacers => viewport-sized DOM for 1000s of msgs; rows in document flow; during a finger scroll corrections go to spacer height not scrollTop (nothing moves under the finger, settled when the scroll ends), otherwise scrollTop; follows newest by default, re-engages within endThreshold of bottom; own scroller or attach to caller (scrollElement)',+ propDescriptions: {+ data: 'rows oldest-first; REFERENCE change detection — replace, never mutate',+ getRowKey:+ 'stable id per row; keys the size cache + running averages — never index-derived',+ renderItem:+ 'renders one row; spacing MUST be padding inside the row, not container gap/margin',+ estimatedItemSize:+ 'height for unmeasured rows (fn = authoritative); bias LOW — too large shrinks the range and the browser clamps you',+ handleRef:+ 'scrollToDistanceFromBottomPx + anchorToKey; both DECLARE a frame, restored as rows measure in',+ getItemType:+ 'per-type running averages; keeps tool stubs from blending with long markdown',+ scrollElement:+ "attach mode: caller's scroller, rows render in one content block; pass the ELEMENT not a ref (parent ref attaches after child layout effects + ref writes are invisible to React) — read it in a passive effect, hold it in state; null (not undefined) while pending, else one commit mounts every row",+ endThreshold:+ 'px from bottom for a user scroll to re-engage follow; too tight = silent unfollow',+ overscanTop: 'px of rows mounted above the viewport',+ overscanBottom: 'px of rows mounted below the viewport',+ label:+ "name of the created scroller (keyboard-focusable group); default 'Messages'; own-container mode only",+ style: 'on the created scroller; own-container mode only',+ className: 'on the created scroller; own-container mode only',+ },+};diff --git a/packages/lab/src/Chat/ChatVirtualizer.test.tsx b/packages/lab/src/Chat/ChatVirtualizer.test.tsxnew file mode 100644index 0000000000..2b6476c04f--- /dev/null+++ b/packages/lab/src/Chat/ChatVirtualizer.test.tsx@@ -0,0 +1,939 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, it, expect, vi} from 'vitest';+import {render, act, screen, waitFor} from '@testing-library/react';+import {createRef, useLayoutEffect} from 'react';+import {TOUCH_QUERY} from '@astryxdesign/core/internal/touch';+import {ChatVirtualizer, type ChatVirtualizerHandle} from './ChatVirtualizer';++// jsdom has no real layout (offsetHeight is 0, ResizeObserver never fires),+// so these tests cover the CONTRACT layer — rendering shape, key handling,+// the imperative handle — not scroll geometry. Geometry behavior is covered+// by the storybook story and, upstream of this PR, by a CDP-driven+// painted-frame benchmark suite (numbers in the PR description).++type Row = {id: string | number; text: string};++const rows = (n: number): Row[] =>+ Array.from({length: n}, (_, i) => ({id: i, text: `message ${i}`}));++function renderList(+ data: Row[],+ extra: Partial<React.ComponentProps<typeof ChatVirtualizer<Row>>> = {},+) {+ return render(+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ {...extra}+ />,+ );+}++describe('ChatVirtualizer', () => {+ it('renders two aria-hidden spacers around the windowed rows', () => {+ const {container} = renderList(rows(5));+ const spacers = container.querySelectorAll('[aria-hidden="true"]');+ expect(spacers.length).toBe(2);+ });++ it('tags every rendered row with its data-pkey identity', () => {+ const {container} = renderList(rows(5));+ for (const el of container.querySelectorAll('[data-pkey]')) {+ const key = el.getAttribute('data-pkey');+ expect(key).toBeTruthy();+ expect(typeof key).toBe('string');+ }+ });++ it('coerces number keys to strings (the dataset round-trip contract)', () => {+ const {container} = renderList(rows(3), {+ // Deliberately returns a number at runtime; the component must coerce+ // so the RO pipeline (which reads dataset.pkey strings) and the size+ // cache stay keyed consistently.+ getRowKey: (m: Row) => m.id as unknown as string,+ });+ const first = container.querySelector('[data-pkey]');+ expect(first?.getAttribute('data-pkey')).toBe('0');+ });++ it('renders an empty list as just the spacers', () => {+ const {container} = renderList([]);+ expect(container.querySelectorAll('[data-pkey]').length).toBe(0);+ expect(container.querySelectorAll('[aria-hidden="true"]').length).toBe(2);+ });++ it('renders one content block in attach mode (no own scroll container)', () => {+ const host = document.createElement('div');+ const {container} = renderList(rows(3), {scrollElement: host});+ // Own-container mode nests the same block inside its scroller div;+ // attach mode renders the block alone, spacers first and last.+ const block = container.firstElementChild as HTMLElement;+ expect(block.style.overflowY).toBe('');+ expect(block.firstElementChild?.getAttribute('aria-hidden')).toBe('true');+ expect(block.lastElementChild?.getAttribute('aria-hidden')).toBe('true');+ });++ // ---- The extent floor ----------------------------------------------------+ // A commit removes rows before anything resizes the spacers, so a layout+ // forced inside it (a row's layout cleanup, a ref callback) would see the+ // extent without them, and the browser would clamp scrollTop for good. The+ // content block's min-height is the floor: written by the pass only, so+ // through the whole commit it is still the extent the last pass described.++ it('keeps the previous extent as the floor while the commit removes rows', () => {+ const seen: string[] = [];+ let block: HTMLElement | null = null;+ function Probe({item}: {item: Row}) {+ useLayoutEffect(+ () => () => {+ seen.push(block?.style.minHeight ?? '');+ },+ [],+ );+ return <span>{item.text}</span>;+ }+ const list = (data: Row[]) => (+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <Probe item={item} />}+ estimatedItemSize={100}+ />+ );+ const {container, rerender} = render(list(rows(5)));+ block = container.querySelector<HTMLElement>(+ '[aria-hidden="true"]',+ )!.parentElement;+ // jsdom lays nothing out, so every row keeps its estimate: 5 x 100.+ expect(block?.style.minHeight).toBe('500px');+ act(() => {+ rerender(list(rows(2)));+ });+ expect(seen).toEqual(['500px', '500px', '500px']);+ expect(block?.style.minHeight).toBe('200px');+ });++ it('renders nothing but spacers while the attach element is pending (null)', () => {+ const {container} = renderList(rows(3), {scrollElement: null});+ // null = attach mode waiting: no own container may be created, or an+ // unbounded parent would mount every row for one commit.+ expect(container.querySelector('[style*="overflow"]')).toBeNull();+ });++ it('exposes the declaration handle via handleRef', () => {+ const ref = createRef<ChatVirtualizerHandle>();+ renderList(rows(3), {handleRef: ref});+ expect(typeof ref.current?.scrollToDistanceFromBottomPx).toBe('function');+ expect(typeof ref.current?.anchorToKey).toBe('function');+ // Declarations must not throw without real layout.+ act(() => {+ ref.current?.scrollToDistanceFromBottomPx(0);+ ref.current?.anchorToKey('1', 0);+ // A key that is not in the data must not throw either — it falls back+ // to follow-at-end on the next pass (dead-anchor fallback).+ ref.current?.anchorToKey('missing-key', 0);+ });+ });++ // ---- Touch write-gate --------------------------------------------------+ // jsdom has no compositor, so these pin the STATE MACHINE (which events+ // open and close the gate, and what the gate suppresses), not the geometry+ // it protects. The painted-position numbers behind it are in the PR.++ function attachedList(el: HTMLElement, data: Row[] = rows(50)) {+ return renderList(data, {scrollElement: el});+ }++ const scroller = (): HTMLElement => {+ const el = document.createElement('div');+ Object.defineProperty(el, 'clientHeight', {value: 400, writable: true});+ Object.defineProperty(el, 'scrollHeight', {value: 5000, writable: true});+ el.scrollTop = 2000;+ document.body.appendChild(el);+ return el;+ };++ // A phone: Core's finger-scroll watch listens only where the primary+ // pointer is coarse.+ let restorePointer: () => void = () => {};+ beforeEach(() => {+ const matchMedia = window.matchMedia;+ const coarse = {+ matches: true,+ media: TOUCH_QUERY,+ onchange: null,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ dispatchEvent: () => false,+ } as unknown as MediaQueryList;+ window.matchMedia = (media: string) =>+ media.trim() === TOUCH_QUERY ? coarse : matchMedia(media);+ restorePointer = () => {+ window.matchMedia = matchMedia;+ };+ });+ afterEach(() => {+ restorePointer();+ });++ /** A finger landing on (`down`) or lifting from the scroller's content. */+ const finger = (el: HTMLElement, type: string, down: boolean): void => {+ const target = el.firstElementChild ?? el;+ const e = new Event(type, {bubbles: true, cancelable: true});+ const entry = {identifier: 1, clientX: 5, clientY: 5, target};+ Object.defineProperty(e, 'changedTouches', {value: [entry]});+ Object.defineProperty(e, 'touches', {value: down ? [entry] : []});+ act(() => {+ target.dispatchEvent(e);+ });+ };+ /** The finger scrolls the scroller to `at`. */+ const fingerScrollTo = (el: HTMLElement, at: number): void => {+ el.scrollTop = at;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ };+ /** The finger lifts and its scroll (momentum included) ends. */+ const fingerScrollEnds = (el: HTMLElement): void => {+ finger(el, 'touchend', false);+ act(() => {+ el.dispatchEvent(new Event('scrollend'));+ });+ };++ // ---- Who moved the scroller ----------------------------------------------+ // The list follows by writing its own bottom on every commit; the question+ // every scroll event answers is whether the USER moved the scroller since.+ // jsdom dispatches no scroll events and clamps nothing, so each test writes+ // the position the browser would have reported and dispatches the event.+ // Follow is observable as the next growth commit writing a larger bottom.++ const tallScroller = (): HTMLElement => {+ const el = document.createElement('div');+ Object.defineProperty(el, 'clientHeight', {value: 400, writable: true});+ Object.defineProperty(el, 'scrollHeight', {value: 1e6, writable: true});+ document.body.appendChild(el);+ return el;+ };+ const attachedTo = (data: Row[], el: HTMLElement) => (+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ scrollElement={el}+ />+ );+ // The mount landing is a declared target in flight; its release (and the+ // end of convergence, during which scroll events may not flip the mode)+ // is a rAF away.+ const settled = async (): Promise<void> => {+ await act(async () => {+ await new Promise(r => setTimeout(r, 40));+ });+ };+ const scrollEvent = (el: HTMLElement, at: number): void => {+ el.scrollTop = at;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ };+ const followsAfterGrowth = (+ el: HTMLElement,+ rerender: (ui: React.ReactElement) => void,+ written: number,+ ): boolean => {+ act(() => {+ rerender(attachedTo(rows(60), el));+ });+ return el.scrollTop > written + 1;+ };++ it('a wheel by itself does not disengage follow', async () => {+ // A wheel this scroller never consumes — over a nested scroller with+ // room above, one with overscroll-behavior: contain, an overscroll at+ // the bottom — moves nothing here. Only the container moving counts.+ const el = tallScroller();+ const {rerender} = render(attachedTo(rows(50), el));+ await settled();+ const written = el.scrollTop;+ act(() => {+ el.dispatchEvent(new WheelEvent('wheel', {deltaY: -120}));+ });+ expect(followsAfterGrowth(el, rerender, written)).toBe(true);+ el.remove();+ });++ it('a scroll-up the next write outruns still disengages', async () => {+ // The list wrote the bottom; the reader wheeled up 100px and the event+ // reporting it carries that net. Against the last write the reader's+ // move shows, whatever the previous event said (here: nothing).+ const el = tallScroller();+ const {rerender} = render(attachedTo(rows(50), el));+ await settled();+ const written = el.scrollTop;+ // jsdom clamps nothing: make the box agree with where the list put it.+ Object.defineProperty(el, 'scrollHeight', {+ value: written + el.clientHeight,+ writable: true,+ });+ scrollEvent(el, written - 100);+ expect(followsAfterGrowth(el, rerender, written)).toBe(false);+ el.remove();+ });++ // ---- How often layout is read (FR4) ----------------------------------------+ // jsdom has no layout, so the trace counts what forces one in a browser: a+ // read of scroll geometry, a rect or a row size after a write to a spacer+ // or to scrollTop. Each such write-then-read turn is one forced layout.+ const traceLayout = () => {+ const ops: Array<'W' | 'R' | 'C'> = [];+ // A scroller like tallScroller whose size reads are traced.+ const el = document.createElement('div');+ Object.defineProperty(el, 'clientHeight', {+ configurable: true,+ get: () => {+ ops.push('C');+ return 400;+ },+ });+ Object.defineProperty(el, 'scrollHeight', {+ configurable: true,+ get: () => {+ ops.push('R');+ return 1e6;+ },+ });+ document.body.appendChild(el);+ const restore: Array<() => void> = [];+ const wrap = (+ target: object,+ prop: string,+ onGet: 'R' | 'C' | null,+ onSet: boolean,+ ): void => {+ let owner: object | null = target;+ let desc: PropertyDescriptor | undefined;+ while (owner !== null && desc === undefined) {+ desc = Object.getOwnPropertyDescriptor(owner, prop);+ owner = desc === undefined ? Object.getPrototypeOf(owner) : owner;+ }+ if (desc === undefined) {+ throw new Error(`no ${prop}`);+ }+ const original = desc;+ let stored = original.value;+ Object.defineProperty(target, prop, {+ configurable: true,+ get(this: unknown) {+ if (onGet !== null) {+ ops.push(onGet);+ }+ return original.get ? original.get.call(this) : stored;+ },+ set(this: unknown, value: unknown) {+ if (onSet) {+ ops.push('W');+ }+ if (original.set) {+ original.set.call(this, value);+ } else {+ stored = value;+ }+ },+ });+ restore.push(() => {+ if (Object.getOwnPropertyDescriptor(target, prop) !== undefined) {+ delete (target as Record<string, unknown>)[prop];+ }+ if (owner === target) {+ Object.defineProperty(target, prop, original);+ }+ });+ };+ wrap(el, 'scrollTop', 'R', true);+ wrap(HTMLElement.prototype, 'offsetHeight', 'R', false);+ wrap(CSSStyleDeclaration.prototype, 'height', null, true);+ wrap(CSSStyleDeclaration.prototype, 'minHeight', null, true);+ const rect = Element.prototype.getBoundingClientRect;+ Element.prototype.getBoundingClientRect = function (this: Element) {+ ops.push('R');+ return rect.call(this);+ };+ restore.push(() => {+ Element.prototype.getBoundingClientRect = rect;+ });+ return {+ el,+ ops,+ /** Write-then-read turns: the layouts a browser would be forced to run. */+ forcedLayouts: (): number => {+ let turns = 0;+ let lastWasWrite = false;+ for (const op of ops) {+ if (op === 'W') {+ lastWasWrite = true;+ } else if (lastWasWrite) {+ turns++;+ lastWasWrite = false;+ }+ }+ return turns;+ },+ // One read of the scroller's size per pass or scroll event.+ sizeReads: (): number => ops.filter(op => op === 'C').length,+ stop: (): void => {+ for (const undo of restore.reverse()) {+ undo();+ }+ },+ };+ };++ it('forces at most two layouts per correction pass, and none in the scroll handler', async () => {+ const trace = traceLayout();+ const {el} = trace;+ try {+ const {rerender} = render(attachedTo(rows(60), el));+ await settled();+ trace.ops.length = 0;+ // Each correction pass reads the size once, so the passes are the size+ // reads, and each has exactly two turns: its first spacer write, then+ // its batch of reads; its last writes, then its one read back.+ const passesForceTwoLayoutsEach = (handlerSizeReads: number): void => {+ const passes = trace.sizeReads() - handlerSizeReads;+ expect(passes).toBeGreaterThan(0);+ expect(trace.forcedLayouts()).toBe(2 * passes);+ trace.ops.length = 0;+ };+ // An append while following.+ act(() => rerender(attachedTo(rows(61), el)));+ await settled();+ passesForceTwoLayoutsEach(0);+ // Scrolling up mounts other rows: one handler read, then the passes.+ // (The test's own write stands for the browser's scroll; not traced.)+ el.scrollTop = 0;+ trace.ops.length = 0;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ await settled();+ passesForceTwoLayoutsEach(1);+ // An append while the reader is in history.+ act(() => rerender(attachedTo(rows(62), el)));+ await settled();+ passesForceTwoLayoutsEach(0);++ // A fling: scroll events with no commit in between. The handler reads+ // once per event and writes nothing, so it forces no layout.+ trace.ops.length = 0;+ const marks: number[] = [];+ const before = (): void => {+ marks.push(trace.ops.length);+ };+ const after = (): void => {+ marks.push(trace.ops.length);+ };+ el.addEventListener('scroll', before, {capture: true});+ el.addEventListener('scroll', after);+ try {+ for (const at of [1000, 1040, 1080, 1120]) {+ el.scrollTop = at;+ trace.ops.length = 0;+ marks.length = 0;+ act(() => {+ el.dispatchEvent(new Event('scroll'));+ });+ const inHandler = trace.ops.slice(marks[0], marks[1]);+ expect(inHandler).not.toContain('W');+ expect(inHandler.filter(op => op === 'C')).toHaveLength(1);+ }+ } finally {+ el.removeEventListener('scroll', before, {capture: true});+ el.removeEventListener('scroll', after);+ }+ } finally {+ trace.stop();+ el.remove();+ }+ });++ it('skips the correction pass for a commit that changes nothing it reads', async () => {+ const trace = traceLayout();+ const {el} = trace;+ try {+ // The same rows array: a re-render that changes nothing the list reads.+ const data = rows(60);+ const list = (label: string) => (+ <div aria-label={label}>{attachedTo(data, el)}</div>+ );+ const {rerender} = render(list('a'));+ await settled();+ await settled();+ trace.ops.length = 0;+ // A parent re-render with the same rows: its commit runs no pass.+ act(() => rerender(list('b')));+ expect(trace.sizeReads()).toBe(0);+ expect(trace.forcedLayouts()).toBe(0);+ } finally {+ trace.stop();+ el.remove();+ }+ });++ it('mounts no more than a window of rows when a large batch is appended while following', async () => {+ const el = tallScroller();+ let rendered = new Set<string>();+ const list = (data: Row[]) => (+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => {+ rendered.add(String(item.id));+ return <span>{item.text}</span>;+ }}+ estimatedItemSize={100}+ scrollElement={el}+ />+ );+ const {rerender} = render(list(rows(40)));+ await settled();+ const window = rendered.size;+ // 2,000 messages arrive at once while the list follows the newest one.+ rendered = new Set();+ act(() => rerender(list(rows(2040))));+ await settled();+ expect(rendered.size).toBeLessThanOrEqual(2 * Math.max(window, 60));+ expect(screen.getByText('message 2039')).toBeInTheDocument();+ el.remove();+ });++ it('mounts at most a window of rows when a large batch arrives while the reader is in history', async () => {+ const el = tallScroller();+ const {container, rerender} = render(attachedTo(rows(60), el));+ await settled();+ scrollEvent(el, 0);+ await settled();+ const window = container.querySelectorAll('[data-pkey]').length;+ act(() => rerender(attachedTo(rows(2060), el)));+ expect(+ container.querySelectorAll('[data-pkey]').length,+ ).toBeLessThanOrEqual(2 * window);+ // The newest message is among the ones that mount.+ expect(screen.getByText('message 2059')).toBeInTheDocument();+ // A second batch and then single arrivals, still in history: the mounted+ // arrivals stay one window's worth of the newest rows.+ act(() => rerender(attachedTo(rows(4060), el)));+ expect(+ container.querySelectorAll('[data-pkey]').length,+ ).toBeLessThanOrEqual(2 * window);+ for (const n of [4061, 4062, 4063]) {+ act(() => rerender(attachedTo(rows(n), el)));+ }+ expect(+ container.querySelectorAll('[data-pkey]').length,+ ).toBeLessThanOrEqual(2 * window);+ expect(screen.getByText('message 4062')).toBeInTheDocument();+ el.remove();+ });++ it('mounts no extra rows when another thread replaces the rows while the reader is in history', async () => {+ const el = tallScroller();+ const thread = (prefix: string, n: number): Row[] =>+ Array.from({length: n}, (_, i) => ({+ id: `${prefix}${i}`,+ text: `${prefix} message ${i}`,+ }));+ // Every row rendered, to see the largest commit.+ let rendered = new Set<string>();+ const list = (data: Row[]) => (+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => {+ rendered.add(String(item.id));+ return <span>{item.text}</span>;+ }}+ estimatedItemSize={100}+ scrollElement={el}+ />+ );+ const {container, rerender} = render(list(thread('a', 3000)));+ await settled();+ await settled();+ scrollEvent(el, 0);+ await settled();+ // The reader is in history: the thread's tail is not mounted.+ expect(screen.queryByText('a message 2999')).toBeNull();+ expect(screen.getByText('a message 0')).toBeInTheDocument();+ const mountedInHistory = container.querySelectorAll('[data-pkey]').length;+ // Another thread replaces the rows: none of it is a tail arrival, so no+ // commit renders more than a window's worth of rows, not the whole thread.+ rendered = new Set();+ act(() => rerender(list(thread('b', 3000))));+ await settled();+ expect(rendered.size).toBeLessThanOrEqual(+ 2 * Math.max(mountedInHistory, 60),+ );+ el.remove();+ });++ it('a clamp onto a new, smaller bottom is not displacement', async () => {+ // A row above shrank outside any commit (an image, a font); the browser+ // pinned the position to the new maximum. The reader did not move.+ const el = tallScroller();+ const {rerender} = render(attachedTo(rows(50), el));+ await settled();+ const written = el.scrollTop;+ scrollEvent(el, written); // the write's own echo+ Object.defineProperty(el, 'scrollHeight', {+ value: written - 300 + el.clientHeight,+ writable: true,+ });+ scrollEvent(el, written - 300);+ expect(followsAfterGrowth(el, rerender, written - 300)).toBe(true);+ el.remove();+ });++ it('turns native anchoring off through an attribute, never the inline style', () => {+ const el = tallScroller();+ el.style.overflowAnchor = 'auto';+ const {unmount} = render(attachedTo(rows(50), el));+ expect(el.getAttribute('data-astryx-scroll-anchoring')).toBe('off');+ expect(el.style.overflowAnchor).toBe('auto');+ const rule = document.head.querySelector(+ '[data-astryx-scroll-anchoring="rule"]',+ );+ expect(rule?.textContent).toContain('overflow-anchor:none !important');+ unmount();+ expect(el.hasAttribute('data-astryx-scroll-anchoring')).toBe(false);+ expect(el.style.overflowAnchor).toBe('auto');+ el.remove();+ });++ it('suppresses scroll writes while a finger scrolls, momentum included', () => {+ const el = scroller();+ const handle = createRef<ChatVirtualizerHandle>();+ renderList(rows(50), {scrollElement: el, handleRef: handle});+ finger(el, 'touchstart', true);+ fingerScrollTo(el, 1234);+ // A declaration while the finger owns the viewport writes nothing.+ act(() => handle.current?.scrollToDistanceFromBottomPx(0));+ expect(el.scrollTop).toBe(1234);+ // The lift starts the momentum: still the finger's.+ finger(el, 'touchend', false);+ act(() => handle.current?.scrollToDistanceFromBottomPx(0));+ expect(el.scrollTop).toBe(1234);+ el.remove();+ });++ it('hands the viewport back when the finger scroll ends', () => {+ const el = scroller();+ const handle = createRef<ChatVirtualizerHandle>();+ renderList(rows(50), {scrollElement: el, handleRef: handle});+ finger(el, 'touchstart', true);+ fingerScrollTo(el, 1234);+ fingerScrollEnds(el);+ act(() => handle.current?.scrollToDistanceFromBottomPx(0));+ expect(el.scrollTop).not.toBe(1234);+ el.remove();+ });++ it('opens no gate for a scroll with no finger down', () => {+ const el = scroller();+ const handle = createRef<ChatVirtualizerHandle>();+ renderList(rows(50), {scrollElement: el, handleRef: handle});+ fingerScrollTo(el, 1234);+ act(() => handle.current?.scrollToDistanceFromBottomPx(0));+ expect(el.scrollTop).not.toBe(1234);+ el.remove();+ });++ it('unmounting mid-gesture leaves nothing pending', () => {+ const el = scroller();+ const {unmount} = attachedList(el);+ finger(el, 'touchstart', true);+ fingerScrollTo(el, 1500);+ unmount();+ expect(() => {+ fingerScrollEnds(el);+ }).not.toThrow();+ el.remove();+ });++ it('keeps row identity stable across data replacement', () => {+ const {container, rerender} = renderList(rows(3));+ const before = container.querySelector('[data-pkey="1"]');+ rerender(+ <ChatVirtualizer<Row>+ data={[...rows(3), {id: 3, text: 'message 3'}]}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ />,+ );+ expect(container.querySelector('[data-pkey="1"]')).toBe(before);+ });++ // ---- History prepend ---------------------------------------------------+ // Loading older messages inserts ABOVE everything placed, so the restore+ // owes a correction the size of the whole page. The component treats that as+ // a convergence; what jsdom can check is the CONTRACT the convergence rests+ // on — that a prepend leaves the rows the user is looking at untouched, so+ // there is a stable identity to converge toward. (Geometry: a 300-row+ // prepend from scrollTop 0 slipped the view a row in 7 runs of 12 before+ // this and 0 of 12 after; numbers in the PR.)++ const listOf = (data: Row[]) => (+ <ChatVirtualizer<Row>+ data={data}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ />+ );++ it('a prepend re-indexes rows without renumbering their keys', () => {+ const {container, rerender} = render(listOf(rows(3)));+ const keysBefore = [...container.querySelectorAll('[data-pkey]')].map(e =>+ e.getAttribute('data-pkey'),+ );+ rerender(+ listOf([+ {id: 'older-a', text: 'a'},+ {id: 'older-b', text: 'b'},+ ...rows(3),+ ]),+ );+ const keysAfter = [...container.querySelectorAll('[data-pkey]')].map(e =>+ e.getAttribute('data-pkey'),+ );+ // Every message that was on screen still answers to the same key at a new+ // index. Keying by index instead renumbers all of them, and the anchor+ // then names a different message — which is what makes a prepend jump.+ for (const k of keysBefore) {+ expect(keysAfter).toContain(k);+ }+ expect(container.querySelector('[data-pkey="older-b"]')).not.toBeNull();+ // Deliberately NOT asserting DOM node identity: a window that recomputes+ // across the intermediate render may legitimately unmount and remount a+ // row, and pinning that would be testing React's reconciliation, not this+ // component's contract.+ });++ it('drops the host geometry when it returns to its own scroller', () => {+ // In attach mode the list measures where its block starts inside the+ // host (headers, padding) and what the host renders below it (the dock).+ // Neither exists in its own scroller: kept, they aimed the follow target+ // past the end of the list.+ const host = tallScroller();+ host.scrollTop = 2000;+ const ref = createRef<ChatVirtualizerHandle>();+ const list = (scrollElement?: HTMLElement) => (+ <ChatVirtualizer<Row>+ data={rows(50)}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ scrollElement={scrollElement}+ handleRef={ref}+ />+ );+ const {container, rerender} = render(list(host));+ act(() => {+ rerender(list(undefined));+ });+ act(() => {+ ref.current?.scrollToDistanceFromBottomPx(0);+ });+ // jsdom reports clientHeight 0 for the own scroller, so its bottom is+ // the modelled total: 50 x 100.+ expect((container.firstElementChild as HTMLElement).scrollTop).toBe(5000);+ host.remove();+ });++ it('survives a gesture that ends with nothing rendered', () => {+ vi.useFakeTimers();+ try {+ const el = scroller();+ const {rerender} = attachedList(el, rows(5));+ finger(el, 'touchstart', true);+ fingerScrollTo(el, 300);+ // The list empties under the finger — the flush has no row to read a+ // reference frame off, and must fall back rather than throw.+ rerender(+ <ChatVirtualizer<Row>+ data={[]}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ scrollElement={el}+ />,+ );+ expect(() => {+ fingerScrollEnds(el);+ act(() => {+ vi.advanceTimersByTime(500);+ });+ }).not.toThrow();+ el.remove();+ } finally {+ vi.useRealTimers();+ }+ });++ // ---- Keyboard and assistive technology ----------------------------------++ it('names its own scroller as a group keyboard users can reach', () => {+ const {container, rerender} = renderList(rows(3));+ const own = container.firstElementChild as HTMLElement;+ expect(own.getAttribute('role')).toBe('group');+ expect(own.getAttribute('aria-label')).toBe('Messages');+ rerender(+ <ChatVirtualizer<Row>+ data={rows(3)}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <span>{item.text}</span>}+ estimatedItemSize={100}+ label="Support thread"+ />,+ );+ expect(own.getAttribute('aria-label')).toBe('Support thread');+ });++ it('keeps a focused row mounted while the window moves away from it', async () => {+ const el = tallScroller();+ const {container} = render(+ <ChatVirtualizer<Row>+ data={rows(60)}+ getRowKey={m => String(m.id)}+ renderItem={({item}) => <button type="button">{item.text}</button>}+ estimatedItemSize={100}+ scrollElement={el}+ />,+ );+ await settled();+ const button = screen.getByRole('button', {name: 'message 58'});+ act(() => button.focus());+ // Scroll to the top: row 58 leaves the window.+ scrollEvent(el, 0);+ await settled();+ expect(button.isConnected).toBe(true);+ expect(document.activeElement).toBe(button);+ expect(screen.queryByRole('button', {name: 'message 50'})).toBeNull();+ // A blur with no next target while the row still holds focus keeps it.+ act(() => {+ button.dispatchEvent(new FocusEvent('focusout', {bubbles: true}));+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(button.isConnected).toBe(true);+ // Focus leaves the list: the row is no longer kept.+ act(() => button.blur());+ await act(async () => {+ await Promise.resolve();+ });+ expect(button.isConnected).toBe(false);+ expect(container.querySelectorAll('[data-pkey]').length).toBeGreaterThan(0);+ el.remove();+ });++ it('delivers the first message of an empty transcript unmarked', async () => {+ const el = tallScroller();+ const list = (n: number) => <div role="log">{attachedTo(rows(n), el)}</div>;+ const {container, rerender} = render(list(0));+ await settled();+ const block = container.querySelector('[role="log"]')!+ .firstElementChild as HTMLElement;+ // The opening message arrives: news for the log, not busy.+ act(() => rerender(list(1)));+ expect(screen.getByText('message 0')).toBeInTheDocument();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ // The reply is news too.+ act(() => rerender(list(2)));+ expect(block.hasAttribute('aria-busy')).toBe(false);+ el.remove();+ });++ it('marks a thread loaded into an empty list, or replacing the rows, as busy for the log', async () => {+ const el = tallScroller();+ const thread = (prefix: string, n: number): Row[] =>+ Array.from({length: n}, (_, i) => ({+ id: `${prefix}${i}`,+ text: `${prefix} message ${i}`,+ }));+ const list = (data: Row[]) => <div role="log">{attachedTo(data, el)}</div>;+ const {container, rerender} = render(list([]));+ await settled();+ const block = container.querySelector('[role="log"]')!+ .firstElementChild as HTMLElement;+ // A thread loads into the empty list: its rows are history, not news.+ act(() => rerender(list(thread('a', 60))));+ expect(block.getAttribute('aria-busy')).toBe('true');+ await settled();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ // Another thread replaces the rows: history again.+ act(() => rerender(list(thread('b', 60))));+ expect(block.getAttribute('aria-busy')).toBe('true');+ await settled();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ el.remove();+ });++ it('marks the rows the window moves over as busy for the log, and new tail rows not', async () => {+ const el = tallScroller();+ const list = (n: number) => <div role="log">{attachedTo(rows(n), el)}</div>;+ const {container, rerender} = render(list(60));+ await settled();+ const block = container.querySelector('[role="log"]')!+ .firstElementChild as HTMLElement;+ expect(block.hasAttribute('aria-busy')).toBe(false);+ // A message appended at the tail while following: news for the log.+ act(() => rerender(list(61)));+ expect(block.hasAttribute('aria-busy')).toBe(false);+ // Scrolling up mounts history: busy for that commit and the next frame.+ scrollEvent(el, 0);+ expect(block.getAttribute('aria-busy')).toBe('true');+ await settled();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ el.remove();+ });++ it('mounts a message that arrives while the reader is in history, unmarked, so the log delivers it', async () => {+ const el = tallScroller();+ const withText = (n: number, last?: string) =>+ rows(n).map((row, i) =>+ last !== undefined && i === n - 1 ? {...row, text: last} : row,+ );+ const list = (data: Row[]) => <div role="log">{attachedTo(data, el)}</div>;+ const {container, rerender} = render(list(withText(60)));+ await settled();+ const block = container.querySelector('[role="log"]')!+ .firstElementChild as HTMLElement;+ // The reader scrolls up into history.+ scrollEvent(el, 0);+ await settled();+ expect(screen.queryByText('message 59')).toBeNull();+ // The history mount's busy mark has cleared.+ await waitFor(() => expect(block.hasAttribute('aria-busy')).toBe(false));+ // A reply arrives at the tail: it mounts now, and the commit is not busy.+ act(() => rerender(list(withText(61))));+ expect(screen.getByText('message 60')).toBeInTheDocument();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ // The reply streams: it stays mounted, and the update is not busy either.+ act(() => rerender(list(withText(61, 'message 60, streamed'))));+ expect(screen.getByText('message 60, streamed')).toBeInTheDocument();+ expect(block.hasAttribute('aria-busy')).toBe(false);+ await settled();+ // The rows between the window and the reply stay unmounted.+ expect(screen.queryByText('message 59')).toBeNull();+ el.remove();+ });+});diff --git a/packages/lab/src/Chat/ChatVirtualizer.tsx b/packages/lab/src/Chat/ChatVirtualizer.tsxnew file mode 100644index 0000000000..0670e6293e--- /dev/null+++ b/packages/lab/src/Chat/ChatVirtualizer.tsx@@ -0,0 +1,1600 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ChatVirtualizer.tsx+ * @input Uses React, Core's scrollable-area hook, finger-scroll watch and+ * scroll-anchoring writer; attaches to a caller-owned scroll container+ * that runs no follow of its own, or renders its own+ * @output Exports ChatVirtualizer component, ChatVirtualizerProps and+ * ChatVirtualizerHandle+ * @position Experimental windowing participant for ChatMessageList children:+ * keeps thousands-of-messages transcripts at a bounded DOM size while+ * owning follow-at-end and read-position stability+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/Chat/index.ts (exports)+ */++import * as React from 'react';+import * as stylex from '@stylexjs/stylex';+import {useScrollableArea} from '@astryxdesign/core/hooks';+import {observeResize} from '@astryxdesign/core/utils';+import {useTranslator} from '@astryxdesign/core/i18n';+import {setScrollAnchoringOff} from '@astryxdesign/core/internal/scroll-anchoring';+import {useFingerScroll} from '@astryxdesign/core/internal/touch';++// "Did the declarative target land?" — a convergence tolerance, deliberately+// NOT the same knob as `endThreshold` (which is a user-intent question).+const CONVERGE_EPSILON_PX = 4;++const GLOBAL_BUCKET = '\u0000global';+// Prior strength for shrinkage in effectiveAvg: at this many real samples+// the bucket's own data and the inherited baseline carry equal weight.+const PRIOR_SAMPLES = 5;++// The block that holds the spacers and the windowed rows, in both modes.+// Its `min-height` is the scroll extent's FLOOR and is written imperatively+// (writeSpacers), never through this object, so React's style diffing+// cannot touch it. React applies a parent's own style only after every+// child mutation of the commit, and this component writes the floor only in+// its own layout effect — after its children's — so from the first row+// removal until the pass re-derives the geometry, the floor is the previous+// extent. The extent then cannot collapse under a forced layout in that+// window (a row's layout cleanup, a ref callback, a child's layout effect),+// and the browser has nothing to clamp scrollTop against.+//+// flow-root keeps row margins inside the block, as the own scroller did+// before this block existed. flexShrink: 0 / alignSelf: stretch — in a+// column-flex host scroller (attach mode) the block is a+// flex item and would otherwise be compressed to fit (default shrink 1),+// silently corrupting the whole geometry.+const styles = stylex.create({+ content: {+ display: 'flow-root',+ flexShrink: 0,+ alignSelf: 'stretch',+ },+ // The own scroller positions nothing itself; `relative` keeps a row's+ // absolutely positioned parts inside it.+ scroller: {+ position: 'relative',+ },+});++// While a finger scroll ends in an elastic overscroll, a write would snap the+// bounce onto the clamp; the flush waits a frame at a time until it is over.+const isBouncing = (vp: ViewportRead): boolean =>+ vp.scrollTop < 0 ||+ vp.scrollTop > Math.max(0, vp.scrollHeight - vp.clientHeight) + 1;++/**+ * The scroller's position and size, read together in one batch. A scroll+ * event reads these once and writes nothing. A correction pass reads them+ * once, after its first spacer write, and forces at most two layouts.+ */+type ViewportRead = {+ scrollTop: number;+ scrollHeight: number;+ clientHeight: number;+};+const readViewport = (el: HTMLElement): ViewportRead => ({+ scrollTop: el.scrollTop,+ scrollHeight: el.scrollHeight,+ clientHeight: el.clientHeight,+});++/** Imperative surface — both methods are declarations, not scroll actions. */+export interface ChatVirtualizerHandle {+ /** Declare "be N px above the bottom edge" (0 = follow-at-end). */+ scrollToDistanceFromBottomPx: (px?: number) => void;+ /**+ * Hold one row at a fixed viewport offset (0 = its top edge at the+ * viewport top — the "pin the new prompt to the top" pattern). Same+ * declaration semantics; the reference frame becomes a row identity+ * instead of the bottom edge, so rows resizing above it are absorbed.+ * The position clamps to the scrollable range, and the key must exist in+ * the CURRENT data: a missing key falls back to follow-at-end on the next+ * pass, so declare after the data commit, not ahead of it.+ */+ anchorToKey: (key: string, viewportOffset?: number) => void;+}++export interface ChatVirtualizerProps<T> {+ /** Row data. Changes are detected by REFERENCE — replace, don't mutate. */+ data: readonly T[];+ /**+ * Stable string identity per row (coerced with String() internally).+ * Never derive keys from indices: the size cache and the running size+ * averages are keyed by identity.+ */+ getRowKey: (item: T, index: number) => string;+ renderItem: (info: {item: T; index: number}) => React.ReactNode;+ /**+ * Static estimate (px) for unmeasured rows, or a function — a function is+ * authoritative and never overridden by the running averages.+ *+ * Bias it LOW. 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; 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, and raising it past typical row height is the one setting that+ * can make a drag look broken.+ *+ * Pass a stable function: a new one each render reprices every row.+ */+ estimatedItemSize?: number | ((item: T, index: number) => number);+ /** Imperative declarations (see ChatVirtualizerHandle). */+ handleRef?: React.Ref<ChatVirtualizerHandle>;+ /**+ * Optional item classifier: measured sizes feed a running average PER+ * TYPE, so a corpus mixing tool-call stubs with long markdown converges+ * to honest per-shape prices instead of one blended number.+ *+ * Pass a stable function: a new one each render reprices every row.+ */+ getItemType?: (item: T, index: number) => string;+ /**+ * ATTACH MODE. By default the list renders its own scroll container. Pass+ * the caller's scroll element instead — a scroller that runs no follow of+ * its own, such as a page shell's content area — and it renders one+ * content block (spacers + windowed rows) into the container the caller+ * already owns: the layout component keeps the scroller, the virtualizer+ * is one participant in it. Not ChatLayout's: ChatLayout runs its own+ * follow on that element with no way to turn it off, so attaching there+ * puts two writers on one position. It cannot host attach mode until it+ * exposes a seam to disable that follow.+ *+ * Pass the ELEMENT, not a ref: a parent's ref attaches after its+ * children's layout effects, so a ref would still read null on the commit+ * that matters, while state holding the element re-renders with it+ * available. Pass null (not undefined) while the+ * element is pending: absent = own-container mode, null = attach mode+ * waiting — falling back to the own container for even one commit mounts+ * EVERY row (unbounded clientHeight) and tears it back down (measured:+ * 10s boot at 2000 messages).+ *+ * CONTRACT: row spacing must live INSIDE the rows (padding), never as+ * flex `gap` or margins on the container — offsetHeight cannot see+ * either, so the geometry would drift by one gap per row. Nest inside+ * ChatMessageList with gap=0.+ */+ scrollElement?: HTMLElement | null;+ /**+ * How close to the bottom (px) a user scroll must land to re-engage+ * follow-at-end. This is the RE-ENGAGE condition only — disengaging is+ * upward movement past it. Default 24 matches the value shipped by a+ * production chat transcript; TanStack Virtual's chat mode uses 1px and+ * Legend List 10% of the viewport, so the useful range is wide. Too tight+ * and a user who stops "visually at the bottom" (trackpad inertia,+ * fractional row heights, page zoom) silently stops following while+ * output grows below them.+ */+ endThreshold?: number;+ overscanTop?: number;+ overscanBottom?: number;+ /**+ * Own-container mode only: the accessible name of the scroll container,+ * which keyboard users can focus and scroll. Defaults to the translated+ * "Messages".+ */+ label?: string;+ /** Own-container mode only. */+ style?: React.CSSProperties;+ /** Own-container mode only. */+ className?: string;+}++type AnchorMode = {kind: 'anchor'; key: string; viewportOffset: number};++type Mode = {kind: 'end'; distance: number} | AnchorMode;++type Win = {start: number; end: number};++type Geo = {+ offsets: number[];+ total: number;+ keys: string[];+ index: Map<string, number>;+};++type Bucket = {sum: number; count: number; eff: number};++export function ChatVirtualizer<T>(+ props: ChatVirtualizerProps<T>,+): React.ReactNode {+ const {+ data,+ getRowKey,+ renderItem,+ estimatedItemSize = 120,+ handleRef,+ getItemType,+ scrollElement,+ endThreshold = 24,+ overscanTop = 1600,+ overscanBottom = 600,+ label,+ style,+ className,+ } = props;+ const t = useTranslator();+ // Own-container mode: keyboard users reach and scroll the scroller, a+ // `group` named by this list. It is always a scroll container, so the+ // machinery's scrollTop writes land before the content first overflows.+ const {getViewportProps, getContentProps} = useScrollableArea({+ axis: 'block',+ stickyContainment: 'always',+ keyboardAccess: {+ owner: 'viewport',+ label: label ?? t('@astryx.chatVirtualizer.label'),+ },+ });++ const ownScrollerRef = React.useRef<HTMLDivElement | null>(null);+ const attachMode = scrollElement !== undefined;+ // CLOSURE DISCIPLINE (canonical statement): the machinery is plain+ // render-scope functions, so same-commit callers always see live props;+ // everything created ONCE and outliving renders — the ResizeObserver+ // callback, the imperative handle, the rAF retry — must go through a+ // live ref (syncRef and the prop mirrors below) instead of its birth+ // closure. A violation froze attach mode for a memoized consumer on the+ // first render's null scroller (geometry stuck on estimates forever).+ const scrollElementRef = React.useRef(scrollElement);+ scrollElementRef.current = scrollElement;+ const overscanTopRef = React.useRef(overscanTop);+ overscanTopRef.current = overscanTop;+ const overscanBottomRef = React.useRef(overscanBottom);+ overscanBottomRef.current = overscanBottom;+ // Single accessor so every pass reads the live element in either mode.+ // In attach mode a pending (null) element makes every pass bail rather+ // than falling back to the own container.+ const getScroller = (): HTMLElement | null =>+ scrollElementRef.current !== undefined+ ? scrollElementRef.current+ : ownScrollerRef.current;+ // The live scroller as a ref, for Core's finger-scroll watch, which reads+ // it after each commit and moves to a replaced element.+ const liveScrollerRef = React.useRef<React.RefObject<HTMLElement | null>>({+ get current(): HTMLElement | null {+ return scrollElementRef.current !== undefined+ ? scrollElementRef.current+ : ownScrollerRef.current;+ },+ }).current;+ const contentRef = React.useRef<HTMLDivElement | null>(null);+ const spacerTopRef = React.useRef<HTMLDivElement | null>(null);+ const spacerBottomRef = React.useRef<HTMLDivElement | null>(null);+ // While a focused row sits outside the window it stays mounted (a keyboard+ // user's focus must not fall to the page), with a gap spacer between it and+ // the window so the geometry is unchanged.+ const gapTopRef = React.useRef<HTMLDivElement | null>(null);+ const gapBottomRef = React.useRef<HTMLDivElement | null>(null);+ const [focusedKey, setFocusedKey] = React.useState<string | null>(null);+ // The focused row this render keeps outside the window, read by the passes.+ const pinnedKeyRef = React.useRef<string | null>(null);+ // Rows a commit mounts that are not new messages (the window moving over+ // history, or history loading above) must not reach the transcript's+ // polite log as news: the content block is marked busy for that commit+ // and the next frame. A message appended at the tail mounts unmarked.+ const renderedKeysRef = React.useRef<ReadonlySet<string>>(new Set());+ // The messages the last data change appended at the tail that have not+ // mounted yet: the only rows that mount as news.+ const newsKeysRef = React.useRef(new Set<string>());+ // The first row of the arrived tail run this render mounts (see+ // `arrival`), for the spacers.+ const tailKeyRef = React.useRef<string | null>(null);+ // The commit the last correction pass ran for, so a commit that changes+ // nothing the pass reads skips it.+ const passedRenderRef = React.useRef<{+ keys: string;+ scroller: HTMLElement | null;+ sizing: readonly unknown[];+ } | null>(null);+ const pendingRenderKeysRef = React.useRef('');+ const gapTailRef = React.useRef<HTMLDivElement | null>(null);+ // This render's rows, and whether they mount history, for its commit.+ const pendingRenderedRef = React.useRef<ReadonlySet<string>>(new Set());+ const pendingBusyRef = React.useRef(false);+ const busyClearRef = React.useRef<number | null>(null);+ const rowEls = React.useRef(new Map<string, HTMLDivElement>());+ const sizes = React.useRef(new Map<string, number>());+ const geo = React.useRef<Geo>({+ offsets: [],+ total: 0,+ keys: [],+ index: new Map(),+ });+ const mode = React.useRef<Mode>({kind: 'end', distance: 0});+ // Echo-matching instead of a time window: we record the exact value we+ // wrote; a scroll event only counts as "ours" if scrollTop matches it.+ // A time gate would swallow real user scrolls arriving within the window,+ // leaving a stale anchor that the next restore then fights (double-writer).+ const progTarget = React.useRef<number | null>(null);+ // Which regime scrollTop is in: USER-DRIVEN (a non-echo scroll event was+ // the latest movement — the live-anchor refresh may re-derive identity+ // from scrollTop every pass, covering the events-lag-rAF staleness) or+ // MACHINE-DRIVEN (a declaration was issued and the user has not scrolled+ // since — the stored identity is the truth and refresh must hold off).+ // A regime, not a one-shot: at high scroll speeds several correction+ // passes run between two scroll events, and clearing per pass re-created+ // the staleness class mid-gesture (measured: 5.2% jitter at 60px steps).+ const userScrolledRef = React.useRef(false);+ // Last scrollTop observed by a scroll event, and the px the user has moved+ // away from where the machinery last placed them — the end→anchor decision+ // runs on the latter (see onScroll).+ const lastEventST = React.useRef<number | null>(null);+ const lastUserEventT = React.useRef(0);+ const userAway = React.useRef(0);+ const geoChanged = React.useRef(false);+ const rafRetry = React.useRef<number | null>(null);+ const prevScrollerRef = React.useRef<HTMLElement | null>(null);+ // ---- Touch write-gate --------------------------------------------------+ // While a finger scrolls the viewport (from its first scroll until that+ // scroll ends, momentum included, as Core's finger-scroll watch reports)+ // the machinery writes no scrollTop at all: near the bottom, per-event+ // restores erase a slow drag's displacement faster than it accumulates,+ // and a write during momentum cancels the fling. Nothing is queued as a+ // ledger — the reference frame is declarative, so the flush is one+ // ordinary syncAndRestore from the re-stated mode, when the finger's+ // scroll ends.+ const gestureActive = React.useRef(false);+ // The flush's retry while the scroll ends in an elastic overscroll.+ const flushRetry = React.useRef<number | null>(null);+ // Did the USER move the viewport this gesture? Only non-echo scrolls count.+ // Kept apart from the clock above because a browser clamp (a spacer shrink+ // near the bottom) is movement for settling purposes but is NOT intent:+ // treating it as such let a plain tap mid-stream re-judge follow against a+ // distance the stream itself had grown, and silently disengage.+ const gestureMoved = React.useRef(false);+ const gestureHeld = (): boolean => gestureActive.current;+ // Spacer-side compensation while the gate holds. Rows measuring in during a+ // drag land their (real - estimate) deltas in the geometry, and with+ // scrollTop untouchable the content would crawl under the finger. Document+ // flow gives a second knob a transform-positioned virtualizer lacks: the TOP+ // SPACER absorbs the delta instead — each pass re-anchors the row at the+ // viewport top across the recompute and rolls the difference in here, so+ // on-screen positions stay invariant with zero scrollTop writes. The flush+ // folds it into the adopted anchor and zeroes it in the same atomic pass.+ const gestureAdj = React.useRef(0);+ // Convergence protection (generalized from a one-shot landing flag):+ // whenever a declarative target is set (mount landing, or any imperative+ // scrollTo*), the list is "converging" — scroll events may not flip the+ // mode (bootstrap writes and transient clamps would otherwise read as+ // user scrolls and hijack the target mid-flight), and every pass keeps+ // retrying until the target is reached. Only INTENT signals (wheel/touch,+ // not scroll effects — those mix in our own writes) break it early.+ const converging = React.useRef(true);+ // Prices hold still while a declared target is in flight: the destination is+ // an offset in the geometry, and repricing mid-flight moves it out from under+ // the target. The release gets a rAF pass of its own, so whatever the+ // averages then owe is derived from a settled geometry rather than appended+ // 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.)+ const priceFreeze = React.useRef(true);+ const rafRelease = React.useRef<number | null>(null);+ const [win, setWin] = React.useState<Win>({start: 0, end: -1});+ const winRef = React.useRef(win);+ winRef.current = win;+ const dataRef = React.useRef(data);+ dataRef.current = data;+ const endThresholdRef = React.useRef(endThreshold);+ endThresholdRef.current = endThreshold;++ // Running average of everything measured so far. A static estimate that+ // undershoots makes the bottom RECEDE while scrolling toward it: each cold+ // row that mounts adds (real - est) px of newly discovered distance, faster+ // than a mouse wheel can close it. Once samples exist they price unmeasured+ // rows, so mounting a cold row discovers ~nothing. An estimatedItemSize+ // FUNCTION is authoritative and never overridden — the consumer knows more+ // than an average does. Averages accumulate per item type when getItemType+ // is given, plus a global cold-start bucket, but the EFFECTIVE price is+ // gated: hysteresis, never while converging, only in scroll-quiet, and every+ // move marks the geometry dirty (see effectiveAvg).+ const bucketsRef = React.useRef(new Map<string, Bucket>());+ const typeByKey = React.useRef(new Map<string, string>());+ const bucket = (t: string): Bucket => {+ let b = bucketsRef.current.get(t);+ if (!b) {+ bucketsRef.current.set(t, (b = {sum: 0, count: 0, eff: 0}));+ }+ return b;+ };+ const noteMeasured = (+ key: string,+ prev: number | undefined,+ px: number,+ ): void => {+ for (const t of [GLOBAL_BUCKET, typeByKey.current.get(key)]) {+ if (t === undefined) {+ continue;+ }+ const b = bucket(t);+ if (prev === undefined) {+ b.sum += px;+ b.count += 1;+ } else {+ b.sum += px - prev;+ }+ }+ };+ // A bucket's effective price INITIALIZES from the inherited baseline (the+ // global average, or the static estimate), so a type first encountered+ // mid-scroll is not a cliff — zero-initialized buckets made the first+ // per-type pricing a mass repricing event.+ // READ ONLY. Whether a price MOVES is decided once per pass, in+ // repriceBuckets — never here, which runs per row.+ const effectiveAvg = (t: string, baseline: number): number => {+ const b = bucketsRef.current.get(t);+ return !b || b.count === 0 || b.eff === 0 ? baseline : b.eff;+ };++ // Decide repricing once per pass, before the rebuild. A clock gate inside+ // the row loop can reprice part of the list.+ const repriceBuckets = (): void => {+ if (typeof estimatedItemSize === 'function') {+ return; // a function estimate is authoritative — nothing to reprice+ }+ if (converging.current || priceFreeze.current) {+ return;+ }+ // Sampled ONCE per pass, and only while scrolling is QUIET: a repricing+ // event moves every unmeasured offset at once, so landing it mid-scroll+ // costs a frame of up-to-step-size deviation. A quarter second of silence+ // defers the same correction into frames nobody is watching. (Streams+ // reprice freely — machinery echoes are not user events.)+ const quiet = performance.now() - lastUserEventT.current > 250;+ // Shrinkage toward the inherited baseline: the baseline counts as+ // PRIOR_SAMPLES virtual samples, so a young bucket's mean is mostly+ // baseline and the data takes over smoothly as samples accumulate.+ const settle = (b: Bucket | undefined, baseline: number): number => {+ if (!b || b.count === 0) {+ return baseline;+ }+ const raw =+ (b.sum + PRIOR_SAMPLES * baseline) / (b.count + PRIOR_SAMPLES);+ if (b.eff === 0) {+ b.eff = baseline > 0 ? baseline : raw;+ }+ if (quiet && Math.abs(raw - b.eff) > b.eff * 0.1) {+ b.eff = raw;+ geoChanged.current = true;+ }+ return b.eff;+ };+ // Global first: it is the baseline every type bucket shrinks toward, so it+ // has to settle before they read it.+ const global = settle(+ bucketsRef.current.get(GLOBAL_BUCKET),+ estimatedItemSize,+ );+ if (getItemType) {+ for (const [t, b] of bucketsRef.current) {+ if (t !== GLOBAL_BUCKET) {+ settle(b, global);+ }+ }+ }+ };+ const estOf = (item: T, i: number): number => {+ if (typeof estimatedItemSize === 'function') {+ return estimatedItemSize(item, i);+ }+ const global = effectiveAvg(GLOBAL_BUCKET, estimatedItemSize);+ return getItemType ? effectiveAvg(getItemType(item, i), global) : global;+ };++ const recompute = (): void => {+ const d = dataRef.current;+ const offsets = new Array<number>(d.length);+ const keys = new Array<string>(d.length);+ let y = 0;+ const index = new Map<string, number>();+ for (let i = 0; i < d.length; i++) {+ // String coercion is part of the key contract: the RO pipeline reads+ // keys back from dataset.pkey (always a string), so a number key would+ // split the size cache in two — the RO copy under the string, the sync+ // copy under the number — and every RO re-measure would feed the+ // averages as a fresh sample. Coercing at both derivation points keeps+ // every internal map keyed consistently.+ keys[i] = String(getRowKey(d[i], i));+ index.set(keys[i], i);+ offsets[i] = y;+ y += sizes.current.get(keys[i]) ?? estOf(d[i], i);+ }+ geo.current = {offsets, total: y, keys, index};+ };++ // index of the last row whose offset <= y+ const indexAt = (y: number): number => {+ const {offsets} = geo.current;+ let lo = 0;+ let hi = offsets.length - 1;+ while (lo < hi) {+ const mid = (lo + hi + 1) >> 1;+ if (offsets[mid] <= y) {+ lo = mid;+ } else {+ hi = mid - 1;+ }+ }+ return lo;+ };++ const computeWindow = (vp: ViewportRead, desiredTop?: number): Win => {+ const g = geo.current;+ if (g.keys.length === 0) {+ return {start: 0, end: -1};+ }+ const top = (desiredTop ?? vp.scrollTop) - paintOrigin();+ const start = indexAt(Math.max(0, top - overscanTopRef.current));+ const bottomEdge = top + vp.clientHeight + overscanBottomRef.current;+ // When the query reaches past the content, include the last row by+ // construction instead of by binary search: a zero-height final row sits+ // AT total, which the search (offsets[i] <= total - 1) can never select.+ const end = bottomEdge >= g.total ? g.keys.length - 1 : indexAt(bottomEdge);+ return {start, end};+ };++ const setWindowIfChanged = (next: Win): void => {+ const cur = winRef.current;+ if (next.start !== cur.start || next.end !== cur.end) {+ geoChanged.current = true;+ setWin(next);+ }+ };++ // Size both spacers so the mounted window occupies its true place in the+ // scroll range, under whatever geometry is current, and move the content+ // block's floor (styles.content) to the extent that geometry describes.+ const writeSpacers = (w: Win): void => {+ const g = geo.current;+ const empty = w.end < w.start || g.offsets.length === 0;+ const offsetAfter = (i: number): number =>+ i + 1 < g.offsets.length ? g.offsets[i + 1] : g.total;+ const pinnedKey = pinnedKeyRef.current;+ const pinned =+ empty || pinnedKey === null ? undefined : g.index.get(pinnedKey);+ const pinnedAbove = pinned !== undefined && pinned < w.start;+ const pinnedBelow = pinned !== undefined && pinned > w.end;+ // The arrived tail run: from its first row to the last row.+ const tailKey = tailKeyRef.current;+ const tailIndex =+ empty || tailKey === null ? undefined : g.index.get(tailKey);+ const tail =+ tailIndex !== undefined && tailIndex > w.end ? tailIndex : undefined;+ const first = pinnedAbove ? pinned : w.start;+ const last =+ tail !== undefined ? g.keys.length - 1 : pinnedBelow ? pinned : w.end;+ // gestureAdj shifts the whole rendered block without touching scrollTop+ // (0 outside a touch gesture). Clamped at the very top of the list —+ // there is no spacer left to absorb into there.+ const top = empty ? 0 : Math.max(0, g.offsets[first] + gestureAdj.current);+ const belowEnd = empty ? 0 : offsetAfter(last);+ const write = (+ ref: React.RefObject<HTMLDivElement | null>,+ prop: 'height' | 'minHeight',+ px: number,+ ): void => {+ if (ref.current) {+ ref.current.style[prop] = `${px}px`;+ }+ };+ write(spacerTopRef, 'height', top);+ write(+ gapTopRef,+ 'height',+ pinnedAbove ? Math.max(0, g.offsets[w.start] - offsetAfter(pinned)) : 0,+ );+ write(+ gapBottomRef,+ 'height',+ pinnedBelow+ ? Math.max(0, g.offsets[pinned] - offsetAfter(w.end))+ : tail !== undefined+ ? Math.max(0, g.offsets[tail] - offsetAfter(w.end))+ : 0,+ );+ write(+ gapTailRef,+ 'height',+ pinnedBelow && tail !== undefined+ ? Math.max(0, g.offsets[tail] - offsetAfter(pinned))+ : 0,+ );+ write(spacerBottomRef, 'height', Math.max(0, g.total - belowEnd));+ // The extent these spacers describe: the model total, plus whatever the+ // top spacer carries beyond its model offset (the gesture adjustment,+ // after the clamp at the very top).+ write(+ contentRef,+ 'minHeight',+ empty ? g.total : g.total + top - g.offsets[first],+ );+ };++ // Where a row identity + viewport offset puts scrollTop under the current+ // geometry, and the reverse: the anchor for whatever is at a scroll offset.+ const anchorAt = (scrollTop: number): Mode => {+ const g = geo.current;+ const y = scrollTop - paintOrigin();+ const idx = indexAt(y);+ return {+ kind: 'anchor',+ key: g.keys[idx],+ viewportOffset: g.offsets[idx] - y,+ };+ };++ // The same reference frame, MEASURED instead of derived. anchorAt's+ // `offsets[idx] - y` IS the anchored row's painted top, but only while+ // painted == model + gestureAdj holds — and the top spacer clamps at 0 when+ // there is nothing above to absorb into, leaving every derived position+ // wrong by the difference. Reading the row's real rect skips the broken map.+ // Same row anchorAt would pick; null when nothing is rendered.+ const anchorFromPaint = (el: HTMLElement, h: number): AnchorMode | null => {+ const g = geo.current;+ const box = el.getBoundingClientRect();+ let best: AnchorMode | null = null;+ for (const [key, rowEl] of rowEls.current) {+ if (!rowEl.isConnected || !g.index.has(key)) {+ continue;+ }+ const r = rowEl.getBoundingClientRect();+ const top = r.top - box.top;+ if (r.bottom - box.top <= 0 || top >= h) {+ continue;+ }+ if (best === null || top < best.viewportOffset) {+ best = {kind: 'anchor', key, viewportOffset: top};+ }+ }+ return best;+ };++ // Scroll offset at which our content starts. Zero when we own the scroller;+ // in attach mode the caller's container can put padding, a header or a+ // sticky region above us, and every offset in `geo` is relative to our first+ // spacer rather than to the scroll box.+ const originRef = React.useRef(0);+ // Content the caller renders BELOW our block (a docked composer's+ // overflow, say: a scroller that deliberately overflows by the composer+ // height so the tail can scroll clear of it). End mode must scroll past+ // it, or the last message parks underneath the overlay (measured:+ // constant 174px).+ const belowRef = React.useRef(0);+ const measureOrigin = (el: HTMLElement, vp: ViewportRead): number => {+ if (scrollElementRef.current == null) {+ // Own container: the content starts at the scroll box and nothing+ // follows it. Stated rather than skipped — a list switched back from+ // attach mode would otherwise keep the host's header and dock offsets+ // and aim every target past the end of its own scroller.+ originRef.current = 0;+ belowRef.current = 0;+ return 0;+ }+ const top = spacerTopRef.current;+ if (!top) {+ return originRef.current;+ }+ originRef.current =+ top.getBoundingClientRect().top -+ el.getBoundingClientRect().top ++ vp.scrollTop;+ belowRef.current = Math.max(+ 0,+ vp.scrollHeight - originRef.current - geo.current.total,+ );+ return originRef.current;+ };+ // Where the model's zero sits ON SCREEN. Identical to the origin except+ // while the touch write-gate holds, when the top spacer carries an extra+ // offset (gestureAdj) that shifts every painted position. Converting+ // through this one function keeps painted space and model space from ever+ // being mixed: anchors read scrollTop through it, targets write back+ // through it.+ const paintOrigin = (): number => originRef.current + gestureAdj.current;++ // Desired scrollTop for a reference frame, clamped to the scrollable range.+ // null when the anchored row no longer exists in the data.+ const targetFor = (m: Mode, clientHeight: number): number | null => {+ const g = geo.current;+ const origin = paintOrigin();+ let raw;+ const below = belowRef.current;+ if (m.kind === 'end') {+ raw = origin + g.total + below - clientHeight - m.distance;+ } else {+ const idx = g.index.get(m.key) ?? -1;+ if (idx < 0) {+ return null;+ }+ raw = origin + g.offsets[idx] - m.viewportOffset;+ }+ return Math.max(0, Math.min(raw, origin + g.total + below - clientHeight));+ };++ // The single correction pass: spacers(old geo) -> measure -> recompute ->+ // spacers(new geo) -> restore.+ const syncAndRestore = (): void => {+ const el = getScroller();+ if (!el) {+ return;+ }+ // Phase 0 — spacers FIRST, from the pre-measure geometry: a window-shift+ // commit swaps rows before the layout effect runs, so the first forced+ // layout below would otherwise place the new rows against stale spacers+ // — every origin and anchor read off it wrong by the swapped rows'+ // height. (The extent itself cannot collapse meanwhile: the content+ // block's floor holds it, see styles.content.) Style writes don't force+ // layout, so the spacers are consistent BEFORE the first read.+ writeSpacers(winRef.current);+ // The pass's one batch of reads, before its next write: position, size,+ // where the content starts, and rows not measured yet (below).+ const vp = readViewport(el);+ const entryScrollTop = vp.scrollTop;+ measureOrigin(el, vp);+ // Refresh the anchor from the LIVE scrollTop against the pre-measure+ // geometry (= what's currently painted). scroll events lag rAF-driven+ // scrolls by a frame; scrollTop itself is ground truth, so deriving the+ // anchor here removes that staleness class entirely.+ if (+ mode.current.kind === 'anchor' &&+ // Re-derive the anchor from the live scrollTop ONLY when scrollTop's+ // latest movement was user-authored. That is the staleness this refresh+ // exists for (scroll events lag rAF scrolls by a frame). When the+ // machinery moved last — a declared anchorToKey landing, a restore, an+ // average repricing — the stored identity is the truth and scrollTop+ // may be mid-correction: re-deriving from it replaced a declared+ // {key, 0} with the neighbouring row at the repricing delta+ // (measured: deterministic 44px landing error).+ userScrolledRef.current &&+ !converging.current &&+ geo.current.keys.length > 0+ ) {+ mode.current = anchorAt(entryScrollTop);+ }+ // Only rows never seen are measured here — the first-mount backstop: an+ // UNMEASURED row is+ // about to paint at its real height while the geometry still carries its+ // estimate, and in document flow that displaces everything below it (the+ // whole viewport) by (real - est) for one frame, then snaps back when RO+ // delivers. Measuring ONCE at mount closes that; growth and reflow of+ // known rows stay on the RO pipeline, so steady-state commits force no+ // layout at all.+ for (const [key, rowEl] of rowEls.current) {+ if (sizes.current.has(key)) {+ continue;+ }+ const px = rowEl.offsetHeight;+ // Never record 0: a row measured while transiently EMPTY (a streaming+ // reply's first commit) would otherwise pin offsets[last] == total,+ // which no bottom-edge query can reach — the row is evicted from the+ // window and, unmounted, can never be re-measured. Deadlock, measured:+ // the streamed reply never rendered at all. Keeping the estimate keeps+ // the row reachable until it has real height.+ if (px === 0) {+ continue;+ }+ const prev = sizes.current.get(key);+ if (prev !== px) {+ noteMeasured(key, prev, px);+ sizes.current.set(key, px);+ geoChanged.current = true;+ }+ }+ // While the write-gate holds, the correction this pass would have written+ // to scrollTop goes into the spacer instead. Anchor to whatever is at the+ // viewport top BEFORE the recompute (identity, so a long momentum keeps+ // re-anchoring to what is on screen now), then absorb the resulting+ // target delta: painted positions come out bit-identical, with no+ // scrollTop write to cancel momentum or fight the finger.+ const heldAnchor =+ gestureHeld() && geo.current.keys.length > 0+ ? anchorAt(entryScrollTop)+ : null;+ repriceBuckets();+ recompute();+ if (heldAnchor !== null) {+ const t = targetFor(heldAnchor, vp.clientHeight);+ if (t !== null) {+ gestureAdj.current -= t - entryScrollTop;+ }+ }+ writeSpacers(winRef.current);++ // restore scrollTop from the stored reference frame+ if (converging.current) {+ geoChanged.current = true;+ }+ let target = targetFor(mode.current, vp.clientHeight);+ // Dead-anchor fallback: a null target means the anchored key is not in+ // the data — an anchorToKey to a missing key, or the anchored row left+ // with a thread switch / history replacement. Convergence could never+ // exit (it only exits by reaching a target, and its gate keeps ignoring+ // scroll events — scrollbar and keyboard could not recover), and a+ // parked dead anchor would neither follow nor restore until the next+ // gesture. Fall back to follow-at-end, the chat default.+ if (target === null) {+ converging.current = false;+ if (dataRef.current.length > 0) {+ mode.current = {kind: 'end', distance: 0};+ userAway.current = 0;+ geoChanged.current = true;+ target = targetFor(mode.current, vp.clientHeight);+ }+ }+ let wroteTarget: number | null = null;+ if (target !== null && geoChanged.current && !gestureHeld()) {+ geoChanged.current = false;+ if (Math.abs(entryScrollTop - target) > 0.5) {+ el.scrollTop = target;+ wroteTarget = target;+ }+ }+ // The pass's one read after its writes: where scrollTop actually is. The+ // browser may clamp our write if the spacer resize hasn't reached layout+ // yet, or clamp on its own when the spacers shrank; either move is ours to+ // claim (below).+ const actual = el.scrollTop;+ if (wroteTarget !== null) {+ // The echo target must be the ACTUAL landing value (otherwise our+ // own clamped write is misread as a user scroll and flips the mode),+ // and a clamp marks the geometry dirty again with a next-frame retry+ // until the write sticks.+ progTarget.current = actual;+ if (Math.abs(actual - wroteTarget) > 1) {+ geoChanged.current = true;+ // One retry slot: consecutive clamped writes coalesce, and unmount+ // cancels it (a post-unmount pass would setWin on a dead tree).+ if (rafRetry.current !== null) {+ cancelAnimationFrame(rafRetry.current);+ }+ rafRetry.current = requestAnimationFrame(() => {+ rafRetry.current = null;+ syncRef.current();+ });+ }+ }+ if (+ converging.current &&+ target !== null &&+ dataRef.current.length > 0 &&+ Math.abs(actual - target) <= CONVERGE_EPSILON_PX+ ) {+ // Reaching the target does not end a HEAD-CHANGE convergence: the rows+ // that arrived above are still measuring in, so the prices and the+ // offsets keep moving for several more passes. Both halves of the+ // protection therefore lift on the SAME later pass — one that sees the+ // settled numbers. Releasing the anchor half here instead let the+ // live-anchor refresh re-derive from a scrollTop still mid-settle and+ // freeze that intermediate position as the new reference frame+ // (measured: a 300-row prepend read at the top moved the reader 33-53px+ // and kept it, every time).+ if (priceFreeze.current) {+ if (rafRelease.current !== null) {+ cancelAnimationFrame(rafRelease.current);+ }+ rafRelease.current = requestAnimationFrame(() => {+ rafRelease.current = null;+ converging.current = false;+ priceFreeze.current = false;+ geoChanged.current = true;+ syncRef.current();+ });+ } else {+ converging.current = false;+ }+ }+ // The window must cover the DESIRED position, not the stale scrollTop:+ // in end mode a newly appended tail row would otherwise never enter the+ // window and its growth stay invisible to the geometry; for a declared+ // anchor it is what renders the destination before the position lands.+ // While the write-gate holds, the viewport belongs to the finger — the+ // desired target is not going to be written, so the window tracks the+ // ACTUAL position (rows must keep mounting under the drag).+ setWindowIfChanged(+ computeWindow(vp, target === null || gestureHeld() ? actual : target),+ );+ // Entry/exit claim: if scrollTop moved during this pass — by our write OR+ // by a SILENT BROWSER CLAMP during a transient layout (spacers not yet+ // caught up with a window shift, an estimate replaced by a smaller+ // measured size) — the movement is machinery-induced, and the coalesced+ // scroll event that dispatches next frame will carry the CURRENT value.+ // Claim it, or that event is misread as a user scroll and hijacks the+ // mode. User input cannot move scrollTop inside synchronous JS+ // (compositor scrolls land at frame boundaries), so this never swallows+ // a real gesture.+ if (actual !== entryScrollTop) {+ progTarget.current = actual;+ }+ };+ // Latest-pass ref for once-created callers (see CLOSURE DISCIPLINE).+ const syncRef = React.useRef(syncAndRestore);+ syncRef.current = syncAndRestore;++ // Data identity change (append / chunk growth) also invalidates geometry.+ const prevData = React.useRef(data);+ if (prevData.current !== data) {+ prevData.current = data;+ geoChanged.current = true;+ // The rows past the last row the previous data had are this change's+ // news, but only for a tail append: the walk must stop at a row the+ // previous data held. A thread loaded into an empty list, or one that+ // replaces the rows, is history, so the log does not read it out. The+ // geometry still indexes the previous data here.+ const previous = geo.current.index;+ const appended = new Set<string>();+ let isTailAppend = false;+ for (let i = data.length - 1; i >= 0; i--) {+ const key = String(getRowKey(data[i], i));+ if (previous.has(key)) {+ isTailAppend = true;+ break;+ }+ appended.add(key);+ }+ // 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();+ // HEAD CHANGE (loading older history, or trimming it). Rows arrived above+ // everything placed, so the restore owes a correction the size of the whole+ // page, paid across several passes as those rows measure in. That is a+ // CONVERGENCE, and treating it as one stops the live-anchor refresh from+ // re-deriving the anchor from a scrollTop still mid-flight — which+ // otherwise freezes the intermediate position as the new anchor, for good.+ // Cannot wedge: every gesture path already clears `converging`.+ const head = data.length > 0 ? String(getRowKey(data[0], 0)) : null;+ if (+ head !== null &&+ geo.current.keys.length > 0 &&+ geo.current.keys[0] !== head+ ) {+ converging.current = true;+ priceFreeze.current = true;+ }+ }++ // The pre-paint correction slot. (No separate initial-landing effect: this+ // pass computes the window from the declared target on the same commits,+ // attach arrival included.) A commit that changes none of what the pass+ // reads — the geometry, the rows mounted, the scroller, the sizing props —+ // skips it: a parent re-render with the same data, a label change.+ React.useLayoutEffect(() => {+ const scroller = getScroller();+ const keys = pendingRenderKeysRef.current;+ const sizing = [+ overscanTop,+ overscanBottom,+ estimatedItemSize,+ getItemType,+ ];+ const passed = passedRenderRef.current;+ if (+ !geoChanged.current &&+ passed !== null &&+ passed.keys === keys &&+ passed.scroller === scroller &&+ passed.sizing.every((value, i) => Object.is(value, sizing[i]))+ ) {+ return;+ }+ passedRenderRef.current = {keys, scroller, sizing};+ syncAndRestore();+ });++ // Marks the content block busy for a commit that mounts history, until+ // the frame after it, so the log does not read those rows out as new.+ React.useLayoutEffect(function markHistoryMountsBusy() {+ // News is news once: a message that has mounted is history after.+ for (const key of pendingRenderedRef.current) {+ newsKeysRef.current.delete(key);+ }+ renderedKeysRef.current = pendingRenderedRef.current;+ const block = contentRef.current;+ if (!pendingBusyRef.current || block === null) {+ return;+ }+ block.setAttribute('aria-busy', 'true');+ if (busyClearRef.current !== null) {+ cancelAnimationFrame(busyClearRef.current);+ }+ busyClearRef.current = requestAnimationFrame(() => {+ busyClearRef.current = requestAnimationFrame(() => {+ busyClearRef.current = null;+ block.removeAttribute('aria-busy');+ });+ });+ });++ // The RO is the measurement pipeline: sizes come from the observed+ // border-box (no forced layout anywhere).+ // Sizes come through Core's shared resize observer, one callback per entry;+ // the sync they trigger runs once per batch, after the last entry.+ const syncQueued = React.useRef(false);+ const onResizeRef = React.useRef<+ ((entry: ResizeObserverEntry) => void) | null+ >(null);+ if (onResizeRef.current === null) {+ onResizeRef.current = entry => {+ // The registration's own synchronous call carries no box: the observer's+ // first real entry follows, so reading the size here would only force a+ // layout.+ if (+ entry.borderBoxSize === undefined &&+ entry.contentRect === undefined+ ) {+ return;+ }+ // One sync for the whole batch: the microtask runs after the shared+ // observer has delivered its last entry.+ if (!syncQueued.current) {+ syncQueued.current = true;+ queueMicrotask(() => {+ syncQueued.current = false;+ syncRef.current();+ });+ }+ const key = (entry.target as HTMLElement).dataset.pkey;+ if (key === undefined) {+ // The scroll CONTAINER (observed in the listener effect): its+ // resize changes clientHeight, which moves the end-mode target and+ // the window coverage with zero row-size changes — without marking+ // the geometry dirty here, a window resize or a growing composer+ // would leave the pinned bottom stranded.+ geoChanged.current = true;+ return;+ }+ // Border box, the same box the sync path reads with offsetHeight —+ // one cache, one definition of a row's size. contentRect is NOT that+ // box (it drops padding and border), so a padded row would be cached+ // short for as long as the fallback is the writer.+ const px =+ entry.borderBoxSize?.[0]?.blockSize ??+ (entry.target as HTMLElement).offsetHeight;+ const prev = sizes.current.get(key);+ if (px > 0 && prev !== px) {+ noteMeasured(key, prev, px);+ sizes.current.set(key, px);+ geoChanged.current = true;+ }+ };+ }+ const unobserveByEl = React.useRef(new Map<Element, () => void>());+ const observeSize = (el: Element): void => {+ if (!unobserveByEl.current.has(el)) {+ unobserveByEl.current.set(el, observeResize(el, onResizeRef.current!));+ }+ };+ const unobserveSize = (el: Element): void => {+ unobserveByEl.current.get(el)?.();+ unobserveByEl.current.delete(el);+ };+ React.useEffect(+ () => () => {+ for (const unobserve of unobserveByEl.current.values()) {+ unobserve();+ }+ unobserveByEl.current.clear();+ if (rafRetry.current !== null) {+ cancelAnimationFrame(rafRetry.current);+ }+ if (rafRelease.current !== null) {+ cancelAnimationFrame(rafRelease.current);+ }+ if (busyClearRef.current !== null) {+ cancelAnimationFrame(busyClearRef.current);+ }+ },+ [],+ );++ // A DECLARATION re-points the reference frame and lets the restore loop+ // converge: machine-driven regime, displacement cleared, protected from+ // mode flips until reached. The window is computed from the declared+ // target first, so the destination renders before the position lands+ // (committed semantics; no blank flash on long jumps).+ const declare = (m: Mode): void => {+ mode.current = m;+ priceFreeze.current = true;+ userScrolledRef.current = false;+ userAway.current = 0;+ converging.current = true;+ geoChanged.current = true;+ syncRef.current(); // captured by the once-created handle: live ref+ };++ // Imperative API — both methods are declarations, not scroll actions.+ // useImperativeHandle so a discarded concurrent render cannot repoint the+ // handle; created once, reads only refs (see CLOSURE DISCIPLINE).+ React.useImperativeHandle(+ handleRef,+ () => ({+ scrollToDistanceFromBottomPx: (px = 0) =>+ declare({kind: 'end', distance: px}),+ anchorToKey: (key, viewportOffset = 0) =>+ declare({kind: 'anchor', key: String(key), viewportOffset}),+ }),+ [],+ );++ // The finger's scroll is over (its scrollend after the lift, momentum+ // included, or the watch's quiet fallback): hand the gesture back.+ const flushGesture = (): void => {+ flushRetry.current = null;+ const el = getScroller();+ if (!el || !gestureActive.current) {+ return;+ }+ // Inside an elastic overscroll a write snaps the bounce onto the clamp+ // and discards where the user let go: wait until it is over.+ // One batch of reads for the gesture's end, before the pass it starts.+ const vp = readViewport(el);+ if (isBouncing(vp)) {+ flushRetry.current = requestAnimationFrame(flushGesture);+ return;+ }+ gestureActive.current = false;+ // Engines report scrollHeight as at least clientHeight, so this is+ // never negative in practice — clamped anyway to hold the same+ // invariant targetFor does.+ const max = Math.max(0, vp.scrollHeight - vp.clientHeight);+ // Re-state the reference frame from the resting position. Whether the+ // gesture MOVED decides the semantics only: a real scroll re-judges+ // follow against the bottom edge, while a scroll that was only our own+ // echo under a resting finger keeps the mode it had — re-judging would+ // read machinery growth as a user pushing away.+ //+ // The re-statement is UNCONDITIONAL, because it is also what hands the+ // gesture adjustment back: the stored viewportOffset is where the+ // anchored row actually IS, so zeroing the adjustment below leaves the+ // sync one balancing scrollTop write, spacers and position moving in the+ // same task. The offset comes from the DOM (anchorFromPaint) rather than+ // being derived, so a clamped spacer cannot make the two disagree.+ if (!converging.current) {+ const atEnd = gestureMoved.current+ ? max - vp.scrollTop <= endThresholdRef.current+ : mode.current.kind === 'end';+ mode.current = atEnd+ ? {kind: 'end', distance: 0}+ : (anchorFromPaint(el, vp.clientHeight) ?? anchorAt(vp.scrollTop));+ userAway.current = 0;+ // The fold is a MACHINE repositioning: the adjustment now lives only+ // in the folded viewportOffset, and the live-anchor refresh — which+ // re-derives from scrollTop once the adjustment is gone — would+ // erase it, dropping the balancing write while the spacers revert+ // (measured: +148px). Machine-driven regime holds the fold until the+ // user actually scrolls again.+ userScrolledRef.current = false;+ }+ gestureAdj.current = 0;+ geoChanged.current = true;+ syncRef.current();+ };+ const flushGestureRef = React.useRef(flushGesture);+ flushGestureRef.current = flushGesture;+ // Core's finger-scroll watch: whether the scroller's scroll is a finger's+ // (only under a coarse primary pointer), and when it ends.+ const isFingerScroll = useFingerScroll(liveScrollerRef, {+ onEnd: () => flushGestureRef.current(),+ });++ const onScroll = (): void => {+ const el = getScroller();+ if (!el) {+ return;+ }+ // The handler's one batch of reads; it writes nothing to the DOM.+ const vp = readViewport(el);+ // The position the machinery last WROTE, kept before the echo slot is+ // cleared below: the user's displacement is measured from there, not+ // from the last event seen. A wheel that lands between two of our+ // writes coalesces with the next write into one event carrying the net,+ // and against the previous event's value that net can still read as+ // "moved down" — the user's own upward step erased by the re-pin.+ const lastWrite = progTarget.current;+ const isEcho =+ lastWrite !== null && Math.abs(vp.scrollTop - lastWrite) <= 1;+ // STICKY echo: k offset changes within one frame queue up to k scroll+ // events, dispatched across successive frames, EACH reading the same+ // final scrollTop. A consume-once slot matches the first and misreads+ // every duplicate as a user scroll. Keep the expectation while events+ // match; only a NON-matching event (a real user scroll) clears it.+ if (!isEcho) {+ progTarget.current = null;+ userScrolledRef.current = true;+ lastUserEventT.current = performance.now();+ }+ const prevEventST = lastEventST.current;+ lastEventST.current = vp.scrollTop;+ if (isFingerScroll()) {+ if (!gestureActive.current) {+ // A finger's scroll begins: an INTENT signal, like a wheel, so it+ // breaks convergence.+ gestureActive.current = true;+ gestureMoved.current = false;+ converging.current = false;+ priceFreeze.current = false;+ }+ // A new finger scroll during a held flush continues the gesture.+ if (flushRetry.current !== null) {+ cancelAnimationFrame(flushRetry.current);+ flushRetry.current = null;+ }+ }+ if (gestureHeld() && !isEcho) {+ gestureMoved.current = true;+ }+ if (!isEcho && !converging.current) {+ const g = geo.current;+ const dist = vp.scrollHeight - vp.clientHeight - vp.scrollTop;+ // With native anchoring off, the one move the browser still makes on+ // its own is the clamp onto a new, smaller bottom (a row shrinking in+ // a way no commit announced — an image, a font). It lands exactly on+ // the bottom, where a user scrolling up never lands, so it is not+ // displacement.+ const landedAtBottom = dist < 1;+ const anchorHere = (): void => {+ mode.current = anchorAt(vp.scrollTop);+ userAway.current = 0;+ };+ if (g.keys.length === 0) {+ mode.current = {kind: 'end', distance: 0};+ userAway.current = 0;+ } else if (mode.current.kind === 'end') {+ // DISENGAGE is judged on the user's own displacement, never on the+ // absolute distance to the bottom: while following, the tail grows+ // between corrections, so the live distance carries machinery+ // movement the user did not make (measured: 6-24px nudges reading as+ // 25-59px, flipping to anchor and stranding the reader mid-stream).+ // Accumulating means a slow, persistent upward scroll still wins even+ // when each individual step is erased by a re-pin.+ const from = lastWrite ?? prevEventST;+ if (from !== null && !landedAtBottom) {+ userAway.current = Math.max(+ 0,+ userAway.current + (from - vp.scrollTop),+ );+ }+ if (userAway.current > endThresholdRef.current) {+ anchorHere();+ }+ } else if (dist <= endThresholdRef.current) {+ // RE-ENGAGE is judged on the absolute distance, which IS honest in+ // anchor mode: nothing is pulling the viewport, so reaching the+ // bottom is the user's own doing.+ mode.current = {kind: 'end', distance: 0};+ userAway.current = 0;+ } else {+ anchorHere();+ }+ }+ setWindowIfChanged(computeWindow(vp));+ };++ // The listener is attached once per scroll element but the handler is read+ // live, so it never closes over a stale render's props.+ const onScrollRef = React.useRef(onScroll);+ onScrollRef.current = onScroll;++ // Listeners are attached imperatively rather than through JSX so both modes+ // take the same path, and so attach mode can also turn OFF the browser's own+ // scroll anchoring on a container it does not render: native anchoring picks+ // its own anchor node and adjusts scrollTop underneath us, which is exactly+ // the job this list is doing from its own reference frame.+ React.useEffect(() => {+ const el = getScroller();+ if (!el) {+ return;+ }+ // A REPLACED scroller (not the first arrival) carries none of the old+ // one's scroll state: a stale lastEventST would difference two unrelated+ // scrollTops into a phantom user displacement (instant spurious unpin),+ // and a stale echo expectation could swallow the first real event.+ if (prevScrollerRef.current !== null && prevScrollerRef.current !== el) {+ lastEventST.current = null;+ userAway.current = 0;+ progTarget.current = null;+ }+ prevScrollerRef.current = el;+ // Intent signals break convergence early: a wheel, or the start of a+ // finger's scroll (see onScroll), is USER INPUT, unlike scroll events,+ // which mix in our own writes and clamps.+ //+ // A wheel does NOT unpin by itself. One this scroller never consumes —+ // over a nested scroller with room above, over one with+ // `overscroll-behavior: contain`, an overscroll at the bottom — moves+ // nothing here, and unpinning on it strands the reader off the tail.+ // Whether the container moved is what onScroll measures, against the+ // position the machinery last wrote, so a wheel the next write outruns+ // still shows there.+ const onWheel = (): void => {+ converging.current = false;+ priceFreeze.current = false;+ };+ setScrollAnchoringOff(el, true);+ const scrollHandler = (): void => onScrollRef.current();+ el.addEventListener('scroll', scrollHandler, {passive: true});+ el.addEventListener('wheel', onWheel, {passive: true});+ // Observe the CONTAINER too (rows alone miss clientHeight changes): a+ // window resize or a growing composer moves the end-mode target and the+ // window coverage without any row changing size. Container entries have+ // no data-pkey — the RO callback marks the geometry dirty for them.+ observeSize(el);+ return () => {+ setScrollAnchoringOff(el, false);+ el.removeEventListener('scroll', scrollHandler);+ el.removeEventListener('wheel', onWheel);+ // A replaced or unmounted scroller ends the gesture with it: the+ // finger-scroll watch moves to the new element and reports no end for+ // the old one. The adjustment is dropped rather than folded — the+ // element carrying it in its spacer is going away, and the replacement+ // re-derives its own frame from the mode on its first pass.+ if (flushRetry.current !== null) {+ cancelAnimationFrame(flushRetry.current);+ flushRetry.current = null;+ }+ gestureActive.current = false;+ gestureMoved.current = false;+ gestureAdj.current = 0;+ unobserveSize(el);+ };+ }, [scrollElement]);++ // Stable per-key ref callbacks: an inline `(el) => …` would be a new+ // identity every render, making React detach + reattach EVERY row's ref on+ // EVERY commit — and each re-observe() fires an initial ResizeObserver+ // callback, so steady-state commits would trigger a full-window RO batch+ // of pure noise.+ const rowRefCbs = React.useRef(+ new Map<string, (el: HTMLDivElement | null) => void>(),+ );+ const rowRef = (key: string): ((el: HTMLDivElement | null) => void) => {+ let cb = rowRefCbs.current.get(key);+ if (!cb) {+ cb = el => {+ if (el) {+ rowEls.current.set(key, el);+ observeSize(el);+ } else {+ const prev = rowEls.current.get(key);+ if (prev) {+ unobserveSize(prev);+ }+ rowEls.current.delete(key);+ rowRefCbs.current.delete(key);+ }+ };+ rowRefCbs.current.set(key, cb);+ }+ return cb;+ };++ // Tail messages the window has not reached. They mount on arrival, after a+ // gap spacer below the window, so the log can deliver them while the reader+ // is in history. State, not a ref: it decides what renders. Only a tail+ // append adds to it, so a replaced thread mounts nothing extra. A row+ // leaves once the window reaches it or it is gone from the data.+ const [arrival, setArrival] = React.useState<{+ data: readonly T[];+ win: Win;+ keys: ReadonlySet<string>;+ }>(() => ({data, win, keys: new Set()}));+ let arrivedKeys = arrival.keys;+ if (arrival.data !== data || arrival.win !== win) {+ const next = new Set<string>();+ const indexOf = new Map<string, number>();+ for (let i = 0; i < data.length; i++) {+ indexOf.set(String(getRowKey(data[i], i)), i);+ }+ const reached = (key: string): boolean =>+ win.end >= win.start && (indexOf.get(key) ?? -1) <= win.end;+ for (const key of arrival.keys) {+ if (indexOf.has(key) && !reached(key)) {+ next.add(key);+ }+ }+ if (arrival.data !== data) {+ const previous = new Set<string>();+ for (let i = 0; i < arrival.data.length; i++) {+ previous.add(String(getRowKey(arrival.data[i], i)));+ }+ const run: string[] = [];+ let isTailAppend = false;+ for (let i = data.length - 1; i >= 0; i--) {+ const key = String(getRowKey(data[i], i));+ if (previous.has(key)) {+ isTailAppend = true;+ break;+ }+ run.push(key);+ }+ // Only while the reader is away from the tail: a window that reached+ // the previous last row follows the append itself.+ const wasAtTail =+ win.end >= win.start && win.end >= arrival.data.length - 1;+ if (isTailAppend && !wasAtTail) {+ for (const key of run) {+ if (!reached(key)) {+ next.add(key);+ }+ }+ }+ }+ // At most one window's worth of the newest arrivals stays mounted, across+ // every batch and single arrival while the reader stays in history. They+ // are the newest rows, so the run they start is that long too.+ const room = Math.max(1, win.end - win.start + 1);+ if (next.size > room) {+ const newest = [...next]+ .sort((a, b) => (indexOf.get(b) ?? -1) - (indexOf.get(a) ?? -1))+ .slice(0, room);+ next.clear();+ for (const key of newest) {+ next.add(key);+ }+ }+ arrivedKeys = next;+ setArrival({data, win, keys: next});+ }++ // A focused row outside the window stays mounted beside it. It keeps its+ // place among its siblings as rows mount and unmount around it, so React+ // never moves its node (a moved node loses focus).+ let pinnedIndex = -1;+ if (focusedKey !== null && win.end >= win.start) {+ pinnedIndex = data.findIndex(+ (item, i) => String(getRowKey(item, i)) === focusedKey,+ );+ if (pinnedIndex >= win.start && pinnedIndex <= win.end) {+ pinnedIndex = -1;+ }+ }+ // The arrived tail run starts at the first arrived row past the window and+ // runs to the last row.+ let tailIndex = -1;+ if (arrivedKeys.size > 0 && win.end >= win.start) {+ for (let i = data.length - 1; i > win.end; i--) {+ if (arrivedKeys.has(String(getRowKey(data[i], i)))) {+ tailIndex = i;+ }+ }+ }+ tailKeyRef.current =+ tailIndex < 0 ? null : String(getRowKey(data[tailIndex], tailIndex));+ // A focused row inside the tail run is drawn by the run.+ if (tailIndex >= 0 && pinnedIndex >= tailIndex) {+ pinnedIndex = -1;+ }+ pinnedKeyRef.current = pinnedIndex < 0 ? null : focusedKey;+ const renderRow = (i: number): React.ReactNode => {+ const key = String(getRowKey(data[i], i));+ if (getItemType) {+ typeByKey.current.set(key, getItemType(data[i], i));+ }+ return (+ <div key={key} ref={rowRef(key)} data-pkey={key}>+ {renderItem({item: data[i], index: i})}+ </div>+ );+ };+ const children: React.ReactNode[] = [+ <div key="__top" ref={spacerTopRef} aria-hidden />,+ ];+ if (pinnedIndex >= 0 && pinnedIndex < win.start) {+ children.push(+ renderRow(pinnedIndex),+ <div key="__gapTop" ref={gapTopRef} aria-hidden />,+ );+ }+ if (win.end >= win.start) {+ for (let i = win.start; i <= Math.min(win.end, data.length - 1); i++) {+ children.push(renderRow(i));+ }+ }+ if (pinnedIndex > win.end) {+ children.push(+ <div key="__gapBottom" ref={gapBottomRef} aria-hidden />,+ renderRow(pinnedIndex),+ );+ }+ if (tailIndex >= 0) {+ children.push(+ pinnedIndex > win.end ? (+ <div key="__gapTail" ref={gapTailRef} aria-hidden />+ ) : (+ <div key="__gapBottom" ref={gapBottomRef} aria-hidden />+ ),+ );+ for (let i = tailIndex; i < data.length; i++) {+ children.push(renderRow(i));+ }+ }+ children.push(<div key="__bottom" ref={spacerBottomRef} aria-hidden />);++ // Busy when this render mounts a row that is not news: the window moving+ // over history, or history loading above.+ const renderedKeys = new Set<string>();+ for (const child of children) {+ const key = (child as React.ReactElement).key;+ if (key !== null && !key.startsWith('__')) {+ renderedKeys.add(key);+ }+ }+ let mountsHistory = false;+ for (const key of renderedKeys) {+ if (!renderedKeysRef.current.has(key) && !newsKeysRef.current.has(key)) {+ mountsHistory = true;+ break;+ }+ }+ pendingRenderedRef.current = renderedKeys;+ pendingRenderKeysRef.current = [...renderedKeys].join('\n');+ pendingBusyRef.current = mountsHistory;++ // Which row holds focus, for the pinning above.+ const onContentFocus = (event: React.FocusEvent<HTMLDivElement>): void => {+ const row = (event.target as Element).closest<HTMLElement>('[data-pkey]');+ const key =+ row != null && event.currentTarget.contains(row)+ ? (row.dataset.pkey ?? null)+ : null;+ setFocusedKey(key);+ };+ const onContentBlur = (event: React.FocusEvent<HTMLDivElement>): void => {+ const next = event.relatedTarget as Node | null;+ if (next != null) {+ if (!event.currentTarget.contains(next)) {+ setFocusedKey(null);+ }+ return;+ }+ // A blur with no next target can come while the row still holds focus+ // (the window switching around it): drop the pin only once focus has+ // really left the list.+ const block = event.currentTarget;+ queueMicrotask(() => {+ if (!block.contains(block.ownerDocument.activeElement)) {+ setFocusedKey(null);+ }+ });+ };++ const contentProps = {+ ref: contentRef,+ onFocus: onContentFocus,+ onBlur: onContentBlur,+ xstyle: styles.content,+ };+ // In own-container mode the scrollable area measures this block's overflow+ // to decide whether keyboard users can scroll.+ const {xstyle: contentXstyle, ...contentDomProps} = attachMode+ ? contentProps+ : getContentProps<HTMLDivElement>(contentProps);+ const content = (+ <div {...contentDomProps} {...stylex.props(contentXstyle)}>+ {children}+ </div>+ );++ if (attachMode) {+ return content;+ }++ return (+ <div+ {...getViewportProps<HTMLDivElement>({+ ref: ownScrollerRef,+ className,+ style,+ xstyle: styles.scroller,+ })}>+ {content}+ </div>+ );+}diff --git a/packages/lab/src/Chat/index.ts b/packages/lab/src/Chat/index.tsindex 2067317928..65defa822a 100644--- a/packages/lab/src/Chat/index.ts+++ b/packages/lab/src/Chat/index.ts@@ -20,3 +20,9 @@ export type {ChatUnreadDividerProps} from './ChatUnreadDivider';export {ChatTypingIndicator} from './ChatTypingIndicator';export type {ChatTypingIndicatorProps} from './ChatTypingIndicator';++export {ChatVirtualizer} from './ChatVirtualizer';+export type {+ ChatVirtualizerProps,+ ChatVirtualizerHandle,+} from './ChatVirtualizer';