diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4dc24093d7..07040aa2c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,6 +103,51 @@ jobs: verbose: true use_oidc: true + browser-test: + # Pinned: Playwright installs Chromium only on the Ubuntu releases it supports, and + # `ubuntu-latest` can move to one it does not support yet (26.04 did). + runs-on: ubuntu-24.04 + name: Browser tests (virtualized lists) + steps: + - uses: actions/checkout@v6 + + - uses: ./.github/actions/setup-node + + - name: Cache Playwright browsers + uses: actions/cache@v5 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ hashFiles('yarn.lock') }} + + # Install scripts are disabled (`enableScripts: false`), so the browser is installed here. + - name: Install Chromium + run: yarn playwright install --with-deps chromium + + # The shipped runtime: invariants, scenarios and fuzz seeds must pass. + - name: Real-browser suites (react-virtuoso 4) + run: yarn vitest run --project browser-v4 + + # The react-virtuoso 2 reference and the trace comparison, recorded for review in the + # artifact below and not gating: on CI's slower runners v2 loses races it is known for + # (opening at the top, losing a jump), which local runs rarely hit. `yarn test:browser` runs + # all three locally, the comparison gating there. + - name: react-virtuoso 2 reference and trace comparison (informational) + continue-on-error: true + run: | + yarn vitest run --project browser-v2 || true + node scripts/compare-virtuoso-traces.mts + + - name: Upload the trace comparison + if: always() + uses: actions/upload-artifact@v5 + with: + name: virtuoso-traces + path: | + .virtuoso-traces/report.md + .virtuoso-traces/browser-v2 + .virtuoso-traces/browser-v4 + if-no-files-found: ignore + deploy-vite-example: concurrency: cancel-in-progress: true diff --git a/.gitignore b/.gitignore index 7b971ec522..98deeba77a 100644 --- a/.gitignore +++ b/.gitignore @@ -100,3 +100,4 @@ shared # On-demand translator/TMS catalog export (`yarn i18n:export`). Generated from the t() call # sites and src/i18n/runtimeDefaults.ts, so it is never checked in. /en.json +.virtuoso-traces/ diff --git a/AGENTS.md b/AGENTS.md index 184481e153..787bb45b6c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,7 +19,7 @@ This is the **v15** line, developed on `master` and published under npm `latest` - **Package manager:** Yarn 4 (Berry). The binary is committed under `.yarn/releases/` and activated via `yarnPath` in `.yarnrc.yml`. Any globally installed `yarn` (even classic 1.x) acts only as a launcher — no Corepack required. - **Workspaces:** Yarn workspaces monorepo (`examples/*`) - **Dependency versions:** read them from `package.json` (`peerDependencies`, `dependencies`, `devDependencies`). They change with every release, so they are not repeated here. -- **Testing:** Vitest + React Testing Library (+ `vitest-axe` for a11y). There is no Jest and no Playwright/e2e suite in this repo. +- **Testing:** Vitest + React Testing Library (+ `vitest-axe` for a11y), in jsdom; a real-browser suite for the virtualized lists runs in Vitest Browser Mode on Playwright Chromium (see Testing). There is no Jest and no end-to-end suite. - **Bundler:** Vite 8 / Rolldown (library mode); `tsc` emits declarations only - **Styles:** Sass compiled to `dist/css/`. Consumers override via CSS layers (see README) — never edit compiled CSS. - **i18n:** the runtime is `@stream-io/i18n` (a regular dependency); this package owns only its key catalog and bindings @@ -55,7 +55,8 @@ yarn start # tsc -p tsconfig.lib.json --watch (emit .d.ts on chan yarn start:css # watch + recompile SCSS # Tests -yarn test # vitest run (single pass) +yarn test # vitest run --project jsdom (single pass) +yarn test:browser # real-browser suites on react-virtuoso 2 and 4, then compares their traces yarn test MessageList # filter by file path substring yarn test -t 'marks read' # filter by test name yarn test:watch # watch mode @@ -271,7 +272,7 @@ useMemo( **Policy:** add or extend tests in the matching module's `__tests__/` folder. Cover React components, hooks, and utility functions. Reuse the repo's fakes/mocks instead of hand-rolling new ones. -**Runner:** Vitest (`vitest.config.ts`) — `globals: true` (no imports needed for `describe`/`it`/`expect`/`vi`), `jsdom`, `pool: 'forks'`, `testTimeout: 15000`, `css: false`, tests matched at `src/**/*.test.{js,jsx,ts,tsx}`. `resolve.dedupe` collapses `@stream-io/state-store`, `@stream-io/i18n`, `stream-chat`, `react` and `react-dom` onto one copy each. `vitest.setup.ts` forces `TZ=UTC`, registers `@testing-library/jest-dom/vitest` + `vitest-axe` matchers, and polyfills `crypto.getRandomValues`, `structuredClone`, `File`, `FileReader`, `URL.createObjectURL`, `matchMedia`, and canvas `getContext`. +**Runner:** Vitest (`vitest.config.ts`), project `jsdom` — `globals: true` (no imports needed for `describe`/`it`/`expect`/`vi`), `jsdom`, `pool: 'forks'`, `testTimeout: 15000`, `css: false`, tests matched at `src/**/*.test.{js,jsx,ts,tsx}`. `resolve.dedupe` collapses `@stream-io/state-store`, `@stream-io/i18n`, `stream-chat`, `react` and `react-dom` onto one copy each. `vitest.setup.ts` forces `TZ=UTC`, registers `@testing-library/jest-dom/vitest` + `vitest-axe` matchers, and polyfills `crypto.getRandomValues`, `structuredClone`, `File`, `FileReader`, `URL.createObjectURL`, `matchMedia`, and canvas `getContext`. Import test helpers from `src/mock-builders` (also aliased as `mock-builders`): @@ -310,6 +311,21 @@ render( Mock modules with `vi.mock('../../EmptyStateIndicator', () => ({ … }))`; use `importOriginal()` to partially mock. Mock methods on the channel/client, never replace the whole object. +### Virtualized lists: jsdom contract tests and the real-browser suite + +jsdom lays nothing out, so react-virtuoso renders no items there. For the parts of its contract the SDK relies on (item indexes, keys across a prepend, `scrollerRef`, `scrollIntoView`'s `done`, the DOM attributes the styles target), render the real component inside `VirtuosoMockContext.Provider value={{ itemHeight, viewportHeight }}` — see `src/components/MessageList/__tests__/virtuosoContract.test.tsx`. + +Scrolling, measuring, prepending and staying at the bottom are covered by `src/components/MessageList/__tests__/browser/*.browser.test.tsx`, run by `yarn test:browser` in headless Chromium (`npx playwright install chromium` once; install scripts are disabled) with the SDK's real styles: + +- **Projects.** `browser-v4` runs the suites on the shipped react-virtuoso; `browser-v2` runs the same suites with `react-virtuoso` aliased to `react-virtuoso-v2` (2.19.1), kept while the v4 upgrade is verified. Same SDK source, different runtime. +- **Harness** (`harness.tsx`, `fakeBackend.ts`). A mocked client whose requests a seeded, in-memory history answers, so pages, jumps and sends go through the real `MessagePaginator`; a synthetic message UI of known heights; helpers to scroll, receive messages, grow a message and wait for the list to settle. +- **Probe and traces** (`virtuosoProbe.tsx`, `trace.ts`). `vi.mock('react-virtuoso')` wraps `Virtuoso` to record every callback between the SDK and Virtuoso (with `followOutput`'s answers); each settled step records geometry, the rendered items, DOM nodes replaced, requests, paginator calls and render counts. +- **Invariants** (`invariants.ts`, `scenario.ts`): the list is shown, items are contiguous and cover the viewport, the at-bottom state agrees with the geometry, a scroll moves the content by exactly the scrolled distance, a scroll to the bottom stays there. They fail the v4 project; on v2 they are recorded. +- **Scenarios and fuzzing.** `VirtualizedMessageList.scroll.browser.test.tsx` (B-xx), `OtherLists.browser.test.tsx` (ThreadList, Channel Detail), and `VirtualizedMessageList.fuzz.browser.test.tsx`: seeded operation sequences (`VIRTUOSO_FUZZ_SEEDS`, 25 by default). +- **Comparison.** `scripts/compare-virtuoso-traces.mts` diffs the two runtimes' traces in `.virtuoso-traces/`; every difference must match `__tests__/browser/expected-differences.json`, which says why the runtimes differ. +- **Gating.** `yarn test:browser` runs `browser-v4` first (it must pass), then `browser-v2` (recorded, not gating: v2 has known races), then the comparison, which gates locally. CI gates on `browser-v4` only and uploads the v2 run and the comparison as an artifact, since on slower runners v2 loses its races often enough to swamp the comparison. +- **Mutation checks.** `VIRTUOSO_MUTATION= yarn vitest run --project browser-v4` injects a breakage between the SDK and Virtuoso (see `VirtuosoMutation` in `virtuosoProbe.tsx`); the comparison must then report it. + ## Build system `yarn build` = `yarn clean` + 4 steps in parallel via `concurrently`, each writing to a separate location: diff --git a/ai-docs/ai-migration-v14-v15.md b/ai-docs/ai-migration-v14-v15.md index 8470b83151..54a2a03e30 100644 --- a/ai-docs/ai-migration-v14-v15.md +++ b/ai-docs/ai-migration-v14-v15.md @@ -2480,7 +2480,32 @@ Pass them to `react-virtuoso` through `additionalVirtuosoProps`. `react-virtuoso | `overscan` | `additionalVirtuosoProps.overscan` | | `scrollSeekPlaceHolder` | `additionalVirtuosoProps.scrollSeekConfiguration` and `additionalVirtuosoProps.components.ScrollSeekPlaceholder` | -In v14, `scrollSeekPlaceHolder` reached `react-virtuoso` as its deprecated `scrollSeek` prop, which logged a warning. `scrollSeekConfiguration` with `components.ScrollSeekPlaceholder` keeps the same behavior without the warning. `defaultItemHeight` and `scrollSeekPlaceHolder` used to win over `additionalVirtuosoProps`; now `additionalVirtuosoProps` is the only source. +In v14, `scrollSeekPlaceHolder` reached `react-virtuoso` as its deprecated `scrollSeek` prop, which logged a warning. `scrollSeekConfiguration` with `components.ScrollSeekPlaceholder` keeps the same behavior. react-virtuoso 4 removed `scrollSeek` and its other v0 aliases (`item`, `header`, `footer`, `emptyComponent`, `*Container`, …), so a value passed under one of those names now lands on the scroller element as an unknown DOM attribute. `defaultItemHeight` and `scrollSeekPlaceHolder` used to win over `additionalVirtuosoProps`; now `additionalVirtuosoProps` is the only source. + +### The virtualized lists run on `react-virtuoso` 4 + +`VirtualizedMessageList`, `ThreadList` and the Channel Detail lists use `react-virtuoso` 4 (previously 2). Code that passes nothing to Virtuoso is not affected. Code that does — `VirtualizedMessageList`'s `additionalVirtuosoProps`, `ThreadList`'s `virtuosoProps`, custom Virtuoso components, tests that select Virtuoso's markup — should check the following. + +- **Types.** `ItemProps` takes the item data type (`ItemProps`), and `Components` takes ``. `VirtuosoProps` no longer has `react18ConcurrentRendering`, and types its DOM event handlers for `HTMLDivElement`. Custom components are typed as receiving a required `context` prop. A custom `Item` receives an `item` prop (`undefined` for `VirtualizedMessageList`, which renders by `totalCount`); do not spread it onto a DOM element. +- **Test IDs.** Virtuoso's `data-test-id` attributes are now `data-testid` (`virtuoso-scroller`, `virtuoso-item-list`, `virtuoso-top-item-list`). `data-virtuoso-scroller`, `data-viewport-type`, `data-index`, `data-item-index` and `data-known-size` are unchanged. +- **`followOutput`.** A `followOutput` function you pass must return `false` to not scroll: `undefined` and `null` now mean `'auto'`. +- **`scrollerRef`.** With `useWindowScroll` or `customScrollParent`, Virtuoso now calls `scrollerRef` with the window or the scroll parent (it used to call nothing). +- **`additionalVirtuosoProps` values of `undefined`.** Pass a prop or leave it out: an explicit `undefined` (for example `itemSize: undefined`) overrides the list's own value, and Virtuoso 4 does not fall back to its default. +- **Opening a list.** While it positions a freshly mounted list (opening a channel or thread, a jump to a message or to the latest messages), Virtuoso keeps the list hidden — about a quarter of a second — and shows it in place, where v2 showed it at once and moved it into position over the first frames. Meanwhile `VirtualizedMessageList` renders the `MessageListPositioningUI` slot over the list, which shows the `LoadingIndicator` by default. Set the slot in `WithComponents` to replace it, or to `null` to render nothing; a `LoadingIndicator` set to `null` hides the default too. The slot is rendered at all times with `isPositioning`, so a component can also animate the reveal: + + ```tsx + // A cover in the list's background color over the list, faded out with a CSS opacity + // transition once the list is positioned: the list appears to fade in. + const FadeIn = ({ isPositioning }: MessageListPositioningUIProps) => ( +
+ ); + + …; + ``` + +- **Scroll position.** Scrolling up through messages not yet rendered keeps the content still; v2 could jump by the difference between estimated and real message heights. +- **Staying at the bottom.** A list scrolled to its bottom now stays there while its content grows: a message that measures taller than estimated, an image that loads late, a reply that streams in. Scrolled up by more than the at-bottom threshold, the list does not move. With `suppressAutoscroll`, new messages do not move the list until the reader scrolls; a message already shown that grows still keeps a reader at the bottom. A `followOutput` you pass in `additionalVirtuosoProps` alone decides whether new messages are followed. In a window of older messages (after a jump), a scroll to its end reaches the end and loads the next newer page, which is not followed. +- **Bundling.** The package is ES2022 with an `exports` map and no dependencies of its own. A build that targets older browsers must transpile it. ```tsx // v14 diff --git a/package.json b/package.json index ffe1fb0758..8589d9bde5 100644 --- a/package.json +++ b/package.json @@ -143,7 +143,7 @@ "react-player": "2.10.1", "react-syntax-highlighter": "^16.1.0", "react-textarea-autosize": "^8.5.9", - "react-virtuoso": "^2.19.1", + "react-virtuoso": "^4.18.22", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "unified": "^11.0.5", @@ -226,6 +226,7 @@ "@types/react-dom": "^19.2.3", "@types/react-syntax-highlighter": "^15.5.13", "@types/use-sync-external-store": "^1.5.0", + "@vitest/browser-playwright": "4.1.9", "@vitest/coverage-v8": "^4.1.9", "@vitest/eslint-plugin": "^1.6.20", "concurrently": "^9.2.1", @@ -241,9 +242,11 @@ "husky": "^9.1.7", "jsdom": "^29.1.1", "lint-staged": "^17.0.5", + "playwright": "1.60.0", "prettier": "^3.8.3", "react": "^19.2.6", "react-dom": "^19.2.6", + "react-virtuoso-v2": "npm:react-virtuoso@2.19.1", "sass": "^1.100.0", "semantic-release": "^25.0.3", "stream-chat": "^10.2.0", @@ -259,7 +262,7 @@ "build": "yarn clean && concurrently 'yarn build-translations' 'vite build' 'tsc --project tsconfig.lib.json' 'yarn build-styling'", "build-styling": "sass --no-charset src/styling/index.scss:dist/css/index.css src/styling/_emoji-replacement.scss:dist/css/emoji-replacement.css src/plugins/Emojis/styling/index.scss:dist/css/emoji-picker.css src/plugins/ChannelDetail/styling/index.scss:dist/css/channel-detail.css src/plugins/AIComponents/styling/index.scss:dist/css/ai-components.css; cp -r src/styling/assets dist/css/assets", "build-translations": "node scripts/generate-i18n-keys.mts && prettier --write --log-level warn src/i18n/keys.ts", - "coverage": "vitest run --coverage", + "coverage": "vitest run --project jsdom --coverage", "i18n:export": "node scripts/generate-i18n-keys.mts --json en.json", "lint": "yarn prettier --list-different && yarn eslint", "lint-fix": "yarn prettier-fix && yarn eslint-fix", @@ -276,8 +279,9 @@ "start:cookbook": "yarn workspace @stream-io/stream-chat-react-cookbook dev", "start:vite": "yarn workspace @stream-io/stream-chat-react-vite dev", "postinstall": "node -e \"require('fs').existsSync('scripts/install-husky.mjs') && import('./scripts/install-husky.mjs')\"", - "test": "vitest run", - "test:watch": "vitest", + "test": "vitest run --project jsdom", + "test:browser": "vitest run --project browser-v4 && (vitest run --project browser-v2 || true) && node scripts/compare-virtuoso-traces.mts", + "test:watch": "vitest --project jsdom", "types": "tsc -p tsconfig.lib.json --noEmit", "types:tests": "tsc --project tsconfig.test.json --noEmit", "validate-translations": "yarn build-translations && git diff --exit-code -- src/i18n/keys.ts", diff --git a/scripts/compare-virtuoso-traces.mts b/scripts/compare-virtuoso-traces.mts new file mode 100644 index 0000000000..cbb1f8f8a0 --- /dev/null +++ b/scripts/compare-virtuoso-traces.mts @@ -0,0 +1,541 @@ +// Compares the scroll traces the browser suites wrote for two react-virtuoso runtimes. +// +// node scripts/compare-virtuoso-traces.mts [--base browser-v2] [--head browser-v4] +// [--dir .virtuoso-traces] [--allow ] +// +// Each scenario is a sequence of settled checkpoints. A difference is any field that disagrees +// beyond its tolerance; it must match an entry of the allowlist (which says why the runtimes +// differ) or the run fails. The report lists every difference, explained or not, and every +// allowlist entry that matched nothing. +import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +type ProbeEvent = { name: string; value: unknown }; + +type FrameSummary = { + blankFrames: number; + finalDistanceFromBottom: number | null; + framesUntilVisible: number; + maxAnchorShift: number | null; +}; + +type Checkpoint = { + commits: number; + dom: unknown; + events: ProbeEvent[]; + firstVisible: { id: string; top: number } | null; + frames?: FrameSummary; + geometry: Record | null; + label: string; + messageRenders: number; + paginatorCalls: string[]; + remounted: string[]; + rendered: string[]; + requests: unknown[]; + timingDependent?: boolean; + visible: boolean; + /** Filled in by `withCarriedState`: the last value of each state callback so far. */ + carried?: Record; +}; + +type Trace = { + checkpoints: Checkpoint[]; + knownDeviations?: string[]; + /** Counts of bad outcomes over repeated attempts: lower is better. */ + metrics?: Record; + consoleErrors: string[]; + framesUntilFirstItem: number | null; + scenario: string; + violations?: string[]; + windowErrors: string[]; +}; + +type AllowEntry = { + scenario: string; + checkpoint?: string; + field: string; + reason: string; + upstream?: string; +}; + +type Difference = { + scenario: string; + checkpoint: string; + field: string; + base: unknown; + head: unknown; + explainedBy?: AllowEntry; + /** Reported, never failing: a value users cannot observe. */ + informational?: boolean; +}; + +const { values: args } = parseArgs({ + options: { + allow: { + default: 'src/components/MessageList/__tests__/browser/expected-differences.json', + type: 'string', + }, + base: { default: 'browser-v2', type: 'string' }, + dir: { default: '.virtuoso-traces', type: 'string' }, + head: { default: 'browser-v4', type: 'string' }, + report: { default: '.virtuoso-traces/report.md', type: 'string' }, + }, +}); + +const GEOMETRY_TOLERANCE_PX = 1; +/** The tolerance of the scenario runner's scroll invariant (see scenario.ts). */ +const SCROLL_TOLERANCE_PX = 2; +const RENDER_TOLERANCE = 0.1; +const RENDER_SLACK = 2; +const METRIC_SLACK = 2; +/** Callbacks whose sequence must match exactly (consecutive repeats collapsed). */ +const EXACT_EVENTS = new Set(['followOutput', 'scrollerRef']); +/** + * State callbacks: only the value reported last in a checkpoint is compared. A transient flip while + * mounting depends on frame timing; what it causes (a page load) is compared through the paginator + * calls and requests instead. + */ +const STATE_EVENTS = ['atBottomStateChange', 'atTopStateChange']; + +/** Annotates each checkpoint with the state callbacks' values as of its end. */ +const withCarriedState = (trace: Trace) => { + const carried: Record = {}; + for (const point of trace.checkpoints) { + for (const event of point.events) { + if ([...STATE_EVENTS, 'itemsRendered'].includes(event.name)) + carried[event.name] = event.value; + } + point.carried = { ...carried }; + } + return trace; +}; + +const readTraces = (runtime: string) => { + const dir = resolve(args.dir, runtime); + const traces = new Map(); + if (!existsSync(dir)) return traces; + for (const file of readdirSync(dir).filter((name) => name.endsWith('.json'))) { + const trace = JSON.parse(readFileSync(join(dir, file), 'utf8')) as Trace; + traces.set(trace.scenario, withCarriedState(trace)); + } + return traces; +}; + +const collapse = (values: string[]) => + values.filter((value, index) => index === 0 || value !== values[index - 1]); + +const eventSequence = (events: ProbeEvent[]) => + collapse( + events + .filter((event) => EXACT_EVENTS.has(event.name) || event.name.startsWith('handle.')) + // Virtuoso may ask `followOutput` more or less often; an answer of `false` changes nothing, + // so only the calls that scroll are compared. + .filter( + (event) => + event.name !== 'followOutput' || + (event.value as { result?: unknown } | null)?.result !== false, + ) + .map((event) => `${event.name}:${JSON.stringify(event.value)}`), + ); + +const lastRendered = (events: ProbeEvent[]) => + [...events].reverse().find((event) => event.name === 'itemsRendered')?.value ?? null; + +const lastTotalHeight = (events: ProbeEvent[]) => + ([...events].reverse().find((event) => event.name === 'totalListHeightChanged') + ?.value as number | undefined) ?? null; + +const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); + +/** + * react-virtuoso 4.7.9 renamed its `data-test-id` attributes to `data-testid` (same values). The + * rename is documented; any other markup difference is still reported. + */ +const normalizeDom = (value: unknown) => + value === undefined || value === null + ? null + : JSON.parse(JSON.stringify(value).replaceAll('data-test-id=', 'data-testid=')); + +const isBackgroundReport = (request: unknown) => + /\/(read|delivered)$/.test((request as { path?: string }).path ?? ''); + +const backgroundReports = (trace: Trace) => { + const counts: Record = {}; + for (const point of trace.checkpoints) { + for (const request of point.requests.filter(isBackgroundReport)) { + const path = (request as { path: string }).path.replace(/.*\//, ''); + counts[path] = (counts[path] ?? 0) + 1; + } + } + return counts; +}; + +const closeNumbers = ( + a: number | null | undefined, + b: number | null | undefined, + tolerance: number, +) => (a == null || b == null ? a === b : Math.abs(a - b) <= tolerance); + +const closeCounts = (base: number, head: number) => + Math.abs(head - base) <= Math.max(RENDER_SLACK, base * RENDER_TOLERANCE); + +const compareCheckpoint = ( + base: Checkpoint, + head: Checkpoint, + push: (field: string, b: unknown, h: unknown, informational?: boolean) => void, +) => { + if (!same(eventSequence(base.events), eventSequence(head.events))) { + push('events', eventSequence(base.events), eventSequence(head.events)); + } + // The state as of the end of the checkpoint, carried over from earlier ones: a runtime that + // re-reports an unchanged value, or reports nothing, still agrees with one that stays put. Within + // Virtuoso's at-bottom threshold of the bottom, but not at it, either at-bottom value is valid + // (the scenario runner's invariant checks it against the geometry), so a difference there is + // informational. + const ambiguousAtBottom = [base, head].some((point) => { + const geometry = point.geometry; + if (!geometry) return false; + const threshold = Math.min(Math.max(geometry.clientHeight * 0.1, 4), 100); + return ( + geometry.distanceFromBottom > 1 && geometry.distanceFromBottom <= threshold + 2 + ); + }); + for (const name of [...STATE_EVENTS, 'itemsRendered']) { + const b = base.carried?.[name] ?? null; + const h = head.carried?.[name] ?? null; + if (same(b, h)) continue; + // While mounting, the last itemsRendered report depends on frame timing; the DOM rendered at + // mount is compared as `rendered`. + if (name === 'itemsRendered') push('itemsRendered', b, h, base.label === 'mounted'); + else push(`state.${name}`, b, h, name === 'atBottomStateChange' && ambiguousAtBottom); + } + // Absolute offsets in a virtualized list depend on the heights estimated for the items never + // rendered, which nobody sees; what the reader sees is compared below (rendered items, the first + // visible item and its offset, whether the list sits at its bottom). + if ( + !closeNumbers( + lastTotalHeight(base.events), + lastTotalHeight(head.events), + GEOMETRY_TOLERANCE_PX, + ) + ) { + push( + 'totalListHeight', + lastTotalHeight(base.events), + lastTotalHeight(head.events), + true, + ); + } + for (const key of ['scrollHeight', 'scrollTop']) { + if ( + !closeNumbers(base.geometry?.[key], head.geometry?.[key], GEOMETRY_TOLERANCE_PX) + ) { + push(`geometry.${key}`, base.geometry?.[key], head.geometry?.[key], true); + } + } + if ( + !closeNumbers( + base.geometry?.clientHeight, + head.geometry?.clientHeight, + GEOMETRY_TOLERANCE_PX, + ) + ) { + push( + 'geometry.clientHeight', + base.geometry?.clientHeight, + head.geometry?.clientHeight, + ); + } + const baseDistance = base.geometry?.distanceFromBottom; + const headDistance = head.geometry?.distanceFromBottom; + const atBottom = (distance: number | undefined) => + distance !== undefined && distance <= GEOMETRY_TOLERANCE_PX; + if (atBottom(baseDistance) !== atBottom(headDistance)) { + push('geometry.atBottom', baseDistance, headDistance); + } else if (!closeNumbers(baseDistance, headDistance, GEOMETRY_TOLERANCE_PX)) { + push('geometry.distanceFromBottom', baseDistance, headDistance, true); + } + if (!same(base.rendered, head.rendered)) push('rendered', base.rendered, head.rendered); + if ( + base.firstVisible?.id !== head.firstVisible?.id || + // Twice the invariant's tolerance: each runtime may be off by it, in opposite directions. + !closeNumbers(base.firstVisible?.top, head.firstVisible?.top, 2 * SCROLL_TOLERANCE_PX) + ) { + push('firstVisible', base.firstVisible, head.firstVisible); + } + if (base.visible !== head.visible) push('visible', base.visible, head.visible); + if (!same(base.remounted, head.remounted)) + push('remounted', base.remounted, head.remounted); + // Page queries follow from scrolling and must match per checkpoint. Read and delivery reports are + // throttled on the wall clock, so which checkpoint they land in varies: their totals are compared + // per scenario instead (see compareTrace). + const pageQueries = (requests: unknown[]) => + requests.filter((request) => !isBackgroundReport(request)); + if (!same(pageQueries(base.requests), pageQueries(head.requests))) { + push('requests', pageQueries(base.requests), pageQueries(head.requests)); + } + // A paginator call that sends no request (e.g. `toHead()` on the latest messages) changes + // nothing; the page loads it does cause are compared through `requests`. + if (!same(base.paginatorCalls, head.paginatorCalls)) { + push('paginatorCalls', base.paginatorCalls, head.paginatorCalls, true); + } + // A step on wall-clock timers renders a varying number of times and is sampled mid-animation: + // only its settled state is comparable. So is mounting, whose frame timing varies run to run. + const timingDependent = + base.timingDependent || head.timingDependent || base.label === 'mounted'; + // Per step, render counts jitter by a few; the budget applies to the scenario's total (see + // compareTrace). + if (!timingDependent && !closeCounts(base.commits, head.commits)) { + push('commits', base.commits, head.commits, true); + } + if (!timingDependent && !closeCounts(base.messageRenders, head.messageRenders)) { + push('messageRenders', base.messageRenders, head.messageRenders, true); + } + for (const part of ['scroller', 'viewport', 'list', 'firstItem']) { + const b = normalizeDom((base.dom as Record)?.[part]); + const h = normalizeDom((head.dom as Record)?.[part]); + if (!same(b, h)) push(`dom.${part}`, b, h); + } + if (!timingDependent && (base.frames || head.frames)) { + const b = base.frames; + const h = head.frames; + // Frame metrics may improve freely; only a regression is a difference. + if ((h?.blankFrames ?? 0) > (b?.blankFrames ?? 0)) + push('frames.blankFrames', b?.blankFrames, h?.blankFrames); + if ((h?.framesUntilVisible ?? 0) > (b?.framesUntilVisible ?? 0) + 2) { + push('frames.framesUntilVisible', b?.framesUntilVisible, h?.framesUntilVisible); + } + if ((h?.maxAnchorShift ?? 0) > (b?.maxAnchorShift ?? 0) + GEOMETRY_TOLERANCE_PX) { + push('frames.maxAnchorShift', b?.maxAnchorShift, h?.maxAnchorShift); + } + // As for the settled geometry: ending at the bottom on one runtime only is a difference; away + // from the bottom the distance follows the runtimes' size estimates and is informational. + const baseFinal = b?.finalDistanceFromBottom ?? undefined; + const headFinal = h?.finalDistanceFromBottom ?? undefined; + if (!closeNumbers(baseFinal, headFinal, GEOMETRY_TOLERANCE_PX)) { + push( + 'frames.finalDistanceFromBottom', + baseFinal, + headFinal, + atBottom(baseFinal) === atBottom(headFinal) && + !atBottom(baseFinal) && + baseFinal !== undefined && + headFinal !== undefined, + ); + } + } +}; + +const compareTrace = ( + base: Trace | undefined, + head: Trace | undefined, + scenario: string, +) => { + const differences: Difference[] = []; + const push = + (checkpoint: string) => + (field: string, b: unknown, h: unknown, informational = false) => + differences.push({ base: b, checkpoint, field, head: h, informational, scenario }); + if (!base || !head) { + push('*')('scenario', !!base, !!head); + return differences; + } + const labels = (trace: Trace) => trace.checkpoints.map((point) => point.label); + if (!same(labels(base), labels(head))) + push('*')('checkpoints', labels(base), labels(head)); + // A fuzzed scenario's steps act on whatever state the earlier steps left, so once two runtimes + // diverge, the later steps compare different situations: only the first diverging checkpoint is + // reported (each runtime's invariants still hold for every step). + const firstDivergenceOnly = base.scenario.startsWith('F-'); + for (const [index, point] of base.checkpoints.entries()) { + const other = head.checkpoints[index]; + if (!other || other.label !== point.label) continue; + const before = differences.length; + // Where the reference runtime broke an invariant at this checkpoint and the new one did not, + // what differs there is the new runtime getting it right. + const violatedAt = (trace: Trace) => + (trace.violations ?? []).some((violation) => + violation.startsWith(`${point.label}:`), + ); + const improvement = violatedAt(base) && !violatedAt(head); + // A scroll past the rendered window lands on messages whose heights were only estimated: where + // exactly is not defined, so landing on overlapping messages counts as the same place. + const overlaps = point.rendered.some((id) => other.rendered.includes(id)); + const estimatedLanding = + /^\d+ scroll by$/.test(point.label) && + overlaps && + !violatedAt(base) && + !violatedAt(head); + const positionField = (field: string) => + ['firstVisible', 'itemsRendered', 'remounted', 'rendered'].includes(field); + compareCheckpoint(point, other, (field, b, h, informational) => + push(point.label)( + field, + b, + h, + informational || improvement || (estimatedLanding && positionField(field)), + ), + ); + // An improvement still puts the runtimes in different places: later steps are not comparable. + const added = differences.slice(before); + const diverged = + improvement || + (estimatedLanding && added.some((difference) => positionField(difference.field))) || + added.some((difference) => !difference.informational); + if (firstDivergenceOnly && diverged) break; + } + // Render budget: the scenario's renders, over the steps that are not timing-dependent, may grow + // by at most RENDER_TOLERANCE. + const totals = (trace: Trace) => + trace.checkpoints + .filter((point) => !point.timingDependent && point.label !== 'mounted') + .reduce( + (sum, point) => ({ + commits: sum.commits + point.commits, + messageRenders: sum.messageRenders + point.messageRenders, + }), + { commits: 0, messageRenders: 0 }, + ); + const baseTotals = totals(base); + const headTotals = totals(head); + for (const key of ['commits', 'messageRenders'] as const) { + // Commits of the list shell that render no message are cheap: one more per step is allowed. + const steps = base.checkpoints.filter( + (point) => !point.timingDependent && point.label !== 'mounted', + ).length; + const budget = Math.max( + RENDER_SLACK * 3, + baseTotals[key] * RENDER_TOLERANCE + (key === 'commits' ? steps : 0), + ); + if (headTotals[key] - baseTotals[key] > budget) { + push('*')(`totals.${key}`, baseTotals[key], headTotals[key]); + } + } + // Shifts both runtimes show when messages measure other than estimated (see scenario.ts): the + // new runtime may not show more of them than the reference. + const deviations = (trace: Trace) => trace.knownDeviations?.length ?? 0; + if (deviations(head) > deviations(base) + 1) { + push('*')('knownDeviations', base.knownDeviations, head.knownDeviations); + } + const baseReports = backgroundReports(base); + const headReports = backgroundReports(head); + for (const path of new Set([ + ...Object.keys(baseReports), + ...Object.keys(headReports), + ])) { + // How often the list reports reads depends on how long it sits at the bottom. + const b = baseReports[path] ?? 0; + const h = headReports[path] ?? 0; + if (Math.abs(b - h) > Math.max(2, b * 0.2)) { + push('*')(`reports.${path}`, baseReports[path] ?? 0, headReports[path] ?? 0); + } + } + // A violation only the reference runtime has is an improvement; only new ones are differences. + const newViolations = (head.violations ?? []).filter( + (violation) => !(base.violations ?? []).includes(violation), + ); + if (newViolations.length > 0) push('*')('violations', base.violations, newViolations); + if (base.consoleErrors.length !== head.consoleErrors.length) { + push('*')('consoleErrors', base.consoleErrors, head.consoleErrors); + } + if (base.windowErrors.length !== head.windowErrors.length) { + push('*')('windowErrors', base.windowErrors.length, head.windowErrors.length); + } + for (const [metric, value] of Object.entries(head.metrics ?? {})) { + // Outcome counts over repeated attempts are noisy: an increase of more than two counts. + if (value > (base.metrics?.[metric] ?? 0) + METRIC_SLACK) { + push('*')(`metrics.${metric}`, base.metrics?.[metric], value); + } + } + // Two runs of the same runtime differ by up to 3 frames here. + if ((head.framesUntilFirstItem ?? 0) > (base.framesUntilFirstItem ?? 0) + 4) { + push('*')( + 'framesUntilFirstItem', + base.framesUntilFirstItem, + head.framesUntilFirstItem, + ); + } + return differences; +}; + +const allowText = existsSync(args.allow) ? readFileSync(args.allow, 'utf8').trim() : ''; +const allowlist: AllowEntry[] = allowText + ? (JSON.parse(allowText) as { differences: AllowEntry[] }).differences + : []; +const used = new Set(); + +const explain = (difference: Difference) => + allowlist.find( + (entry) => + new RegExp(`^(?:${entry.scenario})$`).test(difference.scenario) && + (!entry.checkpoint || + new RegExp(`^(?:${entry.checkpoint})$`).test(difference.checkpoint)) && + (new RegExp(`^(?:${entry.field})$`).test(difference.field) || + difference.field.startsWith(`${entry.field}.`)), + ); + +const baseTraces = readTraces(args.base); +const headTraces = readTraces(args.head); +if (baseTraces.size === 0 || headTraces.size === 0) { + console.error( + `No traces for ${baseTraces.size === 0 ? args.base : args.head} in ${args.dir}: run both browser projects first.`, + ); + process.exit(1); +} + +const scenarios = Array.from( + new Set([...baseTraces.keys(), ...headTraces.keys()]), +).sort(); +const differences = scenarios.flatMap((scenario) => + compareTrace(baseTraces.get(scenario), headTraces.get(scenario), scenario).map( + (difference) => { + const entry = explain(difference); + if (entry) used.add(entry); + return { ...difference, explainedBy: entry }; + }, + ), +); + +const unexplained = differences.filter( + (difference) => !difference.explainedBy && !difference.informational, +); +const show = (value: unknown) => { + const text = JSON.stringify(value); + return text && text.length > 400 ? `${text.slice(0, 400)}…` : text; +}; +const lines = [ + `# react-virtuoso trace comparison: ${args.base} → ${args.head}`, + '', + `${scenarios.length} scenarios, ${differences.length} differences, ${unexplained.length} unexplained.`, + '', + ...differences.map((difference) => + [ + `- ${difference.informational ? 'info' : difference.explainedBy ? 'explained' : '**UNEXPLAINED**'} · \`${difference.scenario}\` · ${difference.checkpoint} · \`${difference.field}\``, + ` - ${args.base}: \`${show(difference.base)}\``, + ` - ${args.head}: \`${show(difference.head)}\``, + ...(difference.explainedBy + ? [ + ` - why: ${difference.explainedBy.reason}${difference.explainedBy.upstream ? ` (${difference.explainedBy.upstream})` : ''}`, + ] + : []), + ].join('\n'), + ), + '', + ...allowlist + .filter((entry) => !used.has(entry)) + .map( + (entry) => `- stale allowlist entry: \`${entry.scenario}\` · \`${entry.field}\``, + ), +]; +writeFileSync(args.report, `${lines.join('\n')}\n`); +console.log(lines.slice(0, 3).join('\n')); +unexplained + .slice(0, 20) + .forEach((difference) => + console.log( + `UNEXPLAINED ${difference.scenario} · ${difference.checkpoint} · ${difference.field}\n ${args.base}: ${show(difference.base)}\n ${args.head}: ${show(difference.head)}`, + ), + ); +console.log(`Full report: ${args.report}`); +process.exit(unexplained.length > 0 ? 1 : 0); diff --git a/src/a11y/hooks/__tests__/useVirtualizedListboxKeyboardNavigation.test.ts b/src/a11y/hooks/__tests__/useVirtualizedListboxKeyboardNavigation.test.ts index 6d0a677783..6c39d077f6 100644 --- a/src/a11y/hooks/__tests__/useVirtualizedListboxKeyboardNavigation.test.ts +++ b/src/a11y/hooks/__tests__/useVirtualizedListboxKeyboardNavigation.test.ts @@ -1,12 +1,15 @@ +import type { KeyboardEvent } from 'react'; import { renderHook } from '@testing-library/react'; import { useVirtualizedListboxKeyboardNavigation } from '../useVirtualizedListboxKeyboardNavigation'; -const makeEvent = (key: string) => ({ - key, - preventDefault: vi.fn(), - stopPropagation: vi.fn(), -}); +// Only what the hook reads of a keyboard event. +const makeEvent = (key: string) => + ({ + key, + preventDefault: vi.fn(), + stopPropagation: vi.fn(), + }) as unknown as KeyboardEvent; describe('useVirtualizedListboxKeyboardNavigation', () => { // The full list; the DOM only ever holds a subset of it (the rendered window). @@ -75,6 +78,127 @@ describe('useVirtualizedListboxKeyboardNavigation', () => { expect(document.activeElement).toBe(optionFor('d')); }); + it('moves on from the pending target while an off-window scroll is still settling', () => { + // react-virtuoso 4 reports a scroll done only once it settled, so a held arrow key presses + // again before the next row is focused: each press must still advance one row. + renderOption('a'); + const pending: (() => void)[] = []; + const deferredScroll = vi.fn((index: number, onRendered: () => void) => { + pending.push(() => { + renderOption(ITEMS[index].id); + onRendered(); + }); + }); + const { result } = setup(deferredScroll); + optionFor('a')!.focus(); + + result.current.onKeyDown(makeEvent('ArrowDown')); + result.current.onKeyDown(makeEvent('ArrowDown')); + expect(deferredScroll).toHaveBeenNthCalledWith(1, 1, expect.any(Function)); + expect(deferredScroll).toHaveBeenNthCalledWith(2, 2, expect.any(Function)); + + pending.forEach((settle) => settle()); + expect(document.activeElement).toBe(optionFor('c')); + }); + + it('starts from the focused row again once focus moved away from a pending chain', () => { + ['a', 'b'].forEach(renderOption); + const neverSettles = vi.fn(); + const { result } = setup(neverSettles); + optionFor('a')!.focus(); + result.current.onKeyDown(makeEvent('End')); + expect(neverSettles).toHaveBeenLastCalledWith(4, expect.any(Function)); + + // The user clicks row b while the scroll to the end is still pending. + optionFor('b')!.focus(); + result.current.onKeyDown(makeEvent('ArrowDown')); + expect(neverSettles).toHaveBeenLastCalledWith(2, expect.any(Function)); + }); + + describe('while an off-window target scrolls in', () => { + const deferred = () => { + const pending: (() => void)[] = []; + const scroll = vi.fn((index: number, onRendered: () => void) => { + pending.push(() => { + renderOption(ITEMS[index].id); + onRendered(); + }); + }); + return { pending, scroll }; + }; + + it('keeps focus in the list, on the scroller, until the target is focused', () => { + renderOption('a'); + const { pending, scroll } = deferred(); + const { result } = setup(scroll); + optionFor('a')!.focus(); + + result.current.onKeyDown(makeEvent('End')); + // The focused row may leave the rendered window now; focus must not fall to . + optionFor('a')!.remove(); + expect(document.activeElement).toBe(scroller); + + pending.forEach((settle) => settle()); + expect(document.activeElement).toBe(optionFor('e')); + }); + + it('drops a target a reload removed, and navigates the items as they are', () => { + // End with 100 threads loaded; a reconnect replaces them with a first page of two while the + // scroll to the end is pending. ArrowUp must not ask for row 98 of a two-row list. + const many = Array.from({ length: 100 }, (_, i) => ({ id: `t${i}` })); + const option = (id: string) => { + const element = document.createElement('button'); + element.setAttribute('role', 'option'); + element.setAttribute('data-thread-id', id); + scroller.appendChild(element); + return element; + }; + option('t0').focus(); + const scroll = vi.fn(); + const { rerender, result } = renderHook( + ({ items }) => + useVirtualizedListboxKeyboardNavigation({ + getItemId: (item: { id: string }) => item.id, + itemIdAttribute: 'data-thread-id', + items, + scrollerRef: { current: scroller }, + scrollIndexIntoView: scroll, + }), + { initialProps: { items: many } }, + ); + result.current.onKeyDown(makeEvent('End')); + expect(scroll).toHaveBeenLastCalledWith(99, expect.any(Function)); + expect(document.activeElement).toBe(scroller); + + scroller.replaceChildren(); + const reloaded = [{ id: 'n0' }, { id: 'n1' }]; + rerender({ items: reloaded }); + option('n0'); + option('n1'); + scroll.mockClear(); + result.current.onKeyDown(makeEvent('ArrowUp')); + expect(scroll).not.toHaveBeenCalled(); + expect(document.activeElement?.getAttribute('data-thread-id')).toBe('n0'); + result.current.onKeyDown(makeEvent('ArrowDown')); + expect(document.activeElement?.getAttribute('data-thread-id')).toBe('n1'); + }); + + it('does not pull focus back once the reader moved it out of the list', () => { + renderOption('a'); + const { pending, scroll } = deferred(); + const { result } = setup(scroll); + optionFor('a')!.focus(); + result.current.onKeyDown(makeEvent('End')); + + const elsewhere = document.createElement('button'); + document.body.appendChild(elsewhere); + elsewhere.focus(); + pending.forEach((settle) => settle()); + expect(document.activeElement).toBe(elsewhere); + elsewhere.remove(); + }); + }); + it('End scrolls to the last item; Home returns to the first', () => { ['a', 'b', 'c'].forEach(renderOption); const scroll = vi.fn(renderingScroll); diff --git a/src/a11y/hooks/useVirtualizedListboxKeyboardNavigation.ts b/src/a11y/hooks/useVirtualizedListboxKeyboardNavigation.ts index c331298948..d4881da0f2 100644 --- a/src/a11y/hooks/useVirtualizedListboxKeyboardNavigation.ts +++ b/src/a11y/hooks/useVirtualizedListboxKeyboardNavigation.ts @@ -1,12 +1,13 @@ import type { KeyboardEvent as ReactKeyboardEvent, RefObject } from 'react'; -import { useCallback, useRef } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import { getNextRovingFocusIndex } from '../a11yUtils'; const DEFAULT_OPTION_SELECTOR = '[role="option"]'; -// A virtual list's "rendered" callback can fire a frame before the row paints, so focusing after a -// scroll retries across a few animation frames. -const MAX_FOCUS_ATTEMPTS_AFTER_SCROLL = 5; +// A virtual list's "rendered" callback can fire before the row paints (react-virtuoso 4 reports a +// long scroll done while it still re-measures), so focusing after a scroll retries every animation +// frame for up to this long. +const FOCUS_AFTER_SCROLL_TIMEOUT_MS = 1000; // Escapes a value for a quoted attribute selector (`[attr="value"]`). const escapeAttributeValue = (value: string) => value.replace(/(["\\])/g, '\\$1'); @@ -49,55 +50,123 @@ export const useVirtualizedListboxKeyboardNavigation = ({ // Bumped on every roving key press. A deferred post-scroll focus chain bails once a newer press // supersedes it, so a slow older scroll cannot steal focus back to an outdated row. const latestFocusRequestRef = useRef(0); + // The item a pending off-window focus chain is heading to, by ID: the items can change while it + // is pending (a reload replaces them with a shorter first page), and an index would then point + // elsewhere, or past the end. A virtual list may report the scroll done only once it settled + // (react-virtuoso 4 waits for the list to stop changing), so a held arrow key presses again before + // that row has focus; navigation moves on from this target, not from the row that still has focus. + const pendingIdRef = useRef(null); + // The item focused when that chain started: focus moved elsewhere since (a click, Tab) makes the + // pending target stale. + const pendingFromIdRef = useRef(undefined); + // The current items, for a chain that outlives the render it started in. + // Updated once a render commits: a render React discards (a suspended transition) must not make + // a pending target that is still on screen look gone. + const itemsRef = useRef(items); + useEffect(() => { + itemsRef.current = items; + }, [items]); - // Focuses the option for `items[index]` if it is in the DOM; returns whether it was. - const focusOptionAt = useCallback( - (index: number) => { - const item = items[index]; - if (!item) return false; + // Focuses the rendered option for the item with this ID; returns whether there was one. + const focusOptionById = useCallback( + (id: string) => { const option = scrollerRef.current?.querySelector( - `${optionSelector}[${itemIdAttribute}="${escapeAttributeValue(getItemId(item))}"]`, + `${optionSelector}[${itemIdAttribute}="${escapeAttributeValue(id)}"]`, ); if (!option) return false; option.focus(); return true; }, - [getItemId, itemIdAttribute, items, optionSelector, scrollerRef], + [itemIdAttribute, optionSelector, scrollerRef], ); + // The ID of the item at or above the focused element; undefined when focus is on no item (the + // scroller itself while a target scrolls in). + const getActiveItemId = useCallback(() => { + const active = document.activeElement; + return active instanceof HTMLElement + ? (active + .closest(`[${itemIdAttribute}]`) + ?.getAttribute(itemIdAttribute) ?? undefined) + : undefined; + }, [itemIdAttribute]); + + // Whether focus is still where the pending chain left it: on the scroller holding it, on the row + // the key was pressed on, or nowhere (fallen to as that row unmounted). Focus the reader + // moved elsewhere (Tab, a click, another row) must not be pulled back when the target renders. + const isFocusStillPending = useCallback(() => { + const active = document.activeElement; + if (!active || active === document.body) return true; + const scroller = scrollerRef.current; + if (!scroller?.contains(active)) return false; + return getActiveItemId() === pendingFromIdRef.current; + }, [getActiveItemId, scrollerRef]); + const focusOptionAfterRender = useCallback( ( - index: number, + id: string, requestId: number, - attemptsLeft = MAX_FOCUS_ATTEMPTS_AFTER_SCROLL, + deadline = Date.now() + FOCUS_AFTER_SCROLL_TIMEOUT_MS, ) => { // A newer key press superseded this chain. if (requestId !== latestFocusRequestRef.current) return; - if (focusOptionAt(index) || attemptsLeft <= 0) return; - requestAnimationFrame(() => - focusOptionAfterRender(index, requestId, attemptsLeft - 1), - ); + // Focus moved elsewhere, or the target is gone from the items (they were replaced). + if ( + !isFocusStillPending() || + !itemsRef.current.some((item) => getItemId(item) === id) + ) { + pendingIdRef.current = null; + return; + } + if (focusOptionById(id)) { + pendingIdRef.current = null; + return; + } + // Given up: the pending target stays, so the next press still moves on from it. + if (Date.now() >= deadline) return; + requestAnimationFrame(() => focusOptionAfterRender(id, requestId, deadline)); }, - [focusOptionAt], + [focusOptionById, getItemId, isFocusStillPending], ); const onKeyDown = useCallback( (event: ReactKeyboardEvent) => { const active = document.activeElement; - const activeId = - active instanceof HTMLElement - ? (active - .closest(`[${itemIdAttribute}]`) - ?.getAttribute(itemIdAttribute) ?? undefined) - : undefined; - const activeIndex = - activeId != null ? items.findIndex((item) => getItemId(item) === activeId) : -1; - const nextIndex = getNextRovingFocusIndex({ + const scroller = scrollerRef.current; + const indexOf = (id: string | null | undefined) => + id != null ? items.findIndex((item) => getItemId(item) === id) : -1; + const activeId = getActiveItemId(); + let activeIndex = indexOf(activeId); + if (pendingIdRef.current !== null && pendingFromIdRef.current === activeId) { + const pendingIndex = indexOf(pendingIdRef.current); + if (pendingIndex !== -1) activeIndex = pendingIndex; + // The pending target is gone from the items: navigation resumes from the list as it is. + else pendingIdRef.current = null; + } + let nextIndex = getNextRovingFocusIndex({ activeIndex, itemCount: items.length, key: event.key, }); + // Focus on the scroller itself, with no target pending (entering the list, or after a reload + // replaced the items): an arrow key enters at the first row on screen, not at an end. + if ( + nextIndex !== null && + activeIndex === -1 && + scroller && + active === scroller && + (event.key === 'ArrowDown' || event.key === 'ArrowUp') + ) { + const firstRendered = scroller.querySelector( + `${optionSelector}[${itemIdAttribute}]`, + ); + const entryIndex = indexOf(firstRendered?.getAttribute(itemIdAttribute)); + if (entryIndex !== -1) nextIndex = entryIndex; + } if (nextIndex === null) return; // Not a roving key. + const nextItem = items[nextIndex]; + if (!nextItem) return; + const nextId = getItemId(nextItem); event.preventDefault(); event.stopPropagation(); @@ -105,16 +174,30 @@ export const useVirtualizedListboxKeyboardNavigation = ({ const requestId = ++latestFocusRequestRef.current; // A rendered row is focused right away (native focus scrolls it fully into view); otherwise // scroll it into existence and focus it once the list has painted it. - if (focusOptionAt(nextIndex)) return; - scrollIndexIntoView(nextIndex, () => focusOptionAfterRender(nextIndex, requestId)); + if (focusOptionById(nextId)) { + pendingIdRef.current = null; + return; + } + // The focused row can leave the rendered window before the target enters it, and focus would + // then fall to , out of reach of this handler. The scroller holds it meanwhile. + if (scroller && active instanceof HTMLElement && scroller.contains(active)) { + if (!scroller.hasAttribute('tabindex')) scroller.tabIndex = -1; + scroller.focus({ preventScroll: true }); + } + pendingIdRef.current = nextId; + pendingFromIdRef.current = getActiveItemId(); + scrollIndexIntoView(nextIndex, () => focusOptionAfterRender(nextId, requestId)); }, [ focusOptionAfterRender, - focusOptionAt, + focusOptionById, + getActiveItemId, getItemId, itemIdAttribute, items, + optionSelector, scrollIndexIntoView, + scrollerRef, ], ); diff --git a/src/components/MessageList/MessageListPositioningUI.tsx b/src/components/MessageList/MessageListPositioningUI.tsx new file mode 100644 index 0000000000..b7ae984d4e --- /dev/null +++ b/src/components/MessageList/MessageListPositioningUI.tsx @@ -0,0 +1,33 @@ +import React from 'react'; + +import { LoadingIndicator as DefaultLoadingIndicator } from '../Loading/LoadingIndicator'; +import { useComponentContext } from '../../context/ComponentContext'; + +export type MessageListPositioningUIProps = { + /** + * True while react-virtuoso keeps the list hidden to position it: when the list opens (a channel + * or thread, a channel switch) and after a jump to a message or to the latest messages, for about + * a quarter of a second. False otherwise, so a component can animate the change (fade the list + * in, say). + */ + isPositioning: boolean; +}; + +/** + * Rendered over `VirtualizedMessageList` at all times, told whether the list is being positioned. + * The default shows the `LoadingIndicator`, centered, while it is; a `LoadingIndicator` set to + * `null` turns it off. Replace it through the `MessageListPositioningUI` key of `WithComponents`, + * or set that key to `null` to render nothing. + */ +export const MessageListPositioningUI = ({ + isPositioning, +}: MessageListPositioningUIProps) => { + // The default applies only to an unset key, so `null` stays `null` and hides the spinner. + const { LoadingIndicator = DefaultLoadingIndicator } = useComponentContext(); + if (!isPositioning || !LoadingIndicator) return null; + return ( +
+ +
+ ); +}; diff --git a/src/components/MessageList/VirtualizedMessageList.tsx b/src/components/MessageList/VirtualizedMessageList.tsx index 97f0738005..1906bf8184 100644 --- a/src/components/MessageList/VirtualizedMessageList.tsx +++ b/src/components/MessageList/VirtualizedMessageList.tsx @@ -18,6 +18,12 @@ import { } from './hooks/VirtualizedMessageList'; import { useMarkRead } from './hooks/useMarkRead'; import { useScrollerViewport } from './hooks/VirtualizedMessageList/useScrollerViewport'; +import { useAfterInitialLocation } from './hooks/VirtualizedMessageList/useAfterInitialLocation'; +import { useStickToBottomOnGrowth } from './hooks/VirtualizedMessageList/useStickToBottomOnGrowth'; +import { + ListPositioningReporterContext, + makePositioningReportingList, +} from './hooks/VirtualizedMessageList/positioningList'; import { useMessageFocusSignalViewed } from './hooks/VirtualizedMessageList/useMessageFocusSignalViewed'; import { @@ -47,6 +53,7 @@ import { messageRenderer, } from './VirtualizedMessageListComponents'; import { VirtualizedMessageListEmptyUI } from './ListStates'; +import { MessageListPositioningUI as DefaultMessageListPositioningUI } from './MessageListPositioningUI'; import { ScrollToLatestMessageButton as DefaultScrollToLatestMessageButton, @@ -281,6 +288,8 @@ const VirtualizedMessageListWithContext = ( const { DateSeparator = DefaultDateSeparator, GiphyPreviewMessage = DefaultGiphyPreviewMessage, + // `null` renders nothing; the default applies only to an unset key. + MessageListPositioningUI = DefaultMessageListPositioningUI, MessageSystem = DefaultMessageSystem, NewMessageNotification = DefaultNewMessageNotification, ScrollToLatestMessageButton = DefaultScrollToLatestMessageButton, @@ -454,12 +463,37 @@ const VirtualizedMessageListWithContext = ( // Content can grow without the scroller resizing or scrolling (e.g. an avatar or image loading // late), which moves the true bottom without firing either event the hook observes. + // A reader at the bottom stays there while the content grows (an image loading, a reply + // streaming in, messages measuring taller than estimated). In an older window that is what lets + // a scroll to its end reach the end, and so load the next newer page, when the revealed messages + // measure taller; the page that loads is not followed. Neither are new messages with + // `suppressAutoscroll`, nor with an integrator's `followOutput`: Virtuoso applies that one, and + // the SDK cannot know what a callback would answer. A custom scroll parent is the integrator's. + // Whether Virtuoso keeps the item list hidden while it positions it, as the list reports it. + const listHiddenRef = useRef(false); + const { messageSetKey } = useMessageSetKey({ + focusSignal: messageFocusSignal, + messages, + }); + + const followOutputFromProps = additionalVirtuosoProps.followOutput; + const stickToBottomOnGrowth = useStickToBottomOnGrowth({ + followNewItems: + !hasMoreNewer && !suppressAutoscroll && followOutputFromProps === undefined, + itemCount: processedMessages.length, + listHiddenRef, + listKey: messageSetKey, + scroller: customScrollParent ? null : scrollerElement, + threshold, + }); + const totalListHeightChanged = useCallback( (height: number) => { remeasure(); + stickToBottomOnGrowth(height); totalListHeightChangedFromProps?.(height); }, - [remeasure, totalListHeightChangedFromProps], + [remeasure, stickToBottomOnGrowth, totalListHeightChangedFromProps], ); useMarkRead({ @@ -511,8 +545,6 @@ const VirtualizedMessageListWithContext = ( withDateSeparator, ); - const { messageSetKey } = useMessageSetKey({ messages }); - const shouldForceScrollToBottom = useShouldForceScrollToBottom( processedMessages, client.userID, @@ -529,6 +561,10 @@ const VirtualizedMessageListWithContext = ( ), [processedMessages, toggleShowUnreadMessagesNotification], ); + // react-virtuoso 4 also scrolls to the bottom on its own when an item grows or the viewport + // shrinks, whenever `followOutput` is anything but `false`, without asking the function. So when + // the list must not follow (an older window, suppressed autoscroll) it gets a literal `false`. + const isFollowingOutput = !messagePaginator.hasMoreHead && !suppressAutoscroll; const followOutput = (isAtBottom: boolean) => { if (messagePaginator.hasMoreHead || suppressAutoscroll) { return false; @@ -542,13 +578,37 @@ const VirtualizedMessageListWithContext = ( }; const computeItemKey = useCallback>( + // While the messages change under it, Virtuoso can ask for an index the list no longer has for + // one pass; the index stands in until it catches up. (index, _, { numItemsPrepended, processedMessages }) => - processedMessages[calculateItemIndex(index, numItemsPrepended)].id, + processedMessages[calculateItemIndex(index, numItemsPrepended)]?.id ?? + `missing-${index}`, [], ); const canPaginateReplies = useCanPaginateReplies(); + // Loading a page from an edge Virtuoso reports while it still positions the list would load the + // wrong page: these run once the list is shown (see useAfterInitialLocation), against the edge + // state Virtuoso reported last. + const atTopRef = useRef(false); + // The same, as state, for what renders while the list is hidden. + const [isListHidden, setIsListHidden] = useState(false); + const reportListHidden = useCallback((hidden: boolean) => { + listHiddenRef.current = hidden; + setIsListHidden(hidden); + }, []); + const ListFromProps = virtuosoComponentsFromProps?.List; + const List = useMemo( + () => makePositioningReportingList(ListFromProps), + [ListFromProps], + ); + const afterInitialLocationAtTop = useAfterInitialLocation(listHiddenRef, messageSetKey); + const afterInitialLocationAtBottom = useAfterInitialLocation( + listHiddenRef, + messageSetKey, + ); + const atBottomStateChange = (isAtBottom: boolean) => { atBottom.current = isAtBottom; setIsMessageListScrolledToBottom(isAtBottom); @@ -556,15 +616,20 @@ const VirtualizedMessageListWithContext = ( if (isAtBottom) { // An empty thread is at both ends at once, so Virtuoso reports both on mount; // `canPaginateReplies` keeps that from becoming a request. - if (canPaginateReplies) void messagePaginator.toHead(); + if (canPaginateReplies) { + afterInitialLocationAtBottom(() => { + if (atBottom.current) void messagePaginator.toHead(); + }); + } setNewMessagesNotification?.(false); } }; const atTopStateChange = (isAtTop: boolean) => { - if (isAtTop) { - if (!canPaginateReplies) return; - void messagePaginator.toTail(); - } + atTopRef.current = isAtTop; + if (!isAtTop || !canPaginateReplies) return; + afterInitialLocationAtTop(() => { + if (atTopRef.current) void messagePaginator.toTail(); + }); }; const focusViewedSignalRef = useMessageFocusSignalViewed({ @@ -611,6 +676,7 @@ const VirtualizedMessageListWithContext = ( /> )}
@@ -620,65 +686,72 @@ const VirtualizedMessageListWithContext = ( scrollElement={floatingDateScrollElement} withDateSeparator={withDateSeparator} /> - - atBottomStateChange={atBottomStateChange} - atBottomThreshold={threshold} - atTopStateChange={atTopStateChange} - atTopThreshold={threshold} - className='str-chat__message-list-scroll' - components={{ - EmptyPlaceholder: VirtualizedMessageListEmptyUI, - Footer, - Header, - Item, - ...virtuosoComponentsFromProps, - }} - computeItemKey={computeItemKey} - context={{ - ...messageProps, - channel, - customClasses, - customMessageRenderer, - DateSeparator, - firstUnreadMessageId: channelUnreadUiState?.firstUnreadMessageId, - focusedMessageId, - groupByUser, - head: threadHead, - lastOwnMessage, - lastReadDate: channelUnreadUiState?.lastReadAt, - lastReadMessageId: channelUnreadUiState?.lastReadMessageId, - lastReceivedMessageId, - loadingEdge, - loadingMore: isLoading, - messageGroupStyles, - MessageSystem, - numItemsPrepended, - ownMessagesDeliveredToOthers, - ownMessagesReadByOthers, - processedMessages, - returnAllReadData, - unreadMessageCount: channelUnreadUiState?.unreadCount, - UnreadMessagesSeparator, - virtuosoRef: virtuoso, - }} - firstItemIndex={calculateFirstItemIndex(numItemsPrepended)} - followOutput={followOutput} - increaseViewportBy={{ bottom: 200, top: 0 }} - initialTopMostItemIndex={calculateInitialTopMostItemIndex( - processedMessages, - focusedMessageId, - )} - itemContent={messageRenderer} - itemSize={fractionalItemSize} - itemsRendered={handleItemsRendered} - key={messageSetKey} - ref={virtuoso} - style={{ overflowX: 'hidden' }} - totalCount={processedMessages.length} - {...overridingVirtuosoProps} - scrollerRef={scrollerRef} - totalListHeightChanged={totalListHeightChanged} - /> + + + atBottomStateChange={atBottomStateChange} + atBottomThreshold={threshold} + atTopStateChange={atTopStateChange} + atTopThreshold={threshold} + className='str-chat__message-list-scroll' + components={{ + EmptyPlaceholder: VirtualizedMessageListEmptyUI, + Footer, + Header, + Item, + ...virtuosoComponentsFromProps, + List, + }} + computeItemKey={computeItemKey} + context={{ + ...messageProps, + channel, + customClasses, + customMessageRenderer, + DateSeparator, + firstUnreadMessageId: channelUnreadUiState?.firstUnreadMessageId, + focusedMessageId, + groupByUser, + head: threadHead, + lastOwnMessage, + lastReadDate: channelUnreadUiState?.lastReadAt, + lastReadMessageId: channelUnreadUiState?.lastReadMessageId, + lastReceivedMessageId, + loadingEdge, + loadingMore: isLoading, + messageGroupStyles, + MessageSystem, + numItemsPrepended, + ownMessagesDeliveredToOthers, + ownMessagesReadByOthers, + processedMessages, + returnAllReadData, + unreadMessageCount: channelUnreadUiState?.unreadCount, + UnreadMessagesSeparator, + virtuosoRef: virtuoso, + }} + firstItemIndex={calculateFirstItemIndex(numItemsPrepended)} + followOutput={isFollowingOutput ? followOutput : false} + increaseViewportBy={{ bottom: 200, top: 0 }} + initialTopMostItemIndex={calculateInitialTopMostItemIndex( + processedMessages, + focusedMessageId, + )} + itemContent={messageRenderer} + itemSize={fractionalItemSize} + itemsRendered={handleItemsRendered} + key={messageSetKey} + ref={virtuoso} + style={{ overflowX: 'hidden' }} + totalCount={processedMessages.length} + {...overridingVirtuosoProps} + scrollerRef={scrollerRef} + totalListHeightChanged={totalListHeightChanged} + /> + + {/* Virtuoso keeps the list hidden while it positions it (opening the list, a jump). */} + {MessageListPositioningUI && ( + + )} {/* Only for messages that arrived while the reader was scrolled up. Reading an older window (e.g. after a jump) is signalled by ScrollToLatestMessageButton instead. */} []) => { const renderedMessages = items .map((item) => { - if (!item.originalIndex) return undefined; - return processedMessages[calculateItemIndex(item.originalIndex, PREPEND_OFFSET)]; + // `originalIndex` is the 0-based position in the data, so 0 is the first loaded message. + if (item.originalIndex === undefined) return undefined; + return processedMessages[item.originalIndex]; }) .filter((msg) => !!msg); renderedItemsActions.forEach((action) => @@ -42,13 +43,22 @@ export type CommonVirtuosoComponentProps = { context?: VirtuosoContext; }; // `display: inline-block` traps the items' CSS margins, preventing incorrect item measurements. -export const Item = ({ context, ...props }: ItemProps & CommonVirtuosoComponentProps) => { +// `item` is the row's data, which Virtuoso passes since v4; this list has none (it renders by +// `totalCount`), and spreading it onto the
would leak it into the DOM. +export const Item = ({ + context, + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- strip `item` so it is not forwarded to the
+ item: _item, + ...props +}: ItemProps & CommonVirtuosoComponentProps) => { if (!context) return <>; const message = context.processedMessages[ calculateItemIndex(props['data-item-index'], context.numItemsPrepended) ]; + // Virtuoso can render an index the list no longer has for one pass (see computeItemKey). + if (!message) return
; const groupStyles: GroupStyle = context.messageGroupStyles[message.id]; return ( diff --git a/src/components/MessageList/__tests__/VirtualizedMessageList.test.tsx b/src/components/MessageList/__tests__/VirtualizedMessageList.test.tsx index 7d91af7e47..de3f971dc7 100644 --- a/src/components/MessageList/__tests__/VirtualizedMessageList.test.tsx +++ b/src/components/MessageList/__tests__/VirtualizedMessageList.test.tsx @@ -437,6 +437,33 @@ describe('VirtualizedMessageList', () => { ); }); + // react-virtuoso 4 scrolls to the bottom on its own (an item grew, the viewport shrank) unless + // `followOutput` is `false`, without calling the function: a list that must not follow passes + // `false` itself. + it.each([ + ['newer pages to load', { hasMoreHead: true }], + ['autoscroll suppressed', { listProps: { suppressAutoscroll: true } }], + ])('J-05 passes followOutput={false} with %s', async (_label, options) => { + const props = await renderList(options); + expect(props.followOutput).toBe(false); + }); + + // A function `followOutput` is followed on any answer but `false` (`undefined` means 'auto'), so + // every branch must answer `false`, 'auto' or the configured behavior, never undefined. + it.each([ + ['latest messages, at the bottom', {}, true, 'smooth'], + ['latest messages, scrolled up', {}, false, false], + [ + 'latest messages, at the bottom, high throughput', + { listProps: { stickToBottomScrollBehavior: 'auto' as const } }, + true, + 'auto', + ], + ])('J-05 followOutput answers %s', async (_label, options, isAtBottom, expected) => { + const props = await renderList(options); + expect(props.followOutput(isAtBottom)).toBe(expected); + }); + it('anchors the initial scroll to the end of the last item', async () => { const props = await renderList(); diff --git a/src/components/MessageList/__tests__/VirtualizedMessageListComponents.test.tsx b/src/components/MessageList/__tests__/VirtualizedMessageListComponents.test.tsx index 8827cf583b..fd7b75bead 100644 --- a/src/components/MessageList/__tests__/VirtualizedMessageListComponents.test.tsx +++ b/src/components/MessageList/__tests__/VirtualizedMessageListComponents.test.tsx @@ -8,6 +8,7 @@ import { messageRenderer, } from '../VirtualizedMessageListComponents'; import { VirtualizedMessageListEmptyUI } from '../ListStates'; +import { MessageListPositioningUI } from '../MessageListPositioningUI'; import type { VirtuosoContext } from '../VirtualizedMessageList'; import { generateMessage, @@ -121,6 +122,8 @@ describe('VirtualizedMessageComponents', () => { 'data-index': PREPEND_OFFSET, 'data-item-index': PREPEND_OFFSET, 'data-known-size': 0, + // react-virtuoso 4 passes the row's data; this list renders by `totalCount`, so none. + item: undefined as never, }; const virtuosoContext = { customClasses, @@ -290,6 +293,32 @@ describe('VirtualizedMessageComponents', () => { }); }); + describe('MessageListPositioningUI', () => { + it('should render the LoadingIndicator over the list while it is positioned', () => { + const { container } = renderElements(, { + LoadingIndicator: () =>
Custom Loading Indicator
, + }); + expect( + container.querySelector('.str-chat__virtual-list__positioning'), + ).toHaveTextContent('Custom Loading Indicator'); + }); + + it('should render nothing once the list is positioned', () => { + const { container } = renderElements( + , + { LoadingIndicator: () =>
Custom Loading Indicator
}, + ); + expect(container).toBeEmptyDOMElement(); + }); + + it('should render nothing while LoadingIndicator is set to null', () => { + const { container } = renderElements(, { + LoadingIndicator: null as unknown as undefined, + }); + expect(container).toBeEmptyDOMElement(); + }); + }); + describe('Footer', () => { it.each([ ['without a Virtuoso context', undefined], diff --git a/src/components/MessageList/__tests__/__snapshots__/VirtualizedMessageList.test.tsx.snap b/src/components/MessageList/__tests__/__snapshots__/VirtualizedMessageList.test.tsx.snap index 7f7e4adf2c..e18a6acc51 100644 --- a/src/components/MessageList/__tests__/__snapshots__/VirtualizedMessageList.test.tsx.snap +++ b/src/components/MessageList/__tests__/__snapshots__/VirtualizedMessageList.test.tsx.snap @@ -14,14 +14,14 @@ exports[`VirtualizedMessageList > should render the list without any message 1`] >
{ + const actual = await importOriginal(); + const { wrapVirtuoso } = await import('./virtuosoProbe'); + return { ...actual, Virtuoso: wrapVirtuoso(actual.Virtuoso as never) }; +}); + +const unmounts: (() => void)[] = []; +afterEach(() => { + unmounts.splice(0).forEach((unmount) => unmount()); +}); + +const mount = async (element: React.ReactElement, height = 400) => { + const container = document.createElement('div'); + container.style.cssText = `height:${height}px;width:420px;display:flex;flex-direction:column`; + document.body.appendChild(container); + const root = createRoot(container); + root.render(element); + unmounts.push(() => { + root.unmount(); + container.remove(); + }); + await waitUntil( + () => !!container.querySelector('[data-virtuoso-scroller]'), + 4000, + 'list', + ); + return container; +}; + +/** A trace of these simpler lists: the DOM Virtuoso renders and the calls the probe saw. */ +const writeTrace = ( + scenario: string, + frame: HTMLElement, + extra: Record, +) => + commands.writeVirtuosoTrace( + scenario, + JSON.stringify({ + checkpoints: [ + { + commits: 0, + dom: describeDom(frame), + events: probe.events.filter((event) => event.name !== 'itemsRendered'), + firstVisible: null, + geometry: null, + label: 'end', + messageRenders: 0, + paginatorCalls: [], + remounted: [], + rendered: [], + requests: [], + visible: true, + }, + ], + consoleErrors: [], + framesUntilFirstItem: null, + metrics: extra, + runtime: RUNTIME, + scenario, + windowErrors: [], + }), + ); + +describe('other virtualized lists in a real browser', () => { + it('B-15 ThreadList: arrow keys reach rows outside the rendered window', async () => { + resetProbe(); + const user = { id: 'own-user' } as UserResponse; + const client = (await getTestClientWithUser(user)) as StreamChat; + const history = buildHistory({ count: 60, rng: createRng(5), users: [user] }); + installFakeBackend({ channelId: 'threads', client, history, users: [user] }); + const channel = client.channel('messaging', 'threads'); + const threads = history.map( + (message) => + new Thread({ channel, client, parentMessage: { ...message, reply_count: 2 } }), + ); + vi.spyOn(client.threads, 'reload').mockResolvedValue(undefined); + const toTail = vi + .spyOn(client.threads.paginator, 'toTail') + .mockResolvedValue(undefined as never); + client.threads.paginator.state.partialNext({ isLoading: false, items: threads }); + + const frame = await mount( + + + , + 500, + ); + const scroller = frame.querySelector('[data-virtuoso-scroller]'); + await waitUntil(() => !!frame.querySelector('[role="option"]'), 4000, 'rows'); + await settle(frame); + expect(scroller?.getAttribute('role'), 'listbox on the scroller').toBe('listbox'); + + frame.querySelector('[role="option"]')?.focus(); + const target = 25; + for (let i = 0; i < target; i += 1) { + await userEvent.keyboard('{ArrowDown}'); + await nextFrame(); + } + await waitUntil( + () => + (document.activeElement as HTMLElement | null) + ?.closest('[data-thread-id]') + ?.getAttribute('data-thread-id') === threads[target].id, + 4000, + 'focus on the 26th thread', + ); + const focused = (document.activeElement as HTMLElement).getBoundingClientRect(); + const box = scroller!.getBoundingClientRect(); + expect(focused.top, 'focused row inside the viewport').toBeGreaterThanOrEqual( + box.top - 1, + ); + expect(focused.bottom).toBeLessThanOrEqual(box.bottom + 1); + + // End and Home jump past the rendered window: the focused row unmounts before the target row + // renders, and focus must stay in the list (on the scroller) meanwhile, never falling to . + const focusedThreadId = () => + (document.activeElement as HTMLElement | null) + ?.closest('[data-thread-id]') + ?.getAttribute('data-thread-id'); + let framesFocusOutsideList = 0; + const pressAndReach = async (key: string, index: number) => { + await userEvent.keyboard(key); + for (let frames = 0; frames < 240; frames += 1) { + if (focusedThreadId() === threads[index].id) return; + if (!scroller!.contains(document.activeElement)) framesFocusOutsideList += 1; + await nextFrame(); + } + throw new Error(`${key}: focus never reached thread ${index}`); + }; + await pressAndReach('{End}', threads.length - 1); + await settle(frame); + await pressAndReach('{Home}', 0); + await settle(frame); + expect(framesFocusOutsideList, 'frames with focus outside the list').toBe(0); + + await writeTrace('B-15-thread-list-keyboard', frame, { + toTailCalls: toTail.mock.calls.length, + }); + }); + + it('B-16 ChannelFilesView layout: month headers stick to the top', async () => { + const Group = forwardRef>(function Group( + { className, ...props }, + ref, + ) { + return ( +
+ ); + }); + const groupCounts = [30, 30, 30]; + const frame = await mount( + ( +
+ month {index} +
+ )} + groupCounts={groupCounts} + itemContent={(index) =>
file {index}
} + style={{ height: 400 }} + />, + ); + const scroller = frame.querySelector('[data-virtuoso-scroller]')!; + await settle(frame); + scroller.scrollTop = 40 * 35; + await settle(frame); + const header = Array.from( + frame.querySelectorAll('.str-chat__channel-detail__files-view__group'), + ).find((element) => element.textContent?.includes('month 1')); + expect(header, 'month 1 header rendered').toBeDefined(); + expect(getComputedStyle(header!).position).toBe('sticky'); + expect( + Math.abs( + header!.getBoundingClientRect().top - scroller.getBoundingClientRect().top, + ), + 'header pinned at the scroller top', + ).toBeLessThanOrEqual(1); + await writeTrace('B-16-files-sticky-groups', frame, {}); + }); + + it('B-17 ChannelDetail VirtualizedList: loads the next page once at the bottom', async () => { + resetProbe(); + const loadNext = vi.fn(); + const items = Array.from({ length: 80 }, (_, i) => + generateMessage({ id: `item-${i}`, text: `item ${i}` }), + ); + const Harness = () => { + const [data] = useState(items); + return ( + item.id} + data={data} + itemContent={(_, item) =>
{item.text}
} + loadNext={loadNext} + role='list' + /> + ); + }; + const frame = await mount(); + const scroller = frame.querySelector('[data-virtuoso-scroller]')!; + await settle(frame); + expect(scroller.getAttribute('aria-label')).toBe('Pinned messages'); + expect(scroller.getAttribute('role')).toBe('list'); + scroller.scrollTop = scroller.scrollHeight; + await settle(frame); + await waitUntil(() => loadNext.mock.calls.length > 0, 2000, 'loadNext'); + scroller.scrollTop -= 10; + await nextFrame(); + await settle(frame); + expect(loadNext, 'loads once while it stays at the bottom').toHaveBeenCalledTimes(1); + await writeTrace('B-17-channel-detail-load-next', frame, { + loadNextCalls: loadNext.mock.calls.length, + }); + }); +}); diff --git a/src/components/MessageList/__tests__/browser/VirtualizedMessageList.fuzz.browser.test.tsx b/src/components/MessageList/__tests__/browser/VirtualizedMessageList.fuzz.browser.test.tsx new file mode 100644 index 0000000000..44e961a138 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/VirtualizedMessageList.fuzz.browser.test.tsx @@ -0,0 +1,85 @@ +import { pickOperation } from './fuzzOperations'; +import type { FuzzState } from './fuzzOperations'; +import { readGeometry, unmountAll, waitUntil } from './harness'; +import { runScenario } from './scenario'; +import { RUNTIME } from './trace'; + +// See VirtualizedMessageList.scroll.browser.test.tsx: the probe records the SDK ↔ Virtuoso calls. +vi.mock('react-virtuoso', async (importOriginal) => { + const actual = await importOriginal(); + const { wrapVirtuoso } = await import('./virtuosoProbe'); + return { ...actual, Virtuoso: wrapVirtuoso(actual.Virtuoso as never) }; +}); + +afterEach(unmountAll); + +declare const VIRTUOSO_TEST_FUZZ_SEEDS: string; + +/** How many seeds to run: `VIRTUOSO_FUZZ_SEEDS`, 25 by default. */ +const SEED_COUNT = Number( + typeof VIRTUOSO_TEST_FUZZ_SEEDS === 'string' && VIRTUOSO_TEST_FUZZ_SEEDS + ? VIRTUOSO_TEST_FUZZ_SEEDS + : 25, +); +const STEPS_PER_SEED = 30; + +describe('VirtualizedMessageList fuzzing', () => { + const seeds = Array.from({ length: SEED_COUNT }, (_, i) => 1000 + i); + + it.each(seeds)( + 'seed %i keeps its invariants', + async (seed) => { + await runScenario( + `F-${seed}`, + { historySize: 300, pageSize: 40, seed }, + async ({ mounted, step, violations }) => { + // The operations draw from their own stream, so the history a seed builds stays the same + // when operations are added. + const { createRng } = await import('./prng'); + const rng = createRng(seed * 7919); + const state: FuzzState = { suppressAutoscroll: false, viewportHeight: 600 }; + for (let index = 0; index < STEPS_PER_SEED; index += 1) { + const operation = pickOperation(rng); + let detail = ''; + const point = await step( + `${index} ${operation.name}`, + async () => { + detail = await operation.run(mounted, rng, state); + }, + // Fuzzing looks for behavior that diverges; render cost is B-20's job. + { settle: { timeoutMs: 6000 }, timingDependent: true }, + ); + // A jump that loads the page around its target centers the target in it, so the list is + // at neither edge and loads no other page: one loaded above or below means the list + // reported an edge while it was being positioned. On v2 that is its known remount race + // (allowlisted for the comparison); on v4 it fails the seed. A jump to a message loaded + // before shows the stretch it is in, whose edge the target may sit at: not checked. + if (operation.name === 'jump to a message' && RUNTIME !== 'browser-v2') { + const queries = point.requests.map( + (request) => + ( + request as { + messages?: { id_around?: string; id_gt?: string; id_lt?: string }; + } + ).messages, + ); + const loadedAround = queries.some((query) => !!query?.id_around); + const pages = queries.filter((query) => !!(query?.id_gt || query?.id_lt)); + if (loadedAround && pages.length) { + violations.push( + `${point.label}: loaded ${pages.length} page(s) besides the jump's own`, + ); + } + } + // Keeps the label informative in the trace without changing the comparison key. + mounted.frame.setAttribute('data-last-operation', detail); + } + await waitUntil(() => !!readGeometry(mounted.frame), 1000); + }, + // v2's known defects (blank frames on prepend) are recorded, not failed; v4 is strict. + { allowViolations: RUNTIME === 'browser-v2' }, + ); + }, + 120_000, + ); +}); diff --git a/src/components/MessageList/__tests__/browser/VirtualizedMessageList.scroll.browser.test.tsx b/src/components/MessageList/__tests__/browser/VirtualizedMessageList.scroll.browser.test.tsx new file mode 100644 index 0000000000..0347a91fef --- /dev/null +++ b/src/components/MessageList/__tests__/browser/VirtualizedMessageList.scroll.browser.test.tsx @@ -0,0 +1,923 @@ +import React, { forwardRef, useState } from 'react'; +import type { ListProps } from 'react-virtuoso'; +import { commands } from 'vitest/browser'; + +import { + isListVisible, + mountList, + nextFrame, + OWN_USER, + readGeometry, + readRenderedItems, + readVisibleItems, + receiveMessage, + scrollBy, + scrollToBottom, + scrollToTop, + setMessageHeight, + settle, + trackResources, + unmountAll, + wait, + waitUntil, +} from './harness'; +import { expectAtBottom } from './invariants'; +import { runScenario, SCROLL_TARGET_RETRY_WINDOW_MS } from './scenario'; +import { createTrace, RUNTIME } from './trace'; +import { VirtualizedMessageList } from '../../VirtualizedMessageList'; +import type { MessageListPositioningUIProps } from '../../MessageListPositioningUI'; +import type { ComponentContextValue } from '../../../../context'; + +// Every Virtuoso the SDK renders goes through the probe, which records the calls crossing the +// SDK ↔ Virtuoso boundary. The same file runs against both runtimes (see vitest.config.ts). +vi.mock('react-virtuoso', async (importOriginal) => { + const actual = await importOriginal(); + const { wrapVirtuoso } = await import('./virtuosoProbe'); + return { ...actual, Virtuoso: wrapVirtuoso(actual.Virtuoso as never) }; +}); + +afterEach(unmountAll); + +const loadedCount = (mounted: { channel: { messagePaginator: { items?: unknown[] } } }) => + mounted.channel.messagePaginator.items?.length ?? 0; + +const clickJumpToLatest = async (frame: HTMLElement) => { + await waitUntil( + () => + !!frame.ownerDocument.querySelector( + '[data-testid="scroll-to-latest-message-button"]', + ), + 2000, + 'jump-to-latest button', + ); + frame.ownerDocument + .querySelector('[data-testid="scroll-to-latest-message-button"]') + ?.click(); +}; + +describe('VirtualizedMessageList in a real browser', () => { + it('B-01 opens at the true bottom', async () => { + await runScenario('B-01-initial-bottom', {}, ({ mounted }) => { + expectAtBottom(mounted.frame); + }); + }); + + it('B-01b opens at the true bottom when the last message is taller than the viewport', async () => { + await runScenario( + 'B-01b-initial-bottom-tall-last', + { heightFor: (index) => (index === 199 ? 900 : 60) }, + ({ mounted }) => { + expectAtBottom(mounted.frame); + }, + ); + }); + + it('B-02 opens centered on a focused message', async () => { + await runScenario( + 'B-02-initial-focus', + { + beforeRender: (channel) => channel.messagePaginator.jumpToMessage('m-0120'), + }, + ({ mounted }) => { + const geometry = readGeometry(mounted.frame); + const target = readRenderedItems(mounted.frame).find( + (item) => item.id === 'm-0120', + ); + expect(target, 'focused message rendered').toBeDefined(); + const center = (target?.top ?? 0) + (target?.height ?? 0) / 2; + expect(Math.abs(center - (geometry?.clientHeight ?? 0) / 2)).toBeLessThanOrEqual( + (target?.height ?? 0) / 2 + 2, + ); + }, + ); + }); + + it('B-03 keeps the reading position while older pages are prepended', async () => { + await runScenario('B-03-prepend', { pageSize: 25 }, async ({ mounted, step }) => { + for (let page = 1; page <= 3; page += 1) { + const before = loadedCount(mounted); + await scrollBy( + mounted.frame, + -(readGeometry(mounted.frame)?.scrollTop ?? 0) + 40, + ); + await settle(mounted.frame); + const anchorId = readVisibleItems(mounted.frame)[1]?.id; + const point = await step( + `prepend ${page}`, + async () => { + await scrollToTop(mounted.frame); + await waitUntil(() => loadedCount(mounted) > before, 4000, `page ${page}`); + }, + { anchorId }, + ); + // v2 paints the deviation and the scroll that cancels it in separate frames, which leaves + // the viewport empty for two frames; v4.18.13 applies both in the same paint. + // Soft: a failure must not cut the trace short, or the comparison sees missing steps. + expect + .soft(point.frames?.blankFrames, 'blank frames') + .toBeLessThanOrEqual(RUNTIME === 'browser-v2' ? 2 : 0); + expect + .soft(point.frames?.maxAnchorShift ?? 0, 'anchor shift') + .toBeLessThanOrEqual(2); + expect.soft(point.remounted, 'remounted items').toEqual([]); + } + }); + }); + + it('B-04 keeps the reading position while prepending under CPU load', async () => { + const throttled = await commands.setCpuThrottlingRate(6); + try { + await runScenario( + 'B-04-prepend-throttled', + { pageSize: 25 }, + async ({ mounted, step }) => { + for (let page = 1; page <= 2; page += 1) { + const before = loadedCount(mounted); + await scrollBy( + mounted.frame, + -(readGeometry(mounted.frame)?.scrollTop ?? 0) + 40, + ); + await settle(mounted.frame); + const anchorId = readVisibleItems(mounted.frame)[1]?.id; + const point = await step( + `prepend ${page}`, + async () => { + await scrollToTop(mounted.frame); + await waitUntil( + () => loadedCount(mounted) > before, + 8000, + `page ${page}`, + ); + }, + { anchorId, settle: { timeoutMs: 8000 } }, + ); + // Under load only the settled position is held to the bound; transient frames may move. + expect(point.firstVisible, 'first visible item').not.toBeNull(); + } + }, + ); + } finally { + if (throttled) await commands.setCpuThrottlingRate(1); + } + }); + + it('B-05 follows new messages only when it should', async () => { + await runScenario('B-05-follow-output', {}, async ({ mounted, step }) => { + await step('other user, at bottom', () => receiveMessage(mounted, mounted.other), { + sample: true, + }); + expectAtBottom(mounted.frame); + + await step('scroll up', () => scrollBy(mounted.frame, -800)); + const scrolledTop = readGeometry(mounted.frame)?.scrollTop ?? 0; + + await step('other user, scrolled up', () => receiveMessage(mounted, mounted.other)); + expect(readGeometry(mounted.frame)?.scrollTop).toBeCloseTo(scrolledTop, 0); + expect( + mounted.frame.ownerDocument.querySelector('[data-testid="message-notification"]'), + 'new message notification', + ).not.toBeNull(); + + await step('own message, scrolled up', () => receiveMessage(mounted, OWN_USER), { + sample: true, + }); + expectAtBottom(mounted.frame); + }); + }); + + it('B-06 ends at the bottom after a burst of messages with smooth scrolling', async () => { + await runScenario('B-06-burst', {}, async ({ mounted, step }) => { + await step( + 'burst of 20', + async () => { + for (let i = 0; i < 20; i += 1) { + await receiveMessage(mounted, mounted.other, 40 + (i % 4) * 30, { + awaitIngest: false, + }); + await wait(50); + } + // The paginator publishes the last ones after its throttle window: settle on all of them. + const lastId = mounted.history[mounted.history.length - 1].id; + await waitUntil( + () => + !!mounted.channel.messagePaginator.items?.some( + (item) => item.id === lastId, + ), + 3000, + 'the last message of the burst', + ); + }, + { + sample: true, + settle: { quietFrames: 20, timeoutMs: 6000 }, + timingDependent: true, + }, + ); + expectAtBottom(mounted.frame); + }); + }); + + it('B-07 stays at the bottom when the last message grows', async () => { + await runScenario('B-07-last-item-grows', {}, async ({ mounted, step }) => { + const lastId = mounted.history[mounted.history.length - 1].id; + await step('grow last by 300px', () => setMessageHeight(lastId, 400), { + sample: true, + }); + expectAtBottom(mounted.frame); + }); + }); + + it('B-08 jumps to an older window and back to the latest', async () => { + // A freshly remounted list can report "at bottom" before its jump scroll lands, and the list + // then pages back to the latest messages (`toHead`), undoing the jump. That is timing-dependent, + // so it is measured as a rate over fresh attempts rather than asserted once. + const attempts = 20; + let reverted = 0; + let returnedToBottom = 0; + for (let attempt = 0; attempt < attempts; attempt += 1) { + const mounted = await mountList({ seed: 100 + attempt }); + await settle(mounted.frame); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + await mounted.channel.messagePaginator.jumpToMessage('m-0060'); + await settle(mounted.frame); + await wait(300); + await settle(mounted.frame); + const landed = readRenderedItems(mounted.frame).some( + (item) => item.id === 'm-0060', + ); + if (!landed) reverted += 1; + if (landed) { + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + await clickJumpToLatest(mounted.frame); + await settle(mounted.frame); + const geometry = readGeometry(mounted.frame); + if ((geometry?.distanceFromBottom ?? Infinity) <= 1) returnedToBottom += 1; + } + mounted.unmount(); + } + await commands.writeVirtuosoTrace( + 'B-08-jump-and-back', + JSON.stringify({ + checkpoints: [], + consoleErrors: [], + framesUntilFirstItem: null, + // Lower is better for every metric: the comparison flags any increase. + metrics: { + jumpNotReturnedToBottom: attempts - reverted - returnedToBottom, + jumpReverted: reverted, + }, + runtime: RUNTIME, + scenario: 'B-08-jump-and-back', + windowErrors: [], + }), + ); + expect(returnedToBottom, 'jumps that returned to the bottom').toBe( + attempts - reverted, + ); + expect(reverted, 'jumps undone by paging to the latest').toBeLessThanOrEqual( + RUNTIME === 'browser-v2' ? attempts : 0, + ); + }, 240_000); + + it('B-09 shows the next channel promptly on a switch', async () => { + const first = await mountList({ seed: 1 }); + await settle(first.frame); + first.unmount(); + await runScenario('B-09-channel-switch', { seed: 2 }, ({ mounted }) => { + expect(mounted.framesUntilFirstItem, 'frames until the first item').not.toBeNull(); + expectAtBottom(mounted.frame); + }); + }); + + it('B-10 marks a short channel read at its true bottom', async () => { + await runScenario( + 'B-10-short-list-mark-read', + { heightFor: () => 60, historySize: 3 }, + async ({ mounted, step }) => { + await step('wait for mark read', () => wait(300)); + const reads = mounted.backend.requests.filter((request) => + request.path.endsWith('/read'), + ); + expect(reads.length, 'mark-read requests').toBeLessThanOrEqual(1); + }, + ); + }); + + it('B-11 floats the date of the messages scrolled past', async () => { + await runScenario( + 'B-11-floating-date', + { gapMinutes: 180, listProps: { withDateSeparator: true } }, + async ({ mounted, step }) => { + await step('scroll up', () => scrollBy(mounted.frame, -700)); + await scrollBy(mounted.frame, -50); + const floating = mounted.frame.ownerDocument.querySelector( + '.str-chat__date-separator--floating', + ); + mounted.frame.setAttribute('data-floating-date', floating?.textContent ?? ''); + await step('record floating date', () => nextFrame(), { skipInvariants: true }); + }, + ); + }); + + it('B-12 treats the first loaded message like any other at the top of the list', async () => { + // A fully loaded channel read up to its first message. At the top, the first message is on + // screen, so the reader is not "below the unread separator" and the unread notification stays + // hidden. If the first item went missing from `itemsRendered`, every rendered message would be + // unread and the notification would show. + await runScenario( + 'B-12-first-item-at-top', + { heightFor: () => 60, historySize: 30, pageSize: 50 }, + async ({ mounted, step }) => { + const [first, second] = mounted.history; + await step('set the unread state', () => { + mounted.channel.messagePaginator.setUnreadSnapshot({ + firstUnreadMessageId: second.id, + lastReadAt: first.created_at, + lastReadMessageId: first.id, + unreadCount: 29, + }); + }); + await step('scroll to the top', async () => { + await scrollToTop(mounted.frame); + await wait(400); + }); + expect( + readRenderedItems(mounted.frame)[0]?.id, + 'first message rendered at the top', + ).toBe(first.id); + expect( + mounted.frame.ownerDocument.querySelector( + '.str-chat__unread-messages-notification', + ), + 'unread notification hidden while the first message is on screen', + ).toBeNull(); + }, + ); + }); + + it('B-13 measures and releases a custom scroll parent', async () => { + const resources = trackResources(); + try { + const ScrollParent = ({ + list, + }: { + list: (parent: HTMLElement) => React.ReactElement; + }) => { + const [parent, setParent] = useState(null); + return ( +
+ {parent && list(parent)} +
+ ); + }; + const baseline = resources.counts(); + const mounted = await mountList({ + measureMount: false, + wrap: () => ( + ( + + )} + /> + ), + }); + await settle(mounted.frame); + mounted.unmount(); + await nextFrame(); + expect(resources.counts(), JSON.stringify(resources.pending(), null, 1)).toEqual( + baseline, + ); + } finally { + resources.restore(); + } + }); + + it('B-14 lands exactly at the bottom with fractional item heights', async () => { + await runScenario( + 'B-14-fractional-heights', + { heightFor: (index) => 40 + ((index * 7.37) % 50) }, + async ({ mounted, step }) => { + for (let round = 1; round <= 5; round += 1) { + await step(`scroll up ${round}`, () => scrollBy(mounted.frame, -1500)); + await step(`jump to latest ${round}`, async () => { + await clickJumpToLatest(mounted.frame); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + }); + expectAtBottom(mounted.frame); + } + }, + ); + }); + + it('B-18 mounts cleanly in StrictMode', async () => { + await runScenario('B-18-strict-mode', { strictMode: true }, ({ mounted }) => { + expectAtBottom(mounted.frame); + }); + }); + + it('B-20 renders no more than needed while scrolling and receiving', async () => { + const result = await runScenario( + 'B-20-render-cost', + { historySize: 500, pageSize: 100 }, + async ({ mounted, step }) => { + for (let i = 1; i <= 15; i += 1) { + await step(`scroll up ${i}`, () => scrollBy(mounted.frame, -400)); + } + await step('jump to latest', async () => { + await clickJumpToLatest(mounted.frame); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + }); + await step('one arrival at bottom', () => receiveMessage(mounted, mounted.other)); + }, + ); + expect(result.trace.checkpoints.length).toBeGreaterThan(0); + }); + + it('B-21 does not paginate while mounting', async () => { + await runScenario( + 'B-21-no-pagination-on-mount', + {}, + async ({ checkpoint, mounted }) => { + await wait(500); + const point = checkpoint('after 500ms'); + expect(mounted.paginatorCalls, 'paginator calls since mount').not.toContain( + 'toTail', + ); + expect(point.requests.filter((request) => request.messages?.id_lt)).toEqual([]); + }, + ); + }); + + it('B-22 stays at the bottom while the last message streams in', async () => { + await runScenario('B-22-streaming-growth', {}, async ({ mounted, step }) => { + const id = await receiveMessage(mounted, mounted.other, 40); + await settle(mounted.frame); + await step( + 'stream 50 chunks', + async () => { + for (let chunk = 1; chunk <= 50; chunk += 1) { + setMessageHeight(id, 40 + chunk * 12); + await wait(30); + } + }, + { sample: true, timingDependent: true }, + ); + expectAtBottom(mounted.frame); + }); + }); + + describe('B-23 never stays hidden', () => { + const cases: [string, Parameters[0]][] = [ + ['one message', { historySize: 1 }], + ['shorter than the viewport', { heightFor: () => 50, historySize: 4 }], + ['zero-height last item', { heightFor: (index) => (index === 199 ? 0 : 60) }], + [ + 'focus on a message not loaded', + { + beforeRender: (channel) => + channel.messagePaginator + .jumpToMessage('missing-message') + .catch(() => undefined), + }, + ], + ]; + it.each(cases)('%s', async (label, options) => { + await runScenario( + `B-23-visible-${label.replace(/\W+/g, '-')}`, + options ?? {}, + ({ mounted }) => { + expect(isListVisible(mounted.frame), 'list visible').toBe(true); + }, + ); + }); + + it('empty, then a first message', async () => { + await runScenario( + 'B-23-visible-empty-then-first', + { historySize: 0, measureMount: false }, + async ({ mounted, step }) => { + await step('first message', () => receiveMessage(mounted, mounted.other)); + expect(isListVisible(mounted.frame), 'list visible').toBe(true); + expect(readVisibleItems(mounted.frame).length).toBeGreaterThan(0); + }, + ); + }); + }); + + it('B-24 handles a message arriving during the first frames', async () => { + const mounted = await mountList({ measureMount: false }); + const trace = createTrace('B-24-message-during-mount', mounted); + await nextFrame(); + const id = await receiveMessage(mounted, mounted.other); + await settle(mounted.frame); + trace.checkpoint('after an early message'); + await trace.save(); + expect(readRenderedItems(mounted.frame).some((item) => item.id === id)).toBe(true); + expectAtBottom(mounted.frame); + }); + + it('B-26 records what a scroll right after opening or jumping does', async () => { + // Characterization only: whether the list keeps the user's scroll or returns to the target is + // compared across runtimes rather than asserted. + await runScenario( + 'B-26-early-scroll', + {}, + async ({ mounted, step }) => { + await step( + 'scroll up 1500 right after mount', + () => scrollBy(mounted.frame, -1500), + { + skipInvariants: true, + }, + ); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + await step('scroll up 1500 at rest', () => scrollBy(mounted.frame, -1500)); + await step( + 'jump to latest, then scroll up at once', + async () => { + await clickJumpToLatest(mounted.frame); + await nextFrame(); + await scrollBy(mounted.frame, -1500); + }, + { skipInvariants: true }, + ); + }, + { quietAfterMountMs: 0 }, + ); + }); + + it('B-27 clears the focus signal once the jump target is viewed, and stops re-centering on it', async () => { + // `MessagePaginator` leaves a jump's highlight countdown to the list. VML starts it once the + // jumped-to message has been viewed and stops scrolling back to it then, so a reader who scrolls + // away is not pulled back when a message arrives (before the fix the signal lived until the + // next jump, and every change of the list re-centered on the target). The target is in the + // latest page, so arriving messages join the rendered list, which is what re-centered it. + await runScenario( + 'B-27-focus-signal-recenter', + { pageSize: 40 }, + async ({ mounted, step }) => { + const focusSignal = () => + mounted.channel.messagePaginator.messageFocusSignal.getLatestValue().signal; + const firstVisibleId = () => readVisibleItems(mounted.frame)[0]?.id; + + await step('jump to m-0170', () => + mounted.channel.messagePaginator.jumpToMessage('m-0170'), + ); + expect( + readVisibleItems(mounted.frame).some((item) => item.id === 'm-0170'), + 'jump target in view', + ).toBe(true); + expect(focusSignal()?.messageId, 'focus signal lives while counting down').toBe( + 'm-0170', + ); + + // Past the window in which Virtuoso re-applies its scroll target, still within the focus + // signal's countdown (3s from when the target was viewed). + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + // Sampled: on v4 the messages revealed at the top measure taller than estimated, and for one + // pass the jumped-to message and the two after it leave the rendered range (and remount); + // no frame may show the viewport uncovered meanwhile. + const scrolled = await step( + 'scroll up within the focus window', + () => scrollBy(mounted.frame, -300), + { sample: true }, + ); + // Soft: a failure must not cut the trace short, or the comparison sees missing steps. + expect.soft(scrolled.frames?.blankFrames, 'blank frames').toBe(0); + const readingAt = firstVisibleId(); + await step('message arrives within the focus window', () => + receiveMessage(mounted, mounted.other), + ); + expect(firstVisibleId(), 'not pulled back to the viewed target').toBe(readingAt); + + await step('focus signal clears', () => + waitUntil(() => !focusSignal(), 6000, 'focus signal to clear'), + ); + await step('another message arrives', () => + receiveMessage(mounted, mounted.other), + ); + expect(firstVisibleId(), 'still where the reader scrolled to').toBe(readingAt); + }, + ); + }); + + it('B-28 does not move on its own with suppressAutoscroll', async () => { + // react-virtuoso 4 scrolls to the bottom when an item grows unless `followOutput` is `false`, + // without asking the function, and then re-applies that scroll for ~1s, undoing the reader's. + await runScenario( + 'B-28-suppressed-autoscroll', + { listProps: { suppressAutoscroll: true } }, + async ({ mounted, step }) => { + await step('scroll up a little', () => scrollBy(mounted.frame, -40)); + const before = readGeometry(mounted.frame)?.scrollTop; + await step('a tall message arrives', () => + receiveMessage(mounted, mounted.other, 300), + ); + expect(readGeometry(mounted.frame)?.scrollTop, 'list did not follow').toBeCloseTo( + before ?? 0, + 0, + ); + const loaded = loadedCount(mounted); + await step('scroll to the top right after', async () => { + await scrollToTop(mounted.frame); + await waitUntil(() => loadedCount(mounted) > loaded, 4000, 'older page'); + }); + expect( + readGeometry(mounted.frame)?.scrollTop, + 'not taken back to the bottom', + ).toBeLessThan((readGeometry(mounted.frame)?.scrollHeight ?? 0) / 2); + }, + ); + }); + + it.each([360, 600])( + 'B-29 keeps the reading position when a message arrives with suppressAutoscroll (%ipx)', + async (viewportHeight) => { + await runScenario( + `B-29-suppressed-arrival-${viewportHeight}`, + { listProps: { suppressAutoscroll: true }, viewportHeight }, + async ({ mounted, step }) => { + const before = readVisibleItems(mounted.frame)[0]; + await step('another user sends twice', async () => { + await receiveMessage(mounted, mounted.other, 80); + await receiveMessage(mounted, mounted.other, 80); + }); + const after = readRenderedItems(mounted.frame).find( + (item) => item.id === before.id, + ); + mounted.frame.setAttribute( + 'data-shift', + String(Math.round((after?.top ?? 0) - before.top)), + ); + expect( + Math.abs((after?.top ?? 0) - before.top), + 'first visible message moved', + ).toBeLessThanOrEqual(2); + }, + ); + }, + ); + + it('B-29b keeps the reading position when suppressAutoscroll is switched on, then messages arrive', async () => { + await runScenario( + 'B-29b-suppressed-later', + { viewportHeight: 360 }, + async ({ mounted, step }) => { + await step('switch suppressAutoscroll on', () => { + mounted.rerender({ props: { suppressAutoscroll: true } }); + }); + const before = readVisibleItems(mounted.frame)[0]; + await step('another user sends twice', async () => { + await receiveMessage(mounted, mounted.other, 80); + await receiveMessage(mounted, mounted.other, 80); + }); + const after = readRenderedItems(mounted.frame).find( + (item) => item.id === before.id, + ); + expect( + Math.abs((after?.top ?? 0) - before.top), + 'first visible message moved', + ).toBeLessThanOrEqual(2); + }, + ); + }); + + it('B-30 keeps the DOM nodes of the messages after one deleted in the middle', async () => { + // Keys come from message IDs (computeItemKey): removing a message must not remount the ones + // after it, as position-based keys would. + // With hideDeletedMessages the row disappears, so every message after it changes position. + await runScenario( + 'B-30-delete-in-the-middle', + { listProps: { hideDeletedMessages: true } }, + async ({ mounted, step }) => { + const visible = readVisibleItems(mounted.frame); + const target = visible[Math.floor(visible.length / 2)]; + const message = mounted.channel.messagePaginator.items?.find( + (item) => item.id === target.id, + ); + const point = await step('delete a visible message', () => + mounted.client.dispatchEvent({ + channel_id: mounted.channel.id, + channel_type: mounted.channel.type, + cid: mounted.channel.cid, + message: { + ...message, + deleted_at: message?.updated_at, + type: 'deleted', + } as never, + type: 'message.deleted', + } as never), + ); + expect(point.remounted, 'messages remounted').toEqual([]); + }, + ); + }); + + it('B-31 jumps to a message just above the loaded page, whose window overlaps it', async () => { + // The "N unread" pill: the first unread message sits just above the loaded page (m-0150 to + // m-0199), so the page around it (m-0115 to m-0164) overlaps it and the paginator shows the two + // merged. To the list that looks like 35 prepended messages, but it is a jump: on + // react-virtuoso 4 the scroll to the target was dropped while it compensated for the prepend, + // and when the newest messages fell off the end instead, it asked for items past the end of + // the list (a crash). + await runScenario('B-31-jump-overlapping-window', {}, async ({ mounted, step }) => { + const errors: string[] = []; + const onError = (event: ErrorEvent) => errors.push(event.message); + window.addEventListener('error', onError); + try { + await step( + 'jump to the message above the page', + () => mounted.channel.messagePaginator.jumpToMessage('m-0140'), + { sample: true }, + ); + } finally { + window.removeEventListener('error', onError); + } + expect(errors, 'uncaught errors').toEqual([]); + expect(isListVisible(mounted.frame), 'list visible').toBe(true); + // v2 can lose the jump to its remount race (see B-08): recorded for the comparison only. + if (RUNTIME !== 'browser-v2') { + const visible = readVisibleItems(mounted.frame).map((item) => item.id); + expect(visible, 'the jumped-to message is in view').toContain('m-0140'); + } + }); + }); + + it('B-32 loads the next newer page with one scroll to the end of an older window', async () => { + // The messages revealed near the end measure other than estimated, and react-virtuoso 4 + // re-measures them after the scroll: kept at the end through that, the list reports it and loads + // the next newer page; left short of it, it loads nothing and the reader must scroll again. + await runScenario('B-32-older-window-end', {}, async ({ mounted, step }) => { + await step('jump to an older message', () => + mounted.channel.messagePaginator.jumpToMessage('m-0060'), + ); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + const point = await step('scroll to the end', () => scrollToBottom(mounted.frame), { + sample: true, + }); + const loadedNewer = point.requests.some( + (request) => !!(request as { messages?: { id_gt?: string } }).messages?.id_gt, + ); + if (RUNTIME !== 'browser-v2') { + expect(loadedNewer, 'the next newer page requested').toBe(true); + } + }); + }); + + it("B-33 does not follow new messages an integrator's followOutput callback declines", async () => { + // Virtuoso applies the integrator's `followOutput`; the SDK's own growth correction must not + // pin the list to the new bottom behind its back. + await runScenario( + 'B-33-integrator-follow-output', + { listProps: { additionalVirtuosoProps: { followOutput: () => false } } }, + async ({ mounted, step }) => { + const scrollTop = readGeometry(mounted.frame)?.scrollTop ?? 0; + await step( + 'other user, at bottom', + () => receiveMessage(mounted, mounted.other, 300), + // The list stays put by design, short of its new bottom. + { skipInvariants: true }, + ); + expect(readGeometry(mounted.frame)?.scrollTop, 'scroll position').toBeCloseTo( + scrollTop, + 0, + ); + }, + ); + }); + + it('B-34 does not paginate while positioning a custom list that renders no test IDs', async () => { + // The guard against paging while Virtuoso positions the hidden list must not depend on the + // markup of Virtuoso's own list: an integrator's `components.List` may drop its test ID. + const BareList = forwardRef(function BareList( + { children, style }, + ref, + ) { + return ( +
+ {children} +
+ ); + }); + await runScenario( + 'B-34-custom-list-positioning', + { listProps: { additionalVirtuosoProps: { components: { List: BareList } } } }, + async ({ checkpoint, mounted, step }) => { + expect( + mounted.frame.querySelector('[data-testid="virtuoso-item-list"]'), + 'no test ID on the list', + ).toBeNull(); + await wait(500); + const mountedPoint = checkpoint('after 500ms'); + expect( + mountedPoint.requests.filter((request) => request.messages?.id_lt), + ).toEqual([]); + const jump = await step('jump to an older message', () => + mounted.channel.messagePaginator.jumpToMessage('m-0060'), + ); + // v2 can lose a jump to its remount race (see B-08): recorded for the comparison only. + if (RUNTIME !== 'browser-v2') { + expect( + jump.requests.filter( + (request) => request.messages?.id_gt || request.messages?.id_lt, + ), + 'pages loaded while the jump was positioned', + ).toEqual([]); + const visible = readVisibleItems(mounted.frame).map((item) => item.id); + expect(visible, 'the jumped-to message is in view').toContain('m-0060'); + } + }, + ); + }); + + it('B-35 renders MessageListPositioningUI while the list is hidden to be positioned', async () => { + // Frame by frame from mount until the list shows: the slot must say the list is positioning on + // every frame it is hidden (react-virtuoso 4 positioning it), and stop once it shows. + const MARKER = 'positioning-marker'; + const CustomPositioningUI = ({ isPositioning }: MessageListPositioningUIProps) => ( +
+ ); + const watchMount = async (componentOverrides?: Partial) => { + const mounted = await mountList({ componentOverrides, measureMount: false }); + const counts = { + customFalseAfter: false, + customTrue: 0, + hidden: 0, + hiddenWithIndicator: 0, + shownWithIndicator: 0, + }; + const read = () => ({ + busy: mounted.frame + .querySelector('.str-chat__virtual-list') + ?.getAttribute('aria-busy'), + custom: mounted.frame + .querySelector(`[data-testid="${MARKER}"]`) + ?.getAttribute('data-is-positioning'), + indicator: !!mounted.frame.querySelector('.str-chat__virtual-list__positioning'), + }); + for (let frames = 0; frames < 240; frames += 1) { + const state = read(); + if (!isListVisible(mounted.frame)) { + counts.hidden += 1; + if (state.indicator && state.busy === 'true') counts.hiddenWithIndicator += 1; + if (state.custom === 'true') counts.customTrue += 1; + } else if (readVisibleItems(mounted.frame).length) { + await settle(mounted.frame); + const after = read(); + if (state.indicator || after.indicator) counts.shownWithIndicator += 1; + counts.customFalseAfter = after.custom === 'false'; + break; + } + await nextFrame(); + } + mounted.unmount(); + return counts; + }; + + const byDefault = await watchMount(); + const off = await watchMount({ MessageListPositioningUI: null }); + const custom = await watchMount({ MessageListPositioningUI: CustomPositioningUI }); + if (RUNTIME !== 'browser-v2') { + expect(byDefault.hidden, 'frames hidden while positioned').toBeGreaterThan(0); + } + // The list reports itself hidden from its first commit, and the slot learns it in the next one: + // the first frame after mount may still be without it. + expect( + byDefault.hiddenWithIndicator, + 'hidden frames with the indicator', + ).toBeGreaterThanOrEqual(byDefault.hidden - 1); + expect(byDefault.shownWithIndicator, 'indicator after the list shows').toBe(0); + expect( + off.hiddenWithIndicator + off.shownWithIndicator, + 'indicator when set to null', + ).toBe(0); + expect( + custom.customTrue, + 'custom slot told it is positioning', + ).toBeGreaterThanOrEqual(custom.hidden - 1); + expect(custom.customFalseAfter, 'custom slot told it is no longer positioning').toBe( + true, + ); + expect(custom.hiddenWithIndicator, 'default indicator with a custom slot').toBe(0); + }); + + it('B-25 releases everything after repeated mounting', async () => { + const resources = trackResources(); + try { + const baseline = resources.counts(); + for (let cycle = 0; cycle < 20; cycle += 1) { + const mounted = await mountList({ measureMount: false, seed: 10 + cycle }); + await settle(mounted.frame); + mounted.unmount(); + } + await nextFrame(); + expect(resources.counts(), JSON.stringify(resources.pending(), null, 1)).toEqual( + baseline, + ); + } finally { + resources.restore(); + } + }); +}); diff --git a/src/components/MessageList/__tests__/browser/expected-differences.json b/src/components/MessageList/__tests__/browser/expected-differences.json new file mode 100644 index 0000000000..498f7ced24 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/expected-differences.json @@ -0,0 +1,80 @@ +{ + "$comment": "Differences between the react-virtuoso 2 and 4 traces that are understood. Each names what differs and why; scenario, checkpoint and field are anchored regular expressions. Read by scripts/compare-virtuoso-traces.mts; an entry that matches nothing is reported as stale.", + "differences": [ + { + "scenario": "[BF]-.*", + "field": "framesUntilFirstItem", + "reason": "v4 hides a freshly mounted list until it reaches initialTopMostItemIndex: about 25 frames to the first visible item against v2's 1-2, where v2 shows the list at once and moves it into place over its first ~6 frames. Kept as is (decision for the upgrade), documented in ai-docs/ai-migration-v14-v15.md.", + "upstream": "react-virtuoso 4.7.4" + }, + { + "scenario": "B-20-render-cost", + "checkpoint": "scroll up \\d+", + "field": "itemsRendered|rendered|firstVisible|remounted", + "reason": "Scrolling up into messages not rendered yet, v2 jumps by the difference between their estimated and real heights (5-7 messages further per 400px here); v4 compensates and moves by the scrolled distance. The scroll invariant (content moves by exactly the scrolled distance) holds on v4 and fails on v2 in the fuzz runs.", + "upstream": "react-virtuoso 4.3.6, 4.12.7" + }, + { + "scenario": "B-26-early-scroll", + "field": ".*", + "reason": "v2 re-applies its initial scroll target for ~1.2s and undoes a scroll made meanwhile; v4 keeps the reader's scroll, so the next scroll reaches the top and loads an older page." + }, + { + "scenario": "B-27-focus-signal-recenter", + "field": "remounted|totals\\.messageRenders", + "reason": "Both runtimes show the same messages at every step and keep the reader where they scrolled. On the first scroll after the jump the messages revealed at the top measure taller than v4 estimated, so for one pass its rendered range ends at m-0169 and the jumped-to message and the two after it (m-0170 to m-0172) leave it and remount; v4 renders messages more often around the jump for the same reason (more re-measuring passes). Every sampled frame of that scroll keeps the viewport covered on v4 (v2 shows one partly uncovered frame)." + }, + { + "scenario": "B-23-visible-zero-height-last-item", + "checkpoint": "mounted", + "field": "geometry.atBottom|firstVisible", + "reason": "With a zero-height last item, v2 opens 8px short of the bottom; v4 opens at the bottom." + }, + { + "scenario": "B-16-files-sticky-groups", + "field": "dom.firstItem", + "reason": "v4 marks GroupedVirtuoso group wrappers with data-index / data-item-index as it does items (v2 left them unmarked), so the first such element is now a month header. No SDK selector relies on it for grouped lists.", + "upstream": "react-virtuoso 4.x" + }, + { + "scenario": "B-24-message-during-mount", + "field": "totals\\.commits", + "reason": "This scenario skips the mount measurement, so its one checkpoint spans the mount, where v4 commits a few more times while it positions the hidden list. Message renders fall (19 to 9) at the same time." + }, + { + "scenario": "B-28-suppressed-autoscroll", + "field": "totals\\.messageRenders", + "reason": "While it applies a prepend, v4 renders the items around the reader once more (before and after the same-paint scroll compensation): +7 message renders for the one older page this scenario loads, with the same final position and items. Across all scripted scenarios v4 renders fewer messages than v2.", + "upstream": "react-virtuoso 4.12.7, 4.18.13" + }, + { + "scenario": "B-12-first-item-at-top", + "field": ".*", + "reason": "v2 sometimes opens this 30-message channel at its top instead of its end (initialTopMostItemIndex `align: 'end'` loses a race with v2's initial scroll; it varies between runs); v4 opens it at the bottom, so every later step starts from a different place." + }, + { + "scenario": "F-1024", + "checkpoint": "7 scroll by", + "field": "requests", + "reason": "Scrolling up to the top of the window: in some runs v2 stops about 175px short of the top (scrolling into messages not measured yet, as in B-20) and loads no older page; v4 reaches the top and loads it. Varies between runs, also without the focus-signal fix (1 in 3), so the entry is stale in runs where the two agree." + }, + { + "scenario": "B-31-jump-overlapping-window", + "checkpoint": "jump to the message above the page", + "field": "state\\.atBottomStateChange|itemsRendered|geometry\\.atBottom|rendered|firstVisible|remounted|frames\\.framesUntilVisible|frames\\.finalDistanceFromBottom", + "reason": "The jump remounts the list (a page overlapping the loaded one). v2 loses it to its remount race (see B-08): the remounted list reports itself at the bottom, loads the next newer page and stays at the latest messages. v4 keeps the list hidden while it positions it (19 frames here) and opens it on the jumped-to message, with no blank frame (v2 shows one)." + }, + { + "scenario": "F-.*", + "checkpoint": "\\d+ jump to a message", + "field": "requests|itemsRendered|rendered|firstVisible|state\\.atBottomStateChange|geometry\\.atBottom|events", + "reason": "In some runs v2 loses a jump to its remount race (see B-08, B-31): the remounted list reports itself at the bottom and loads the next newer page, ending elsewhere. v4 must land on the target (the fuzz step waits until it was viewed) and, when it loaded the page around the target, no other page: the fuzz test fails a v4 jump step that does, so this entry cannot hide such a v4 request. Varies between runs, so the entry is stale in runs where v2 keeps its jumps." + }, + { + "scenario": "F-1023", + "checkpoint": "16 jump to latest", + "field": "itemsRendered", + "reason": "Both runtimes end at the bottom with the same messages rendered (live-291 to live-293). v4's last itemsRendered report comes while it still positions the remounted list and lists only the last message; v2 reports all three." + } + ] +} diff --git a/src/components/MessageList/__tests__/browser/fakeBackend.ts b/src/components/MessageList/__tests__/browser/fakeBackend.ts new file mode 100644 index 0000000000..1ff5e33a17 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/fakeBackend.ts @@ -0,0 +1,175 @@ +import type { LocalMessage, StreamChat, UserResponse } from 'stream-chat'; + +import { + generateChannel, + generateMember, + generateMessage, +} from '../../../../mock-builders'; + +type ChannelAPIResponse = ReturnType; +import type { Rng } from './prng'; + +/** One request the client made, reduced to what a trace compares. */ +export type RequestRecord = { + method: string; + /** The path without host or query string, with the channel ID replaced by `:id`. */ + path: string; + /** The `messages` pagination params of a channel query. */ + messages?: Record; +}; + +export type FakeBackend = { + channelResponse: ChannelAPIResponse; + /** Every message the server holds, oldest first. */ + history: LocalMessage[]; + requests: RequestRecord[]; + /** Holds every channel query until the returned function is called. */ + holdQueries: () => () => void; +}; + +const BASE_TIME = Date.UTC(2026, 0, 5, 9, 0, 0); + +export type MessageSpec = { + /** Gap to the previous message, in minutes. */ + gapMinutes?: number; + user: UserResponse; +}; + +/** Messages `m-0000`, `m-0001`, … from `users`, one every `gapMinutes` (default 1) minutes. */ +export const buildHistory = ({ + count, + gapMinutes = 1, + rng, + users, +}: { + count: number; + gapMinutes?: number; + rng: Rng; + users: UserResponse[]; +}) => { + const history: LocalMessage[] = []; + for (let i = 0; i < count; i += 1) { + history.push( + generateMessage({ + id: `m-${String(i).padStart(4, '0')}`, + text: `message ${i}`, + timestamp: new Date(BASE_TIME + i * gapMinutes * 60_000), + user: rng.pick(users), + }), + ); + } + return history; +}; + +const sliceForQuery = (history: LocalMessage[], params: Record = {}) => { + const limit = typeof params.limit === 'number' ? params.limit : 100; + const indexOf = (id: unknown) => history.findIndex((message) => message.id === id); + if (params.id_lt) { + const index = indexOf(params.id_lt); + return history.slice(Math.max(0, index - limit), index); + } + if (params.id_gt) { + const index = indexOf(params.id_gt); + return history.slice(index + 1, index + 1 + limit); + } + if (params.id_around) { + const index = indexOf(params.id_around); + const start = Math.max( + 0, + Math.min(history.length - limit, index - Math.floor(limit / 2)), + ); + return history.slice(start, start + limit); + } + return history.slice(Math.max(0, history.length - limit)); +}; + +/** + * Answers the client's requests from an in-memory history: a channel query gets the page its + * `messages` params select, every other request an empty success. Installed on + * `client.axiosInstance.request`, the one funnel every `stream-chat` request goes through. + */ +export const installFakeBackend = ({ + channelId, + client, + history, + users, +}: { + channelId: string; + client: StreamChat; + history: LocalMessage[]; + users: UserResponse[]; +}): FakeBackend => { + const channelResponse = generateChannel({ + channel: { id: channelId, type: 'messaging' }, + members: users.map((user) => generateMember({ user })), + messages: [], + }); + const requests: RequestRecord[] = []; + let hold: Promise | null = null; + + const backend: FakeBackend = { + channelResponse, + history, + holdQueries: () => { + let release = () => undefined as void; + hold = new Promise((resolve) => { + release = resolve; + }); + return () => { + hold = null; + release(); + }; + }, + requests, + }; + + (vi.spyOn(client.axiosInstance as any, 'request') as any).mockImplementation( + (async (config: { data?: unknown; method?: string; url?: string }) => { + const method = String(config.method ?? 'get').toLowerCase(); + const url = new URL(String(config.url), 'http://localhost'); + const path = url.pathname.replace(channelId, ':id'); + const body = + typeof config.data === 'string' ? JSON.parse(config.data) : (config.data ?? {}); + const isChannelQuery = /\/channels\/messaging\/:id\/query$/.test(path); + requests.push({ + method, + path, + ...(isChannelQuery && { messages: body.messages ?? {} }), + }); + + let data: unknown = { duration: '0.01ms' }; + // A send echoes the message back the way the server confirms it. + if (method === 'post' && /\/channels\/messaging\/:id\/message$/.test(path)) { + const last = backend.history[backend.history.length - 1]; + const createdAt = Number(last?.created_at ?? 0) + 60_000 * 1e6; + const sent = { + ...body.message, + cid: channelResponse.channel.cid, + created_at: createdAt, + status: 'received', + type: 'regular', + updated_at: createdAt, + user: client.user, + }; + backend.history.push(sent as LocalMessage); + data = { duration: '0.01ms', message: sent }; + } + if (isChannelQuery) { + if (hold) await hold; + const cid = channelResponse.channel.cid; + data = { + ...channelResponse, + duration: '0.01ms', + messages: sliceForQuery(backend.history, body.messages).map((message) => ({ + ...message, + cid, + })), + read: [], + }; + } + return { config, data, headers: {}, request: {}, status: 200, statusText: '' }; + }) as never, + ); + + return backend; +}; diff --git a/src/components/MessageList/__tests__/browser/fuzzOperations.ts b/src/components/MessageList/__tests__/browser/fuzzOperations.ts new file mode 100644 index 0000000000..8663743527 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/fuzzOperations.ts @@ -0,0 +1,204 @@ +import { + OWN_USER, + readRenderedItems, + receiveMessage, + scrollBy, + scrollToBottom, + scrollToTop, + setMessageHeight, + wait, + waitUntil, +} from './harness'; +import type { Mounted } from './harness'; +import type { Rng } from './prng'; +import { SCROLL_TARGET_RETRY_WINDOW_MS } from './scenario'; +import { RUNTIME } from './trace'; + +/** The operations the fuzzer draws from, weighted. Shared with replays of a single seed. */ +export type Operation = { + name: string; + run: (mounted: Mounted, rng: Rng, state: FuzzState) => Promise | string; + weight: number; +}; + +export type FuzzState = { suppressAutoscroll: boolean; viewportHeight: number }; + +const renderedMessageIds = (mounted: Mounted) => + readRenderedItems(mounted.frame) + .map((item) => item.id) + .filter((id) => id.startsWith('m-') || id.startsWith('live-')); + +const dispatch = (mounted: Mounted, type: string, message: unknown) => + mounted.client.dispatchEvent({ + channel_id: mounted.channel.id, + channel_type: mounted.channel.type, + cid: mounted.channel.cid, + message: message as never, + type, + } as never); + +const findLoaded = (mounted: Mounted, id: string) => + mounted.channel.messagePaginator.items?.find((item) => item.id === id); + +export const OPERATIONS: Operation[] = [ + { + name: 'append from other', + run: async (mounted, rng) => { + const count = rng.int(1, 3); + for (let i = 0; i < count; i += 1) { + await receiveMessage(mounted, mounted.other, rng.pick([40, 64, 120, 300])); + } + return `${count}`; + }, + weight: 4, + }, + { + name: 'append own', + run: async (mounted, rng) => { + await receiveMessage(mounted, OWN_USER, rng.pick([40, 64, 120])); + return ''; + }, + weight: 2, + }, + { + name: 'scroll to top (load older)', + run: async (mounted) => { + await scrollToTop(mounted.frame); + await wait(400); + return ''; + }, + weight: 2, + }, + { + name: 'scroll by', + run: async (mounted, rng) => { + const delta = rng.int(-1200, 1200); + await scrollBy(mounted.frame, delta); + return `${delta}`; + }, + weight: 5, + }, + { + name: 'scroll to bottom', + run: async (mounted) => { + // Stays at the bottom with `suppressAutoscroll` too: no new messages arrive in this step. + await scrollToBottom(mounted.frame); + return ''; + }, + weight: 2, + }, + { + name: 'grow or shrink a rendered message', + run: (mounted, rng) => { + const ids = renderedMessageIds(mounted); + if (!ids.length) return 'none rendered'; + const id = rng.pick(ids); + const height = rng.pick([20, 48, 160, 420]); + setMessageHeight(id, height); + return `${id}→${height}`; + }, + weight: 3, + }, + { + name: 'edit a rendered message', + run: (mounted, rng) => { + const ids = renderedMessageIds(mounted); + const message = ids.length ? findLoaded(mounted, rng.pick(ids)) : undefined; + if (!message) return 'none rendered'; + dispatch(mounted, 'message.updated', { + ...message, + text: `${message.text} (edited)`, + }); + return message.id; + }, + weight: 1, + }, + { + name: 'delete a rendered message', + run: (mounted, rng) => { + const ids = renderedMessageIds(mounted); + const message = ids.length ? findLoaded(mounted, rng.pick(ids)) : undefined; + if (!message) return 'none rendered'; + dispatch(mounted, 'message.deleted', { + ...message, + deleted_at: message.updated_at, + type: 'deleted', + }); + return message.id; + }, + weight: 1, + }, + { + name: 'jump to a message', + run: async (mounted, rng) => { + const target = rng.pick(mounted.history.slice(0, mounted.history.length - 10)); + await mounted.channel.messagePaginator.jumpToMessage(target.id); + // VML clears the jump's focus signal (and its highlight) once the target was viewed; waiting + // for that keeps later steps' renders the same across runtimes and fails a list that never + // clears it. Then past the window in which the scroll target is re-applied. + const signalCleared = waitUntil( + () => + !mounted.channel.messagePaginator.messageFocusSignal.getLatestValue().signal, + 6000, + 'focus signal to clear', + ); + // v2 can lose a jump to its remount race (see B-08), and the target is then never viewed: + // recorded for the comparison, not failed on. + if (RUNTIME === 'browser-v2') { + const cleared = await signalCleared.then( + () => true, + () => false, + ); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + return cleared ? target.id : `${target.id} (lost)`; + } + await signalCleared; + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + return target.id; + }, + weight: 1, + }, + { + name: 'jump to latest', + run: async (mounted) => { + const button = mounted.frame.ownerDocument.querySelector( + '[data-testid="scroll-to-latest-message-button"]', + ); + if (!button) return 'no button'; + button.click(); + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + return ''; + }, + weight: 1, + }, + { + name: 'resize viewport', + run: async (mounted, rng, state) => { + state.viewportHeight = rng.pick([360, 480, 600, 820]); + mounted.rerender({ height: state.viewportHeight }); + // A resize re-arms a pending scroll target's retry window (B-26 covers acting inside it). + await wait(SCROLL_TARGET_RETRY_WINDOW_MS); + return `${state.viewportHeight}`; + }, + weight: 1, + }, + { + name: 'toggle suppressAutoscroll', + run: (mounted, _rng, state) => { + state.suppressAutoscroll = !state.suppressAutoscroll; + mounted.rerender({ props: { suppressAutoscroll: state.suppressAutoscroll } }); + return `${state.suppressAutoscroll}`; + }, + weight: 1, + }, +]; + +export const pickOperation = (rng: Rng) => { + const total = OPERATIONS.reduce((sum, operation) => sum + operation.weight, 0); + let roll = rng.next() * total; + for (const operation of OPERATIONS) { + roll -= operation.weight; + if (roll < 0) return operation; + } + return OPERATIONS[OPERATIONS.length - 1]; +}; diff --git a/src/components/MessageList/__tests__/browser/harness.tsx b/src/components/MessageList/__tests__/browser/harness.tsx new file mode 100644 index 0000000000..a3cbdc0397 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/harness.tsx @@ -0,0 +1,695 @@ +import type { ComponentContextValue } from '../../../../context'; +import React, { Profiler, StrictMode, useEffect, useState } from 'react'; +import { createRoot } from 'react-dom/client'; +import type { Root } from 'react-dom/client'; +import type { + LocalMessage, + Channel as StreamChannel, + StreamChat, + UserResponse, +} from 'stream-chat'; + +import { Channel } from '../../../Channel'; +import { Chat } from '../../../Chat'; +import { WithComponents } from '../../../../context'; +import { useMessageContext } from '../../../../context/MessageContext'; +import { getTestClientWithUser } from '../../../../mock-builders'; +import { generateUser } from '../../../../mock-builders/generator'; +import { VirtualizedMessageList } from '../../VirtualizedMessageList'; +import type { VirtualizedMessageListProps } from '../../VirtualizedMessageList'; +import { buildHistory, installFakeBackend } from './fakeBackend'; +import { createRng } from './prng'; +import type { Rng } from './prng'; +import { probe, resetProbe } from './virtuosoProbe'; + +// --------------------------------------------------------------------------------------------- +// Message heights: the synthetic message UI renders a box of a height looked up here, so item +// geometry is deterministic and can be changed on demand (an image loading, a streamed reply). + +type HeightListener = () => void; +const heights = new Map(); +const heightListeners = new Set(); + +export const setMessageHeight = (id: string, height: number) => { + heights.set(id, height); + heightListeners.forEach((listener) => listener()); +}; + +const useMessageHeight = (id: string) => { + const [height, setHeight] = useState(() => heights.get(id) ?? 48); + useEffect(() => { + const listener = () => setHeight(heights.get(id) ?? 48); + heightListeners.add(listener); + listener(); + return () => { + heightListeners.delete(listener); + }; + }, [id]); + return height; +}; + +/** How often each message rendered, for the render-count comparison. */ +export const renderCounts = new Map(); + +/** Stands in for `MessageUI`: a box of the message's assigned height, tagged with its ID. */ +const SyntheticMessage = () => { + const { message } = useMessageContext(); + const height = useMessageHeight(message.id); + renderCounts.set(message.id, (renderCounts.get(message.id) ?? 0) + 1); + return ( +
+ {message.text} +
+ ); +}; + +// Module-level so the overrides keep one identity across renders, as an app's would. +const NO_OVERRIDES = {}; +const SYNTHETIC_OVERRIDES = { VirtualMessage: SyntheticMessage }; + +// --------------------------------------------------------------------------------------------- +// Mounting + +export type MountOptions = { + /** Total messages on the server. */ + historySize?: number; + /** Size of the first page and of every following one. */ + pageSize?: number; + gapMinutes?: number; + seed?: number; + listProps?: VirtualizedMessageListProps; + viewportHeight?: number; + /** Heights assigned to the messages, by index; a default spread otherwise. */ + heightFor?: (index: number, rng: Rng) => number; + /** Renders the SDK's own message UI instead of the synthetic boxes. */ + realMessageUI?: boolean; + /** Further `WithComponents` overrides, over the message UI's. */ + componentOverrides?: Partial; + strictMode?: boolean; + /** Wraps the list, e.g. in a custom scroll parent. */ + wrap?: (list: React.ReactElement) => React.ReactElement; + /** Runs after the first page loaded and before the list renders, e.g. to jump. */ + beforeRender?: (channel: StreamChannel) => Promise; + /** Counts frames until the first item shows. Off for scenarios that act during those frames. */ + measureMount?: boolean; +}; + +export type Mounted = Awaited>; + +export const OWN_USER: UserResponse = { + id: 'own-user', + name: 'Own User', +} as UserResponse; + +export const mountList = async ({ + beforeRender, + componentOverrides, + gapMinutes, + heightFor = (_index, rng) => rng.pick([40, 48, 64, 96, 140, 220]), + historySize = 200, + listProps, + measureMount = true, + pageSize = 50, + realMessageUI = false, + seed = 1, + strictMode = false, + viewportHeight = 600, + wrap = (list) => list, +}: MountOptions = {}) => { + resetProbe(); + renderCounts.clear(); + heights.clear(); + const rng = createRng(seed); + const other = generateUser({ id: 'other-user', name: 'Other User' }) as UserResponse; + const users = [OWN_USER, other]; + const history = buildHistory({ count: historySize, gapMinutes, rng, users }); + history.forEach((message, index) => heights.set(message.id, heightFor(index, rng))); + + const client = (await getTestClientWithUser(OWN_USER)) as StreamChat; + const channelId = `virtuoso-${seed}`; + const backend = installFakeBackend({ channelId, client, history, users }); + const channel = client.channel('messaging', channelId); + channel.messagePaginator.pageSize = pageSize; + await channel.watch(); + await beforeRender?.(channel); + + const paginatorCalls: string[] = []; + const paginator = channel.messagePaginator; + for (const method of [ + 'toTail', + 'toHead', + 'jumpToTheLatestMessage', + 'jumpToMessage', + ] as const) { + const original = paginator[method] as (...args: unknown[]) => unknown; + (paginator as unknown as Record)[method] = (...args: unknown[]) => { + paginatorCalls.push(method); + return original(...args); + }; + } + + let commits = 0; + const onRender = () => { + commits += 1; + }; + // Builds the tree for the given list props and viewport height, so a test can re-render the list + // with other props (`rerender`) the way a parent component would. + const buildTree = (props: VirtualizedMessageListProps | undefined, height: number) => { + const list = ( + + + + ); + const tree = ( + + + +
+ {wrap(list)} +
+
+
+
+ ); + return strictMode ? {tree} : tree; + }; + + const container = document.createElement('div'); + document.body.appendChild(container); + const root = createRoot(container); + const unmount = () => { + root.unmount(); + container.remove(); + roots.delete(root); + }; + roots.set(root, unmount); + let currentProps = listProps; + let currentHeight = viewportHeight; + root.render(buildTree(currentProps, currentHeight)); + const rerender = ({ + height = currentHeight, + props = currentProps, + }: { + height?: number; + props?: VirtualizedMessageListProps; + }) => { + currentProps = props; + currentHeight = height; + root.render(buildTree(currentProps, currentHeight)); + }; + await waitUntil( + () => !!container.querySelector('[data-testid="list-frame"]'), + 4000, + 'mount', + ); + const frame = container.querySelector( + '[data-testid="list-frame"]', + ) as HTMLElement; + + // Frames from the first render until an item is on screen: the cost of a channel switch. + let framesUntilFirstItem: number | null = null; + if (measureMount) { + for (let frames = 0; frames < 600; frames += 1) { + if (isListVisible(frame) && readVisibleItems(frame).length > 0) { + framesUntilFirstItem = frames; + break; + } + await nextFrame(); + } + } + + return { + backend, + channel, + client, + commits: () => commits, + frame, + framesUntilFirstItem, + history, + other, + paginatorCalls, + rerender, + rng, + unmount, + users, + }; +}; + +const roots = new Map void>(); + +/** Unmounts every list mounted by the current test, as an app does on navigation. */ +export const unmountAll = () => { + Array.from(roots.values()).forEach((unmount) => unmount()); +}; + +// --------------------------------------------------------------------------------------------- +// Driving the list + +/** Resolves on the next animation frame. */ +export const nextFrame = () => + new Promise((resolve) => requestAnimationFrame(resolve)); + +export const wait = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)); + +export const getScroller = (frame: HTMLElement) => + frame.querySelector('[data-virtuoso-scroller]'); + +/** + * What a scroll just done must lead to once the list settles, checked by the scenario runner: + * - `shift`: the content moved by exactly the scrolled distance. The anchor, the first message on + * screen before, sits `applied` pixels further down (up for a positive scroll), whatever Virtuoso + * measured or loaded meanwhile. + * - `bottom`: a scroll to the very bottom stays there while the items it reveals are measured. + */ +export type ScrollExpectation = + | { + anchorId: string; + applied: number; + expectedTop: number; + kind: 'shift'; + scrollHeightBefore: number; + } + | { kind: 'bottom' }; + +let pendingExpectation: ScrollExpectation | null = null; + +/** Returns the expectation of the last scroll and clears it. */ +export const takeScrollExpectation = () => { + const expectation = pendingExpectation; + pendingExpectation = null; + return expectation; +}; + +const isMessageId = (id: string) => id.startsWith('m-') || id.startsWith('live-'); + +// A reader's scroll starts with input (a wheel turn, a key, a touch, a scrollbar press), which the +// list may react to before the scroll event; a scroll set from script has none. +const readerInput = (scroller: HTMLElement, deltaY: number) => + scroller.dispatchEvent( + new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY }), + ); + +/** Scrolls by `delta` pixels the way a wheel does: the browser fires the scroll event. */ + +export const scrollBy = async (frame: HTMLElement, delta: number) => { + const scroller = getScroller(frame); + if (!scroller) throw new Error('no scroller'); + readerInput(scroller, delta); + const anchor = readVisibleItems(frame).find((item) => isMessageId(item.id)); + const before = scroller.scrollTop; + scroller.scrollTop += delta; + // Setting scrollTop clamps it synchronously: this is the distance the browser scrolled. + const applied = scroller.scrollTop - before; + // At an edge the list shows the edge: content above (or below) that measures taller than + // estimated is not compensated for there, and should not be. + const atEdge = + scroller.scrollTop <= 0 || + scroller.scrollTop >= scroller.scrollHeight - scroller.clientHeight - 1; + pendingExpectation = + anchor && Math.abs(applied) >= 1 && !atEdge + ? { + anchorId: anchor.id, + applied, + expectedTop: anchor.top - applied, + kind: 'shift', + scrollHeightBefore: scroller.scrollHeight, + } + : null; + await nextFrame(); +}; + +export const scrollToTop = async (frame: HTMLElement) => { + const scroller = getScroller(frame); + if (!scroller) throw new Error('no scroller'); + readerInput(scroller, -scroller.scrollTop); + scroller.scrollTop = 0; + pendingExpectation = null; + await nextFrame(); +}; + +/** + * Scrolls to the very bottom, as the End key or a scrollbar drag does. Expects the list to stay + * there unless `expectStaysAtBottom` is false (with `suppressAutoscroll` the list must not move). + */ +export const scrollToBottom = async ( + frame: HTMLElement, + { expectStaysAtBottom = true }: { expectStaysAtBottom?: boolean } = {}, +) => { + const scroller = getScroller(frame); + if (!scroller) throw new Error('no scroller'); + readerInput(scroller, scroller.scrollHeight - scroller.scrollTop); + scroller.scrollTop = scroller.scrollHeight; + pendingExpectation = expectStaysAtBottom ? { kind: 'bottom' } : null; + await nextFrame(); +}; + +let messageSequence = 0; + +/** `MessagePaginator` coalesces live publishes of its items to one per 500ms. */ +const LIVE_PUBLISH_THROTTLE_MS = 500; + +/** + * A message from `user` arriving over the WebSocket, `bodyHeight` pixels tall. Resolves once the + * paginator published it (live publishes are throttled), unless `awaitIngest` is false. + */ +export const receiveMessage = async ( + mounted: Mounted, + user: UserResponse, + bodyHeight = 64, + { awaitIngest = true }: { awaitIngest?: boolean } = {}, +) => { + messageSequence += 1; + const last = mounted.history[mounted.history.length - 1]; + const id = `live-${messageSequence}`; + // Unix nanoseconds, as the generated history carries them: one minute after the last message. + const createdAt = Number(last?.created_at ?? 0) + 60_000 * 1e6; + const message = { + ...last, + cid: mounted.channel.cid, + created_at: createdAt, + id, + status: 'received', + text: `live ${messageSequence}`, + updated_at: createdAt, + user, + } as unknown as LocalMessage; + setMessageHeight(id, bodyHeight); + mounted.history.push(message); + mounted.client.dispatchEvent({ + channel_id: mounted.channel.id, + channel_type: mounted.channel.type, + cid: mounted.channel.cid, + message: message as never, + type: 'message.new', + user, + } as never); + if (awaitIngest) { + // Shown (after the throttled publish) while the latest window is the active one. An older + // window open after a jump does not grow, so there is nothing to wait for but the publish delay. + const paginator = mounted.channel.messagePaginator; + if (paginator.state.getLatestValue().hasMoreHead) { + await wait(LIVE_PUBLISH_THROTTLE_MS + 100); + } else { + await waitUntil( + () => !!paginator.items?.some((item) => item.id === id), + 3000, + `ingest of ${id}`, + ); + } + } + return id; +}; + +// --------------------------------------------------------------------------------------------- +// Observing the list + +export type Geometry = { + clientHeight: number; + distanceFromBottom: number; + scrollHeight: number; + scrollTop: number; +}; + +export const readGeometry = (frame: HTMLElement): Geometry | null => { + const scroller = getScroller(frame); + if (!scroller) return null; + return { + clientHeight: scroller.clientHeight, + distanceFromBottom: + scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight, + scrollHeight: scroller.scrollHeight, + scrollTop: scroller.scrollTop, + }; +}; + +const itemId = (item: Element) => { + const message = item.querySelector('[data-message-id]'); + if (message) return message.getAttribute('data-message-id') as string; + const messageRoot = item.querySelector('[data-message-id], .str-chat__message'); + if (messageRoot?.id) return messageRoot.id; + if (item.querySelector('.str-chat__date-separator')) return 'date-separator'; + return 'item'; +}; + +/** The rendered items in DOM order, with their position relative to the scroller's top. */ +export const readRenderedItems = (frame: HTMLElement) => { + const scroller = getScroller(frame); + if (!scroller) return []; + const top = scroller.getBoundingClientRect().top; + return Array.from(scroller.querySelectorAll('[data-item-index]')).map((item) => { + const rect = item.getBoundingClientRect(); + return { + element: item, + height: rect.height, + id: itemId(item), + index: Number(item.getAttribute('data-item-index')), + top: rect.top - top, + }; + }); +}; + +/** The items intersecting the viewport. */ +export const readVisibleItems = (frame: HTMLElement) => { + const geometry = readGeometry(frame); + if (!geometry) return []; + return readRenderedItems(frame).filter( + (item) => item.top + item.height > 0.5 && item.top < geometry.clientHeight - 0.5, + ); +}; + +/** Whether Virtuoso shows its item list (v4 hides it until the initial location is reached). */ +export const isListVisible = (frame: HTMLElement) => { + const scroller = getScroller(frame); + if (!scroller) return false; + // A custom `components.List` may render no test ID: the item list is then the viewport's child. + const list = + scroller.querySelector( + '[data-testid="virtuoso-item-list"], [data-test-id="virtuoso-item-list"]', + ) ?? scroller.querySelector('[data-viewport-type] > :first-child'); + // An empty list renders the empty placeholder instead of the item list. + if (!list) return true; + return getComputedStyle(list).visibility !== 'hidden'; +}; + +/** How long `settle` waits for a hidden list to be revealed before treating it as settled. */ +const HIDDEN_LIST_GRACE_MS = 2000; + +/** + * Resolves once the list has been still for `quietFrames` frames in a row: same geometry, same + * rendered items, visible. Throws after `timeoutMs`. + */ +export const settle = async ( + frame: HTMLElement, + { minMs = 50, quietFrames = 10, timeoutMs = 4000 } = {}, +) => { + const startedAt = performance.now(); + let previous = ''; + let quiet = 0; + while (performance.now() - startedAt < timeoutMs) { + await nextFrame(); + const signature = JSON.stringify({ + geometry: readGeometry(frame), + items: readRenderedItems(frame).map((item) => [item.id, Math.round(item.top)]), + visible: isListVisible(frame), + }); + quiet = signature === previous ? quiet + 1 : 0; + previous = signature; + // A hidden list is not at rest: react-virtuoso 4 hides it while it positions it. + const shown = + isListVisible(frame) || performance.now() - startedAt > HIDDEN_LIST_GRACE_MS; + if (shown && quiet >= quietFrames && performance.now() - startedAt >= minMs) return; + } + throw new Error(`list did not settle within ${timeoutMs}ms: ${previous}`); +}; + +/** Waits until `predicate` holds, checking once per frame. */ +export const waitUntil = async ( + predicate: () => boolean, + timeoutMs = 4000, + label = '', +) => { + const startedAt = performance.now(); + while (!predicate()) { + if (performance.now() - startedAt > timeoutMs) { + throw new Error(`timed out waiting${label ? ` for ${label}` : ''}`); + } + await nextFrame(); + } +}; + +export type FrameSample = { + anchorTop: number | null; + blank: boolean; + distanceFromBottom: number | null; + visible: boolean; +}; + +/** + * Samples the list once per frame while `action` runs and for `framesAfter` frames after it: + * where `anchorId` sits, whether the viewport shows no item at all, the distance to the bottom. + */ +export const sampleFrames = async ( + frame: HTMLElement, + action: () => unknown, + { anchorId, framesAfter = 30 }: { anchorId?: string; framesAfter?: number } = {}, +) => { + const samples: FrameSample[] = []; + let done = false; + let remaining = framesAfter; + const sample = () => { + const geometry = readGeometry(frame); + const items = readRenderedItems(frame); + const anchor = anchorId ? items.find((item) => item.id === anchorId) : undefined; + samples.push({ + anchorTop: anchor ? anchor.top : null, + blank: + !!geometry && geometry.clientHeight > 0 && readVisibleItems(frame).length === 0, + distanceFromBottom: geometry?.distanceFromBottom ?? null, + visible: isListVisible(frame), + }); + }; + const loop = new Promise((resolve) => { + const tick = () => { + sample(); + if (done) remaining -= 1; + if (done && remaining <= 0) return resolve(); + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + await action(); + done = true; + await loop; + return samples; +}; + +export { probe }; + +// --------------------------------------------------------------------------------------------- +// Leak tracking + +/** + * Counts the `scroll` / `resize` listeners on long-lived targets (window, document, ``, + * ``) and the ResizeObservers alive from now on, so a test can check that unmounting releases + * everything mounting acquired. Listeners on elements are left out: they go with their element, and + * React's own delegation listeners on a root container are never removed by design. Call + * `restore()` when done. + */ +export const trackResources = () => { + type Entry = { stack: string; target: string; type: string }; + const live = new Map(); + const identities = new WeakMap(); + let nextIdentity = 0; + const identityOf = (value: object) => { + if (!identities.has(value)) identities.set(value, (nextIdentity += 1)); + return identities.get(value); + }; + const captureOf = (options: unknown) => + typeof options === 'object' + ? !!(options as AddEventListenerOptions)?.capture + : !!options; + const targetName = (target: EventTarget) => + target === window + ? 'window' + : target === document + ? 'document' + : target === document.body + ? 'body' + : 'html'; + const isLongLived = (target: EventTarget) => + target === window || + target === document || + target === document.documentElement || + target === document.body; + const entryKey = ( + target: EventTarget, + type: string, + listener: object, + options: unknown, + ) => `${identityOf(target)}:${type}:${identityOf(listener)}:${captureOf(options)}`; + + const originalAdd = EventTarget.prototype.addEventListener; + const originalRemove = EventTarget.prototype.removeEventListener; + EventTarget.prototype.addEventListener = function (type, listener, options) { + const stack = new Error().stack ?? ''; + // React delegates events once per root or portal container (here: a portal into ) and + // never removes those listeners by design; they are not owned by any one component. + const isReactDelegation = stack.includes('listenToAllSupportedEvents'); + if ( + (type === 'scroll' || type === 'resize') && + listener && + isLongLived(this) && + !isReactDelegation + ) { + live.set(entryKey(this, type, listener as object, options), { + stack: stack.split('\n').slice(2, 7).join('\n'), + target: targetName(this), + type, + }); + } + return originalAdd.call(this, type, listener, options); + }; + EventTarget.prototype.removeEventListener = function (type, listener, options) { + if ((type === 'scroll' || type === 'resize') && listener && isLongLived(this)) { + live.delete(entryKey(this, type, listener as object, options)); + } + return originalRemove.call(this, type, listener, options); + }; + + // Observations, not observers: an observer whose elements were all unobserved is released with + // them even if it is never disconnected. + const OriginalResizeObserver = globalThis.ResizeObserver; + let observations = 0; + globalThis.ResizeObserver = class extends OriginalResizeObserver { + private observed = new Set(); + observe(target: Element, options?: ResizeObserverOptions) { + if (!this.observed.has(target)) observations += 1; + this.observed.add(target); + super.observe(target, options); + } + unobserve(target: Element) { + if (this.observed.delete(target)) observations -= 1; + super.unobserve(target); + } + disconnect() { + observations -= this.observed.size; + this.observed.clear(); + super.disconnect(); + } + }; + + return { + counts: () => ({ + longLivedListeners: live.size, + // Observations of elements still in the document are not leaks. + resizeObservations: observations, + }), + /** Where each listener still registered was added. */ + pending: () => Array.from(live.values()), + restore: () => { + EventTarget.prototype.addEventListener = originalAdd; + EventTarget.prototype.removeEventListener = originalRemove; + globalThis.ResizeObserver = OriginalResizeObserver; + }, + }; +}; diff --git a/src/components/MessageList/__tests__/browser/invariants.ts b/src/components/MessageList/__tests__/browser/invariants.ts new file mode 100644 index 0000000000..7d3eb39cf4 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/invariants.ts @@ -0,0 +1,73 @@ +import type { Checkpoint } from './trace'; +import { readGeometry, readRenderedItems, readVisibleItems } from './harness'; +import { probe } from './virtuosoProbe'; + +/** + * Properties that must hold after every settled step, whatever the runtime: they need no + * reference trace, so they also catch a bug both runtimes share. + */ + +const threshold = (clientHeight: number) => + Math.min(Math.max(clientHeight * 0.1, 4), 100); + +/** The scroller sits at its true bottom. */ +export const expectAtBottom = (frame: HTMLElement, tolerance = 1) => { + const geometry = readGeometry(frame); + expect(geometry, 'scroller').not.toBeNull(); + expect(geometry?.distanceFromBottom, 'distance from the bottom').toBeLessThanOrEqual( + tolerance, + ); +}; + +/** Rendered items are consecutive Virtuoso indexes, in DOM order. */ +export const expectContiguousItems = (frame: HTMLElement) => { + const indexes = readRenderedItems(frame).map((item) => item.index); + indexes.forEach((index, position) => { + if (position === 0) return; + expect(index, `item after ${indexes[position - 1]}`).toBe(indexes[position - 1] + 1); + }); +}; + +/** Items fill the viewport whenever the content is taller than it. */ +export const expectViewportCovered = (frame: HTMLElement) => { + const geometry = readGeometry(frame); + if (!geometry || geometry.scrollHeight <= geometry.clientHeight + 1) return; + const visible = readVisibleItems(frame); + expect(visible.length, 'items in the viewport').toBeGreaterThan(0); + const first = visible[0]; + const last = visible[visible.length - 1]; + // The header (thread head, loading indicator) may sit above the first item at the very top. + if (geometry.scrollTop > 1) + expect(first.top, 'first item top').toBeLessThanOrEqual(0.5); + if (geometry.distanceFromBottom > 1) { + expect(last.top + last.height, 'last item bottom').toBeGreaterThanOrEqual( + geometry.clientHeight - 0.5, + ); + } +}; + +/** Messages that stayed rendered kept their DOM nodes: keys are stable. */ +export const expectNoRemounts = (point: Checkpoint) => { + expect(point.remounted, 'remounted items').toEqual([]); +}; + +/** The last at-bottom state Virtuoso reported agrees with the measured geometry. */ +export const expectAtBottomStateAgrees = (frame: HTMLElement) => { + const geometry = readGeometry(frame); + if (!geometry) return; + const reports = probe.events.filter((event) => event.name === 'atBottomStateChange'); + const last = reports[reports.length - 1]?.value; + if (last === undefined) return; + if (geometry.distanceFromBottom <= 1) expect(last, 'reported at bottom').toBe(true); + if (geometry.distanceFromBottom > threshold(geometry.clientHeight) + 2) { + expect(last, 'reported at bottom').toBe(false); + } +}; + +/** Every settled-state invariant at once. */ +export const expectSettledInvariants = (frame: HTMLElement, point: Checkpoint) => { + expect(point.visible, 'list visible').toBe(true); + expectContiguousItems(frame); + expectViewportCovered(frame); + expectAtBottomStateAgrees(frame); +}; diff --git a/src/components/MessageList/__tests__/browser/prng.ts b/src/components/MessageList/__tests__/browser/prng.ts new file mode 100644 index 0000000000..f014ae4247 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/prng.ts @@ -0,0 +1,19 @@ +/** Deterministic PRNG (mulberry32): the same seed yields the same scenario on every runtime. */ +export const createRng = (seed: number) => { + let state = seed >>> 0; + const next = () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + return { + /** Integer in [min, max]. */ + int: (min: number, max: number) => min + Math.floor(next() * (max - min + 1)), + next, + pick: (items: readonly T[]): T => items[Math.floor(next() * items.length)], + }; +}; + +export type Rng = ReturnType; diff --git a/src/components/MessageList/__tests__/browser/scenario.ts b/src/components/MessageList/__tests__/browser/scenario.ts new file mode 100644 index 0000000000..e78e63ee95 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/scenario.ts @@ -0,0 +1,183 @@ +import type { Mounted, MountOptions } from './harness'; +import { + mountList, + readGeometry, + readRenderedItems, + sampleFrames, + settle, + takeScrollExpectation, + wait, +} from './harness'; +import type { ScrollExpectation } from './harness'; +import { RUNTIME } from './trace'; + +/** + * After `scrollToIndex` (the initial `initialTopMostItemIndex` scroll included), Virtuoso re-scrolls + * to the same target whenever item sizes change for a while (v2.19: about 1.2s), so a user scroll + * within that window is undone. Steps that test something else start after it. + */ +export const SCROLL_TARGET_RETRY_WINDOW_MS = 1300; +import { expectSettledInvariants } from './invariants'; +import type { Checkpoint } from './trace'; +import { createTrace, summarizeFrames } from './trace'; + +export type StepOptions = { + /** Samples every frame while the step runs, tracking where this message sits. */ + anchorId?: string; + sample?: boolean; + /** Skips the settled-state invariants, for a step whose end state is not settled by design. */ + skipInvariants?: boolean; + settle?: Parameters[1]; + /** + * The step runs on wall-clock timers (a burst, a stream), so how many renders it took and where an + * animation stood when sampling stopped vary between runs. Only its settled state is compared. + */ + timingDependent?: boolean; +}; + +export type ScenarioContext = { + mounted: Mounted; + /** Runs `action`, waits for the list to settle, and records a checkpoint. */ + step: ( + label: string, + action: () => unknown, + options?: StepOptions, + ) => Promise; + checkpoint: (label: string) => Checkpoint; + /** Invariant failures so far, as messages. */ + violations: string[]; +}; + +/** Pixels a scroll expectation may be off by: sub-pixel layout and rounding. */ +const SCROLL_TOLERANCE_PX = 2; + +const checkScrollExpectation = ( + mounted: Mounted, + point: Checkpoint, + expectation: ScrollExpectation | null, + violations: string[], + knownDeviations: string[], +) => { + if (!expectation) return; + if (expectation.kind === 'bottom') { + // The end of an older window loads the next newer page below it, and the reader then stays + // put above it: that step passes. Otherwise the scroll must end at the end, in an older window + // too, where ending short of it loads nothing and leaves the reader to scroll again. + const loadedNewer = point.requests.some( + (request) => !!(request as { messages?: { id_gt?: string } }).messages?.id_gt, + ); + if (loadedNewer) return; + const distance = readGeometry(mounted.frame)?.distanceFromBottom ?? 0; + if (distance > SCROLL_TOLERANCE_PX) { + const where = mounted.channel.messagePaginator.hasMoreHead + ? 'the end of an older window, loading no newer page,' + : 'the bottom'; + violations.push( + `${point.label}: ${Math.round(distance)}px short of ${where} after scrolling to it`, + ); + } + return; + } + const anchor = readRenderedItems(mounted.frame).find( + (item) => item.id === expectation.anchorId, + ); + // Scrolled out of the rendered window: nothing to compare. + if (!anchor) return; + const error = anchor.top - expectation.expectedTop; + // Known in both react-virtuoso 2 and 4, intermittently: messages scrolled into view that measure + // other than estimated can move the content by up to the height the list gained or lost, when the + // runtime misses compensating it. Recorded and compared (the comparison fails if v4 shows more of + // them than v2), not failed on. + const heightChange = + (readGeometry(mounted.frame)?.scrollHeight ?? 0) - expectation.scrollHeightBefore; + if ( + Math.abs(error) > SCROLL_TOLERANCE_PX && + Math.sign(error) === Math.sign(heightChange) && + Math.abs(error) <= Math.abs(heightChange) + SCROLL_TOLERANCE_PX + ) { + knownDeviations.push( + `${point.label}: content moved ${Math.round(error)}px with messages measuring ${Math.round(heightChange)}px off their estimate`, + ); + return; + } + if (Math.abs(error) > SCROLL_TOLERANCE_PX) { + violations.push( + `${point.label}: content moved ${Math.round(error)}px more than the ${Math.round(expectation.applied)}px scrolled (anchor ${expectation.anchorId})`, + ); + } +}; + +const runInvariants = (mounted: Mounted, point: Checkpoint, violations: string[]) => { + try { + expectSettledInvariants(mounted.frame, point); + } catch (error) { + violations.push(`${point.label}: ${(error as Error).message.split('\n')[0]}`); + } +}; + +/** + * Mounts the list, records the scenario as a trace of settled checkpoints, checks the settled-state + * invariants after every step, and writes the trace for the cross-runtime comparison. Invariant + * failures are collected rather than thrown, so the trace is written either way; the test fails at + * the end when any were found. + */ +export const runScenario = async ( + name: string, + options: MountOptions, + body: (context: ScenarioContext) => Promise | void, + { + allowViolations = false, + quietAfterMountMs = SCROLL_TARGET_RETRY_WINDOW_MS, + }: { allowViolations?: boolean; quietAfterMountMs?: number } = {}, +) => { + const mounted = await mountList(options); + const trace = createTrace(name, mounted); + const violations: string[] = []; + const knownDeviations: string[] = []; + + await settle(mounted.frame); + // Lets the initial scroll finish retrying (see SCROLL_TARGET_RETRY_WINDOW_MS) so steps act on a + // list at rest; B-26 covers acting inside that window. + await wait(quietAfterMountMs); + await settle(mounted.frame); + runInvariants(mounted, trace.checkpoint('mounted'), violations); + + const step: ScenarioContext['step'] = async (label, action, stepOptions = {}) => { + // An expectation left by a scroll outside a step does not belong to this one. + takeScrollExpectation(); + let frames; + if (stepOptions.sample || stepOptions.anchorId) { + const samples = await sampleFrames(mounted.frame, action, { + anchorId: stepOptions.anchorId, + }); + frames = summarizeFrames(samples); + } else { + await action(); + } + await settle(mounted.frame, stepOptions.settle); + const point = trace.checkpoint(label, frames); + if (stepOptions.timingDependent) point.timingDependent = true; + const expectation = takeScrollExpectation(); + if (!stepOptions.skipInvariants) { + runInvariants(mounted, point, violations); + checkScrollExpectation(mounted, point, expectation, violations, knownDeviations); + } + return point; + }; + + try { + await body({ + checkpoint: (label) => trace.checkpoint(label), + mounted, + step, + violations, + }); + } finally { + await trace.save({ knownDeviations, violations }); + } + // The v2 runtime is the reference: its defects are recorded for the comparison, not failed on. + if (!allowViolations && RUNTIME !== 'browser-v2') { + expect(violations, 'invariant violations').toEqual([]); + } + return { mounted, trace, violations }; +}; diff --git a/src/components/MessageList/__tests__/browser/trace.ts b/src/components/MessageList/__tests__/browser/trace.ts new file mode 100644 index 0000000000..5899820c6f --- /dev/null +++ b/src/components/MessageList/__tests__/browser/trace.ts @@ -0,0 +1,198 @@ +import { commands } from 'vitest/browser'; + +import type { FrameSample, Mounted } from './harness'; +import { isListVisible, readGeometry, readRenderedItems, renderCounts } from './harness'; +import { probe } from './virtuosoProbe'; +import type { ProbeEvent } from './virtuosoProbe'; + +declare module 'vitest/browser' { + interface BrowserCommands { + setCpuThrottlingRate: (rate: number) => Promise; + writeVirtuosoTrace: (name: string, json: string) => Promise; + } +} + +declare const VIRTUOSO_TEST_RUNTIME: string; + +/** Which react-virtuoso runtime this project bundles: `browser-v2` or `browser-v4`. */ +export const RUNTIME = + typeof VIRTUOSO_TEST_RUNTIME === 'string' ? VIRTUOSO_TEST_RUNTIME : ''; + +/** Inline style properties whose values follow the content; only their presence is compared. */ +const LAYOUT_DEPENDENT_STYLES = new Set([ + 'height', + 'margin-top', + 'padding-bottom', + 'padding-top', + 'top', + 'transform', +]); + +const describeElement = (element: Element | null | undefined) => { + if (!element) return null; + const attributes = Array.from(element.attributes) + .filter((attribute) => attribute.name !== 'style') + .map((attribute) => + // The item's position and message are compared as `rendered` and `firstVisible`. + attribute.name.startsWith('data-') && /index|size|message-id/.test(attribute.name) + ? attribute.name + : `${attribute.name}=${attribute.value}`, + ) + .sort(); + const style = (element as HTMLElement).style; + const styles = Array.from({ length: style?.length ?? 0 }, (_, i) => style[i]) + .map((property) => + LAYOUT_DEPENDENT_STYLES.has(property) + ? property + : `${property}:${style.getPropertyValue(property)}`, + ) + .sort(); + return { attributes, styles, tag: element.tagName.toLowerCase() }; +}; + +/** The scroller, viewport and item list Virtuoso renders, without content-dependent values. */ +export const describeDom = (frame: HTMLElement) => { + const scroller = frame.querySelector('[data-virtuoso-scroller]'); + const viewport = scroller?.querySelector('[data-viewport-type]'); + const list = scroller?.querySelector( + '[data-testid="virtuoso-item-list"], [data-test-id="virtuoso-item-list"]', + ); + const firstItem = scroller?.querySelector('[data-item-index]'); + return { + firstItem: describeElement(firstItem), + list: describeElement(list), + scroller: describeElement(scroller), + viewport: describeElement(viewport), + }; +}; + +export type Checkpoint = { + label: string; + geometry: ReturnType; + rendered: string[]; + firstVisible: { id: string; top: number } | null; + visible: boolean; + /** IDs rendered at the previous checkpoint and now, whose DOM element was replaced. */ + remounted: string[]; + events: ProbeEvent[]; + requests: Mounted['backend']['requests']; + paginatorCalls: string[]; + commits: number; + messageRenders: number; + dom: ReturnType; + frames?: FrameSummary; + /** See `StepOptions.timingDependent`. */ + timingDependent?: boolean; +}; + +export type FrameSummary = { + blankFrames: number; + framesUntilVisible: number; + maxAnchorShift: number | null; + finalDistanceFromBottom: number | null; +}; + +export const summarizeFrames = (samples: FrameSample[]): FrameSummary => { + const anchors = samples.map((sample) => sample.anchorTop).filter((top) => top !== null); + const reference = anchors[0] ?? null; + const firstVisible = samples.findIndex((sample) => sample.visible); + return { + blankFrames: samples.filter((sample) => sample.visible && sample.blank).length, + finalDistanceFromBottom: samples[samples.length - 1]?.distanceFromBottom ?? null, + framesUntilVisible: firstVisible === -1 ? samples.length : firstVisible, + maxAnchorShift: + reference === null + ? null + : Math.max( + ...anchors.map((top) => Math.abs((top as number) - (reference as number))), + ), + }; +}; + +/** + * Records a scenario as a sequence of checkpoints. Each checkpoint holds what changed since the + * previous one (callbacks, requests, paginator calls, renders) and the list's state at that point. + */ +export const createTrace = (scenario: string, mounted: Mounted) => { + const checkpoints: Checkpoint[] = []; + let eventCursor = 0; + let requestCursor = 0; + let paginatorCursor = 0; + let commitCursor = 0; + let renderCursor = 0; + let elements = new Map(); + const consoleErrors: string[] = []; + + // Capture phase on the window: sees errors even when a later listener stops their propagation. + const windowErrors: string[] = []; + const onWindowError = (event: ErrorEvent) => windowErrors.push(event.message); + window.addEventListener('error', onWindowError, true); + + const originalError = console.error; + console.error = (...args: unknown[]) => { + consoleErrors.push(args.map(String).join(' ').slice(0, 300)); + originalError(...args); + }; + + const totalRenders = () => + Array.from(renderCounts.values()).reduce((sum, n) => sum + n, 0); + + const checkpoint = (label: string, frames?: FrameSummary) => { + const items = readRenderedItems(mounted.frame); + const geometry = readGeometry(mounted.frame); + const remounted = items + .filter((item) => elements.has(item.id) && elements.get(item.id) !== item.element) + .map((item) => item.id); + elements = new Map(items.map((item) => [item.id, item.element])); + const visibleItems = items.filter( + (item) => item.top + item.height > 0.5 && item.top < (geometry?.clientHeight ?? 0), + ); + const point: Checkpoint = { + commits: mounted.commits() - commitCursor, + dom: describeDom(mounted.frame), + events: probe.events.slice(eventCursor), + firstVisible: visibleItems[0] + ? { id: visibleItems[0].id, top: Math.round(visibleItems[0].top) } + : null, + frames, + geometry, + label, + messageRenders: totalRenders() - renderCursor, + paginatorCalls: mounted.paginatorCalls.slice(paginatorCursor), + remounted, + rendered: items.map((item) => item.id), + requests: mounted.backend.requests.slice(requestCursor), + visible: isListVisible(mounted.frame), + }; + eventCursor = probe.events.length; + requestCursor = mounted.backend.requests.length; + paginatorCursor = mounted.paginatorCalls.length; + commitCursor = mounted.commits(); + renderCursor = totalRenders(); + checkpoints.push(point); + return point; + }; + + const save = async (extra: Record = {}) => { + console.error = originalError; + window.removeEventListener('error', onWindowError, true); + await commands.writeVirtuosoTrace( + scenario, + JSON.stringify( + { + checkpoints, + consoleErrors, + ...extra, + framesUntilFirstItem: mounted.framesUntilFirstItem, + runtime: RUNTIME, + scenario, + windowErrors, + }, + null, + 2, + ), + ); + }; + + return { checkpoint, checkpoints, consoleErrors, save, windowErrors }; +}; diff --git a/src/components/MessageList/__tests__/browser/virtuosoProbe.tsx b/src/components/MessageList/__tests__/browser/virtuosoProbe.tsx new file mode 100644 index 0000000000..1fc546d930 --- /dev/null +++ b/src/components/MessageList/__tests__/browser/virtuosoProbe.tsx @@ -0,0 +1,191 @@ +import React, { forwardRef, useImperativeHandle, useRef } from 'react'; +import type { ComponentType } from 'react'; + +import type { RenderedMessage } from '../../utils'; + +/** One call Virtuoso made into the SDK, or the SDK made into Virtuoso. */ +export type ProbeEvent = { name: string; value: unknown }; + +type AnyProps = Record; + +/** + * Deliberate breakages injected between the SDK and Virtuoso, to prove the trace comparison + * notices a behavior change (see "mutation checks" in the upgrade plan). Selected with the + * `VIRTUOSO_MUTATION` environment variable. + */ +export type VirtuosoMutation = + | 'atTopThresholdZero' + | 'computeItemKeyIndex' + | 'dropFirstRenderedItem' + | 'firstItemIndexFrozen' + | 'followOutputUndefined' + | 'increaseViewportTop' + | 'noInitialTopMostItemIndex'; + +declare const VIRTUOSO_TEST_MUTATION: string; + +export const activeMutation = ( + typeof VIRTUOSO_TEST_MUTATION === 'string' ? VIRTUOSO_TEST_MUTATION : '' +) as VirtuosoMutation | ''; + +type ProbeState = { + events: ProbeEvent[]; + /** The props Virtuoso received on its latest render. */ + lastProps: AnyProps | null; + frozenFirstItemIndex: number | null; +}; + +export const probe: ProbeState = { + events: [], + frozenFirstItemIndex: null, + lastProps: null, +}; + +export const resetProbe = () => { + probe.events = []; + probe.frozenFirstItemIndex = null; + probe.lastProps = null; +}; + +const record = (name: string, value: unknown) => probe.events.push({ name, value }); + +/** A JSON copy of a call argument, as it was when the call was made. */ +const snapshot = (value: unknown) => { + if (value === undefined || value === null) return null; + if (typeof value === 'function') return 'function'; + try { + return JSON.parse( + JSON.stringify(value, (_key, v) => (typeof v === 'function' ? 'function' : v)), + ); + } catch { + return String(value); + } +}; + +const scrollerKind = (element: unknown) => { + if (element === null) return 'null'; + if (typeof window !== 'undefined' && element === window) return 'window'; + if (element instanceof HTMLElement) { + return element.hasAttribute('data-virtuoso-scroller') ? 'scroller' : 'element'; + } + return typeof element; +}; + +const renderedIds = ( + items: { originalIndex?: number }[], + context: AnyProps | undefined, +) => { + const messages: RenderedMessage[] = context?.processedMessages ?? []; + return items.map((item) => + item.originalIndex === undefined ? '?' : (messages[item.originalIndex]?.id ?? '?'), + ); +}; + +const wrappers = new WeakMap(); + +/** The recording wrapper of `original`, created once per function; `undefined` stays `undefined`. */ +function wrap(original: T, make: (original: any) => unknown): T { + if (typeof original !== 'function') return original; + if (!wrappers.has(original)) wrappers.set(original, make(original)); + return wrappers.get(original) as T; +} + +/** + * Wraps a Virtuoso component so every callback crossing the SDK ↔ Virtuoso boundary is recorded + * with its arguments (and, for `followOutput`, its return value), without changing what either + * side sees. The wrapper adds no DOM, so both runtimes lay out exactly as in an app. + */ +export const wrapVirtuoso = (Virtuoso: ComponentType) => + forwardRef(function ProbedVirtuoso(props, ref) { + const innerRef = useRef(null); + const contextRef = useRef(undefined); + useImperativeHandle( + ref, + () => + new Proxy( + {}, + { + get: (_target, key: string) => { + const value = innerRef.current?.[key]; + if (typeof value !== 'function') return value; + return (...args: unknown[]) => { + // A copy: react-virtuoso 2 adds defaults to the location object it is given. + record(`handle.${key}`, snapshot(args[0])); + return value(...args); + }; + }, + }, + ), + [], + ); + + const next: AnyProps = { ...props }; + + // Each wrapper is cached per wrapped function, so its identity changes exactly when the SDK's + // own callback does: Virtuoso must not see a prop change the SDK did not make. + next.atBottomStateChange = wrap( + props.atBottomStateChange, + (original) => (value: boolean) => { + record('atBottomStateChange', value); + original(value); + }, + ); + next.atTopStateChange = wrap( + props.atTopStateChange, + (original) => (value: boolean) => { + record('atTopStateChange', value); + original(value); + }, + ); + next.followOutput = wrap(props.followOutput, (original) => (isAtBottom: boolean) => { + let result = original(isAtBottom); + if (activeMutation === 'followOutputUndefined' && result === false) + result = undefined; + record('followOutput', { + isAtBottom, + result: result === undefined ? 'undefined' : result, + }); + return result; + }); + next.itemsRendered = wrap( + props.itemsRendered, + (original) => (items: { originalIndex?: number }[]) => { + record('itemsRendered', renderedIds(items, contextRef.current)); + const forwarded = + activeMutation === 'dropFirstRenderedItem' + ? items.filter((item) => item.originalIndex !== 0) + : items; + original(forwarded); + }, + ); + next.scrollerRef = wrap(props.scrollerRef, (original) => (element: unknown) => { + record('scrollerRef', scrollerKind(element)); + original(element); + }); + next.totalListHeightChanged = wrap( + props.totalListHeightChanged, + (original) => (height: number) => { + record('totalListHeightChanged', Math.round(height)); + original(height); + }, + ); + contextRef.current = props.context; + + if (activeMutation === 'atTopThresholdZero') next.atTopThreshold = 0; + if (activeMutation === 'computeItemKeyIndex') + next.computeItemKey = (index: number) => index; + if (activeMutation === 'increaseViewportTop') + next.increaseViewportBy = { bottom: 200, top: 200 }; + if (activeMutation === 'noInitialTopMostItemIndex') + delete next.initialTopMostItemIndex; + if ( + activeMutation === 'firstItemIndexFrozen' && + typeof props.firstItemIndex === 'number' + ) { + probe.frozenFirstItemIndex ??= props.firstItemIndex; + next.firstItemIndex = probe.frozenFirstItemIndex; + } + + probe.lastProps = props; + return ; + }); diff --git a/src/components/MessageList/__tests__/makeItemsRenderedHandler.test.ts b/src/components/MessageList/__tests__/makeItemsRenderedHandler.test.ts new file mode 100644 index 0000000000..9d54ac0245 --- /dev/null +++ b/src/components/MessageList/__tests__/makeItemsRenderedHandler.test.ts @@ -0,0 +1,38 @@ +import type { ListItem } from 'react-virtuoso'; + +import { makeItemsRenderedHandler } from '../VirtualizedMessageListComponents'; +import type { RenderedMessage } from '../utils'; +import type { UnknownType } from '../../../types/types'; + +vi.mock('lodash.throttle', () => ({ + default: (fn: (...args: unknown[]) => unknown) => fn, +})); + +const messages = ['a', 'b', 'c'].map((id) => ({ id }) as RenderedMessage); + +// Virtuoso reports each rendered item's position in the data as `originalIndex` (0-based), apart +// from the absolute `index` that includes `firstItemIndex`. +const item = (originalIndex: number): ListItem => + ({ + index: 10 ** 7 + originalIndex, + offset: 0, + originalIndex, + size: 30, + }) as ListItem; + +describe('makeItemsRenderedHandler', () => { + it('passes the rendered messages, the first loaded one included', () => { + const action = vi.fn(); + makeItemsRenderedHandler([action], messages)([item(0), item(1)]); + expect(action).toHaveBeenCalledWith([messages[0], messages[1]]); + }); + + it('skips items Virtuoso reports without a data position', () => { + const action = vi.fn(); + makeItemsRenderedHandler( + [action], + messages, + )([{ index: 0, offset: 0, size: 30 } as ListItem, item(2)]); + expect(action).toHaveBeenCalledWith([messages[2]]); + }); +}); diff --git a/src/components/MessageList/__tests__/virtuosoContract.test.tsx b/src/components/MessageList/__tests__/virtuosoContract.test.tsx new file mode 100644 index 0000000000..d9ec677045 --- /dev/null +++ b/src/components/MessageList/__tests__/virtuosoContract.test.tsx @@ -0,0 +1,282 @@ +import React, { createRef } from 'react'; +import { act, render, screen, waitFor } from '@testing-library/react'; +import { GroupedVirtuoso, Virtuoso, VirtuosoMockContext } from 'react-virtuoso'; +import type { ItemProps, VirtuosoHandle } from 'react-virtuoso'; + +/** + * The parts of react-virtuoso's contract the SDK builds on, pinned against the real component. + * jsdom has no layout, so `VirtuosoMockContext` supplies the viewport and item sizes. Real scrolling + * and measurement are covered by the browser suites (`__tests__/browser`). + */ + +const mockContext = { itemHeight: 30, viewportHeight: 300 }; + +// jsdom implements neither Element.scrollTo nor Element.scrollBy, through which Virtuoso scrolls +// (initial location, scrollIntoView, prepend compensation). These set scrollTop, as a browser does +// for an instant scroll. +type ScrollArgs = [ScrollToOptions | number | undefined, number?]; +const toTop = (element: Element, args: ScrollArgs, relative: boolean) => { + const [first, second] = args; + const top = typeof first === 'object' ? first?.top : second; + if (typeof top !== 'number') return; + element.scrollTop = relative ? element.scrollTop + top : top; + element.dispatchEvent(new Event('scroll')); +}; +beforeAll(() => { + Element.prototype.scrollTo = function (this: Element, ...args: ScrollArgs) { + toTop(this, args, false); + } as Element['scrollTo']; + Element.prototype.scrollBy = function (this: Element, ...args: ScrollArgs) { + toTop(this, args, true); + } as Element['scrollBy']; +}); +afterAll(() => { + delete (Element.prototype as Partial).scrollTo; + delete (Element.prototype as Partial).scrollBy; +}); + +const renderInMock = (element: React.ReactElement) => + render( + + {element} + , + ); + +const PREPEND_OFFSET = 10 ** 7; + +describe('react-virtuoso contract', () => { + it('J-01 hands a custom Item its absolute index and keeps the item data off the DOM', () => { + const seen: number[] = []; + // The shape of the SDK's own `Item` (VirtualizedMessageListComponents): it reads + // `data-item-index` and spreads the rest onto a
. + const Item = ({ + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- kept off the
, as the SDK's Item does + context: _context, + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- kept off the
, as the SDK's Item does + item: _item, + ...props + }: ItemProps & { context?: unknown }) => { + seen.push(props['data-item-index']); + return
; + }; + const { container } = renderInMock( + row {index}} + totalCount={20} + />, + ); + expect(seen[0]).toBe(PREPEND_OFFSET - 5); + const wrapper = container.querySelector('[data-item-index]'); + expect(wrapper?.getAttribute('data-item-index')).toBe(String(PREPEND_OFFSET - 5)); + expect(wrapper?.hasAttribute('item')).toBe(false); + }); + + it('J-02 keeps the DOM node of an item that stays rendered across a prepend', () => { + const ids = Array.from({ length: 10 }, (_, i) => `m-${i}`); + const view = (items: string[], firstItemIndex: number) => ( + + items[index - firstItemIndex]} + firstItemIndex={firstItemIndex} + itemContent={(index) => } + totalCount={items.length} + /> + + ); + const { container, rerender } = render(view(ids, PREPEND_OFFSET)); + const before = container.querySelector('[data-id="m-2"]'); + rerender(view(['p-0', 'p-1', ...ids], PREPEND_OFFSET - 2)); + expect(container.querySelector('[data-id="m-2"]')).toBe(before); + }); + + it('J-03 reports rendered items with 0-based original indexes, the first one included', () => { + const reports: (number | undefined)[][] = []; + renderInMock( + {index}} + itemsRendered={(items) => reports.push(items.map((item) => item.originalIndex))} + totalCount={20} + />, + ); + const last = reports[reports.length - 1]; + expect(last[0]).toBe(0); + expect(last).toContain(1); + }); + + it('J-04 re-renders visible items when `context` changes', () => { + const view = (label: string) => ( + + ( + + {context.label} {index} + + )} + totalCount={5} + /> + + ); + const { rerender } = render(view('before')); + expect(screen.getByText('before 0')).toBeInTheDocument(); + rerender(view('after')); + expect(screen.getByText('after 0')).toBeInTheDocument(); + }); + + // Virtuoso positions a list asynchronously (it waits frames, then for the list to stop changing). + const POSITIONING_TIMEOUT = { timeout: 2000 }; + + it('J-06 survives an empty list opened at its end, then filling it', async () => { + const view = (count: number) => ( + +
empty
}} + initialTopMostItemIndex={{ align: 'end', index: count - 1 }} + itemContent={(index) => row {index}} + totalCount={count} + /> +
+ ); + const { rerender } = render(view(0)); + expect(screen.getByText('empty')).toBeInTheDocument(); + rerender(view(5)); + expect(screen.queryByText('empty')).not.toBeInTheDocument(); + expect( + await screen.findByText('row 4', undefined, POSITIONING_TIMEOUT), + ).toBeInTheDocument(); + }); + + it('J-06b opens at the requested end of the list', async () => { + renderInMock( + row {index}} + totalCount={100} + />, + ); + expect( + await screen.findByText('row 99', undefined, POSITIONING_TIMEOUT), + ).toBeInTheDocument(); + }); + + it('J-07 renders the scroller as the root, carrying the props the SDK and its styles rely on', () => { + const onKeyDown = vi.fn(); + const { container } = renderInMock( + row {index}} + onKeyDown={onKeyDown} + role='listbox' + style={{ overflowX: 'hidden' }} + totalCount={5} + />, + ); + const root = container.firstElementChild as HTMLElement; + expect(root.getAttribute('data-virtuoso-scroller')).toBe('true'); + expect(root).toHaveClass('str-chat__thread-list'); + expect(root.getAttribute('role')).toBe('listbox'); + expect(root.getAttribute('aria-label')).toBe('Thread list'); + expect(root.getAttribute('tabindex')).toBe('0'); + expect(root.style.overflowX).toBe('hidden'); + expect(root.querySelector('[data-viewport-type="element"]')).not.toBeNull(); + root.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })); + expect(onKeyDown).toHaveBeenCalled(); + }); + + describe('J-08 scrollerRef', () => { + // Virtuoso's window and custom-parent viewports observe their size; jsdom has no + // ResizeObserver. + const OriginalResizeObserver = globalThis.ResizeObserver; + beforeEach(() => { + globalThis.ResizeObserver = class { + disconnect() {} + observe() {} + unobserve() {} + } as unknown as typeof ResizeObserver; + }); + afterEach(() => { + globalThis.ResizeObserver = OriginalResizeObserver; + }); + + it('gets the scroller element, then null on unmount', () => { + const scrollerRef = vi.fn(); + const { unmount } = renderInMock( + {i}} + scrollerRef={scrollerRef} + totalCount={3} + />, + ); + const element = scrollerRef.mock.calls.find( + ([value]) => value instanceof HTMLElement, + )?.[0]; + expect(element?.getAttribute('data-virtuoso-scroller')).toBe('true'); + unmount(); + expect(scrollerRef).toHaveBeenLastCalledWith(null); + }); + + it('gets the window with useWindowScroll', () => { + const scrollerRef = vi.fn(); + renderInMock( + {i}} + scrollerRef={scrollerRef} + totalCount={3} + useWindowScroll + />, + ); + expect(scrollerRef).toHaveBeenCalledWith(window); + }); + + it('gets the custom scroll parent', () => { + const scrollerRef = vi.fn(); + const parent = document.createElement('div'); + document.body.appendChild(parent); + renderInMock( + {i}} + scrollerRef={scrollerRef} + totalCount={3} + />, + ); + expect(scrollerRef).toHaveBeenCalledWith(parent); + parent.remove(); + }); + }); + + it('J-09 calls `done` once scrollIntoView rendered the target', async () => { + const ref = createRef(); + renderInMock( + row {i}} ref={ref} totalCount={200} />, + ); + const done = vi.fn(); + act(() => { + ref.current?.scrollIntoView({ done, index: 150 }); + }); + await waitFor(() => expect(done).toHaveBeenCalled(), POSITIONING_TIMEOUT); + }); + + it('J-10 GroupedVirtuoso passes flat item indexes and sticks its group wrappers', () => { + const indexes: number[] = []; + const { container } = renderInMock( + group {group}} + groupCounts={[2, 3]} + itemContent={(index) => { + indexes.push(index); + return item {index}; + }} + />, + ); + expect(indexes.slice(0, 5)).toEqual([0, 1, 2, 3, 4]); + const group = screen.getByText('group 0').parentElement as HTMLElement; + // jsdom serializes the prefixed spelling. + expect(['sticky', '-webkit-sticky']).toContain(group.style.position); + expect(container).toBeTruthy(); + }); +}); diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/positioningList.test.tsx b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/positioningList.test.tsx new file mode 100644 index 0000000000..7e5423c0dd --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/positioningList.test.tsx @@ -0,0 +1,154 @@ +import React, { forwardRef } from 'react'; +import { act, render, renderHook } from '@testing-library/react'; +import type { ListProps } from 'react-virtuoso'; + +import { + ListPositioningReporterContext, + makePositioningReportingList, +} from '../positioningList'; +import { useAfterInitialLocation } from '../useAfterInitialLocation'; + +const flushFrame = () => new Promise((resolve) => requestAnimationFrame(resolve)); + +// A custom list that keeps no test ID and ignores the style it is given. +const BareList = forwardRef(function BareList( + { children }, + ref, +) { + return ( +
+ {children} +
+ ); +}); + +describe('makePositioningReportingList', () => { + const renderList = ( + List: ReturnType, + report: (hidden: boolean) => void, + visibility?: 'hidden', + ) => ( + + +
item
+
+
+ ); + + it("reports a custom list hidden from Virtuoso's style, whatever markup it renders", () => { + const report = vi.fn(); + const List = makePositioningReportingList(BareList as never); + const { container, rerender, unmount } = render(renderList(List, report, 'hidden')); + expect(container.querySelector('[data-custom-list]')).not.toBeNull(); + expect(container.querySelector('[data-testid]')).toBeNull(); + expect(report).toHaveBeenLastCalledWith(true); + rerender(renderList(List, report)); + expect(report).toHaveBeenLastCalledWith(false); + rerender(renderList(List, report, 'hidden')); + unmount(); + expect(report).toHaveBeenLastCalledWith(false); + }); + + it('leaves the report to the main list: the top-item list neither reports nor clears it', () => { + // Virtuoso renders the items pinned by `topItemCount` with the same `components.List`; that + // list unmounting while the main one is still hidden must not report the list shown. + const report = vi.fn(); + const List = makePositioningReportingList(); + const { unmount } = render( + + +
pinned
+
+
, + ); + unmount(); + expect(report).not.toHaveBeenCalled(); + }); + + it("renders Virtuoso's own list as Virtuoso does, without the context prop", () => { + const report = vi.fn(); + const List = makePositioningReportingList(); + const { container } = render(renderList(List, report, 'hidden')); + const list = container.querySelector( + '[data-testid="virtuoso-item-list"]', + ); + expect(list?.tagName).toBe('DIV'); + expect(list?.style.visibility).toBe('hidden'); + expect(list?.hasAttribute('context')).toBe(false); + expect(report).toHaveBeenLastCalledWith(true); + }); +}); + +describe('useAfterInitialLocation', () => { + it('runs at once while the list is shown', () => { + const hiddenRef = { current: false }; + const { result } = renderHook(() => useAfterInitialLocation(hiddenRef, 0)); + const callback = vi.fn(); + result.current(callback); + expect(callback).toHaveBeenCalledTimes(1); + }); + + const withFakeTimeouts = async (body: () => Promise) => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + await body(); + } finally { + vi.useRealTimers(); + } + }; + + it('waits while the list is hidden, and runs once it is shown', () => + withFakeTimeouts(async () => { + const hiddenRef = { current: true }; + const { result } = renderHook(() => useAfterInitialLocation(hiddenRef, 0)); + const callback = vi.fn(); + result.current(callback); + await act(flushFrame); + await act(flushFrame); + vi.advanceTimersByTime(100); + expect(callback).not.toHaveBeenCalled(); + hiddenRef.current = false; + await act(flushFrame); + vi.advanceTimersByTime(100); + expect(callback).toHaveBeenCalledTimes(1); + })); + + it('drops a pending callback when the list is replaced (a jump remounts it)', () => + withFakeTimeouts(async () => { + const hiddenRef = { current: false }; + const { rerender, result } = renderHook( + ({ listKey }) => useAfterInitialLocation(hiddenRef, listKey), + { initialProps: { listKey: 0 } }, + ); + const callback = vi.fn(); + hiddenRef.current = true; + result.current(callback); + hiddenRef.current = false; + await act(flushFrame); + // The settle timeout is pending when the next jump replaces the list. + rerender({ listKey: 1 }); + vi.advanceTimersByTime(100); + expect(callback).not.toHaveBeenCalled(); + })); + + it('waits again when the list is hidden again by the time the callback is due', () => + withFakeTimeouts(async () => { + const hiddenRef = { current: true }; + const { result } = renderHook(() => useAfterInitialLocation(hiddenRef, 0)); + const callback = vi.fn(); + result.current(callback); + hiddenRef.current = false; + await act(flushFrame); + hiddenRef.current = true; + vi.advanceTimersByTime(100); + expect(callback).not.toHaveBeenCalled(); + hiddenRef.current = false; + await act(flushFrame); + vi.advanceTimersByTime(100); + expect(callback).toHaveBeenCalledTimes(1); + })); +}); diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useMessageSetKey.test.ts b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useMessageSetKey.test.ts new file mode 100644 index 0000000000..c1a3bb8a8c --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useMessageSetKey.test.ts @@ -0,0 +1,143 @@ +import { renderHook } from '@testing-library/react'; +import type { LocalMessage } from 'stream-chat'; + +import { useMessageSetKey } from '../useMessageSetKey'; + +const set = (...ids: string[]) => ids.map((id) => ({ id }) as LocalMessage); + +const setup = (initial: LocalMessage[]) => + renderHook(({ messages }) => useMessageSetKey({ messages }).messageSetKey, { + initialProps: { messages: initial }, + }); + +describe('useMessageSetKey', () => { + it('keeps the key the list mounted with', () => { + const { rerender, result } = setup(set('a', 'b')); + const mounted = result.current; + rerender({ messages: set('a', 'b') }); + expect(result.current).toBe(mounted); + }); + + it('keeps the key when messages are appended or prepended', () => { + const { rerender, result } = setup(set('b', 'c')); + const mounted = result.current; + rerender({ messages: set('b', 'c', 'd') }); + rerender({ messages: set('a', 'b', 'c', 'd') }); + expect(result.current).toBe(mounted); + }); + + it('keeps the key when the last message is removed', () => { + const { rerender, result } = setup(set('a', 'b', 'c')); + const mounted = result.current; + rerender({ messages: set('a', 'b') }); + expect(result.current).toBe(mounted); + }); + + it('renews the key when a page overlapping the previous one replaces it from above', () => { + // A jump to a message just above the loaded page: older messages before the previous first + // one, the previous newest ones gone. + const { rerender, result } = setup(set('c', 'd', 'e', 'f')); + const before = result.current; + rerender({ messages: set('a', 'b', 'c', 'd') }); + expect(result.current).not.toBe(before); + }); + + describe('jumps', () => { + const setupWithSignal = (initial: LocalMessage[]) => + renderHook( + ({ focusSignal, messages }) => + useMessageSetKey({ focusSignal, messages }).messageSetKey, + { + initialProps: { + focusSignal: null as { messageId: string } | null, + messages: initial, + }, + }, + ); + + it('renews the key for a jump to a message that arrived with the change', () => { + // The page around the target overlaps the loaded one, so it looks like a prepend. + const { rerender, result } = setupWithSignal(set('c', 'd', 'e')); + const before = result.current; + rerender({ + focusSignal: { messageId: 'b' }, + messages: set('a', 'b', 'c', 'd', 'e'), + }); + expect(result.current).not.toBe(before); + }); + + it('renews the key when the signal renders after the messages', () => { + const { rerender, result } = setupWithSignal(set('c', 'd', 'e')); + const before = result.current; + const merged = set('a', 'b', 'c', 'd', 'e'); + rerender({ focusSignal: null, messages: merged }); + expect(result.current).toBe(before); + rerender({ focusSignal: { messageId: 'b' }, messages: merged }); + expect(result.current).not.toBe(before); + }); + + it('keeps the key for a jump to a message already shown, and renews it once per jump', () => { + const { rerender, result } = setupWithSignal(set('a', 'b', 'c')); + const before = result.current; + const signal = { messageId: 'b' }; + rerender({ focusSignal: signal, messages: set('a', 'b', 'c') }); + expect(result.current).toBe(before); + rerender({ focusSignal: signal, messages: set('a', 'b', 'c', 'd') }); + expect(result.current).toBe(before); + }); + }); + + describe('jumps to messages loaded before', () => { + const setupWithSignal = (initial: LocalMessage[]) => + renderHook( + ({ focusSignal, messages }) => + useMessageSetKey({ focusSignal, messages }).messageSetKey, + { + initialProps: { + focusSignal: null as { messageId: string } | null, + messages: initial, + }, + }, + ); + + it('keeps the key for a later jump to a message that arrived live', () => { + const { rerender, result } = setupWithSignal(set('a', 'b')); + const before = result.current; + const withLive = set('a', 'b', 'live'); + rerender({ focusSignal: null, messages: withLive }); + // The reader later finds it through search and jumps to it. + rerender({ focusSignal: { messageId: 'live' }, messages: withLive }); + expect(result.current).toBe(before); + }); + + it('keeps the key for a jump to a message an older page brought several changes ago', () => { + const { rerender, result } = setupWithSignal(set('c', 'd')); + const before = result.current; + rerender({ focusSignal: null, messages: set('a', 'b', 'c', 'd') }); + rerender({ focusSignal: null, messages: set('a', 'b', 'c', 'd', 'e') }); + rerender({ + focusSignal: { messageId: 'b' }, + messages: set('a', 'b', 'c', 'd', 'e'), + }); + expect(result.current).toBe(before); + }); + }); + + it('renews the key when the first messages arrive in an empty list', () => { + const { rerender, result } = setup([]); + const empty = result.current; + rerender({ messages: set('a') }); + expect(result.current).not.toBe(empty); + }); + + it('renews the key when the list jumps to a set without the previous first message', () => { + const { rerender, result } = setup(set('a', 'b')); + const before = result.current; + rerender({ messages: set('x', 'y') }); + const afterFirstJump = result.current; + expect(afterFirstJump).not.toBe(before); + // A second jump in the same millisecond still renews the key. + rerender({ messages: set('p', 'q') }); + expect(result.current).not.toBe(afterFirstJump); + }); +}); diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useStickToBottomOnGrowth.test.ts b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useStickToBottomOnGrowth.test.ts new file mode 100644 index 0000000000..81225063f8 --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/__tests__/useStickToBottomOnGrowth.test.ts @@ -0,0 +1,483 @@ +import { renderHook } from '@testing-library/react'; + +import { useStickToBottomOnGrowth } from '../useStickToBottomOnGrowth'; + +// jsdom has no layout: the scroller's geometry is set by hand. +const makeScroller = ({ + clientHeight = 500, + scrollHeight = 2000, + scrollTop = 1500, +} = {}) => { + const scroller = document.createElement('div'); + scroller.setAttribute('data-virtuoso-scroller', 'true'); + let height = scrollHeight; + Object.defineProperty(scroller, 'clientHeight', { + configurable: true, + value: clientHeight, + }); + Object.defineProperty(scroller, 'scrollHeight', { + configurable: true, + get: () => height, + }); + scroller.scrollTop = scrollTop; + return { + grow: (by: number) => { + height += by; + }, + scroller, + }; +}; + +const flushFrame = () => new Promise((resolve) => requestAnimationFrame(resolve)); + +const setup = ( + scroller: HTMLElement | Window | null, + { followNewItems = true, itemCount = 10, listKey = 0, threshold = 50 } = {}, +) => + renderHook((props) => useStickToBottomOnGrowth(props), { + initialProps: { followNewItems, itemCount, listKey, scroller, threshold }, + }); + +describe('useStickToBottomOnGrowth', () => { + it('keeps a list at its bottom while its content grows', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + grow(300); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('leaves a list the reader scrolled up in place', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + scroller.scrollTop = 800; + scroller.dispatchEvent(new Event('scroll')); + grow(300); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(800); + }); + + it('reads the position scrolled to before a later scroll listener grows the list', async () => { + // Virtuoso's own scroll listener, registered first, renders the newly revealed items at once. + const { grow, scroller } = makeScroller({ scrollTop: 800 }); + scroller.addEventListener('scroll', () => grow(300)); + const { result } = setup(scroller); + result.current(2000); + scroller.scrollTop = 1500; + scroller.dispatchEvent(new Event('scroll')); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('counts a position within the threshold as the bottom', async () => { + const { grow, scroller } = makeScroller({ scrollTop: 1460 }); + const { result } = setup(scroller, { threshold: 50 }); + result.current(2000); + grow(200); + result.current(2200); + await flushFrame(); + expect(scroller.scrollTop).toBe(2200); + }); + + it('in an older window, reaches the end on growth but does not follow the newer page', async () => { + // Scrolled to the end of an older window, the revealed messages measure taller: the reader is + // kept at the end, which is what loads the next newer page. That page then arrives below the + // reader (the last one turns following back on), and the list must not follow it. + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + grow(300); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + rerender({ + followNewItems: true, + itemCount: 30, + listKey: 0, + scroller, + threshold: 50, + }); + grow(1500); + result.current(3800); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('with new items not followed, keeps still for new items but not for growth', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + const settled = scroller.scrollTop; + + // A new message arrives: the list must not move. + rerender({ + followNewItems: false, + itemCount: 11, + listKey: 0, + scroller, + threshold: 50, + }); + grow(100); + result.current(2100); + await flushFrame(); + expect(scroller.scrollTop).toBe(settled); + + // The reader scrolls to the bottom, then a message already shown grows (an image loads): the + // reader stays at the bottom. + scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: 100 })); + scroller.scrollTop = 1600; + scroller.dispatchEvent(new Event('scroll')); + grow(200); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('does not undo a scroll made between the growth and its pin', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + grow(300); + result.current(2300); + // The reader scrolls up before the next frame, ahead of the scroll event. + scroller.scrollTop = 0; + await flushFrame(); + expect(scroller.scrollTop).toBe(0); + }); + + it('with new items not followed, keeps still while a new item measures in', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + const settled = scroller.scrollTop; + rerender({ + followNewItems: false, + itemCount: 11, + listKey: 0, + scroller, + threshold: 50, + }); + // Reported once at its estimated height, then again once measured, with no new item between. + grow(50); + result.current(2050); + grow(250); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(settled); + }); + + it('with new items not followed, still pins when the reader scrolls to the bottom later', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + // A message arrives (not followed) and measures in; the list keeps still. + rerender({ + followNewItems: false, + itemCount: 11, + listKey: 0, + scroller, + threshold: 50, + }); + grow(100); + result.current(2100); + await flushFrame(); + // Later the reader scrolls to the bottom, and what it reveals measures taller. + scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: 100 })); + scroller.scrollTop = 1600; + scroller.dispatchEvent(new Event('scroll')); + grow(200); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('stays at the bottom when content shrinks and the offset is compensated twice', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + // The revealed messages measure 300px shorter: the browser clamps the offset, then the list's + // own compensation subtracts the 300px again. + grow(-300); + scroller.scrollTop = 1200; + result.current(1700); + scroller.scrollTop = 900; + await flushFrame(); + expect(scroller.scrollTop).toBe(1700); + }); + + it('keeps the bottom when the list compensates a growth above the viewport first', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller, { threshold: 36 }); + result.current(2000); + scroller.dispatchEvent(new Event('scroll')); + await flushFrame(); + // A message above the viewport grows by 120px; the list shifts the offset by 72px to keep it in + // place (a scroll event, 48px short now), and only then reports the new height. + grow(120); + scroller.scrollTop = 1572; + scroller.dispatchEvent(new Event('scroll')); + result.current(2120); + await flushFrame(); + expect(scroller.scrollTop).toBe(2120); + }); + + it('does not chase the bottom once the reader scrolled away after a shrink', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + grow(-100); + result.current(1900); + scroller.scrollTop = 200; + await flushFrame(); + expect(scroller.scrollTop).toBe(200); + }); + + describe('with new items not followed', () => { + type Props = { + followNewItems: boolean; + itemCount: number; + listKey: number; + scroller: HTMLElement | Window | null; + threshold: number; + }; + const arrive = ( + rerender: (props: Props) => void, + scroller: HTMLElement, + itemCount = 11, + ) => + rerender({ + followNewItems: false, + itemCount, + listKey: 0, + scroller, + threshold: 50, + }); + + it("keeps still when the list's own compensating scroll comes between", async () => { + // A new message arrives; the list compensates a growth above the viewport (a scroll event in + // the direction of the growth, no further), then the message measures shorter than estimated. + // The compensation is no reader scroll: the list must not be pinned (pulling the reader). + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + arrive(rerender, scroller); + grow(120); + result.current(2120); + scroller.scrollTop = 1560; + scroller.dispatchEvent(new Event('scroll')); + grow(-76); + result.current(2044); + await flushFrame(); + expect(scroller.scrollTop).toBe(1560); + }); + + it('lets the reader take over with input, and then keeps them at the bottom', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + arrive(rerender, scroller); + grow(100); + result.current(2100); + await flushFrame(); + // The reader turns the wheel at the bottom; then a message already shown grows. + scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: 100 })); + scroller.scrollTop = 1600; + scroller.dispatchEvent(new Event('scroll')); + grow(200); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(2300); + }); + + it('keeps still when the reader clicks in the list without scrolling', async () => { + // A click on a message action is input, but no scroll: the new message is still not followed. + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + arrive(rerender, scroller); + const button = document.createElement('button'); + scroller.appendChild(button); + button.dispatchEvent(new Event('pointerdown', { bubbles: true })); + grow(300); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(1500); + }); + + it('keeps still when the listener re-subscribes (a new threshold) while a message is held', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + arrive(rerender, scroller); + // The viewport resizes: a new threshold re-subscribes the scroll listener. + rerender({ + followNewItems: false, + itemCount: 11, + listKey: 0, + scroller, + threshold: 60, + }); + grow(300); + result.current(2300); + await flushFrame(); + expect(scroller.scrollTop).toBe(1500); + }); + + it("keeps still when a click comes right before the list's own compensating scroll", async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + arrive(rerender, scroller); + const button = document.createElement('button'); + scroller.appendChild(button); + button.dispatchEvent(new Event('pointerdown', { bubbles: true })); + // The list compensates a growth above the viewport, then the new message measures taller. + grow(120); + result.current(2120); + scroller.scrollTop = 1560; + scroller.dispatchEvent(new Event('scroll')); + grow(100); + result.current(2220); + await flushFrame(); + expect(scroller.scrollTop).toBe(1560); + }); + + it('drops a pin scheduled before new items arrived', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller, { followNewItems: false }); + result.current(2000); + await flushFrame(); + // A message already shown grows (a pin is scheduled), then a new one arrives before it runs. + grow(100); + result.current(2100); + arrive(rerender, scroller); + await flushFrame(); + expect(scroller.scrollTop).toBe(1500); + }); + }); + + it('drops a scheduled pin when the reader starts scrolling', async () => { + // The reader scrolls up 40px before the pin runs: less than the growth could explain, but input + // shows it is the reader. + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + grow(100); + result.current(2100); + scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -40 })); + scroller.scrollTop = 1460; + await flushFrame(); + expect(scroller.scrollTop).toBe(1460); + }); + + it('does not undo a jump made after a pin, within the allowance the pin started with', async () => { + // A growth of 1000px allows 2050px of movement; the first check pins to the bottom. A jump + // (no reader input) then moves the list up by more than that from the pinned position. + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + grow(1000); + result.current(3000); + await flushFrame(); + expect(scroller.scrollTop).toBe(3000); + scroller.scrollTop = 200; + await flushFrame(); + await flushFrame(); + expect(scroller.scrollTop).toBe(200); + }); + + it('counts a scrolling key as the reader, and a key typed in a text field not', async () => { + const { grow, scroller } = makeScroller(); + const { result } = setup(scroller); + result.current(2000); + await flushFrame(); + grow(100); + result.current(2100); + // Typing in a field inside the list: no scroll, the pin goes ahead. + const input = document.createElement('input'); + scroller.appendChild(input); + input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowUp' })); + await flushFrame(); + expect(scroller.scrollTop).toBe(2100); + // PageUp on the list: the reader scrolls, and a pending pin is dropped. + grow(100); + result.current(2200); + scroller.dispatchEvent( + new KeyboardEvent('keydown', { bubbles: true, key: 'PageUp' }), + ); + scroller.scrollTop = 1700; + await flushFrame(); + expect(scroller.scrollTop).toBe(1700); + }); + + it('keeps a scroller from another window at its bottom', async () => { + // e.g. a popout rendered through a portal: no instance of this window's HTMLElement. + const iframe = document.createElement('iframe'); + document.body.appendChild(iframe); + const foreign = iframe.contentDocument!.createElement('div'); + let height = 2000; + Object.defineProperty(foreign, 'clientHeight', { configurable: true, value: 500 }); + Object.defineProperty(foreign, 'scrollHeight', { + configurable: true, + get: () => height, + }); + foreign.scrollTop = 1500; + const { result } = setup(foreign); + result.current(2000); + height = 2300; + result.current(2300); + await flushFrame(); + expect(foreign.scrollTop).toBe(2300); + iframe.remove(); + }); + + it('starts over when the list is remounted (a jump), pinning nothing for the new list', async () => { + const { grow, scroller } = makeScroller(); + const { rerender, result } = setup(scroller); + result.current(2000); + await flushFrame(); + // The jump remounts the list, which positions itself on the target; its first heights must not + // pull it to the bottom because the previous list was there. + rerender({ + followNewItems: true, + itemCount: 10, + listKey: 1, + scroller, + threshold: 50, + }); + scroller.scrollTop = 600; + result.current(3000); + grow(400); + result.current(3400); + await flushFrame(); + expect(scroller.scrollTop).toBe(600); + }); + + it('leaves a window scroller alone', () => { + const { result } = setup(window); + const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => undefined); + result.current(2000); + result.current(2300); + expect(scrollTo).not.toHaveBeenCalled(); + scrollTo.mockRestore(); + }); +}); diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/positioningList.tsx b/src/components/MessageList/hooks/VirtualizedMessageList/positioningList.tsx new file mode 100644 index 0000000000..6ab9cc8e4e --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/positioningList.tsx @@ -0,0 +1,55 @@ +import React, { + createContext, + forwardRef, + useContext, + useEffect, + useLayoutEffect, +} from 'react'; +import type { ComponentType } from 'react'; +import type { Components, ListProps } from 'react-virtuoso'; + +/** Receives whether Virtuoso keeps the item list hidden while it positions it. */ +export const ListPositioningReporterContext = createContext< + ((hidden: boolean) => void) | undefined +>(undefined); + +const useIsomorphicLayoutEffect = + typeof window !== 'undefined' ? useLayoutEffect : useEffect; + +type ListComponent = NonNullable['List']>; + +/** + * The test ID Virtuoso passes to the list of items pinned at the top (`topItemCount`), which it + * renders with the same `components.List`. It is positioned with the main list and is not reported. + */ +const TOP_ITEM_LIST_TEST_ID = 'virtuoso-top-item-list'; + +/** + * Wraps the item list (Virtuoso's own `div`, or an integrator's `components.List`) to report the + * `visibility: hidden` react-virtuoso 4 sets in the list's `style` until it reaches + * `initialTopMostItemIndex`. Read from the props Virtuoso passes, so a custom list that renders + * other markup (no test ID, its own style) is still told apart while it is positioned. + */ +export const makePositioningReportingList = ( + CustomList?: ListComponent, +) => { + const List = forwardRef( + function PositioningReportingList({ context, ...props }, ref) { + const reportFromContext = useContext(ListPositioningReporterContext); + // Read from the prop Virtuoso passes, not from what the list renders. + const report = + props['data-testid'] === TOP_ITEM_LIST_TEST_ID ? undefined : reportFromContext; + const hidden = props.style?.visibility === 'hidden'; + useIsomorphicLayoutEffect(() => { + report?.(hidden); + }, [hidden, report]); + useIsomorphicLayoutEffect(() => () => report?.(false), [report]); + if (CustomList) { + const Custom = CustomList as ComponentType; + return ; + } + return
; + }, + ); + return List as unknown as ListComponent; +}; diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/useAfterInitialLocation.ts b/src/components/MessageList/hooks/VirtualizedMessageList/useAfterInitialLocation.ts new file mode 100644 index 0000000000..f3c1fa4b58 --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/useAfterInitialLocation.ts @@ -0,0 +1,70 @@ +import { useCallback, useEffect, useRef } from 'react'; +import type { RefObject } from 'react'; + +/** Virtuoso reports at-top / at-bottom changes at most once per 50ms. */ +const STATE_REPORT_SETTLE_MS = 60; +/** Gives up waiting for the reveal after about two seconds and runs the callback anyway. */ +const MAX_WAIT_FRAMES = 120; + +/** + * react-virtuoso 4 keeps the item list hidden, at scroll offset 0, until it reaches + * `initialTopMostItemIndex`. Meanwhile it reports the list as "at the top" (and, for a short + * window, "at the bottom"), which would load a page of older (or newer) messages while the list + * is being positioned and leave it somewhere else. + * + * `listHiddenRef` holds whether the list is hidden for that, as the list itself reports it (see + * `makePositioningReportingList`), whatever markup a custom list renders. + * + * Returns a function that runs `callback` at once while the list is shown, or once it is revealed + * and Virtuoso has had time to report where the list really is. A later call replaces a pending + * one. A pending callback belongs to the list it was scheduled for: a change of `listKey` (the list + * remounted, e.g. for a jump) or unmounting cancels it, and one whose list is hidden again when it + * is due waits for that list instead. + */ +export const useAfterInitialLocation = ( + listHiddenRef: RefObject, + listKey: unknown, +) => { + const frameRef = useRef(null); + const timeoutRef = useRef | null>(null); + + const cancel = useCallback(() => { + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + if (timeoutRef.current !== null) clearTimeout(timeoutRef.current); + frameRef.current = null; + timeoutRef.current = null; + }, []); + + // Runs on unmount and whenever the list is replaced. + useEffect(() => cancel, [cancel, listKey]); + + return useCallback( + (callback: () => void) => { + cancel(); + if (!listHiddenRef.current) { + callback(); + return; + } + let frames = 0; + const poll = () => { + frameRef.current = null; + if (listHiddenRef.current && frames < MAX_WAIT_FRAMES) { + frames += 1; + frameRef.current = requestAnimationFrame(poll); + return; + } + timeoutRef.current = setTimeout(() => { + timeoutRef.current = null; + // Hidden again: another positioning started meanwhile, which must not be paged under. + if (listHiddenRef.current && frames < MAX_WAIT_FRAMES) { + frameRef.current = requestAnimationFrame(poll); + return; + } + callback(); + }, STATE_REPORT_SETTLE_MS); + }; + frameRef.current = requestAnimationFrame(poll); + }, + [cancel, listHiddenRef], + ); +}; diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/useMessageSetKey.ts b/src/components/MessageList/hooks/VirtualizedMessageList/useMessageSetKey.ts index 8048b10cd2..383507b0c1 100644 --- a/src/components/MessageList/hooks/VirtualizedMessageList/useMessageSetKey.ts +++ b/src/components/MessageList/hooks/VirtualizedMessageList/useMessageSetKey.ts @@ -2,23 +2,93 @@ import { useEffect, useRef, useState } from 'react'; import type { LocalMessage } from 'stream-chat'; type UseMessageSetKeyParams = { + /** The paginator's focus signal: a jump to a message (its ID). */ + focusSignal?: { messageId: string } | null; messages?: LocalMessage[]; }; -/** Key for the Virtuoso list, renewed when the list jumps to a new location. */ -export const useMessageSetKey = ({ messages }: UseMessageSetKeyParams) => { - const [messageSetKey, setMessageSetKey] = useState(+new Date()); - const firstMessageId = useRef(undefined); +/** + * Key for the Virtuoso list, renewed when the list jumps to a new location: + * - the shown messages no longer include the previous first message (an empty list counts as + * having none); + * - older messages arrived before the previous first message while the previous last message is + * gone: a page around a message just above the loaded one, which overlaps it. Counted as a + * prepend instead, the newest messages falling off the end would leave Virtuoso asking for items + * past the end of the list; + * - a jump targets a message that arrived above the previous first message with the change just + * before it (the page loaded around the target, overlapping the loaded one, so the change looks + * like a prepend). react-virtuoso 4 drops a scroll to the target requested while it compensates + * for a prepend. Remounted, the list opens on the target (`initialTopMostItemIndex`). + * + * Appending, prepending or removing messages keeps the key, and so does the set the list mounted + * with: remounting it would only repeat Virtuoso's initial positioning, during which + * react-virtuoso 4 hides the list. So does a jump to a message already loaded before (one that + * arrived live, one an earlier page brought), which scrolls to it. + */ +export const useMessageSetKey = ({ focusSignal, messages }: UseMessageSetKeyParams) => { + // A counter, not a timestamp: two renewals within one millisecond still change the key. + const [messageSetKey, setMessageSetKey] = useState(0); + // IDs, not the array: the array can be updated in place (see usePrependedMessagesCount). + const currentIds = useRef([]); + // The IDs before the messages last changed, which a jump's target is checked against: the + // paginator shows the page and then emits the signal, which React 17 may render separately. + const idsBeforeChange = useRef([]); + // The jump last checked, so one jump renews the key at most once. + const checkedFocusSignal = useRef(undefined); + // Counts the runs below, to tie a jump to the change of messages right before it. + const runRef = useRef(0); + const lastChangeRunRef = useRef(0); + const hasRun = useRef(false); + const messageCount = messages?.length; useEffect(() => { - const continuousSet = messages?.find( - (message) => message.id === firstMessageId.current, - ); - if (!continuousSet) { - setMessageSetKey(+new Date()); + runRef.current += 1; + const previous = currentIds.current; + const ids = (messages ?? []).map((message) => message.id); + const messagesChanged = + ids.length !== previous.length || ids.some((id, index) => id !== previous[index]); + if (messagesChanged) { + idsBeforeChange.current = previous; + currentIds.current = ids; + lastChangeRunRef.current = runRef.current; } - firstMessageId.current = messages?.[0]?.id; - }, [messages]); + if (!hasRun.current) { + hasRun.current = true; + // A jump the list mounted with is positioned by the mount itself. + checkedFocusSignal.current = focusSignal; + idsBeforeChange.current = ids; + return; + } + + let continuousSet = true; + if (messagesChanged) { + const previousFirstIndex = previous.length ? ids.indexOf(previous[0]) : -1; + continuousSet = + previousFirstIndex === 0 || + (previousFirstIndex > 0 && ids.includes(previous[previous.length - 1])); + } + + let jumpedToLoadedTarget = false; + if (focusSignal && focusSignal !== checkedFocusSignal.current) { + checkedFocusSignal.current = focusSignal; + const before = idsBeforeChange.current; + const targetIndex = ids.indexOf(focusSignal.messageId); + const previousFirstIndex = before.length ? ids.indexOf(before[0]) : -1; + jumpedToLoadedTarget = + // The change came with this jump: in this run, or in the run before when React rendered + // the page and the signal separately. + runRef.current - lastChangeRunRef.current <= 1 && + targetIndex !== -1 && + !before.includes(focusSignal.messageId) && + // It arrived above the previous first message: the change looks like a prepend. + previousFirstIndex > targetIndex; + } + + if (!continuousSet || jumpedToLoadedTarget) { + setMessageSetKey((key) => key + 1); + } + // `messageCount`: an array updated in place keeps its identity. + }, [focusSignal, messages, messageCount]); return { messageSetKey, diff --git a/src/components/MessageList/hooks/VirtualizedMessageList/useStickToBottomOnGrowth.ts b/src/components/MessageList/hooks/VirtualizedMessageList/useStickToBottomOnGrowth.ts new file mode 100644 index 0000000000..6a5a2442e1 --- /dev/null +++ b/src/components/MessageList/hooks/VirtualizedMessageList/useStickToBottomOnGrowth.ts @@ -0,0 +1,299 @@ +import { useCallback, useEffect, useRef } from 'react'; +import type { RefObject } from 'react'; + +type ScrollSnapshot = { atBottom: boolean; scrollHeight: number; scrollTop: number }; + +/** Frames after a height change in which the list is kept at its bottom. */ +const PIN_CHECK_FRAMES = 3; + +/** Input events that may scroll a list; see isScrollInput for which of them do. */ +const READER_INPUT_EVENTS = ['wheel', 'touchmove', 'keydown', 'pointerdown'] as const; + +/** Keys that scroll a list whose content (or the list itself) has focus. */ +const SCROLL_KEYS = new Set([ + ' ', + 'ArrowDown', + 'ArrowUp', + 'End', + 'Home', + 'PageDown', + 'PageUp', +]); + +const isEditable = (target: Element) => + target.closest( + 'input, textarea, select, [contenteditable=""], [contenteditable="true"]', + ) !== null; + +// Whether an input event is a reader scrolling the list, as opposed to using its content: a click +// or tap on a message action, typing, a key that activates a button. A wheel turn and a touch +// that moves scroll; a press scrolls only on the scroller itself (its scrollbar); a key scrolls +// when it is a scrolling key outside a text field (and, for the space bar, outside a control). +const isScrollInput = (event: Event, scroller: Element) => { + if (event.type === 'wheel' || event.type === 'touchmove') return true; + if (event.type === 'pointerdown') return event.target === scroller; + if (event.type !== 'keydown') return false; + const { key, target } = event as KeyboardEvent; + if (!SCROLL_KEYS.has(key)) return false; + if (!(target instanceof Element) || target === scroller) return true; + if (isEditable(target)) return false; + return key !== ' ' || target.closest('button, a[href], [role="button"]') === null; +}; + +/** How long after reader input the next scroll counts as the reader's. */ +const READER_INPUT_SCROLL_WINDOW_MS = 300; + +// Whether a scroll moved the list in the direction its height changed, by no more than that: the +// list compensating for content that grew (or shrank) above the viewport, not a reader. +const isCompensatingScroll = (previous: ScrollSnapshot, next: ScrollSnapshot) => { + const moved = next.scrollTop - previous.scrollTop; + const grew = next.scrollHeight - previous.scrollHeight; + return ( + grew !== 0 && + Math.sign(moved) === Math.sign(grew) && + Math.abs(moved) <= Math.abs(grew) + 1 + ); +}; + +// The list's own scroll element; a window has no `scrollTop` and is left alone. Duck-typed, as a +// scroller from another window (a popout) is no instance of this window's `HTMLElement`, and a +// server render has no `HTMLElement` at all. +const asScrollElement = (scroller: HTMLElement | Window | null) => + scroller && 'scrollTop' in scroller ? scroller : null; + +export type UseStickToBottomOnGrowthParams = { + /** + * False while new items must not scroll the list: an older window (a page of newer messages + * loads at its bottom, below the reader), `suppressAutoscroll`. Growth that comes with a change + * of `itemCount` is then left alone, as it is when this turns true with that change (the last + * newer page of an older window). Growth of the items already shown (one measuring taller, an + * image loading) still keeps the reader at the bottom. + */ + followNewItems: boolean; + /** Number of items in the list, to tell new items from items that grew. */ + itemCount: number; + /** + * True while Virtuoso keeps the list hidden to position it (react-virtuoso 4, on mount and after + * a jump): the list is going where Virtuoso takes it, and is left alone meanwhile. + */ + listHiddenRef?: RefObject; + /** + * Identifies the list; a change means it was remounted (a jump), and the new list positions + * itself: nothing known about the previous one (at the bottom, a pin in progress) carries over. + */ + listKey: unknown; + /** The element Virtuoso scrolls; a window scroller is left alone, and so is `null`. */ + scroller: HTMLElement | Window | null; + /** Distance from the bottom, in pixels, that still counts as being at the bottom. */ + threshold: number; +}; + +/** + * Keeps a list that sits at its bottom there while its content changes height: a message rendered + * for the first time measures taller (or shorter) than estimated, an image loads, a reply streams + * in. Virtuoso keeps the scroll offset in those cases (or over-compensates it), which leaves the + * reader short of the latest message. + * + * Whether the list sits at its bottom is taken from the last scroll, so a growth, which fires no + * scroll event, does not change it. Returns the handler for Virtuoso's `totalListHeightChanged`. + * Only the list's own scroller is moved; a window or custom scroll parent scrolls the page, which + * the list does not own. + */ +export const useStickToBottomOnGrowth = ({ + followNewItems, + itemCount, + listHiddenRef, + listKey, + scroller, + threshold, +}: UseStickToBottomOnGrowthParams) => { + const element = asScrollElement(scroller); + const atBottomRef = useRef(false); + // The geometry at the last two scroll events, to tell the list's own compensation from a reader. + const lastScrollRef = useRef(null); + const previousScrollRef = useRef(null); + const lastHeightRef = useRef(0); + const frameRef = useRef(null); + // The pin in progress: where the list was when it started, and how far the height changes since + // then can move it without the reader (see the callback below). + const pinRef = useRef<{ + explainedMove: number; + /** The offset the last check left the list at. */ + lastTop: number; + scrollTopAtStart: number; + } | null>(null); + // New items arrived while they are not to be followed: the growth that follows (those items + // measuring in) is theirs, so the list keeps still until the reader scrolls again. Input alone (a + // click on a message action) is no scroll, and a scroll the list makes to compensate for that + // growth is not the reader's. Noted while + // rendering, as Virtuoso (a child) reports the new height from its layout effects, before any of + // this component's effects run; repeating it in a StrictMode double render changes nothing. + const holdUntilScrollRef = useRef(false); + const itemCountRef = useRef(itemCount); + const followNewItemsRef = useRef(followNewItems); + // When the reader last gave input that may scroll the list, until a scroll follows it: only that + // scroll is the reader's. A later one (the list compensating a new message) is not. + const readerInputAtRef = useRef(null); + if (itemCount > itemCountRef.current && !(followNewItems && followNewItemsRef.current)) + holdUntilScrollRef.current = true; + itemCountRef.current = itemCount; + followNewItemsRef.current = followNewItems; + + // A remounted list starts over. Reset while rendering, as the new list reports its first heights + // from its layout effects, before this component's effects run; repeating it changes nothing. + const listKeyRef = useRef(listKey); + if (listKeyRef.current !== listKey) { + listKeyRef.current = listKey; + atBottomRef.current = false; + lastScrollRef.current = null; + previousScrollRef.current = null; + lastHeightRef.current = 0; + holdUntilScrollRef.current = false; + pinRef.current = null; + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + frameRef.current = null; + } + + useEffect(() => { + if (!element) return; + const readSnapshot = (): ScrollSnapshot => { + atBottomRef.current = + element.scrollHeight - element.scrollTop - element.clientHeight <= threshold; + return { + atBottom: atBottomRef.current, + scrollHeight: element.scrollHeight, + scrollTop: element.scrollTop, + }; + }; + const onScroll = () => { + const next = readSnapshot(); + const last = lastScrollRef.current; + const inputAt = readerInputAtRef.current; + readerInputAtRef.current = null; + const byReader = + inputAt !== null && performance.now() - inputAt <= READER_INPUT_SCROLL_WINDOW_MS; + if (byReader || !last || !isCompensatingScroll(last, next)) { + holdUntilScrollRef.current = false; + } + previousScrollRef.current = last; + lastScrollRef.current = next; + }; + // A reader scrolling takes over: a pin scheduled for an earlier growth must not pull them back, + // even when their first scroll is still within what that growth could explain. The hold on new + // items is released only by the scroll that follows (see onScroll). + const onReaderInput = (event: Event) => { + if (!isScrollInput(event, element)) return; + readerInputAtRef.current = performance.now(); + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + frameRef.current = null; + pinRef.current = null; + }; + // Seeds the geometry when subscribing (a new scroller, a new threshold). That is no scroll: it + // must not release the hold on new messages, nor use up a reader's input. + previousScrollRef.current = lastScrollRef.current; + lastScrollRef.current = readSnapshot(); + // Capture: runs before Virtuoso's own scroll listener, which renders the newly revealed items at + // once and so changes the height this reads. What counts is where the reader scrolled to. + element.addEventListener('scroll', onScroll, { capture: true, passive: true }); + READER_INPUT_EVENTS.forEach((type) => + element.addEventListener(type, onReaderInput, { capture: true, passive: true }), + ); + return () => { + element.removeEventListener('scroll', onScroll, { capture: true }); + READER_INPUT_EVENTS.forEach((type) => + element.removeEventListener(type, onReaderInput, { capture: true }), + ); + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + frameRef.current = null; + pinRef.current = null; + }; + }, [element, threshold]); + + // Whether the last scroll moved the list in the direction its height changed, by no more than + // that, from a position at the bottom: the list compensating for content growing (or shrinking) + // above the viewport, which fires a scroll event before the new height is reported. A reader + // scrolling up moves against the growth, or further than it. + const isLayoutCompensation = useCallback(() => { + const previous = previousScrollRef.current; + const last = lastScrollRef.current; + // An empty list (no taller than its viewport) has nothing to compensate: a list mounting empty + // is "at the bottom", and its first move is Virtuoso positioning it as the messages arrive. + if (!previous?.atBottom || !last || !element) return false; + if (previous.scrollHeight <= element.clientHeight) return false; + return isCompensatingScroll(previous, last); + }, [element]); + + return useCallback( + (height: number) => { + const previousHeight = lastHeightRef.current; + lastHeightRef.current = height; + // The first report is the list's own initial layout, which Virtuoso positions itself. + if (previousHeight === 0) return; + const change = height - previousHeight; + if (change === 0 || !element) return; + if (holdUntilScrollRef.current || listHiddenRef?.current) { + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + frameRef.current = null; + pinRef.current = null; + return; + } + // Virtuoso reports the new height before the DOM has it, and may compensate the scroll offset + // for it a frame later: when content at the bottom measures shorter than estimated, the browser + // clamps the offset and Virtuoso then subtracts the difference again, which leaves a gap. The + // messages revealed by a scroll re-measure over several frames, each report moving the list + // again. So the list is checked over the next few frames and pinned whenever it is short of the + // bottom; a report during a pin extends it. It stops when the list moved up by more than the + // height changes since it started could explain (twice each, as Virtuoso may compensate a + // change twice), or when something moved it down short of the bottom (a jump, a positioning + // scroll): neither is the list's own compensation. A reader scrolling away gives input, which + // ends the pin at once (see onReaderInput). + const pin = pinRef.current; + if (pin && element.scrollTop <= pin.lastTop + 1) { + pin.explainedMove += 2 * Math.abs(change); + } else { + pinRef.current = null; + if (!atBottomRef.current && !isLayoutCompensation()) return; + pinRef.current = { + explainedMove: 2 * Math.abs(change) + threshold, + lastTop: element.scrollTop, + scrollTopAtStart: element.scrollTop, + }; + } + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + let framesLeft = PIN_CHECK_FRAMES; + const check = () => { + frameRef.current = null; + const current = pinRef.current; + // New items that are not to be followed may have arrived since this was scheduled, or the + // list is being positioned again. + if (!current || holdUntilScrollRef.current || listHiddenRef?.current) { + pinRef.current = null; + return; + } + const short = element.scrollHeight - element.scrollTop - element.clientHeight > 1; + if ( + current.scrollTopAtStart - element.scrollTop > current.explainedMove || + (short && element.scrollTop > current.lastTop + 1) + ) { + pinRef.current = null; + return; + } + if (short) { + // From here on the list's movement is measured from where this pin left it, against what + // is left of the allowance once the movement tolerated so far is taken off it: a jump that + // moves the list up from the pinned bottom is not mistaken for compensation and undone. + const tolerated = Math.max(0, current.scrollTopAtStart - element.scrollTop); + element.scrollTop = element.scrollHeight; + current.explainedMove = Math.max(threshold, current.explainedMove - tolerated); + current.scrollTopAtStart = element.scrollTop; + } + current.lastTop = element.scrollTop; + framesLeft -= 1; + if (framesLeft > 0) frameRef.current = requestAnimationFrame(check); + else pinRef.current = null; + }; + frameRef.current = requestAnimationFrame(check); + }, + [element, isLayoutCompensation, listHiddenRef, threshold], + ); +}; diff --git a/src/components/MessageList/index.ts b/src/components/MessageList/index.ts index 373ad8cc85..7383ce373a 100644 --- a/src/components/MessageList/index.ts +++ b/src/components/MessageList/index.ts @@ -1,5 +1,6 @@ export * from './GiphyPreviewMessage'; export * from './MessageList'; +export * from './MessageListPositioningUI'; export * from './NewMessageNotification'; export * from './ScrollToLatestMessageButton'; export * from './UnreadMessagesNotification'; diff --git a/src/components/MessageList/styling/VirtualizedMessageList.scss b/src/components/MessageList/styling/VirtualizedMessageList.scss index 797bd4587c..3672679848 100644 --- a/src/components/MessageList/styling/VirtualizedMessageList.scss +++ b/src/components/MessageList/styling/VirtualizedMessageList.scss @@ -38,6 +38,16 @@ position: absolute; } + // Over the list while react-virtuoso keeps it hidden to position it (opening the list, a jump). + &__positioning { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + pointer-events: none; + } + p { margin: 0 !important; // always use padding, margin mess up the height calculations diff --git a/src/components/Threads/ThreadList/ThreadList.tsx b/src/components/Threads/ThreadList/ThreadList.tsx index a9b5bf5e8d..b2b86e5916 100644 --- a/src/components/Threads/ThreadList/ThreadList.tsx +++ b/src/components/Threads/ThreadList/ThreadList.tsx @@ -23,6 +23,7 @@ import { useTranslationContext, } from '../../../context'; import { useStateStore } from '../../../store'; +import { asVirtuosoSlot } from '../../../utils/virtuosoSlot'; import { ThreadListHeader as DefaultThreadListHeader } from './ThreadListHeader'; const noThreads: Thread[] = []; @@ -129,8 +130,8 @@ export const ThreadList = ({ virtuosoProps }: ThreadListProps) => { atBottomStateChange={(atBottom) => atBottom && client.threads.paginator.toTail()} className='str-chat__thread-list' components={{ - EmptyPlaceholder: ThreadListEmptyUI, - Footer: ThreadListLoadingNextPageUI, + EmptyPlaceholder: asVirtuosoSlot(ThreadListEmptyUI), + Footer: asVirtuosoSlot(ThreadListLoadingNextPageUI), }} computeItemKey={computeItemKey} data={threads} diff --git a/src/context/ComponentContext.tsx b/src/context/ComponentContext.tsx index bcc1f7f0ef..8e7d114a76 100644 --- a/src/context/ComponentContext.tsx +++ b/src/context/ComponentContext.tsx @@ -26,6 +26,7 @@ import { type MessageBouncePromptProps, type MessageDeletedProps, type MessageListItemProps, + type MessageListPositioningUIProps, type MessageListWrapperProps, type MessageProps, type MessageReactionsDetailProps, @@ -297,6 +298,13 @@ export type ComponentContextValue = { /** Bubble of a deleted message. */ MessageDeletedBubble?: React.ComponentType; MessageListMainPanel?: React.ComponentType; + /** + * Rendered over `VirtualizedMessageList` at all times, with `isPositioning` true while + * react-virtuoso keeps the list hidden to position it (opening the list, a channel switch, a + * jump; about a quarter of a second). The default shows the `LoadingIndicator` meanwhile. A custom + * one can render anything, or animate the change (fade the list in, say). `null` renders nothing. + */ + MessageListPositioningUI?: React.ComponentType | null; /** A single notification in `NotificationList`. */ Notification?: React.ForwardRefExoticComponent< NotificationProps & React.RefAttributes diff --git a/src/plugins/ChannelDetail/VirtualizedList/VirtualizedList.tsx b/src/plugins/ChannelDetail/VirtualizedList/VirtualizedList.tsx index e2d6e16ab5..2ca5aad4ad 100644 --- a/src/plugins/ChannelDetail/VirtualizedList/VirtualizedList.tsx +++ b/src/plugins/ChannelDetail/VirtualizedList/VirtualizedList.tsx @@ -4,6 +4,8 @@ import React, { forwardRef, useCallback, useMemo } from 'react'; import type { ComputeItemKey, VirtuosoProps } from 'react-virtuoso'; import { Virtuoso } from 'react-virtuoso'; +import { asVirtuosoSlot } from '../../../utils/virtuosoSlot'; + // Wraps the virtualized item list so views can attach padding to a stable class instead of // Virtuoso's internal markup. const VirtualizedListContent = forwardRef>( @@ -58,8 +60,8 @@ export const VirtualizedList = ({ const components = useMemo( () => ({ - EmptyPlaceholder, - Footer, + EmptyPlaceholder: asVirtuosoSlot(EmptyPlaceholder), + Footer: asVirtuosoSlot(Footer), List: VirtualizedListContent, }), [EmptyPlaceholder, Footer], diff --git a/src/utils/virtuosoSlot.ts b/src/utils/virtuosoSlot.ts new file mode 100644 index 0000000000..a75e8cacc7 --- /dev/null +++ b/src/utils/virtuosoSlot.ts @@ -0,0 +1,12 @@ +import type { ComponentType } from 'react'; +import type { ContextProp } from 'react-virtuoso'; + +/** + * Types a component that ignores Virtuoso's `context` as a Virtuoso slot (`EmptyPlaceholder`, + * `Footer`, …). Since react-virtuoso 4, every slot is typed as receiving `context`; Virtuoso does + * pass it, and a component that does not read it ignores the extra prop, so only the type changes. + */ +export const asVirtuosoSlot = ( + Component: ComponentType | undefined, +): ComponentType> | undefined => + Component as ComponentType> | undefined; diff --git a/vitest.browser.setup.ts b/vitest.browser.setup.ts new file mode 100644 index 0000000000..39bacac87b --- /dev/null +++ b/vitest.browser.setup.ts @@ -0,0 +1,10 @@ +// Setup for the real-browser projects (`*.browser.test.tsx`). Unlike jsdom, the browser lays the +// list out, so the SDK's own styles are loaded: item measurements depend on them. +import '@testing-library/jest-dom/vitest'; +import './src/styling/index.scss'; + +document.documentElement.style.setProperty('font-family', 'Arial, sans-serif'); + +// The browser renders asynchronously as in an app: React's `act()` batching would hide exactly the +// frame-by-frame behavior these suites observe, and warns about every update made outside it. +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = false; diff --git a/vitest.config.ts b/vitest.config.ts index 362820d44f..f69079a592 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,7 +1,80 @@ -import { resolve } from 'path'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'path'; +import type { BrowserCommand } from 'vitest/node'; import { defineConfig } from 'vitest/config'; +import { playwright } from '@vitest/browser-playwright'; +import type { PlaywrightBrowserProvider } from '@vitest/browser-playwright'; import getPackageVersion from './scripts/get-package-version.mjs'; +const BROWSER_TEST_GLOB = 'src/**/*.browser.test.{ts,tsx}'; + +/** Where the browser suites write the scroll traces compared by `scripts/compare-virtuoso-traces.mts`. */ +const VIRTUOSO_TRACE_DIR = resolve(__dirname, '.virtuoso-traces'); + +// Lets a browser test persist a trace: the test runs in the page, which has no file system. +const writeVirtuosoTrace: BrowserCommand<[name: string, json: string]> = async ( + { project }, + name, + json, +) => { + // `project.name` carries the browser instance, e.g. `browser-v4 (chromium)`. + const runtime = project.name.replace(/ \(.*\)$/, ''); + const file = resolve(VIRTUOSO_TRACE_DIR, runtime, `${name}.json`); + await mkdir(dirname(file), { recursive: true }); + await writeFile(file, json); +}; + +// CPU throttling through the Chrome DevTools Protocol, for scenarios that only fail under load. +const setCpuThrottlingRate: BrowserCommand<[rate: number]> = async (context, rate) => { + if (context.provider.name !== 'playwright') return false; + const { page } = (context.provider as PlaywrightBrowserProvider).getCommandsContext( + context.sessionId, + ); + if (page.context().browser()?.browserType().name() !== 'chromium') return false; + const session = await page.context().newCDPSession(page); + await session.send('Emulation.setCPUThrottlingRate', { rate }); + return true; +}; + +/** + * A real-layout project. `virtuosoModule` swaps the `react-virtuoso` runtime the SDK source is + * bundled against, so the same suites run against two versions and their traces can be diffed. + */ +const browserProject = (name: string, virtuosoModule?: string) => ({ + define: { + VIRTUOSO_TEST_FUZZ_SEEDS: JSON.stringify(process.env.VIRTUOSO_FUZZ_SEEDS ?? ''), + VIRTUOSO_TEST_MUTATION: JSON.stringify(process.env.VIRTUOSO_MUTATION ?? ''), + VIRTUOSO_TEST_RUNTIME: JSON.stringify(name), + }, + extends: true as const, + // Discovered late, these would make Vite re-optimize and reload the page mid-run. + optimizeDeps: { + include: ['react-dom/client', virtuosoModule ?? 'react-virtuoso', 'stream-chat'], + }, + resolve: virtuosoModule + ? { alias: [{ find: /^react-virtuoso$/, replacement: virtuosoModule }] } + : undefined, + test: { + browser: { + commands: { setCpuThrottlingRate, writeVirtuosoTrace }, + enabled: true, + headless: true, + instances: [{ browser: 'chromium' as const }], + provider: playwright({ contextOptions: { timezoneId: 'UTC' } }), + screenshotFailures: false, + viewport: { height: 900, width: 1200 }, + }, + css: true, + // Real layout and timing: suites in one file must not race each other's frames. + fileParallelism: false, + globals: true, + include: [BROWSER_TEST_GLOB], + name, + setupFiles: ['./vitest.browser.setup.ts'], + testTimeout: 60000, + }, +}); + export default defineConfig({ define: { 'process.env.STREAM_CHAT_REACT_VERSION': JSON.stringify(getPackageVersion()), @@ -24,26 +97,44 @@ export default defineConfig({ ], }, test: { - globals: true, - environment: 'jsdom', - setupFiles: ['./vitest.setup.ts'], - include: ['src/**/*.test.{js,jsx,ts,tsx}'], - exclude: ['**/node_modules/**', '**/examples/**', '**/__snapshots__/**', '**/e2e/**'], - pool: 'forks', - watch: false, - testTimeout: 15000, - fileParallelism: true, - css: false, coverage: { - provider: 'v8', - reporter: ['json', 'text-summary'], - include: ['src/**/*.{ts,tsx,js,jsx}'], exclude: [ 'src/**/__tests__/**', 'src/mock-builders/**', 'src/@types/**', 'src/**/*.json', ], + include: ['src/**/*.{ts,tsx,js,jsx}'], + provider: 'v8', + reporter: ['json', 'text-summary'], }, + projects: [ + { + extends: true, + test: { + css: false, + environment: 'jsdom', + exclude: [ + '**/node_modules/**', + '**/examples/**', + '**/__snapshots__/**', + '**/e2e/**', + BROWSER_TEST_GLOB, + ], + fileParallelism: true, + globals: true, + include: ['src/**/*.test.{js,jsx,ts,tsx}'], + name: 'jsdom', + pool: 'forks', + setupFiles: ['./vitest.setup.ts'], + testTimeout: 15000, + }, + }, + // The runtime the package ships with. + browserProject('browser-v4'), + // The previous runtime, kept only while the react-virtuoso v4 upgrade is verified. + browserProject('browser-v2', 'react-virtuoso-v2'), + ], + watch: false, }, }); diff --git a/yarn.lock b/yarn.lock index 354f0e53b2..528c9b1c61 100644 --- a/yarn.lock +++ b/yarn.lock @@ -337,6 +337,13 @@ __metadata: languageName: node linkType: hard +"@blazediff/core@npm:1.9.1": + version: 1.9.1 + resolution: "@blazediff/core@npm:1.9.1" + checksum: 10c0/fd45cdd0544002341d74831a179ef693a81414abd348c1ff0c01086c0ea03f5e5ee284c4e16c2e6fb3670c265f90a3d85752b9360320efa9a835928e604dae77 + languageName: node + linkType: hard + "@braintree/sanitize-url@npm:^7.1.2": version: 7.1.2 resolution: "@braintree/sanitize-url@npm:7.1.2" @@ -1958,6 +1965,13 @@ __metadata: languageName: node linkType: hard +"@polka/url@npm:^1.0.0-next.24": + version: 1.0.0-next.29 + resolution: "@polka/url@npm:1.0.0-next.29" + checksum: 10c0/0d58e081844095cb029d3c19a659bfefd09d5d51a2f791bc61eba7ea826f13d6ee204a8a448c2f5a855c17df07b37517373ff916dd05801063c0568ae9937684 + languageName: node + linkType: hard + "@preact/signals-core@npm:^1.14.2": version: 1.14.5 resolution: "@preact/signals-core@npm:1.14.5" @@ -4126,6 +4140,41 @@ __metadata: languageName: node linkType: hard +"@vitest/browser-playwright@npm:4.1.9": + version: 4.1.9 + resolution: "@vitest/browser-playwright@npm:4.1.9" + dependencies: + "@vitest/browser": "npm:4.1.9" + "@vitest/mocker": "npm:4.1.9" + tinyrainbow: "npm:^3.1.0" + peerDependencies: + playwright: "*" + vitest: 4.1.9 + peerDependenciesMeta: + playwright: + optional: false + checksum: 10c0/4c042c980bb0aa950646d4d1f0f131f44156141d86f54eb96f5f69863ed05720cac7ef1a0901ab71e18929a62c41e5d64a428b2612ea708905bf423ff961dcf4 + languageName: node + linkType: hard + +"@vitest/browser@npm:4.1.9": + version: 4.1.9 + resolution: "@vitest/browser@npm:4.1.9" + dependencies: + "@blazediff/core": "npm:1.9.1" + "@vitest/mocker": "npm:4.1.9" + "@vitest/utils": "npm:4.1.9" + magic-string: "npm:^0.30.21" + pngjs: "npm:^7.0.0" + sirv: "npm:^3.0.2" + tinyrainbow: "npm:^3.1.0" + ws: "npm:^8.19.0" + peerDependencies: + vitest: 4.1.9 + checksum: 10c0/9ff634e56b0bd5a3727f2eec7666f97a089b92fb596d5b9e4fbe2a2e4fd988aa7a7bd2a7b98d7cf14790717db69db8f72bae6dc007f2fac613b9bb93d8e8edfb + languageName: node + linkType: hard + "@vitest/coverage-v8@npm:^4.1.9": version: 4.1.9 resolution: "@vitest/coverage-v8@npm:4.1.9" @@ -9557,6 +9606,13 @@ __metadata: languageName: node linkType: hard +"mrmime@npm:^2.0.0": + version: 2.0.1 + resolution: "mrmime@npm:2.0.1" + checksum: 10c0/af05afd95af202fdd620422f976ad67dc18e6ee29beb03dd1ce950ea6ef664de378e44197246df4c7cdd73d47f2e7143a6e26e473084b9e4aa2095c0ad1e1761 + languageName: node + linkType: hard + "ms@npm:^2.1.1, ms@npm:^2.1.2, ms@npm:^2.1.3": version: 2.1.3 resolution: "ms@npm:2.1.3" @@ -10508,6 +10564,13 @@ __metadata: languageName: node linkType: hard +"pngjs@npm:^7.0.0": + version: 7.0.0 + resolution: "pngjs@npm:7.0.0" + checksum: 10c0/0d4c7a0fd476a9c33df7d0a2a73e1d56537628a668841f6995c2bca070cf30819f9254a64363266bc14ef2fee47659dd3b4f2b18eec7ab65143015139f497b38 + languageName: node + linkType: hard + "possible-typed-array-names@npm:^1.0.0": version: 1.1.0 resolution: "possible-typed-array-names@npm:1.1.0" @@ -10976,7 +11039,7 @@ __metadata: languageName: node linkType: hard -"react-virtuoso@npm:^2.19.1": +"react-virtuoso-v2@npm:react-virtuoso@2.19.1": version: 2.19.1 resolution: "react-virtuoso@npm:2.19.1" dependencies: @@ -10989,6 +11052,16 @@ __metadata: languageName: node linkType: hard +"react-virtuoso@npm:^4.18.22": + version: 4.18.22 + resolution: "react-virtuoso@npm:4.18.22" + peerDependencies: + react: ">=16 || >=17 || >= 18 || >= 19" + react-dom: ">=16 || >=17 || >= 18 || >=19" + checksum: 10c0/b3ec29ad9ed949dea258beae7a78c0437c9afea2237512fe8b2978101a94ef4bb3c7f725a27848cd453a9ddf657bb29af057eb3aeee0193be7c0c84d8e09a212 + languageName: node + linkType: hard + "react@npm:^19.2.6": version: 19.2.6 resolution: "react@npm:19.2.6" @@ -11807,6 +11880,17 @@ __metadata: languageName: node linkType: hard +"sirv@npm:^3.0.2": + version: 3.0.2 + resolution: "sirv@npm:3.0.2" + dependencies: + "@polka/url": "npm:^1.0.0-next.24" + mrmime: "npm:^2.0.0" + totalist: "npm:^3.0.0" + checksum: 10c0/5930e4397afdb14fbae13751c3be983af4bda5c9aadec832607dc2af15a7162f7d518c71b30e83ae3644b9a24cea041543cc969e5fe2b80af6ce8ea3174b2d04 + languageName: node + linkType: hard + "skin-tone@npm:^2.0.0": version: 2.0.0 resolution: "skin-tone@npm:2.0.0" @@ -12016,6 +12100,7 @@ __metadata: "@types/react-dom": "npm:^19.2.3" "@types/react-syntax-highlighter": "npm:^15.5.13" "@types/use-sync-external-store": "npm:^1.5.0" + "@vitest/browser-playwright": "npm:4.1.9" "@vitest/coverage-v8": "npm:^4.1.9" "@vitest/eslint-plugin": "npm:^1.6.20" chart.js: "npm:^4.5.1" @@ -12043,6 +12128,7 @@ __metadata: lodash.uniqby: "npm:^4.7.0" mdast-util-to-string: "npm:^4.0.0" nanoid: "npm:^3.3.12" + playwright: "npm:1.60.0" prettier: "npm:^3.8.3" react: "npm:^19.2.6" react-chartjs-2: "npm:^5.3.1" @@ -12053,7 +12139,8 @@ __metadata: react-player: "npm:2.10.1" react-syntax-highlighter: "npm:^16.1.0" react-textarea-autosize: "npm:^8.5.9" - react-virtuoso: "npm:^2.19.1" + react-virtuoso: "npm:^4.18.22" + react-virtuoso-v2: "npm:react-virtuoso@2.19.1" remark-gfm: "npm:^4.0.1" remark-parse: "npm:^11.0.0" sass: "npm:^1.100.0" @@ -12599,6 +12686,13 @@ __metadata: languageName: node linkType: hard +"totalist@npm:^3.0.0": + version: 3.0.1 + resolution: "totalist@npm:3.0.1" + checksum: 10c0/4bb1fadb69c3edbef91c73ebef9d25b33bbf69afe1e37ce544d5f7d13854cda15e47132f3e0dc4cafe300ddb8578c77c50a65004d8b6e97e77934a69aa924863 + languageName: node + linkType: hard + "tough-cookie@npm:^6.0.1": version: 6.0.1 resolution: "tough-cookie@npm:6.0.1" @@ -13566,6 +13660,21 @@ __metadata: languageName: node linkType: hard +"ws@npm:^8.19.0": + version: 8.22.2 + resolution: "ws@npm:8.22.2" + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ">=5.0.2" + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + checksum: 10c0/77e7f9b2a4b790419bbc799b519a74e856ad0adb46ba0b22445f96d493ca6d4c8758643dc07f1de1f0609ed318bc329571d09a3e6b5327677b5ec31aca730a45 + languageName: node + linkType: hard + "xml-name-validator@npm:^5.0.0": version: 5.0.0 resolution: "xml-name-validator@npm:5.0.0"