Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify conversation entry positioning (#1084)

Gener746f40a544a4
diff --git a/scripts/ci/app-store-capture.test.ts b/scripts/ci/app-store-capture.test.ts
index 7f54c8083..f4753b7ff 100644
--- a/scripts/ci/app-store-capture.test.ts
+++ b/scripts/ci/app-store-capture.test.ts
@@ -1,5 +1,4 @@
import { spawn } from "node:child_process"
-import { createHash } from "node:crypto"
import { once } from "node:events"
import { existsSync } from "node:fs"
import { readFile } from "node:fs/promises"
@@ -9,6 +8,7 @@ import { resolve } from "node:path"
import sharp from "sharp"
import { describe, expect, it, vi } from "vitest"
import { captures, selectCaptures, captureArtwork, captureInputHashes, main, stopCaptureProcess } from "../../src/web/app-store-capture/capture.mjs"
+import { assertArtworkHash, assertArtworkProvenance } from "./artwork-manifest"
const root = resolve(import.meta.dirname, "../..")
const captureRoot = resolve(root, "src/web/app-store-capture")
@@ -50,16 +50,18 @@ describe("component-rendered App Store artwork", () => {
expect(lintProject.include).toContain("app-store-capture/**/*")
})
- it("ships actual component viewports and JPEGs bound to the current direct source inputs", async () => {
+ it("ships actual component viewports and JPEGs bound to their recorded render inputs", async () => {
const manifest = JSON.parse(await readFile(resolve(root, "assets/app-store/manifest.json"), "utf8"))
expect(manifest).toMatchObject({ clock: "2026-10-25T00:00:00Z", locale: "en-US", timezone: "UTC" })
+ expect(manifest.renderer).toMatch(/^\d+\./)
+ expect(manifest.repositoryHead).toMatch(/^[a-f0-9]{40}$/)
expect(manifest.outputs.filter(output => output.path !== "overview.jpg").map(output => output.path)).toEqual(captures.map(capture => capture.filename))
for (const capture of captures) {
const bytes = await readFile(resolve(root, "assets/app-store", capture.filename))
const metadata = await sharp(bytes).metadata()
expect(metadata).toMatchObject({ format: "jpeg", width: capture.width, height: capture.height, channels: 3, hasAlpha: false, space: "srgb" })
const output = manifest.outputs.find(output => output.path === capture.filename)
- expect(output.sha256).toBe(createHash("sha256").update(bytes).digest("hex"))
+ assertArtworkHash(bytes, output.sha256)
expect(output.surfaces.length).toBeGreaterThan(0)
for (const surface of output.surfaces) {
expect(surface.rootFontSize).toBe("16px")
@@ -72,19 +74,7 @@ describe("component-rendered App Store artwork", () => {
}
const duo = manifest.outputs.find(output => output.path === "duo-2007x2853/06-existing-setup.jpg")
expect(duo.surfaces.map(surface => [surface.width, surface.height])).toEqual([[951, 669], [466, 678]])
- expect(manifest.inputs).toEqual(await captureInputHashes())
- if (manifest.renderBatches) {
- const paths = manifest.renderBatches.flatMap(batch => batch.outputPaths)
- expect(paths.length).toBe(new Set(paths).size)
- expect([...paths].sort()).toEqual(captures.map(capture => capture.filename).sort())
- for (const batch of manifest.renderBatches) {
- expect(batch.renderer).toMatch(/^\d+\./)
- expect(batch.clock).toBe(manifest.clock)
- expect(Object.keys(batch.inputs).sort()).toEqual(Object.keys(manifest.inputs).sort())
- expect(Object.values(batch.inputs).every(hash => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash))).toBe(true)
- }
- expect(manifest.renderBatches.at(-1).inputs).toEqual(manifest.inputs)
- }
+ assertArtworkProvenance(manifest, captures.map(capture => capture.filename))
})
it("keeps the original source-package manifests as history rather than live screenshot inputs", async () => {
diff --git a/scripts/ci/app-store-creative.test.ts b/scripts/ci/app-store-creative.test.ts
index ed34ba6b7..73eba0211 100644
--- a/scripts/ci/app-store-creative.test.ts
+++ b/scripts/ci/app-store-creative.test.ts
@@ -1,11 +1,11 @@
-import { createHash } from "node:crypto"
import { readFile } from "node:fs/promises"
import { createServer, Server } from "node:http"
import { createRequire } from "node:module"
import { resolve } from "node:path"
import sharp from "sharp"
import { describe, expect, it, vi } from "vitest"
-import { creativeCaptures, selectCreatives, creativeInputHashes, startCreativeServer, captureCreatives, main } from "../../src/web/app-store-capture/creative/capture.mjs"
+import { creativeCaptures, selectCreatives, startCreativeServer, captureCreatives, main } from "../../src/web/app-store-capture/creative/capture.mjs"
+import { assertArtworkHash, assertArtworkProvenance } from "./artwork-manifest"
const root = resolve(import.meta.dirname, "../..")
const { chromium } = createRequire(resolve(root, "src/web/package.json"))("@playwright/test")
@@ -90,13 +90,15 @@ describe("App Store creative PNG capture", () => {
const source = JSON.parse(await readFile(resolve(root, "src/web/app-store-capture/creative/source.json"), "utf8"))
expect(manifest.approvedPrototypeSha256).toBe(source.approvedPrototypeSha256)
expect(manifest.encoding).toBe("RGB PNG")
+ expect(manifest.renderer).toMatch(/^\d+\./)
+ expect(manifest.repositoryHead).toMatch(/^[a-f0-9]{40}$/)
expect(manifest.outputs.map(output => output.path)).toEqual(creativeCaptures.map(capture => capture.filename))
- expect(manifest.inputs).toEqual(await creativeInputHashes())
+ assertArtworkProvenance(manifest, creativeCaptures.map(capture => capture.filename))
for (const capture of creativeCaptures) {
const bytes = await readFile(resolve(directory, capture.filename))
expect(await sharp(bytes).metadata()).toMatchObject({ format: "png", width: capture.width, height: capture.height, channels: 3, hasAlpha: false, space: "srgb" })
const output = manifest.outputs.find(output => output.asset === capture.asset)
- expect(output.sha256).toBe(createHash("sha256").update(bytes).digest("hex"))
+ assertArtworkHash(bytes, output.sha256)
expect(output.fontsLoaded).toBe(true)
expect(output.images).toHaveLength(5)
expect(output.criticalBounds).toHaveLength(8)
diff --git a/scripts/ci/artwork-manifest.test.ts b/scripts/ci/artwork-manifest.test.ts
new file mode 100644
index 000000000..dca3b14cd
--- /dev/null
+++ b/scripts/ci/artwork-manifest.test.ts
@@ -0,0 +1,69 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join, resolve } from "node:path"
+import { describe, expect, it } from "vitest"
+import { artworkInputHashes } from "../../src/web/app-store-capture/provenance.mjs"
+import { assertArtworkHash, assertArtworkProvenance } from "./artwork-manifest"
+
+const root = resolve(import.meta.dirname, "../..")
+const gallery = JSON.parse(readFileSync(join(root, "assets/app-store/manifest.json"), "utf8"))
+const creative = JSON.parse(readFileSync(join(root, "assets/app-store/creative/manifest.json"), "utf8"))
+const paths = gallery.outputs.map(output => output.path)
+const batches = () => ({ ...gallery, renderBatches: [
+ { renderer: gallery.renderer, clock: gallery.clock, inputs: creative.inputs, outputPaths: paths.slice(0, 1) },
+ { renderer: gallery.renderer, clock: gallery.clock, inputs: gallery.inputs, outputPaths: paths.slice(1) },
+] })
+
+describe("saved artwork integrity independent of current source", () => {
+ it("keeps real recorded digests valid after their source bytes change", () => {
+ const directory = mkdtempSync(join(tmpdir(), "alook-saved-artwork-"))
+ try {
+ const file = join(directory, "surface.css")
+ writeFileSync(file, "body { color: red }")
+ const inputs = artworkInputHashes([file], [])
+ const saved = { inputs }
+ assertArtworkProvenance(saved, [])
+ writeFileSync(file, "body { color: blue }")
+ expect(artworkInputHashes([file], [])).not.toEqual(inputs)
+ expect(() => assertArtworkProvenance(saved, [])).not.toThrow()
+ expect(saved.inputs).toBe(inputs)
+ } finally { rmSync(directory, { recursive: true, force: true }) }
+ })
+ it("accepts historical batches with different real source closures", () => {
+ expect(Object.keys(creative.inputs).sort()).not.toEqual(Object.keys(gallery.inputs).sort())
+ expect(() => assertArtworkProvenance(batches(), paths)).not.toThrow()
+ expect(() => assertArtworkProvenance(creative, creative.outputs.map(output => output.path))).not.toThrow()
+ })
+ it.each([null, [], {}, { source: "invalid" }, { "": Object.values(gallery.inputs)[0] }, { source: 42 }])("rejects malformed saved inputs %j", inputs => {
+ expect(() => assertArtworkProvenance({ inputs }, paths)).toThrow("Invalid recorded artwork inputs")
+ })
+ it.each([null, {}, []])("rejects invalid batch collections %j", renderBatches => {
+ expect(() => assertArtworkProvenance({ ...gallery, renderBatches }, paths)).toThrow("Invalid artwork render batches")
+ })
+ it.each([null, { renderer: "invalid" }, { clock: "wrong" }, { outputPaths: [] }, { outputPaths: [null] }, { inputs: {} }])("rejects malformed batch %j", change => {
+ const manifest = batches()
+ manifest.renderBatches[0] = change === null ? null : { ...manifest.renderBatches[0], ...change }
+ expect(() => assertArtworkProvenance(manifest, paths)).toThrow()
+ })
+ it.each(["duplicate", "missing", "latest-inputs", "latest-key-set", "latest-value"])("rejects inconsistent %s records", change => {
+ const manifest = batches()
+ if (change === "duplicate") manifest.renderBatches[1].outputPaths.push(paths[0])
+ if (change === "missing") manifest.renderBatches[1].outputPaths.pop()
+ if (change === "latest-inputs") manifest.renderBatches[1].inputs = creative.inputs
+ if (change === "latest-key-set") manifest.renderBatches[1].inputs = { ...gallery.inputs, ...creative.inputs }
+ if (change === "latest-value") {
+ const [key, hash] = Object.entries(gallery.inputs)[0]
+ manifest.renderBatches[1].inputs = { ...gallery.inputs, [key]: Object.values(gallery.inputs).find(value => value !== hash) }
+ }
+ expect(() => assertArtworkProvenance(manifest, paths)).toThrow()
+ })
+ it("still rejects corrupted output bytes and missing or malformed output hashes", () => {
+ const output = gallery.outputs[0]
+ const bytes = readFileSync(join(root, "assets/app-store", output.path))
+ expect(() => assertArtworkHash(bytes, output.sha256)).not.toThrow()
+ const corrupt = Buffer.from(bytes)
+ corrupt[0] ^= 1
+ expect(() => assertArtworkHash(corrupt, output.sha256)).toThrow("Artwork output hash mismatch")
+ for (const hash of [undefined, "invalid", gallery.outputs[1].sha256]) expect(() => assertArtworkHash(bytes, hash)).toThrow("Artwork output hash mismatch")
+ })
+})
diff --git a/scripts/ci/artwork-manifest.ts b/scripts/ci/artwork-manifest.ts
new file mode 100644
index 000000000..1c21ae6ab
--- /dev/null
+++ b/scripts/ci/artwork-manifest.ts
@@ -0,0 +1,33 @@
+import { createHash } from "node:crypto"
+
+function recordedInputs(value: unknown): asserts value is Record<string, string> {
+ if (!value || typeof value !== "object" || Array.isArray(value)
+ || !Object.keys(value).length || Object.entries(value).some(([key, hash]) => !key.trim()
+ || typeof hash !== "string" || !/^[a-f0-9]{64}$/.test(hash))) throw new Error("Invalid recorded artwork inputs")
+}
+
+export function assertArtworkProvenance(manifest: { inputs: unknown; clock?: unknown; renderBatches?: unknown }, outputPaths: string[]) {
+ recordedInputs(manifest.inputs)
+ if (manifest.renderBatches === undefined) return
+ if (!Array.isArray(manifest.renderBatches) || !manifest.renderBatches.length) throw new Error("Invalid artwork render batches")
+ const paths: string[] = []
+ for (const batch of manifest.renderBatches) {
+ if (!batch || typeof batch.renderer !== "string" || !/^\d+\./.test(batch.renderer)
+ || typeof batch.clock !== "string" || batch.clock !== manifest.clock
+ || !Array.isArray(batch.outputPaths) || !batch.outputPaths.length
+ || batch.outputPaths.some(path => typeof path !== "string" || !path)) throw new Error("Invalid artwork render batch")
+ recordedInputs(batch.inputs)
+ paths.push(...batch.outputPaths)
+ }
+ if (new Set(paths).size !== paths.length || JSON.stringify([...paths].sort()) !== JSON.stringify([...outputPaths].sort())) {
+ throw new Error("Artwork render batches must cover each output once")
+ }
+ const latest = manifest.renderBatches.at(-1).inputs as Record<string, string>
+ if (Object.keys(latest).length !== Object.keys(manifest.inputs).length
+ || Object.entries(manifest.inputs).some(([key, hash]) => latest[key] !== hash)) throw new Error("Latest artwork inputs do not match the manifest")
+}
+
+export function assertArtworkHash(bytes: Uint8Array, sha256: unknown) {
+ if (typeof sha256 !== "string" || !/^[a-f0-9]{64}$/.test(sha256)
+ || createHash("sha256").update(bytes).digest("hex") !== sha256) throw new Error("Artwork output hash mismatch")
+}
diff --git a/src/web/app-store-capture/README.md b/src/web/app-store-capture/README.md
index 9445daf53..d9c2a9a1e 100644
--- a/src/web/app-store-capture/README.md
+++ b/src/web/app-store-capture/README.md
@@ -47,9 +47,11 @@ pnpm app-store:capture --device tablet --overview --output /tmp/alook-ipad-overv
The generator starts its own Next process group on an unused loopback port and launches installed Chrome with `channel: "chrome"`, without an existing profile. It opens the narrow community general channel through its actual control, waits for real surfaces, fonts and images, rejects unexpected external requests/resource errors, captures each poster and validates RGB JPEG metadata. Success, errors and signals close its owned browser and Next group. Fixtures require no private account, backend write or production credentials.
-`manifest.json` records actual Chrome version, source/asset hashes and a renderer dependency projection, repository HEAD, fixed fixture reference clock (2026-10-25 UTC), locale/timezone, measured viewports and output hashes. An optional `renderBatches` list preserves the actual renderer/input hashes and output paths when unchanged images are retained across a targeted rerender. The committed Duo-only revision retains the eighteen phone/iPad images under their earlier batch; the latest `inputs` belong to the new six-image Duo batch. A complete default run replaces this with a fresh single-run manifest. Uncommitted candidates additionally need their full review tree/file binding. The gallery follows local runtime imports from its templates and includes explicit CSS/font/asset inputs. `renderer:pnpm-dependencies` hashes the selected renderer packages and their locked transitive package/snapshot records, including integrity, peer resolutions and relevant patches. The creative renderer selects only Playwright and Sharp with their closures. The entire lockfile and root package metadata are not screenshot inputs, so unrelated upgrades or script edits do not require recapture. This is a conservative source-import closure, not a tree-shaken browser bundle graph; browser/font rasterization can still change bytes. Review actual composition and native-size changed regions as well as hashes.
+`manifest.json` records actual Chrome version, source/asset hashes and a renderer dependency projection, repository HEAD, fixed fixture reference clock (2026-10-25 UTC), locale/timezone, measured viewports and output hashes. Committed images and manifests retain the inputs from their actual render; ordinary source changes do not require recapture. CI checks declared files, actual output hashes, dimensions/encoding, saved measurements, well-formed recorded input digests and batch consistency. It does not compare historical input hashes or batch input-key sets with today's source graph. Missing or corrupt outputs and malformed or inconsistent provenance still fail. Like `readme-capture`, generation happens only when someone explicitly runs the documented capture command.
-See [SOURCES.md](SOURCES.md) for component, reference and geometry provenance. Edit a composition or fixture consumer, regenerate the affected complete set and review every story/crop. Keep production rendering free of capture flags. Creative product-page headers/search artwork are separate from these screenshots; their central template safe area does not constrain these screenshot layouts. These marketing renders do not prove native layout parity, store acceptance or a particular installed build.
+An optional `renderBatches` list preserves the actual renderer/input hashes and output paths when unchanged images are retained across a targeted rerender. The committed Duo-only revision retains the eighteen phone/iPad images under their earlier batch; the latest `inputs` belong to the new six-image Duo batch. A complete default run replaces this with a fresh single-run manifest. Uncommitted candidates additionally need their full review tree/file binding. The gallery follows local runtime imports from its templates and includes explicit CSS/font/asset inputs. `renderer:pnpm-dependencies` hashes the selected renderer packages and their locked transitive package/snapshot records, including integrity, peer resolutions and relevant patches. The creative renderer selects only Playwright and Sharp with their closures. The entire lockfile and root package metadata are not screenshot inputs, so unrelated upgrades or script edits do not require recapture. This is a conservative source-import closure, not a tree-shaken browser bundle graph; browser/font rasterization can still change bytes. Review actual composition and native-size changed regions as well as hashes.
+
+See [SOURCES.md](SOURCES.md) for component, reference and geometry provenance. When an artwork update is requested, run the manual command for the affected complete set and review every selected story/crop. Each manual run still records its real current source/dependency hashes. Keep prior source hashes and untouched output bytes for retained images; do not re-hash old pictures to claim a new render. Keep production rendering free of capture flags. Creative product-page headers/search artwork are separate from these screenshots; their central template safe area does not constrain these screenshot layouts. These marketing renders do not prove native layout parity, store acceptance or a particular installed build.
## Product-page header and search creatives
diff --git a/src/web/app-store-capture/SOURCES.md b/src/web/app-store-capture/SOURCES.md
index e602bf9f7..3b49aef66 100644
--- a/src/web/app-store-capture/SOURCES.md
+++ b/src/web/app-store-capture/SOURCES.md
@@ -1,5 +1,9 @@
# Artwork sources
+## Manual generation and recorded provenance
+
+`pnpm app-store:capture` and `pnpm app-store:creative` explicitly regenerate selected artwork. Committed images remain bound to their recorded render inputs when application source changes. CI verifies stored artifacts and provenance integrity, without requiring those historical inputs to match current source. A later manual render records the actual new input closure; retained batches can have different source-key sets. Old hashes and image bytes are preserved until that artwork is deliberately updated.
+
## Current component rendering
`app/` is a local Next application outside the production router. `captures/poster.tsx` and `poster.css` retain the selected warm-orange composition, copy and illustrated hardware. Screen content comes from imported Web components, with the same data objects used by the public [Alook homepage](https://alook.ai/):
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 0a8cb299a..b4e0781fa 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -143,7 +143,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
navigationBlocked,
anchorReconciled,
readSnapshot, readSnapshotFetching, initialPositionKnown,
- initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionDataState, messageWindow,
+ initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, messageWindow,
} = useDmMessages(dmId, {
enabled: !dmBlocked && !metadata.revoked && !metadata.denied,
viewerUserId: currentUser.id,
@@ -461,6 +461,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
historyStartKnown={historyStartKnown}
initialPositionMessageId={initialPositionMessageId}
positionEntry={positionEntry}
+ positionScope={positionScope}
positionDataState={positionDataState}
messageWindow={messageWindow}
active={routeCommitted}
diff --git a/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx
new file mode 100644
index 000000000..eb508d9a9
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
+import { ForumPostList } from "./forum-post-list"
+import type { ForumThread } from "@/lib/community/models/message"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
+import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
+import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+
+beforeEach(installMessageScrollFixture)
+afterEach(restoreMessageScrollFixture)
+const posts = Array.from({ length: 40 }, (_, index) => ({ id: `p${index}`, openerMessageId: `m${index}` } as ForumThread))
+const renderPost = (post: ForumThread) => <div data-msg-id={post.openerMessageId} />
+
+describe("Forum native list identity and restoration", () => {
+ it("keeps an unscoped native list readable without creating a snapshot record", () => {
+ const view = render(<ForumPostList posts={posts} renderPost={renderPost} loadingContent={<span>Loading</span>} />)
+ resize()
+ const root = view.getByTestId("community-forum-post-list")
+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "true")
+ expect(root.scrollTop).toBe(0)
+ })
+
+ it.each(["same", "other-tag", "messages", "width", "hidden"] as const)("restores only the matching forum layout: %s", async mode => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "forum"), kind: "forum", tag: null }
+ const props = { posts, renderPost, loadingContent: <span>Loading</span>, positionScope }
+ const first = render(<ForumPostList {...props} />)
+ resize()
+ const root = first.getByTestId("community-forum-post-list")
+ act(() => root.scrollTo({ top: 800 }))
+ runFrames()
+ resize()
+ const before = root.scrollTop
+ const saved = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))
+ expect(saved?.offset).toBe(before)
+ first.unmount()
+ const scope = mode === "other-tag" ? { ...positionScope, tag: "bug" }
+ : mode === "messages" ? { ...positionScope, kind: "messages" as const } : positionScope
+ if (mode === "width") scrollFixture.width = 600
+ if (mode === "hidden") { scrollFixture.width = 0; scrollFixture.height = 0 }
+ const second = render(<ForumPostList {...props} positionScope={scope} />)
+ resize()
+ if (mode === "hidden") {
+ expect(second.getByTestId("community-forum-post-list").querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ scrollFixture.width = 320
+ scrollFixture.height = 500
+ resize()
+ }
+ const restored = second.getByTestId("community-forum-post-list")
+ expect(restored.scrollTop).toBe(mode === "same" || mode === "hidden" ? before : 0)
+ expect(restored.querySelector("[data-read-position-ready]")?.getAttribute("data-read-position-ready")).toBe("true")
+ })
+
+ it("admits a cached list after loading and retains its current instance across ordinary updates", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "forum"), kind: "forum", tag: null }
+ const props = { renderPost, loadingContent: <span>Loading</span>, positionScope }
+ const view = render(<ForumPostList {...props} posts={[]} loading />)
+ expect(view.getByText("Loading")).toBeDefined()
+ view.rerender(<ForumPostList {...props} posts={posts} />)
+ resize()
+ const root = view.getByTestId("community-forum-post-list")
+ fireEvent.wheel(root, { deltaY: 20 })
+ act(() => root.scrollTo({ top: 700 }))
+ runFrames()
+ resize()
+ view.rerender(<ForumPostList {...props} posts={posts} isFetching />)
+ resize()
+ expect(view.getByTestId("community-forum-post-list")).toBe(root)
+ expect(root.scrollTop).toBe(700)
+ })
+})
diff --git a/src/web/src/components/community/channels/forum-post-list.tsx b/src/web/src/components/community/channels/forum-post-list.tsx
new file mode 100644
index 000000000..7c9427594
--- /dev/null
+++ b/src/web/src/components/community/channels/forum-post-list.tsx
@@ -0,0 +1,147 @@
+"use client"
+
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"
+import { defaultRangeExtractor, measureElement, useVirtualizer, type Range, type Virtualizer } from "@tanstack/react-virtual"
+import { ListChevronsUpDown } from "lucide-react"
+import { hashKey } from "@tanstack/react-query"
+import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
+import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
+import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"
+import { useObservedRegion, type ResourceObservation } from "@/lib/observability/regions"
+import { visibleVirtualItems } from "@/lib/observability/virtual-window"
+import type { ForumThread } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
+import { EmptyState } from "../empty-state"
+import { VirtualRows } from "../messages/virtual-cursor-list"
+
+const OVERSCAN = 5
+const forumRangeExtractor = (range: Range) => defaultRangeExtractor({ ...range, overscan: range.overscan + range.endIndex - range.startIndex + 1 })
+type Props = {
+ posts: ForumThread[]
+ loading?: boolean
+ observation?: ResourceObservation
+ positionScope?: VirtualListPositionScope
+ hasMore?: boolean
+ loadingMore?: boolean
+ isFetching?: boolean
+ isError?: boolean
+ onLoadMore?: () => void
+ onScrollRoot?: (node: HTMLDivElement | null) => void
+ loadingContent: ReactNode
+ renderPost: (post: ForumThread, index: number) => ReactNode
+}
+
+export function ForumPostList(props: Props) {
+ return <ForumPostListEntry key={props.positionScope ? hashKey(virtualListPositionKey(props.positionScope)) : undefined} {...props} />
+}
+
+function ForumPostListEntry(props: Props) {
+ const [admitted, setAdmitted] = useState(false)
+ if (!props.loading && !admitted || props.posts.length > 0 && !admitted) setAdmitted(true)
+ if (!admitted && props.loading && !props.posts.length) return <div data-testid={tid.forumPostList} className="flex-1 overflow-y-auto thin-scrollbar px-0 py-2 sm:px-4">{props.loadingContent}</div>
+ return <ForumPostListOwner {...props} />
+}
+
+function ForumPostListOwner({ posts, loading, observation, positionScope, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost }: Props) {
+ const scrollRef = useRef<HTMLDivElement>(null)
+ const fingerprint = useMemo(() => virtualListLayoutFingerprint(posts), [posts])
+ const [initialSnapshot] = useState(() => readVirtualListPosition(positionScope, fingerprint))
+ const initialized = useRef(false)
+ const savedPosition = useRef<{ scope: VirtualListPositionScope | undefined; fingerprint: string; offset: number; width: number; height: number; total: number } | null>(null)
+ const [positionReady, setPositionReady] = useState(false)
+ const context = useRef({ positionScope, fingerprint, posts })
+ useLayoutEffect(() => { context.current = { positionScope, fingerprint, posts } }, [positionScope, fingerprint, posts])
+ const bindScrollRoot = useCallback((node: HTMLDivElement | null) => { scrollRef.current = node; onScrollRoot?.(node) }, [onScrollRoot])
+ const inspectPosition = useCallback((native: Virtualizer<HTMLDivElement, Element>) => {
+ const root = scrollRef.current
+ const current = context.current
+ if (!initialized.current || !root || !root.isConnected || root.clientWidth <= 0 || root.clientHeight <= 0
+ || native.isScrolling || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1
+ || native.options.count !== current.posts.length
+ || current.posts.some((post, index) => native.options.getItemKey(index) !== post.id)) return
+ const fold = native.getVirtualItemForOffset(root.scrollTop + 1)
+ const wrapper = fold && root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)
+ const rect = wrapper?.getBoundingClientRect()
+ const padding = Number.parseFloat(window.getComputedStyle(root).paddingTop) || 0
+ if (!fold || !rect || rect.height <= 0 || Math.abs(rect.height - fold.size) > 1
+ || Math.abs(rect.top - root.getBoundingClientRect().top + root.scrollTop - padding - fold.start) > 1) return
+ setPositionReady(true)
+ const previous = savedPosition.current
+ const total = native.getTotalSize()
+ if (previous && previous.scope === current.positionScope && previous.fingerprint === current.fingerprint
+ && previous.offset === root.scrollTop && previous.width === root.clientWidth && previous.height === root.clientHeight
+ && previous.total === total) return
+ saveVirtualListPosition(current.positionScope, {
+ version: 1, fingerprint: current.fingerprint, offset: root.scrollTop,
+ width: root.clientWidth, height: root.clientHeight,
+ paddingStart: native.options.paddingStart ?? 0, paddingEnd: native.options.paddingEnd ?? 0,
+ anchorKey: fold.key, anchorOffset: fold.start - root.scrollTop,
+ measurements: current.positionScope ? native.takeSnapshot() : [], at: Date.now(),
+ })
+ savedPosition.current = { scope: current.positionScope, fingerprint: current.fingerprint,
+ offset: root.scrollTop, width: root.clientWidth, height: root.clientHeight, total }
+ }, [])
+ const getItemKey = useCallback((index: number) => posts[index]?.id ?? index, [posts])
+ const initializePosition = useCallback((native: Virtualizer<HTMLDivElement, Element>) => {
+ const current = context.current
+ if (initialized.current || !current.posts.length || native.options.count !== current.posts.length
+ || current.posts.some((post, index) => native.options.getItemKey(index) !== post.id)) return
+ const root = scrollRef.current
+ if (initialSnapshot && (!root || root.clientWidth <= 0 || root.clientHeight <= 0)) return
+ initialized.current = true
+ if (initialSnapshot && initialSnapshot.fingerprint === current.fingerprint
+ && root?.clientWidth === initialSnapshot.width && root.clientHeight === initialSnapshot.height) {
+ if (Math.abs(root.scrollTop - initialSnapshot.offset) > 1) native.scrollToOffset(initialSnapshot.offset, { behavior: "auto" })
+ } else {
+ if (initialSnapshot) {
+ native.setOptions({ ...native.options, initialMeasurementsCache: [] })
+ native.measure()
+ }
+ native.scrollToIndex(0, { align: "start" })
+ }
+ }, [initialSnapshot])
+ // eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
+ const virtualizer = useVirtualizer({
+ ...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
+ directDomUpdatesMode: "position",
+ count: posts.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => 128,
+ measureElement: (element, entry, instance) => {
+ const size = measureElement(element, entry, instance)
+ if (size > 0) return size
+ const index = instance.indexFromElement(element)
+ const cached = instance.itemSizeCache.get(instance.options.getItemKey(index))
+ return cached && cached > 0 ? cached : instance.options.estimateSize(index)
+ },
+ getItemKey,
+ overscan: OVERSCAN,
+ rangeExtractor: forumRangeExtractor,
+ initialRect: initialSnapshot ? { width: initialSnapshot.width, height: initialSnapshot.height } : { width: 0, height: 800 },
+ initialOffset: initialSnapshot?.offset ?? 0,
+ initialMeasurementsCache: initialSnapshot?.measurements ?? [],
+ onChange: native => { initializePosition(native); inspectPosition(native) },
+ })
+ useLayoutEffect(() => {
+ initializePosition(virtualizer)
+ inspectPosition(virtualizer)
+ })
+ const virtualItems = virtualizer.getVirtualItems()
+ const range = virtualizer.range
+ const paginationItems = useMemo(() => {
+ if (!range) return []
+ const indexes = new Set(defaultRangeExtractor({ ...range, count: posts.length, overscan: OVERSCAN }))
+ return virtualItems.filter(item => indexes.has(item.index))
+ }, [posts.length, range, virtualItems])
+ const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])
+ useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)
+ useVirtualCursorPagination({
+ virtualizer: { getVirtualItems: () => paginationItems }, count: posts.length, enabled: !loading,
+ hasMore, isFetching: isFetching || loadingMore, isError, onLoad: onLoadMore, edge: "end",
+ })
+ return <div ref={bindScrollRoot} role="main" data-testid={tid.forumPostList} className="flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] px-0 py-2 sm:px-4">
+ {!posts.length ? <div data-message-list-content aria-hidden="false" data-read-position-ready="true"><EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." /></div>
+ : <VirtualRows directDomUpdatesMode="position" items={posts} virtualizer={virtualizer} renderItem={renderPost}
+ containerAttributes={{ "data-message-list-content": "", "aria-hidden": false, "data-read-position-ready": positionReady ? "true" : "false" }} />}
+ </div>
+}
diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsx
index 393b97bb5..82ea54594 100644
--- a/src/web/src/components/community/channels/forum-surface.tsx
+++ b/src/web/src/components/community/channels/forum-surface.tsx
@@ -1,6 +1,7 @@
"use client"
-import { useRef } from "react"
+import { useMemo, useRef } from "react"
+import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import type { NewForumThread } from "../messages/create-forum-thread"
@@ -32,6 +33,9 @@ export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag,
}) {
const feed = useForumFeed(serverId, forumChannelId, { routeTag, onSelectTag })
const readState = useConversationEntry(feed.selectionReady ? { channelId: forumChannelId, serverId, tag: feed.tag === "All" ? null : feed.tag } : null)
+ const proof = readState.resource?.proof
+ const positionScope = useMemo<VirtualListPositionScope | undefined>(() => readState.canRead && proof
+ ? { proof, kind: "forum", tag: feed.tag === "All" ? null : feed.tag } : undefined, [readState.canRead, proof, feed.tag])
const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
const retryScope = JSON.stringify([forumChannelId, feed.tag])
const [retryAttempt, setRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))
@@ -84,6 +88,7 @@ export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag,
}
return <ForumView
forumChannelId={forumChannelId}
+ positionScope={positionScope}
{...props}
posts={feed.posts}
observation={feed.observation}
diff --git a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
index 997fec917..12392a37a 100644
--- a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
@@ -9,7 +9,7 @@ let requestOlder: (() => void) | undefined
let sentinelEdge: string | undefined
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count, getItemKey }: { count: number; getItemKey: (index: number) => string | number }) => ({
- options: { scrollMargin: 0 },
+ options: { scrollMargin: 0, count, getItemKey },
scrollToIndex,
getTotalSize: () => count * 160,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ key: getItemKey(index), index, start: index * 160 })),
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index 3589cdb11..13b58701b 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -1,12 +1,8 @@
"use client"
-import { useObservedRegion } from "@/lib/observability/regions"
-import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { memo, useCallback, useLayoutEffect, useMemo, useRef } from "react"
-import { defaultRangeExtractor, measureElement, useVirtualizer, type Range } from "@tanstack/react-virtual"
-import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
-import { Archive, ArchiveRestore, MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"
+import { memo, useRef } from "react"
+import { Archive, ArchiveRestore, MessagesSquare, Plus, Tag, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { LineClamp } from "@/components/ui/line-clamp"
import { formatRelativeTime } from "@/lib/community/format-time"
@@ -14,7 +10,6 @@ import { Skeleton } from "@/components/ui/skeleton"
import { Avatar } from "../avatar"
import { AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
-import { EmptyState } from "../empty-state"
import { CreateForumThread, type NewForumThread } from "../messages/create-forum-thread"
import type { ComposerProps } from "../messages/composer"
import { PostTagDialog } from "./post-tag-dialog"
@@ -22,11 +17,11 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { tid } from "@/lib/community/testids"
import type { ForumThread } from "@/lib/community/models/message"
import type { Member } from "@/lib/community/models/people"
-import { VirtualRows } from "../messages/virtual-cursor-list"
-import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"
import { cn } from "@/lib/utils"
import { FORUM_ARCHIVE_TAG } from "@alook/shared"
+import { ForumPostList } from "./forum-post-list"
+import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
import {
@@ -37,13 +32,7 @@ import {
const MAX_AVATARS = 5
const MAX_VISIBLE_TAGS = 2
-const FORUM_VIRTUALIZER_DOM_MODE = "position"
-const FORUM_VIRTUALIZER_OVERSCAN = 5
const POST_ACTION_CLASS = "grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground opacity-100 sm:opacity-0 sm:group-focus-within/card:opacity-100 sm:group-hover/card:opacity-100 sm:data-popup-open:opacity-100 disabled:cursor-not-allowed disabled:opacity-50"
-const forumRangeExtractor = (range: Range) => defaultRangeExtractor({
- ...range,
- overscan: range.overscan + range.endIndex - range.startIndex + 1,
-})
export function shouldActivateForumRow(event: {
key: string
@@ -138,9 +127,10 @@ export function ForumView({
tagsKnown = true, tagsError = false, onRetryTags,
hasMore, loadingMore, isFetching, isError, onLoadMore,
onDeletePost, canDeletePost, deletingPost,
- onScrollRoot,
+ onScrollRoot, positionScope,
}: {
forumChannelId: string
+ positionScope?: VirtualListPositionScope
members: Member[]
mentionCandidates?: ComposerProps["mentionCandidates"]
observation?: import("@/lib/observability/regions").ResourceObservation
@@ -182,46 +172,6 @@ export function ForumView({
const deletingFor = posts.find((post) => post.id === deletingForId) ?? null
const setDeletingFor = (post: ForumThread | null) => setDeletingForId(post?.id ?? null)
const newPostTriggerRef = useRef<HTMLButtonElement>(null)
- const scrollRef = useRef<HTMLDivElement>(null)
- const bindScrollRoot = useCallback((node: HTMLDivElement | null) => {
- scrollRef.current = node
- onScrollRoot?.(node)
- }, [onScrollRoot])
- const alignedTagRef = useRef<string | null>(null)
- const getItemKey = useCallback((index: number) => posts[index]?.id ?? index, [posts])
- const estimateSize = useCallback(() => 128, [])
- // eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
- const virtualizer = useVirtualizer({
- ...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
- directDomUpdatesMode: FORUM_VIRTUALIZER_DOM_MODE,
- count: posts.length,
- getScrollElement: () => scrollRef.current,
- estimateSize,
- measureElement: (element, entry, instance) => {
- const size = measureElement(element, entry, instance)
- if (size > 0) return size
- const index = instance.indexFromElement(element)
- const cached = instance.itemSizeCache.get(instance.options.getItemKey(index))
- return cached && cached > 0 ? cached : instance.options.estimateSize(index)
- },
- getItemKey,
- overscan: FORUM_VIRTUALIZER_OVERSCAN,
- rangeExtractor: forumRangeExtractor,
- initialRect: { width: 0, height: 800 },
- })
- const virtualItems = virtualizer.getVirtualItems()
- const paginationRange = virtualizer.range
- const paginationItems = useMemo(() => {
- if (!paginationRange) return []
- const indexes = new Set(defaultRangeExtractor({
- ...paginationRange,
- count: posts.length,
- overscan: FORUM_VIRTUALIZER_OVERSCAN,
- }))
- return virtualItems.filter(item => indexes.has(item.index))
- }, [paginationRange, posts.length, virtualItems])
- const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])
- useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)
const filterTags = [...new Set(availableTags)]
const hasArchivedPosts = filterTags.includes(FORUM_ARCHIVE_TAG)
const displayFilterTags = [
@@ -239,21 +189,6 @@ export function ForumView({
contentKey: filterTagKey,
selectedKey: tag,
})
- useLayoutEffect(() => {
- if (posts.length === 0 || alignedTagRef.current === tag) return
- alignedTagRef.current = tag
- virtualizer.scrollToIndex(0, { align: "start" })
- }, [posts.length, tag, virtualizer])
- useVirtualCursorPagination({
- virtualizer: { getVirtualItems: () => paginationItems },
- count: posts.length,
- enabled: !loading,
- hasMore,
- isFetching: isFetching || loadingMore,
- isError,
- onLoad: onLoadMore,
- edge: "end",
- })
const closeCompose = () => {
setComposing(false)
@@ -348,23 +283,12 @@ export function ForumView({
</div>
)}
- <div
- ref={bindScrollRoot}
- role="main"
- data-testid={tid.forumPostList}
- className="flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] px-0 py-2 sm:px-4"
- >
- {loading && posts.length === 0 ? (
- <ForumListSkeleton />
- ) : posts.length === 0 ? (
- <EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." />
- ) : (
- <>
- <VirtualRows
- directDomUpdatesMode={FORUM_VIRTUALIZER_DOM_MODE}
- items={posts}
- virtualizer={virtualizer}
- renderItem={(p, index) => {
+ <ForumPostList
+ key={JSON.stringify([forumChannelId, tag])}
+ posts={posts} loading={loading} observation={observation} positionScope={positionScope}
+ hasMore={hasMore} loadingMore={loadingMore} isFetching={isFetching} isError={isError}
+ onLoadMore={onLoadMore} onScrollRoot={onScrollRoot} loadingContent={<ForumListSkeleton />}
+ renderPost={(p, index) => {
const canEdit = !!onEditPostTags && (canEditPostTags?.(p) ?? false)
const canDelete = !!onDeletePost && (canDeletePost?.(p) ?? false)
const archived = p.tags.includes(FORUM_ARCHIVE_TAG)
@@ -496,11 +420,8 @@ export function ForumView({
</div>
</div>
)
- }}
- />
- </>
- )}
- </div>
+ }}
+ />
{deletingFor && (
<ConfirmDialog
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index c242f3988..4327ef545 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -162,6 +162,7 @@ export function TextChannelSurface({
historyStartKnown={feed.historyStartKnown}
initialPositionMessageId={feed.initialPositionMessageId}
positionEntry={feed.positionEntry}
+ positionScope={feed.positionScope}
positionDataState={feed.positionDataState}
messageWindow={feed.messageWindow}
isFetching={feed.isFetching}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 3f0b000e6..52768f1e0 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -274,6 +274,7 @@ export function ThreadChannelSurface({
historyStartKnown={controller.feed.historyStartKnown}
initialPositionMessageId={controller.feed.initialPositionMessageId}
positionEntry={controller.feed.positionEntry}
+ positionScope={controller.feed.positionScope}
positionDataState={controller.feed.positionDataState}
messageWindow={controller.feed.messageWindow}
isFetching={controller.feed.isFetching}
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index 8c2e5d193..21925c516 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -21,12 +21,15 @@ const mocks = vi.hoisted(() => ({
scrollToBottom: vi.fn(),
requestPresentPosition: vi.fn(),
onImageLoad: vi.fn(),
+ finishPosition: (_outcome: "pending" | "success") => {},
captureOlderPageAnchor: vi.fn(),
captureNewerPageAnchor: vi.fn(),
}))
vi.mock("@/hooks/community/use-scroll-anchor", () => ({
- useScrollAnchor: (input: { tailPaddingEnd?: number; scrollToMessageId?: string | null; items: Array<{ kind: string; m?: { id: string } }>; onScrollTargetPositioned: (id: string) => void; onInitialPositionSettled: () => void }) => {
+ useScrollAnchor: (input: { tailPaddingEnd?: number; scrollToMessageId?: string | null; items: Array<{ kind: string; m?: { id: string } }>; onScrollTargetPositioned: (id: string) => void }) => {
+ const [positionOutcome, setPositionOutcome] = React.useState<"pending" | "success">("pending")
+ mocks.finishPosition = setPositionOutcome
const consumed = React.useRef<string | null>(null)
const loaded = input.items.some((item) => item.m?.id === input.scrollToMessageId)
React.useLayoutEffect(() => {
@@ -45,6 +48,7 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({
scrollToBottom: mocks.scrollToBottom,
requestPresentPosition: mocks.requestPresentPosition,
jumpTo: mocks.jumpToIndex,
+ positionOutcome,
readPositionReady: false,
paginationEnabled: false,
captureOlderPageAnchor: mocks.captureOlderPageAnchor,
@@ -176,12 +180,15 @@ describe("useMessageListController", () => {
it("requires a new positioning settlement for a fresh entry on the retained list", () => {
const value = props({ positionEntry: {} })
const view = rtlRender(React.createElement(Probe, { value }))
- const settled = () => (mocks.scrollInputs.at(-1) as { onInitialPositionSettled: () => void }).onInitialPositionSettled()
+ const settled = () => mocks.finishPosition("success")
act(settled)
expect(latest.initialPosition.phase).toBe("revealed")
view.rerender(React.createElement(Probe, { value: { ...value } }))
expect(latest.initialPosition.phase).toBe("revealed")
- view.rerender(React.createElement(Probe, { value: { ...value, positionEntry: {} } }))
+ act(() => {
+ mocks.finishPosition("pending")
+ view.rerender(React.createElement(Probe, { value: { ...value, positionEntry: {} } }))
+ })
expect(latest.initialPosition.phase).toBe("positioning")
act(settled)
expect(latest.initialPosition.phase).toBe("revealed")
@@ -221,9 +228,12 @@ describe("useMessageListController", () => {
initialScrollReady: true,
positionDataState: "pending",
positionEntry: undefined,
+ positionScope: undefined,
initialPositionMessageId: undefined,
messageWindow: undefined,
active: undefined,
+ positioningActive: undefined,
+ presentRequest: undefined,
hasMoreNewer: undefined,
isFetchingOlder: undefined,
isFetchingNewer: undefined,
@@ -231,7 +241,6 @@ describe("useMessageListController", () => {
localSubmitVersion: undefined,
hasMoreOlder: undefined,
tailPaddingEnd: 32,
- onInitialPositionSettled: expect.any(Function),
scrollToMessageId: undefined,
onScrollTargetCancelled: undefined,
onScrollTargetPositioned: expect.any(Function),
@@ -241,6 +250,7 @@ describe("useMessageListController", () => {
virtualizer: mocks.virtualizer,
count: latest.items.length,
enabled: false,
+ requestKey: undefined,
hasMore: undefined,
isFetching: undefined,
isError: false,
@@ -252,6 +262,7 @@ describe("useMessageListController", () => {
virtualizer: mocks.virtualizer,
count: latest.items.length,
enabled: false,
+ requestKey: undefined,
hasMore: undefined,
isFetching: undefined,
isError: false,
@@ -322,7 +333,7 @@ describe("useMessageListController", () => {
expect(vi.getTimerCount()).toBe(0)
})
- it("waits for the hook-owned post-action settlement callback on ordinary windows", () => {
+ it("uses the scroll owner outcome for reveal while retaining separate read qualification", () => {
let view: ReturnType<typeof rtlRender>
act(() => {
view = rtlRender(React.createElement(Probe, { value: props() }))
@@ -333,9 +344,7 @@ describe("useMessageListController", () => {
contentVisible: false,
contentInteractive: false,
})
- const settle = (mocks.scrollInputs.at(-1) as {
- onInitialPositionSettled: () => void
- }).onInitialPositionSettled
+ const settle = () => mocks.finishPosition("success")
act(() => settle())
expect(latest.initialPosition).toMatchObject({
phase: "revealed",
@@ -378,6 +387,14 @@ describe("useMessageListController", () => {
expect(mocks.scrollInputs.at(-1)).toEqual({
items: expect.any(Array),
newDividerBefore: "m1",
+ positionScope: undefined,
+ positionEntry: undefined,
+ positionDataState: undefined,
+ positioningActive: undefined,
+ messageWindow: undefined,
+ initialPositionMessageId: undefined,
+ active: undefined,
+ presentRequest: undefined,
initialScrollReady: false,
hasMoreNewer: true,
isFetchingOlder: true,
@@ -386,7 +403,6 @@ describe("useMessageListController", () => {
localSubmitVersion: undefined,
hasMoreOlder: true,
tailPaddingEnd: 32,
- onInitialPositionSettled: expect.any(Function),
scrollToMessageId: undefined,
onScrollTargetCancelled: undefined,
onScrollTargetPositioned: expect.any(Function),
@@ -396,6 +412,7 @@ describe("useMessageListController", () => {
virtualizer: mocks.virtualizer,
count: latest.items.length,
enabled: false,
+ requestKey: undefined,
hasMore: true,
isFetching: true,
isError: false,
@@ -407,6 +424,7 @@ describe("useMessageListController", () => {
virtualizer: mocks.virtualizer,
count: latest.items.length,
enabled: false,
+ requestKey: undefined,
hasMore: true,
isFetching: true,
isError: false,
@@ -458,9 +476,7 @@ describe("useMessageListController", () => {
})
expect((mocks.scrollInputs.at(-1) as { initialScrollReady: boolean }).initialScrollReady).toBe(true)
expect(consumed).toHaveBeenCalledOnce()
- const settleAnchor = (mocks.scrollInputs.at(-1) as {
- onInitialPositionSettled: () => void
- }).onInitialPositionSettled
+ const settleAnchor = () => mocks.finishPosition("success")
act(() => settleAnchor())
expect(latest.initialPosition.phase).toBe("revealed")
visibleMessageIds = ["m2"]
@@ -686,9 +702,7 @@ describe("useMessageListController", () => {
React.createElement(Probe, { value: props() })
)
})
- act(() => (mocks.scrollInputs.at(-1) as {
- onInitialPositionSettled: () => void
- }).onInitialPositionSettled())
+ act(() => mocks.finishPosition("success"))
expect(latest.initialPosition.phase).toBe("revealed")
expect(latest.initialPosition.phase).toBe("revealed")
act(() => latest.jumpTo("m1", "auto"))
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index f06233632..e23e7750f 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -1,6 +1,6 @@
"use client"
-import { createAtom, useAtom, useCreateAtom } from "@tanstack/react-store";
+import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useCallback, useEffect, useMemo, useRef } from "react"
import type { RenderMsg } from "@/lib/community/models/message"
import { flattenMessageItems } from "@/lib/community/message-list-items"
@@ -17,6 +17,7 @@ export function useMessageListController({
scrollToMessageId,
initialPositionMessageId,
positionEntry,
+ positionScope,
positionDataState,
messageWindow,
active,
@@ -39,8 +40,6 @@ export function useMessageListController({
}: ResolvedMessageListProps) {
const [jumpRevision, setJumpRevision] = useAtom(useCreateAtom(0))
const [jumped, setJumped] = useAtom(useCreateAtom<string | null>(null))
- const settledEntry = useMemo(() => ({ entry: positionEntry, atom: createAtom(false) }), [positionEntry])
- const [anchorPositionSettled, setAnchorPositionSettled] = useAtom(settledEntry.atom)
const items = useMemo(
() => flattenMessageItems(messages, newDividerBefore, !!hasMore, !!hasMoreNewer),
@@ -90,7 +89,6 @@ export function useMessageListController({
const isLoading = (!!loading || !!initialLoadError) && messages.length === 0
const authoritativeEmpty = !loading && !initialLoadError && messages.length === 0
- const settleAnchorPosition = useCallback(() => setAnchorPositionSettled(true), [setAnchorPositionSettled])
const {
scrollRef,
virtualizer,
@@ -104,6 +102,7 @@ export function useMessageListController({
paginationRequestPending,
captureOlderPageAnchor,
captureNewerPageAnchor,
+ positionOutcome,
} = useScrollAnchor({
items,
newDividerBefore,
@@ -111,6 +110,7 @@ export function useMessageListController({
scrollToMessageId,
initialPositionMessageId,
positionEntry,
+ positionScope,
positionDataState: positionDataState ?? (initialLoadError ? "error" : loading ? "pending" : undefined),
messageWindow,
active,
@@ -124,12 +124,11 @@ export function useMessageListController({
presentRequest,
localSubmitVersion,
hasMoreOlder: hasMore,
- onInitialPositionSettled: settleAnchorPosition,
})
const initialPosition = useInitialPositionTransition({
firstWindowReady: !isLoading && (messages.length > 0 || !initialLoadError),
authoritativeEmpty,
- positionSettled: anchorPositionSettled,
+ positionSettled: positionOutcome !== "pending",
})
useEffect(() => {
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 77a1d9720..a11801c8d 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -2,6 +2,7 @@ import type { ReactNode } from "react"
import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { MessagePositionState, MessageRequest } from "@/lib/community/message-position"
+import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
export type MessageListProps = {
observation?: import("@/lib/observability/regions").ResourceObservation
@@ -34,6 +35,7 @@ export type MessageListProps = {
scrollToMessageId?: string | null
initialPositionMessageId?: string | null
positionEntry?: object | null
+ positionScope?: VirtualListPositionScope
positionDataState?: MessagePositionState
messageWindow?: object
active?: boolean
diff --git a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
index 8cafb07ae..0154c7f64 100644
--- a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts
@@ -15,8 +15,8 @@ const target = { id: "m_target", type: "chat" as const, authorId: "user_2", auth
const unrelated = { ...target, id: "m_other", content: "Other" }
const newer = { ...target, id: "m_newer", content: "Newer", createdAt: new Date(1).toISOString() }
const consumed = vi.fn()
-function view(messages: typeof target[], scrollToMessageId: string | null) {
- return React.createElement(MessageList, { channel: "general", messages, loading: false, initialScrollReady: false, positionDataState: "ready", hasMoreNewer: true, scrollToMessageId, onScrollTargetConsumed: consumed, onOpenThread: vi.fn() })
+function view(messages: typeof target[], scrollToMessageId: string | null, positionDataState: "pending" | "ready" = "ready") {
+ return React.createElement(MessageList, { channel: "general", messages, loading: false, initialScrollReady: false, positionDataState, hasMoreNewer: true, scrollToMessageId, onScrollTargetConsumed: consumed, onOpenThread: vi.fn() })
}
function highlighted(container: HTMLElement) {
return container.querySelector('[data-row-id="m_target"]')?.getAttribute("data-highlighted") === "true"
@@ -26,7 +26,7 @@ describe("MessageList pending jump target with the installed native adapter", ()
beforeEach(() => { installMessageScrollFixture(); consumed.mockClear() })
afterEach(restoreMessageScrollFixture)
it("waits for the actual target body, consumes once, and resets after null", () => {
- const renderer = render(view([unrelated], "m_target"))
+ const renderer = render(view([unrelated], "m_target", "pending"))
resize()
expect(consumed).not.toHaveBeenCalled()
expect(renderer.container.querySelector('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "false")
diff --git a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
index bd372ceb1..3447279d4 100644
--- a/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.mount-identity.dom.test.ts
@@ -2,8 +2,11 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"
import React from "react"
import { MessageList } from "./message-list"
import { ConversationFooterShell, ConversationFooterSlotProvider } from "./conversation-footer-shell"
-import { render } from "@/test/react-dom-harness"
-import { installMessageScrollFixture, restoreMessageScrollFixture, resize, scrollFixture } from "@/test/message-scroll-fixture"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
+import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
+import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
import { tid } from "@/lib/community/testids"
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
@@ -58,4 +61,33 @@ describe("MessageList loading-to-loaded mount identity", () => {
expect(root.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height).toBe("500px")
expect(root.querySelector('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
})
+
+ it("initializes from the qualified snapshot after loading and then retains the mounted list", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const messages = Array.from({ length: 40 }, (_, index) => ({ id: `m${index}`, type: "chat" as const,
+ authorId: "peer", authorName: "Alice", content: "Message", createdAt: new Date(index * 1000).toISOString() }))
+ const props = { channel: "A", onOpenThread: () => {}, positionScope }
+ const first = render(React.createElement(MessageList, { ...props, messages }))
+ resize()
+ const root = first.getByTestId(tid.messageScroller)
+ fireEvent.wheel(root, { deltaY: -30 })
+ act(() => root.scrollTo({ top: 800 }))
+ runFrames()
+ resize()
+ const before = root.scrollTop
+ expect(client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))?.offset).toBe(before)
+ first.unmount()
+ const second = render(React.createElement(MessageList, { ...props, messages: [], loading: true, initialScrollReady: false }))
+ resize()
+ second.rerender(React.createElement(MessageList, { ...props, messages, initialScrollReady: true }))
+ resize()
+ const restored = second.getByTestId(tid.messageScroller)
+ expect(restored.scrollTop).toBeCloseTo(before, 0)
+ expect(restored.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "true")
+ second.rerender(React.createElement(MessageList, { ...props, messages, initialScrollReady: true, isFetching: true }))
+ resize()
+ expect(second.getByTestId(tid.messageScroller)).toBe(restored)
+ expect(restored.scrollTop).toBeCloseTo(before, 0)
+ })
})
diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
index 3e7444dd2..2dd934e9e 100644
--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts
@@ -4,6 +4,7 @@ import { tid } from "@/lib/community/testids"
import { act, fireEvent, render } from "@/test/react-dom-harness"
import { MessageList } from "./message-list"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames } from "@/test/message-scroll-fixture"
+import type { MessageRequestResult } from "@/lib/community/message-position"
const breakpoint = vi.hoisted(() => ({ value: "desktop" as "desktop" | "mobile" }))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => breakpoint.value }))
@@ -11,17 +12,53 @@ vi.mock("./message-row", () => ({ MessageRow: () => React.createElement("div") }
vi.mock("@/components/ui/number-ticker", () => ({ NumberTicker: ({ value }: { value: number }) => React.createElement("span", null, value) }))
describe("MessageList native range pagination", () => {
- it("loads and settles ordinary older pages after the position deadline while read remains closed", () => {
+ it.each(["response-first", "rows-first"] as const)("serializes accepted older requests through body settlement (%s)", async order => {
+ const message = (i: number) => ({ id: `m${i}`, type: "chat" as const, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(i * 1000).toISOString() })
+ let messages = Array.from({ length: 50 }, (_, i) => message(i + 40))
+ const before = {}, received = {}
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ const onLoadOlder = vi.fn(() => ({ accepted: true as const, completed }))
+ const view = (messageWindow = before, isFetchingOlder = false, positionDataState: "ready" | "pending" = "ready") => React.createElement(MessageList, {
+ channel: "general", messages, messageWindow, initialScrollReady: true, positionDataState,
+ hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn(),
+ })
+ const renderer = render(view())
+ resize()
+ const root = renderer.getByTestId(tid.messageScroller)
+ fireEvent.wheel(root, { deltaY: -30000 })
+ act(() => root.scrollTo({ top: 0 }))
+ resize()
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+ const top = renderer.getByTestId(tid.message("m40")).getBoundingClientRect().top
+ renderer.rerender(view(before, true))
+ if (order === "rows-first") {
+ messages = [...Array.from({ length: 39 }, (_, i) => message(i + 1)), ...messages]
+ renderer.rerender(view(before, true))
+ resize()
+ }
+ await act(async () => { complete({ status: "success", window: received }) })
+ renderer.rerender(view(received, false, "pending"))
+ resize()
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+ if (order === "response-first") messages = [...Array.from({ length: 39 }, (_, i) => message(i + 1)), ...messages]
+ renderer.rerender(view(received))
+ resize()
+ expect(renderer.getByTestId(tid.message("m40")).getBoundingClientRect().top).toBeCloseTo(top, 0)
+ expect(onLoadOlder).toHaveBeenCalledOnce()
+ })
+ it("loads and settles ordinary older pages after explicit positioning failure while read remains closed", () => {
const messages = Array.from({ length: 50 }, (_, i) => ({ id: `m${i}`, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))
const onLoadOlder = vi.fn()
- const view = (isFetchingOlder: boolean) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, scrollToMessageId: "not-loaded", hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
- const renderer = render(view(false))
+ const view = (isFetchingOlder: boolean, positionDataState: "pending" | "ready" | "error" = "ready") => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, positionDataState, scrollToMessageId: "not-loaded", hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
+ const renderer = render(view(false, "pending"))
resize()
const scroller = renderer.getByTestId(tid.messageScroller)
act(() => { scroller.scrollTo({ top: 0 }) })
runFrames()
expect(onLoadOlder).not.toHaveBeenCalled()
- act(() => vi.advanceTimersByTime(5000))
+ renderer.rerender(view(false, "error"))
+ renderer.rerender(view(false))
runFrames()
act(() => { scroller.scrollTo({ top: 0 }) })
resize()
@@ -43,10 +80,11 @@ describe("MessageList native range pagination", () => {
const message = (i: number) => ({ id: `m${i}`, type: "chat" as const, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(i * 1000).toISOString() })
let messages = Array.from({ length: 50 }, (_, i) => message(i + 40))
const onLoadOlder = vi.fn()
- const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, scrollToMessageId: "not-loaded", hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
- const renderer = render(view(false, fold === "header" || pendingMove))
+ const view = (isFetchingOlder: boolean, hasMore = true, positionDataState: "pending" | "ready" | "error" = "ready") => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, positionDataState, scrollToMessageId: "not-loaded", hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })
+ const renderer = render(view(false, fold === "header" || pendingMove, "pending"))
resize()
- act(() => vi.advanceTimersByTime(5000))
+ renderer.rerender(view(false, fold === "header" || pendingMove, "error"))
+ renderer.rerender(view(false, fold === "header" || pendingMove))
runFrames()
const root = renderer.getByTestId(tid.messageScroller)
act(() => root.scrollTo({ top: 0 }))
diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsx
index fa124e378..5cbc3c170 100644
--- a/src/web/src/components/community/messages/message-list.tsx
+++ b/src/web/src/components/community/messages/message-list.tsx
@@ -3,21 +3,39 @@
import { isConversationAccessError } from "@/lib/community/conversation-read"
import { useObservedRegion } from "@/lib/observability/regions"
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
-import { useContext, useLayoutEffect } from "react"
+import { useContext, useLayoutEffect, useState } from "react"
+import { hashKey } from "@tanstack/react-query"
+import { virtualListPositionKey } from "@/lib/community/virtual-list-position"
import { useMessageListController } from "./message-list-controller"
import { useHoverCapable } from "@/hooks/use-hover-capable"
import { useConversationFooterSlot } from "./conversation-footer-shell"
import type { MessageListProps, ResolvedMessageListProps } from "./message-list-types"
import { renderMessageListRow } from "./message-list-row"
-import { renderMessageListView } from "./message-list-view"
+import { MessageListSkeleton, renderMessageListView } from "./message-list-view"
import { VirtualRows } from "./virtual-cursor-list"
import { ConversationPresentationContext, useConversationActivity } from "@/contexts/community/conversation-activity"
-export function MessageList({
+export function MessageList(props: MessageListProps) {
+ return <MessageListEntry key={props.positionScope ? hashKey(virtualListPositionKey(props.positionScope)) : undefined} {...props} />
+}
+
+function MessageListEntry({
variant = "channel",
initialScrollReady = true,
...props
}: MessageListProps) {
+ const [admitted, setAdmitted] = useState(false)
+ const ready = initialScrollReady && (props.messages.length > 0 || !props.loading && !props.initialLoadError)
+ || !!props.scrollToMessageId && props.positionDataState === "ready" && props.messages.length > 0
+ if (ready && !admitted) setAdmitted(true)
+ if (props.positionScope && !admitted && !ready && !props.initialLoadError) return <MessageListSkeleton variant={variant} />
+ return <MessageListOwner {...props} variant={variant} initialScrollReady={initialScrollReady} />
+}
+
+function MessageListOwner({ variant, initialScrollReady, ...props }: MessageListProps & {
+ variant: "channel" | "dm"
+ initialScrollReady: boolean
+}) {
const hoverCapable = useHoverCapable()
const conversationActive = useConversationActivity()
const conversationPresented = useContext(ConversationPresentationContext) ?? conversationActive
diff --git a/src/web/src/components/community/messages/virtual-cursor-list.tsx b/src/web/src/components/community/messages/virtual-cursor-list.tsx
index 9ed809b1a..98415a102 100644
--- a/src/web/src/components/community/messages/virtual-cursor-list.tsx
+++ b/src/web/src/components/community/messages/virtual-cursor-list.tsx
@@ -2,7 +2,7 @@
/* eslint-disable react-hooks/refs -- TanStack Virtual exposes an imperative instance whose render-time getters and ref callbacks are its supported React API. */
-import { useLayoutEffect, type ReactNode } from "react"
+import { useLayoutEffect, type HTMLAttributes, type ReactNode } from "react"
import type { ReactVirtualizer } from "@tanstack/react-virtual"
import type { VirtualRowsLayoutSnapshot } from "@/hooks/community/virtualizer-react-options"
@@ -16,6 +16,7 @@ export function VirtualRows<T>({
children,
getRowAttributes,
onLayoutCommit,
+ containerAttributes,
}: {
items: T[]
virtualizer: ReactVirtualizer<HTMLDivElement, Element>
@@ -26,6 +27,7 @@ export function VirtualRows<T>({
children?: ReactNode
getRowAttributes?: (item: T, index: number) => Record<`data-${string}`, string | number | undefined>
onLayoutCommit?: (snapshot: VirtualRowsLayoutSnapshot | null) => void
+ containerAttributes?: Pick<HTMLAttributes<HTMLDivElement>, "aria-hidden" | "inert"> & Record<`data-${string}`, string | number | undefined>
}) {
const totalSize = reactLayout ? virtualizer.getTotalSize() : null
const virtualRows = virtualizer.getVirtualItems()
@@ -42,6 +44,7 @@ export function VirtualRows<T>({
})
return (
<div
+ {...containerAttributes}
ref={virtualizer.containerRef}
style={{
position: "relative",
diff --git a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
index a2cd177fa..ebe73c89c 100644
--- a/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
+++ b/src/web/src/components/community/messages/virtualizer-direct-dom.contract.test.ts
@@ -62,7 +62,7 @@ describe("community virtualizer direct DOM contract", () => {
})
it("keeps ForumView on the shared direct DOM row contract", () => {
- const forumView = readComponent("../channels/forum-view.tsx")
+ const forumView = readComponent("../channels/forum-post-list.tsx")
expect(forumView).toContain("...COMMUNITY_VIRTUALIZER_REACT_OPTIONS")
expect(forumView).toContain("<VirtualRows")
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index 5f46f921c..8ed9a2ff1 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -369,7 +369,7 @@ describe("conversation entry return during accepted reading", () => {
return { view, root, visible, get latest() { return latest } }
}
- it.each([30, 42])("reveals cached reading at %s through a slow real entry without granting reads or following late NEW", async readSeq => {
+ it.each([30, 42])("reveals cached reading at %s through a slow real entry without granting early reads and consumes a first late NEW once", async readSeq => {
const owner = await readingOwner()
const held = deferred<ReturnType<typeof fixture>>()
const fresh = fixture()
@@ -413,7 +413,12 @@ describe("conversation entry return during accepted reading", () => {
await act(async () => held.resolve(fresh))
await act(async () => vi.advanceTimersByTimeAsync(0))
resize()
- expect(view.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
+ if (readSeq === 30) expect(view.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
+ else {
+ const index = view.latest.controller.items.findIndex(item => item.kind === "divider" && item.newDivider && item.messageId === `m${readSeq + 1}`)
+ expect(index).toBeGreaterThanOrEqual(0)
+ expect(view.root.scrollTop).toBeCloseTo(view.latest.controller.virtualizer.getOffsetForIndex(index, "center")![0], 0)
+ }
expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(readSeq)
expect(view.latest.newDividerBefore).toBe(`m${readSeq + 1}`)
expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
index f5455bf2f..d18dd4087 100644
--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
@@ -62,8 +62,8 @@ function Conversation({ channelId, kind, anchorMessageId }: { channelId: string;
const props = { channel: "Conversation", messages: feed.messages,
loading: feed.isLoading, initialLoadError: feed.initialLoadError,
newDividerBefore: feed.newDividerBefore, initialPositionMessageId: feed.initialPositionMessageId,
- initialScrollReady: !feed.readSnapshotFetching && feed.anchorInCache,
- positionEntry: feed.positionEntry,
+ initialScrollReady: feed.initialPositionKnown,
+ positionEntry: feed.positionEntry, positionScope: feed.positionScope,
positionDataState: feed.positionDataState, messageWindow: feed.messageWindow, presentRequest: feed.presentRequest,
scrollToMessageId: channel.scrollTargetId, onScrollTargetConsumed: channel.consumeScrollTarget,
hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer, historyStartKnown: feed.historyStartKnown,
@@ -393,6 +393,49 @@ describe("conversation entry positioning through real reading owners", () => {
expect(view.root()).toBe(root)
})
+ it.each([false, true])("cancels a target lost by the current ready query window without granting its old observer a read (StrictMode=%s)", async strict => {
+ const view = await setup("channel", false, strict), root = view.root()
+ const previousRow = root.querySelector('[data-msg-id="m31"]')!
+ const previousObserver = boundObserver(previousRow)
+ const explicit = entry("channel")
+ explicit.selection = { reason: "explicit_anchor", anchorMessageId: "m5" }
+ await act(async () => { await seedConversationEntry(owner.client, explicit, {
+ channelId: "c1", serverId: "s1", anchorMessageId: "m5",
+ }) })
+ await view.navigate("/c/channels/s1/c1?msg=m5", { settle: false })
+ const positionEntry = latest.feed.positionEntry
+ expect(latest.channel.scrollTargetId).toBe("m5")
+ expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "true")
+ const covered = latest.feed.messageWindow!
+ const query = owner.client.getQueryCache().getAll().find(query => query.state.data === covered)!
+ await act(async () => {
+ owner.client.setQueryData(query.queryKey, {
+ ...covered, pages: covered.pages.map(page => ({ ...page, messages: page.messages.filter(message => message.id !== "m5") })),
+ })
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(latest.feed.positionDataState).toBe("ready")
+ expect(latest.feed.messages.some(message => message.id === "m5")).toBe(false)
+ expect(latest.feed.positionEntry).toBe(positionEntry)
+ resize()
+ expect(view.root()).toBe(root)
+ expect(latest.channel.scrollTargetId).toBeNull()
+ expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "false")
+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ await act(async () => {
+ owner.client.setQueryData(query.queryKey, covered)
+ previousObserver.callback([intersection(previousRow)], {} as IntersectionObserver)
+ await vi.advanceTimersByTimeAsync(20000)
+ })
+ resize()
+ expect(latest.feed.positionEntry).toBe(positionEntry)
+ expect(latest.channel.scrollTargetId).toBeNull()
+ expect(view.visible("m5")).toBe(false)
+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
+ expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)
+ })
+
it.each(["channel", "post", "thread"] as const)("returns to observer-admitted %s reading before PUT confirmation or canonical publication", async kind => {
const view = await setup(kind)
await view.tail()
@@ -412,7 +455,7 @@ describe("conversation entry positioning through real reading owners", () => {
expect(load.mock.calls.some(([url]) => String(url).includes("messages"))).toBe(false)
})
- it("keeps canonical landing when return precedes observer admission, ignores the retired callback and freezes late publication", async () => {
+ it("restores layout without promoting a retired observation to a reading cursor and freezes late publication", async () => {
const view = await setup("channel")
await view.tail()
const row = view.root().querySelector('[data-msg-id="m42"]')!, observer = boundObserver(row), record = intersection(row)
@@ -421,8 +464,9 @@ describe("conversation entry positioning through real reading owners", () => {
act(() => observer.callback([record], {} as IntersectionObserver))
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m31")).toBe(true)
- expect(view.visible("m42")).toBe(false)
+ expect(view.visible("m42")).toBe(true)
+ expect(view.visible("m31")).toBe(false)
+ expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
const offset = view.root().scrollTop
await view.canonical(42)
expect(latest.feed.readSnapshot?.lastReadSeq).toBe(30)
@@ -430,7 +474,7 @@ describe("conversation entry positioning through real reading owners", () => {
expect(messageOrReadRequests()).toEqual([])
})
- it.each(["threshold", "inert", "document-hidden", "own-author"] as const)("does not turn a rejected %s observation into a newer return position", async control => {
+ it.each(["threshold", "inert", "document-hidden", "own-author"] as const)("restores layout without turning a rejected %s observation into a reading cursor", async control => {
const view = await setup("channel", control === "own-author")
await view.tail()
const row = view.root().querySelector('[data-msg-id="m42"]')!, observer = boundObserver(row)
@@ -441,7 +485,9 @@ describe("conversation entry positioning through real reading owners", () => {
visibility = "visible"
await view.navigate("/c/channels/s1/c2")
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m42")).toBe(true)
+ expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
expect(messageOrReadRequests()).toEqual([])
})
})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 009619a3a..af3e626e7 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -18,6 +18,7 @@ import type { Msg } from "@/lib/community/models/message"
import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
import { ConversationReadTimeoutError, withConversationReadDeadline } from "@/lib/community/conversation-read"
import { messageReconcileOptions } from "./community-ws/reconnect-messages"
+import type { VirtualListPositionScope } from "@/lib/community/virtual-list-position"
export { channelMessagesQueryFn } from "@/lib/community/message-window"
export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"
@@ -87,6 +88,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const anchorMessageId = opts?.anchorMessageId ?? null
const entry = useConversationEntry(channelId && opts?.enabled !== false ? { channelId, serverId, anchorMessageId, tag } : null)
const proof = entry.resource?.proof
+ const positionScope = useMemo<VirtualListPositionScope | undefined>(() => entry.canRead && proof
+ ? { proof, kind: "messages", tag } : undefined, [entry.canRead, proof, tag])
const viewKey = hashKey([channelId, serverId, anchorMessageId, tag, proof?.accountEpoch ?? -1, proof?.accessEpoch ?? -1,
channelId ? proof?.channelScopes.get(channelId)?.generation ?? 0 : 0])
const present = useMemo(() => ({ viewKey, intent: entry.intent,
@@ -246,7 +249,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
navigationBlocked: !entry.canRead,
readSnapshot: entry.snapshot, readSnapshotFetching,
initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending,
- initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionDataState, messageWindow: query.data,
+ initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, messageWindow: query.data,
retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,
entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
index a3a47d327..4954a3548 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
@@ -112,7 +112,7 @@ describe("qualified positioning lifecycle", () => {
})
it.each((["local", "unread", "tail"] as const).flatMap(target => [false, true].flatMap(strict =>
- [320, 1280].map(width => [target, strict, width] as const))))("finishes cached %s positioning with StrictMode=%s at %spx while reads remain pending and retains it through late NEW", (target, strict, width) => {
+ [320, 1280].map(width => [target, strict, width] as const))))("finishes cached %s positioning with StrictMode=%s at %spx while reads remain pending and consumes late NEW at most once", (target, strict, width) => {
scrollFixture.width = width
const settled = vi.fn()
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 5 }))
@@ -134,30 +134,40 @@ describe("qualified positioning lifecycle", () => {
act(() => vi.advanceTimersByTime(6500))
h.update({ items: [...items.map(item => ({ ...item, newDivider: false })),
{ ...message("m14"), newDivider: true }, message("m15")], newDividerBefore: "m14" })
- expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ if (target === "unread") {
+ expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ expect(index).not.toHaveBeenCalled()
+ } else {
+ const targetIndex = native.getVirtualItems().find(row => row.key === "divider:msg:m14")!.index
+ expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(targetIndex, "center")![0], 0)
+ expect(index).toHaveBeenCalledOnce()
+ }
expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const landed = h.root.scrollTop
+ const commands = index.mock.calls.length
h.update({ positionDataState: "ready" })
- expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ expect(h.root.scrollTop).toBeCloseTo(landed, 0)
expect(scrollFixture.latest.readPositionReady).toBe(true)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
expect(end).not.toHaveBeenCalled()
- expect(index).not.toHaveBeenCalled()
+ expect(index).toHaveBeenCalledTimes(commands)
expect(settled).toHaveBeenCalledOnce()
})
- it("withdraws reading during a new data wait without restarting settled cached positioning", () => {
+ it("withdraws reading during a data wait and admits its first late NEW without repeating initial reveal", () => {
const settled = vi.fn()
const h = mount({ initialPositionMessageId: "m5", onInitialPositionSettled: settled })
- const before = bodyTop(h.root, "m5")
- const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ const native = scrollFixture.latest.virtualizer
+ const index = vi.spyOn(native, "scrollToIndex")
h.update({ positionDataState: "pending" })
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(false)
act(() => vi.advanceTimersByTime(6500))
h.update({ positionDataState: "ready", newDividerBefore: "m10" })
- expect(bodyTop(h.root, "m5")).toBeCloseTo(before, 0)
+ const targetIndex = native.getVirtualItems().find(row => row.key === "msg:m10")!.index
+ expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(targetIndex, "center")![0], 0)
expect(scrollFixture.latest.readPositionReady).toBe(true)
- expect(index).not.toHaveBeenCalled()
+ expect(index).toHaveBeenCalledOnce()
expect(settled).toHaveBeenCalledOnce()
})
@@ -179,50 +189,65 @@ describe("qualified positioning lifecycle", () => {
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("degrades a cached zero-size layout on the geometry deadline without claiming success or reviving", () => {
+ it("waits without application frames for a cached zero-size layout and positions after a late viewport event", () => {
scrollFixture.height = 0
const settled = vi.fn()
const h = mount({ initialScrollReady: true, positionDataState: "pending", onInitialPositionSettled: settled }, false, undefined, undefined, 0)
- runFrames(320)
- expect(settled).toHaveBeenCalledOnce()
+ runFrames(2)
+ expect(scrollFixture.frames.size).toBe(0)
+ act(() => vi.advanceTimersByTime(20000))
+ expect(settled).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
scrollFixture.height = 500
- h.update({ positionDataState: "ready" })
- expect(end).not.toHaveBeenCalled()
+ resize()
+ expect(end).toHaveBeenCalledOnce()
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(h.root.scrollTop).toBe(0)
+ const offset = h.root.scrollTop
+ h.update({ positionDataState: "ready" })
+ expect(h.root.scrollTop).toBe(offset)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("keeps only the original remaining layout budget when read state becomes pending", () => {
+ it("retains an unsettled command across a data wait and resumes from an actual viewport change", () => {
scrollFixture.height = 0
const settled = vi.fn()
const h = mount({ onInitialPositionSettled: settled }, false, undefined, undefined, 0)
act(() => vi.advanceTimersByTime(4800))
h.stage({ positionDataState: "pending" })
scrollFixture.height = 500
- resize(0)
- vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
- runFrames(1)
- act(() => vi.advanceTimersByTime(184))
+ const scroll = vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
+ resize(400)
+ act(() => vi.advanceTimersByTime(10000))
+ expect(settled).not.toHaveBeenCalled()
+ expect(scrollFixture.frames.size).toBe(0)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ scroll.mockRestore()
+ scrollFixture.width = 390
+ resize()
expect(settled).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(false)
h.update({ positionDataState: "ready" })
- expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("leaves the visible cached fallback when its initial local target is absent and the budget expires", () => {
+ it("waits for an absent local target without polling and finishes through its current data event", () => {
const settled = vi.fn()
const h = mount({ initialPositionMessageId: "missing", positionDataState: "pending", onInitialPositionSettled: settled })
- const before = bodyTop(h.root, "m0")
- act(() => vi.advanceTimersByTime(5000))
- expect(settled).toHaveBeenCalledOnce()
+ act(() => vi.advanceTimersByTime(10000))
+ expect(settled).not.toHaveBeenCalled()
+ expect(scrollFixture.frames.size).toBe(0)
expect(scrollFixture.latest.readPositionReady).toBe(false)
const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
h.update({ positionDataState: "ready", items: [...h.input.items, message("missing")] })
- expect(index).not.toHaveBeenCalled()
- expect(bodyTop(h.root, "m0")).toBe(before)
- expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(index).toHaveBeenCalledOnce()
+ expect(bodyTop(h.root, "missing")).toBeGreaterThan(0)
+ expect(bodyTop(h.root, "missing")).toBeLessThan(h.root.clientHeight)
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it("keeps precommit user takeover after data and route commit arrive", () => {
@@ -311,47 +336,53 @@ describe("qualified positioning lifecycle", () => {
expect(end).not.toHaveBeenCalled()
})
- it.each([false, true])("bounds a qualified zero viewport once, including StrictMode=%s", strict => {
+ it.each([false, true])("resumes a late positive viewport without a positioning deadline, StrictMode=%s", strict => {
scrollFixture.height = 0
const h = mount({}, strict, undefined, undefined, 0)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
- act(() => vi.advanceTimersByTime(4999))
+ runFrames(2)
+ act(() => vi.advanceTimersByTime(20000))
+ expect(scrollFixture.frames.size).toBe(0)
expect(scrollFixture.latest.paginationEnabled).toBe(false)
- act(() => vi.advanceTimersByTime(1))
- expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.positionOutcome).toBe("pending")
scrollFixture.height = 500
resize()
- expect(end).not.toHaveBeenCalled()
- expect(h.root.scrollTop).toBe(0)
- expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(end).toHaveBeenCalledOnce()
+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("bounds a qualified zero-width viewport without accepting a vertical-only landing", () => {
+ it("waits for a positive width without accepting vertical-only geometry or polling", () => {
scrollFixture.width = 0
const h = mount({}, false, undefined, undefined, 0)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
- runFrames(320)
+ runFrames(2)
+ act(() => vi.advanceTimersByTime(10000))
+ expect(scrollFixture.frames.size).toBe(0)
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
scrollFixture.width = 320
resize()
- expect(end).not.toHaveBeenCalled()
- expect(h.root.scrollTop).toBe(0)
+ expect(end).toHaveBeenCalledOnce()
+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("gives a late native command only the remaining qualified budget", () => {
+ it("keeps a blocked command current past five seconds and retires it on explicit failure", () => {
scrollFixture.height = 0
const h = mount({}, false, undefined, undefined, 0)
- act(() => vi.advanceTimersByTime(4800))
scrollFixture.height = 500
- resize(0)
vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
- runFrames(1)
- act(() => vi.advanceTimersByTime(184))
- expect(cancel).toHaveBeenCalledOnce()
+ resize(400)
+ act(() => vi.advanceTimersByTime(10000))
+ expect(scrollFixture.frames.size).toBe(0)
+ expect(cancel).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ h.update({ positionDataState: "error" })
+ expect(cancel).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.positionOutcome).toBe("error")
})
it("retires hidden unfinished work and ignores all of its old frames on resume", () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
index d57ca7233..5723145be 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts
@@ -1,11 +1,120 @@
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent } from "@/test/react-dom-harness"
-import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import type { MessageRequestResult } from "@/lib/community/message-position"
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
describe("native pagination and original semantic epoch", () => {
+ it.each(["viewport", "body"] as const)("waits for a real %s geometry event after an accepted page without a frame chain", async box => {
+ const h = mount({ messageWindow: {} })
+ h.move(0)
+ const top = bodyTop(h.root, "m0")
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed }))
+ if (box === "viewport") scrollFixture.height = 0
+ else scrollFixture.bodyHeights.set("m0", 0)
+ const received = {}
+ await act(async () => { complete({ status: "success", window: received }) })
+ h.update({ items: [...Array.from({ length: 50 }, (_, i) => message(`older${i}`)), ...h.input.items], messageWindow: received })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ expect(scrollFixture.frames.size).toBe(0)
+ act(() => vi.advanceTimersByTime(20000))
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ expect(scrollFixture.frames.size).toBe(0)
+ if (box === "viewport") scrollFixture.height = 500
+ else scrollFixture.bodyHeights.set("m0", 100)
+ resize()
+ expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ expect(scrollFixture.frames.size).toBe(0)
+ })
+ it.each(["empty", "error"] as const)("retires a pending receipt when the current view becomes %s", state => {
+ const h = mount({ messageWindow: {} })
+ h.move(0)
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed: new Promise<MessageRequestResult>(() => {}) }))
+ h.update({ positionDataState: state, ...(state === "empty" ? { items: [] } : {}) })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ runFrames()
+ expect(scrollFixture.frames.size).toBe(0)
+ })
+ it.each(["error", "retired", "unchanged", "superseded"] as const)("releases a %s receipt without inventing a body position", async outcome => {
+ const before = {}, received = {}
+ const h = mount({ messageWindow: before })
+ h.move(0)
+ const top = bodyTop(h.root, "m0")
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed }))
+ await act(async () => {
+ complete(outcome === "error" || outcome === "retired" ? { status: outcome }
+ : { status: "success", window: outcome === "unchanged" ? before : received })
+ })
+ h.update({ messageWindow: outcome === "superseded" ? {} : before })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ expect(bodyTop(h.root, "m0")).toBe(top)
+ })
+ it("does not restore an accepted page after the user takes a new reading position", async () => {
+ const h = mount({ messageWindow: {} })
+ h.move(0)
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed }))
+ h.move(300)
+ const top = bodyTop(h.root, "m3")
+ const received = {}
+ await act(async () => { complete({ status: "success", window: received }) })
+ h.update({ messageWindow: received, items: [message("older"), ...h.input.items] })
+ expect(bodyTop(h.root, "m3")).toBeCloseTo(top, 0)
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ const settled = h.root.scrollTop
+ runFrames()
+ expect(h.root.scrollTop).toBe(settled)
+ })
+ it("keeps an accepted page pending until its new rows and body position commit", async () => {
+ const before = {}, received = {}
+ const h = mount({ messageWindow: before })
+ h.move(0)
+ const top = bodyTop(h.root, "m0")
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed }))
+ h.update({ isFetchingOlder: true })
+ await act(async () => { complete({ status: "success", window: received }) })
+ h.update({ messageWindow: received, isFetchingOlder: false, positionDataState: "pending" })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ expect(bodyTop(h.root, "m0")).toBe(top)
+ h.update({ positionDataState: "ready" })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ h.stage({ items: [...Array.from({ length: 50 }, (_, i) => message(`older${i}`)), ...h.input.items] })
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ runFrames()
+ expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ })
+ it("preserves the same body through a second prepend before the first command retires", async () => {
+ const h = mount({ messageWindow: {} })
+ h.move(0)
+ const top = bodyTop(h.root, "m0")
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ act(() => scrollFixture.latest.captureOlderPageAnchor()({ accepted: true, completed }))
+ const received = {}
+ await act(async () => { complete({ status: "success", window: received }) })
+ h.stage({ items: [...Array.from({ length: 50 }, (_, i) => message(`older${i}`)), ...h.input.items], messageWindow: received })
+ runFrames(1)
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
+ h.stage({ items: [...Array.from({ length: 27 }, (_, i) => message(`oldest${i}`)), ...h.input.items] })
+ scrollFixture.bodyHeights.set("older49", 144)
+ h.update({ items: [...h.input.items] })
+ expect(bodyTop(h.root, "m0")).toBeCloseTo(top, 0)
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
+ const settled = h.root.scrollTop
+ runFrames()
+ expect(h.root.scrollTop).toBe(settled)
+ })
it("restores initial New intent and bounded settling after StrictMode effect replay", () => {
const shown = vi.fn()
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
@@ -84,12 +193,12 @@ describe("native pagination and original semantic epoch", () => {
const stale = [...scrollFixture.frames.values()]
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
- h.stage({ scrollToMessageId: "unloaded" })
+ h.stage({ scrollToMessageId: "unloaded", positionDataState: "pending" })
expect(cancel).toHaveBeenCalledTimes(1)
expect(offset).not.toHaveBeenCalled()
act(() => stale.forEach(callback => callback(performance.now())))
expect(consumed).not.toHaveBeenCalled()
- h.update({ items: [...h.input.items, message("unloaded")] })
+ h.update({ items: [...h.input.items, message("unloaded")], positionDataState: "ready" })
expect(consumed).toHaveBeenCalledExactlyOnceWith("unloaded")
})
it("cancels an owned native index on user takeover without canceling ordinary native compensation", () => {
@@ -183,7 +292,7 @@ describe("native pagination and original semantic epoch", () => {
const offset = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToOffset")
act(() => scrollFixture.latest.scrollToBottom())
const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")
- h.stage({ scrollToMessageId: "unloaded" })
+ h.stage({ scrollToMessageId: "unloaded", positionDataState: "pending" })
const before = h.root.scrollTop
expect(cancel).toHaveBeenCalledOnce()
expect(offset).not.toHaveBeenCalled()
@@ -194,16 +303,18 @@ describe("native pagination and original semantic epoch", () => {
expect(offset).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
})
- it("waits for an absent explicit target, closes read, and finishes through its finite deadline", () => {
+ it("waits for an absent explicit target without polling past five seconds and finishes through its data event", () => {
const consumed = vi.fn()
const h = mount({ onScrollTargetPositioned: consumed })
- h.update({ scrollToMessageId: "not-loaded" })
+ h.update({ scrollToMessageId: "not-loaded", positionDataState: "pending" })
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(consumed).not.toHaveBeenCalled()
- act(() => vi.advanceTimersByTime(5000))
+ act(() => vi.advanceTimersByTime(20000))
expect(scrollFixture.latest.readPositionReady).toBe(false)
- h.update({ items: [...h.input.items, message("not-loaded")] })
- expect(consumed).not.toHaveBeenCalled()
+ expect(scrollFixture.frames.size).toBe(0)
+ h.update({ items: [...h.input.items, message("not-loaded")], positionDataState: "ready" })
+ expect(consumed).toHaveBeenCalledExactlyOnceWith("not-loaded")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it("opens an explicit target only after its actual body geometry and ignores target data arriving after user takeover", () => {
const consumed = vi.fn()
@@ -211,10 +322,10 @@ describe("native pagination and original semantic epoch", () => {
h.update({ scrollToMessageId: "m4" })
expect(consumed).toHaveBeenCalledWith("m4")
expect(scrollFixture.latest.readPositionReady).toBe(true)
- h.update({ scrollToMessageId: "unloaded" })
+ h.update({ scrollToMessageId: "unloaded", positionDataState: "pending" })
fireEvent.wheel(h.root, { deltaY: -20 })
runFrames()
- h.update({ items: [...h.input.items, message("unloaded")] })
+ h.update({ items: [...h.input.items, message("unloaded")], positionDataState: "ready" })
expect(consumed).toHaveBeenCalledTimes(1)
})
})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
index 32eac1f94..99b31c1b6 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
@@ -6,11 +6,13 @@ import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, mess
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
-function retiredInitialReader(onInitialPositionSettled?: () => void) {
+function failedInitialReader(onInitialPositionSettled?: () => void) {
const h = mount({ hasMoreNewer: true, onInitialPositionSettled }, false, undefined, undefined, 0)
runFrames(1)
+ h.stage({ positionDataState: "error" })
+ h.update({ positionDataState: "ready" })
act(() => h.root.scrollTo({ top: 0 }))
- runFrames(320)
+ runFrames()
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
return h
@@ -104,26 +106,26 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(end).not.toHaveBeenCalled()
expect(h.root.scrollTop).toBe(300)
})
- it("does not let a delayed frame send after the original nonempty-list budget expires", () => {
- const started = Date.now()
+ it("issues the initial command only after a positive viewport even beyond the old deadline", () => {
scrollFixture.height = 0
const shown = vi.fn()
const h = mount({ onInitialPositionSettled: shown }, false, undefined, undefined, 0)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
- act(() => vi.advanceTimersByTime(4900))
+ runFrames(2)
+ act(() => vi.advanceTimersByTime(20000))
+ expect(scrollFixture.frames.size).toBe(0)
+ expect(shown).not.toHaveBeenCalled()
scrollFixture.height = 500
resize(0)
- expect(shown).not.toHaveBeenCalled()
- vi.setSystemTime(started + 5001)
- runFrames(1)
expect(end).not.toHaveBeenCalled()
- expect(scrollFixture.latest.readPositionReady).toBe(false)
- act(() => vi.advanceTimersByTime(100))
+ expect(shown).not.toHaveBeenCalled()
+ runFrames()
+ expect(end).toHaveBeenCalledOnce()
expect(shown).toHaveBeenCalledOnce()
- resize()
- expect(end).not.toHaveBeenCalled()
- expect(h.root.scrollTop).toBe(0)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)
})
+
it("does not reissue an initial end after an external scroll retires its first native command", () => {
const h = mount({ items: Array.from({ length: 50 }, (_, index) => message(`m${index}`)) }, false, undefined, undefined, 0)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
@@ -445,7 +447,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.latest.readPositionReady).toBe(true)
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
})
- it("uses auto for loaded-tail Present and retires once at its finite deadline without reissue", () => {
+ it("uses auto for loaded-tail Present and waits without polling until an actual viewport change or user takeover", () => {
const h = mount()
h.move(0)
const native = scrollFixture.latest.virtualizer
@@ -461,11 +463,11 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.frames.size).toBe(0)
scrollFixture.width = 390
resize(2)
- expect(end).toHaveBeenCalledTimes(1)
+ expect(end).toHaveBeenCalledTimes(2)
act(() => vi.advanceTimersByTime(2100))
expect(offset).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(cancel).toHaveBeenCalledOnce()
+ expect(cancel).not.toHaveBeenCalled()
cancel.mockClear()
fireEvent.wheel(h.root, { deltaY: -20 })
expect(cancel).toHaveBeenCalledOnce()
@@ -646,7 +648,7 @@ describe("locked native adapter and existing message scroll owner", () => {
})
it("retires failed qualified positioning while keeping read and peer follow closed", () => {
const shown = vi.fn()
- const h = retiredInitialReader(shown)
+ const h = failedInitialReader(shown)
expect(shown).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
@@ -659,7 +661,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it.each([0, 2, 100, 300])("preserves a retired unconfirmed reader through composer shrink and grow at %ipx", distance => {
- const h = retiredInitialReader()
+ const h = failedInitialReader()
const native = scrollFixture.latest.virtualizer
const end = vi.spyOn(native, "scrollToEnd")
const index = vi.spyOn(native, "scrollToIndex")
@@ -687,7 +689,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(index).not.toHaveBeenCalled()
})
it.each(["rectangle", "row"])("rejects an invalid %s during an unconfirmed reader resize", async invalid => {
- const h = retiredInitialReader()
+ const h = failedInitialReader()
act(() => h.root.scrollTo({ top: h.root.scrollHeight - h.root.clientHeight }))
runFrames()
const native = scrollFixture.latest.virtualizer
@@ -714,8 +716,8 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(native.options.followOnAppend).toBe(false)
})
- it("preserves and settles a prefix page after deadline retirement without opening read or peer follow", () => {
- const h = retiredInitialReader()
+ it("preserves and settles a prefix page after explicit failure without opening read or peer follow", () => {
+ const h = failedInitialReader()
act(() => h.root.scrollTo({ top: 0 }))
resize()
act(() => scrollFixture.latest.captureOlderPageAnchor())
@@ -730,7 +732,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })
})
it.each(["m0", "m1"])("uses native row anchoring when the pending page reaches %s with an unchanged body inset", id => {
- const h = retiredInitialReader()
+ const h = failedInitialReader()
act(() => h.root.scrollTo({ top: 0 }))
resize()
act(() => scrollFixture.latest.captureOlderPageAnchor())
@@ -865,12 +867,14 @@ describe("locked native adapter and existing message scroll owner", () => {
h.update({ isFetchingOlder: true })
const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
- resize(0)
+ resize(1)
expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeTypeOf("function")
+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)
scrollFixture.height -= 40
resize()
expect(bodyTop(h.root, "m0")).toBe(restoredTop)
expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)
const readingTop = bodyTop(h.root, "older-29")
scrollFixture.bodyHeights.set("older-29", 108)
resize()
diff --git a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
new file mode 100644
index 000000000..56bc8b63c
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
+import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
+import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+
+beforeEach(installMessageScrollFixture)
+afterEach(restoreMessageScrollFixture)
+
+describe("native snapshot restoration and one-shot late unread ownership", () => {
+ it.each([false, true])("keeps the saved body offset when prepend changes an unsettled restore index (StrictMode=%s)", async strict => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
+ const original = mount({ positionScope, items }, strict)
+ original.move(800)
+ const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!
+ const anchorId = String(snapshot.anchorKey).slice(4)
+ const top = bodyTop(original.root, anchorId)
+ original.view.unmount()
+ const restored = mount({ positionScope, items }, strict, undefined, undefined, 0)
+ scrollFixture.bodyHeights.set(anchorId, 0)
+ resize(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.positionOutcome).toBe("pending")
+ restored.stage({ items: [message("prepended"), ...items] })
+ runFrames(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ scrollFixture.bodyHeights.set(anchorId, 100)
+ resize()
+ expect(bodyTop(restored.root, anchorId)).toBeCloseTo(top, 0)
+ expect(restored.root.querySelector(`[data-msg-id="${anchorId}"]`)!.closest<HTMLElement>("[data-message-row-key]")!.dataset.messageRowKey).toBe(snapshot.anchorKey)
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+ it.each([false, true])("restores a destroyed instance from its own measured snapshot (StrictMode=%s)", async strict => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
+ const h = mount({ positionScope, items }, strict)
+ h.move(800)
+ resize()
+ const before = h.root.scrollTop
+ const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))
+ expect(snapshot?.offset).toBe(before)
+ expect(snapshot!.measurements.length).toBeGreaterThan(0)
+ h.view.unmount()
+ const restored = mount({ positionScope, items }, strict)
+ expect(scrollFixture.latest.virtualizer.options.initialMeasurementsCache.length).toBeGreaterThan(0)
+ expect(scrollFixture.latest.virtualizer.options.initialOffset).toBe(before)
+ expect(restored.root.scrollTop).toBeCloseTo(before, 0)
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it.each(["other-channel", "other-account", "changed-rows", "changed-width", "explicit-target"] as const)("does not restore stale pixels for %s", async mode => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
+ const h = mount({ positionScope, items })
+ h.move(600)
+ resize()
+ h.view.unmount()
+ const otherClient = mode === "other-account" ? (await createCommunityQueryOwner("other")).client : client
+ const scope = mode === "other-channel" || mode === "other-account"
+ ? { ...positionScope, proof: captureChannelMetadataToken(otherClient, mode === "other-channel" ? "B" : "A") } : positionScope
+ if (mode === "changed-width") scrollFixture.width = 600
+ const restored = mount({ positionScope: scope,
+ items: mode === "changed-rows" ? items.map((item, index) => index === 1 ? { ...item, m: { ...item.m, content: "Edited body" } } : item) : items,
+ ...(mode === "explicit-target" ? { scrollToMessageId: "m5" } : {}),
+ })
+ const native = scrollFixture.latest.virtualizer
+ if (mode === "explicit-target") {
+ const index = native.getVirtualItems().find(row => row.key === "msg:m5")!.index
+ expect(restored.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
+ } else expect(restored.root.scrollHeight - restored.root.clientHeight - restored.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.positionOutcome).toBe("success")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it("centers the first late NEW once while data is pending and never restarts it for later boundaries", () => {
+ const h = mount({ initialPositionMessageId: "m4", positionDataState: "pending" })
+ const native = scrollFixture.latest.virtualizer
+ const index = vi.spyOn(native, "scrollToIndex")
+ h.update({ newDividerBefore: "m8" })
+ expect(index).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const before = h.root.scrollTop
+ h.update({ newDividerBefore: "m10" })
+ expect(index).toHaveBeenCalledOnce()
+ expect(h.root.scrollTop).toBe(before)
+ h.update({ positionDataState: "ready" })
+ expect(h.root.scrollTop).toBe(before)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it("keeps the first late NEW eligible beyond five seconds and waits for a real viewport without polling", () => {
+ scrollFixture.height = 0
+ const shown = vi.fn()
+ const h = mount({ onInitialPositionSettled: shown }, false, undefined, undefined, 0)
+ runFrames(2)
+ act(() => vi.advanceTimersByTime(20000))
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.stage({ items: h.input.items.map((item, offset) => ({ ...item, newDivider: offset === 8 })), newDividerBefore: "m8" })
+ runFrames(2)
+ expect(scrollFixture.frames.size).toBe(0)
+ expect(shown).not.toHaveBeenCalled()
+ expect(index).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ scrollFixture.height = 500
+ resize()
+ expect(index).toHaveBeenCalledOnce()
+ const marker = h.root.querySelector("[data-new-divider]")!.getBoundingClientRect()
+ expect((marker.top + marker.bottom) / 2).toBeCloseTo(250, 0)
+ expect(shown).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it.each(["user", "explicit", "present", "leave", "error"] as const)("rejects a late NEW after %s retires its automatic eligibility", mode => {
+ const h = mount()
+ if (mode === "user") fireEvent.wheel(h.root, { deltaY: -30 })
+ if (mode === "explicit") h.update({ scrollToMessageId: "m4" })
+ if (mode === "present") act(() => scrollFixture.latest.scrollToBottom())
+ if (mode === "leave") { h.update({ active: false }); h.update({ active: true }) }
+ if (mode === "error") { h.update({ positionDataState: "error" }); h.update({ positionDataState: "ready" }) }
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ const before = h.root.scrollTop
+ h.update({ newDividerBefore: "m8" })
+ expect(index).not.toHaveBeenCalled()
+ expect(h.root.scrollTop).toBe(before)
+ })
+
+ it("retires a NEW withdrawn before its layout commits instead of centering a different message", () => {
+ const h = mount({ initialPositionMessageId: "m4" })
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ const before = h.root.scrollTop
+ h.stage({ newDividerBefore: "m8" })
+ h.stage({ newDividerBefore: "m10" })
+ resize()
+ expect(index).not.toHaveBeenCalled()
+ expect(h.root.scrollTop).toBe(before)
+ })
+
+ it("gives a late NEW priority over native append following before issuing either command", () => {
+ const h = mount()
+ const native = scrollFixture.latest.virtualizer
+ const end = vi.spyOn(native, "scrollToEnd"), index = vi.spyOn(native, "scrollToIndex")
+ h.stage({ items: [...h.input.items, { ...message("m14"), newDivider: true }, message("m15")], newDividerBefore: "m14" })
+ expect(native.options.followOnAppend).toBe(false)
+ expect(end).not.toHaveBeenCalled()
+ resize()
+ expect(index).toHaveBeenCalledOnce()
+ expect(end).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts
new file mode 100644
index 000000000..7bb37a81f
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
+import { virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"
+import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+
+beforeEach(installMessageScrollFixture)
+afterEach(restoreMessageScrollFixture)
+
+describe("current ready-window target retirement through the native position owner", () => {
+ it.each(["local", "explicit"] as const)("cancels an absent %s target on ready without waiting for a viewport", kind => {
+ scrollFixture.height = 0
+ const settled = vi.fn(), cancelled = vi.fn(), positioned = vi.fn()
+ const h = mount({ positionDataState: "pending", onInitialPositionSettled: settled,
+ onScrollTargetCancelled: cancelled, onScrollTargetPositioned: positioned,
+ ...(kind === "local" ? { initialPositionMessageId: "missing" } : { scrollToMessageId: "missing" }),
+ })
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ act(() => vi.advanceTimersByTime(20000))
+ expect(settled).not.toHaveBeenCalled()
+ expect(scrollFixture.frames.size).toBe(0)
+ h.update({ positionDataState: "ready" })
+ expect(scrollFixture.latest.positionOutcome).toBe("cancelled")
+ expect(settled).toHaveBeenCalledExactlyOnceWith("cancelled")
+ expect(cancelled.mock.calls).toEqual(kind === "explicit" ? [["missing"]] : [])
+ expect(positioned).not.toHaveBeenCalled()
+ expect(index).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ scrollFixture.height = 500
+ h.update({ items: [...h.input.items, message("missing")] })
+ expect(index).not.toHaveBeenCalled()
+ expect(settled).toHaveBeenCalledOnce()
+ expect(positioned).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ })
+
+ it.each(["local", "explicit"] as const)("keeps an issued %s intent pending until its missing target becomes definitively ready", kind => {
+ const settled = vi.fn(), cancelled = vi.fn(), positioned = vi.fn()
+ const h = mount({ positionDataState: "ready", onInitialPositionSettled: settled,
+ onScrollTargetCancelled: cancelled, onScrollTargetPositioned: positioned,
+ ...(kind === "local" ? { initialPositionMessageId: "m4" } : { scrollToMessageId: "m4" }),
+ }, false, undefined, undefined, 0)
+ const native = scrollFixture.latest.virtualizer
+ const index = vi.spyOn(native, "scrollToIndex").mockImplementation(() => {})
+ const cancelScroll = vi.spyOn(native, "cancelScroll")
+ runFrames(1)
+ expect(index).toHaveBeenCalledOnce()
+ expect(settled).not.toHaveBeenCalled()
+ const original = h.input.items
+ h.update({ positionDataState: "pending", items: original.filter(item => item.kind !== "message" || item.m.id !== "m4") })
+ act(() => vi.advanceTimersByTime(20000))
+ expect(settled).not.toHaveBeenCalled()
+ expect(cancelled).not.toHaveBeenCalled()
+ expect(scrollFixture.frames.size).toBe(0)
+ h.update({ positionDataState: "ready" })
+ expect(settled).toHaveBeenCalledExactlyOnceWith("cancelled")
+ expect(cancelScroll).toHaveBeenCalled()
+ expect(cancelled.mock.calls).toEqual(kind === "explicit" ? [["m4"]] : [])
+ expect(positioned).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ index.mockRestore()
+ h.update({ items: original })
+ expect(positioned).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ scrollToMessageId: "m10" })
+ expect(positioned).toHaveBeenCalledExactlyOnceWith("m10")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(settled).toHaveBeenCalledOnce()
+ })
+
+ it.each(["local", "explicit"] as const)("lands a pending %s target when it arrives after twenty seconds", kind => {
+ const settled = vi.fn(), positioned = vi.fn(), cancelled = vi.fn()
+ const h = mount({ positionDataState: "pending", onInitialPositionSettled: settled,
+ onScrollTargetPositioned: positioned, onScrollTargetCancelled: cancelled,
+ ...(kind === "local" ? { initialPositionMessageId: "missing" } : { scrollToMessageId: "missing" }),
+ })
+ act(() => vi.advanceTimersByTime(20000))
+ expect(scrollFixture.frames.size).toBe(0)
+ expect(settled).not.toHaveBeenCalled()
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ positionDataState: "ready", items: [...h.input.items, message("missing")] })
+ expect(index).toHaveBeenCalledOnce()
+ expect(settled).toHaveBeenCalledExactlyOnceWith("success")
+ expect(cancelled).not.toHaveBeenCalled()
+ expect(positioned.mock.calls).toEqual(kind === "explicit" ? [["missing"]] : [])
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it("cancels a restored anchor removed from a ready window before its command is issued", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))
+ const first = mount({ positionScope, items })
+ first.move(800)
+ resize()
+ const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!
+ first.view.unmount()
+ const settled = vi.fn()
+ const restored = mount({ positionScope, items, onInitialPositionSettled: settled }, false, undefined, undefined, 0)
+ const native = scrollFixture.latest.virtualizer
+ expect(native.options.initialMeasurementsCache.length).toBeGreaterThan(0)
+ const index = vi.spyOn(native, "scrollToIndex")
+ restored.update({ positionDataState: "ready", items: items.filter(item => item.key !== snapshot.anchorKey) })
+ expect(index).not.toHaveBeenCalled()
+ expect(settled).toHaveBeenCalledExactlyOnceWith("cancelled")
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ restored.update({ items })
+ expect(index).not.toHaveBeenCalled()
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 40f0b6fd5..98f864e29 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -1,14 +1,15 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useLayoutEffect, useRef, useState } from "react"
+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"
import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS, type VirtualRowsLayoutSnapshot } from "./virtualizer-react-options"
import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"
import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"
import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
+import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"
-const INITIAL_POSITION_TIMEOUT_MS = 5_000
export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100
const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100
+type PositionOutcome = "pending" | "success" | "user-cancelled" | "cancelled" | "empty" | "error"
type ViewportResizeAnchor = "tail" | "start"
export interface ResolveViewportResizeAnchorInput {
@@ -83,6 +84,7 @@ export function useScrollAnchor({
scrollToMessageId,
initialPositionMessageId,
positionEntry,
+ positionScope,
onScrollTargetPositioned,
onScrollTargetCancelled,
hasMoreOlder,
@@ -105,6 +107,7 @@ export function useScrollAnchor({
scrollToMessageId?: string | null
initialPositionMessageId?: string | null
positionEntry?: object | null
+ positionScope?: VirtualListPositionScope
onScrollTargetPositioned?: (id: string) => void
onScrollTargetCancelled?: (id: string) => void
hasMoreOlder?: boolean
@@ -115,12 +118,12 @@ export function useScrollAnchor({
presentRequest?: MessageRequest | null
localSubmitVersion?: number
tailPaddingEnd?: number
- onInitialPositionSettled?: () => void
+ onInitialPositionSettled?: (outcome: PositionOutcome) => void
}) {
- type Kind = "initial" | "target" | "present" | "idle"
+ type Kind = "initial" | "late-new" | "target" | "present" | "idle"
type Intent = {
epoch: number
- type: "unread" | "target" | "end"
+ type: "unread" | "target" | "end" | "restore"
id: string | null
index: number | null
behavior: ScrollBehavior
@@ -128,7 +131,8 @@ export function useScrollAnchor({
loadedTailPresent: boolean
awaitingData: boolean
viewport: { width: number; height: number }
- pendingInitialEnd: { root: HTMLDivElement | null; scrollTop: number } | null
+ issued: boolean
+ origin: { root: HTMLDivElement | null; offset: number } | null
}
type Geometry = {
epoch: number
@@ -144,13 +148,17 @@ export function useScrollAnchor({
isScrolling: boolean
}
const scrollRef = useRef<HTMLDivElement>(null)
+ const fingerprint = useMemo(() => virtualListLayoutFingerprint(items), [items])
+ const [initialSnapshot] = useState(() => scrollToMessageId ? null : readVirtualListPosition(positionScope, fingerprint))
+ const restorationRef = useRef(initialSnapshot)
+ const snapshotContextRef = useRef({ scope: positionScope, fingerprint })
const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)
const positionOwnerRef = useRef({ epoch: 0, active: true })
const [documentVisible, setDocumentVisible] = useState(() => typeof document === "undefined" || document.visibilityState !== "hidden")
const visible = positioningActive && documentVisible
const entryActivationRef = useRef({ entry: positionEntry, seen: visible })
const dataState = positionDataState ?? (initialScrollReady ? items.some(item => item.kind === "message") ? "ready" : "empty" : "pending")
- const contextRef = useRef({ dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible })
+ const contextRef = useRef({ dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore })
const [requestRevision, setRequestRevision] = useState(0)
const [committedEntry, setCommittedEntry] = useState(positionEntry)
const entryChanged = committedEntry !== positionEntry
@@ -161,21 +169,23 @@ export function useScrollAnchor({
const readReady = useCreateAtom(false)
const [readPositionReady, setReadPositionReady] = useAtom(readReady)
const [resumeValidated, setResumeValidated] = useState(true)
- const [shortGap, setShortGap] = useAtom(useCreateAtom(0))
+ const [shortGap, setShortGap] = useAtom(useCreateAtom(initialSnapshot?.paddingStart ?? 0))
+ const presentation = useCreateAtom<PositionOutcome>("pending")
+ const [positionOutcome, setPositionOutcome] = useAtom(presentation)
const [paginationDirection, setPaginationDirection] = useAtom(useCreateAtom<"older" | "newer" | null>(null))
const paginationRef = useRef<{
direction: "older" | "newer"
phase: "pending" | "fetching" | "settling"
- receipt?: { result?: MessageRequestResult; before?: object }
+ receipt?: { result?: MessageRequestResult; before?: object; beforeItems: FlatItem[] }
+ restoringBody?: boolean
+ bodyItems?: FlatItem[]
anchor?: { key: string; viewportOffset: number; bodyInset: number; header: boolean; firstKey: string; epoch: number }
} | null>(null)
const scrollPaddingStartRef = useRef(0)
- const olderMeasurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)
+ const measurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)
const entryResolvedRef = useRef(false)
const initialRetiredRef = useRef(false)
- const initialEndIssuedRef = useRef(false)
- const initialPositionSettledRef = useRef(false)
- const initialDeadlineRef = useRef<{ handle: number; at: number } | null>(null)
+ const lateNewRef = useRef({ allowed: true, consumed: false })
const initialSettleFrameRef = useRef<number | null>(null)
const semanticIntentRef = useRef<Intent | null>(null)
const committedRowsRef = useRef<{
@@ -202,12 +212,16 @@ export function useScrollAnchor({
onTargetPositionedRef.current = onScrollTargetPositioned
onTargetCancelledRef.current = onScrollTargetCancelled
settleCallbackRef.current = onInitialPositionSettled
- contextRef.current = { dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible }
- }, [items, positionEntry, initialScrollReady, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
+ contextRef.current = { dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore }
+ snapshotContextRef.current = { scope: positionScope, fingerprint }
+ }, [items, positionEntry, positionScope, fingerprint, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
const followSuspension = useCreateAtom(false)
const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
const acceptedGeometryRef = useRef<Geometry | null>(null)
+ const savedPositionRef = useRef<{ scope: VirtualListPositionScope; fingerprint: string; geometry: Geometry } | null>(null)
const geometryFrameRef = useRef<number | null>(null)
+ const geometryObserverRef = useRef<ResizeObserver | null>(null)
+ const observedPageBodyRef = useRef<HTMLElement | null>(null)
const scheduleGeometryRef = useRef<() => void>(() => {})
const reconcileViewportRef = useRef<() => void>(() => {})
const userInputRef = useRef({ touch: false, pointers: new Set<number>(), handover: false })
@@ -222,49 +236,61 @@ export function useScrollAnchor({
if (initialSettleFrameRef.current !== null) window.cancelAnimationFrame(initialSettleFrameRef.current)
initialSettleFrameRef.current = null
}, [])
- const settlePresentation = useCallback(() => {
- if (!positionOwnerRef.current.active || initialPositionSettledRef.current) return
- initialPositionSettledRef.current = true
- settleCallbackRef.current?.()
- }, [])
- const clearBudget = useCallback(() => {
- if (initialDeadlineRef.current !== null) window.clearTimeout(initialDeadlineRef.current.handle)
- initialDeadlineRef.current = null
- }, [])
- const clearOlderMeasurementAnchor = useCallback(() => {
- olderMeasurementAnchorRef.current = null
+ const settlePresentation = useCallback((outcome: PositionOutcome = "success") => {
+ if (!positionOwnerRef.current.active || presentation.get() !== "pending") return
+ setPositionOutcome(outcome)
+ settleCallbackRef.current?.(outcome)
+ }, [presentation, setPositionOutcome])
+ const clearMeasurementAnchor = useCallback(() => {
+ measurementAnchorRef.current = null
if (virtualizerRef.current) virtualizerRef.current.shouldAdjustScrollPositionOnItemSizeChange = undefined
}, [])
- const adjustOlderMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item) => {
- const anchor = olderMeasurementAnchorRef.current
+ const observePageBody = useCallback(() => {
+ const observer = geometryObserverRef.current
+ if (!observer) return
+ const key = paginationRef.current?.anchor?.key
+ const item = key ? currentItemsRef.current.find(item => item.key === key) : undefined
+ const body = item?.kind === "message" ? Array.from(scrollRef.current?.querySelectorAll<HTMLElement>("[data-msg-id]") ?? [])
+ .find(body => body.dataset.msgId === item.m.id) ?? null : null
+ if (observedPageBodyRef.current === body) return
+ if (observedPageBodyRef.current) observer.unobserve(observedPageBodyRef.current)
+ observedPageBodyRef.current = body
+ if (body) observer.observe(body)
+ }, [])
+ const adjustAnchoredMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item) => {
+ const anchor = measurementAnchorRef.current
const owner = positionOwnerRef.current
- const index = anchor && anchor.epoch === owner.epoch && owner.active && positionKind.get() === "idle"
+ const intent = semanticIntentRef.current
+ const ownsAnchor = positionKind.get() === "idle" || intent?.type === "restore" && intent.epoch === owner.epoch && intent.id === anchor?.key
+ const index = anchor && anchor.epoch === owner.epoch && owner.active && ownsAnchor
? currentItemsRef.current.findIndex(row => row.key === anchor.key) : -1
return item.index < index
}, [positionKind])
const claimPosition = useCallback((kind: Kind) => {
+ if (kind === "target" || kind === "present") lateNewRef.current.allowed = false
const owner = positionOwnerRef.current
virtualizerRef.current?.cancelScroll()
- clearOlderMeasurementAnchor()
+ clearMeasurementAnchor()
scrollPaddingStartRef.current = 0
paginationRef.current = null
+ observePageBody()
setPaginationDirection(null)
owner.epoch += 1
setOwnerKind(kind)
cancelFrame()
- clearBudget()
semanticIntentRef.current = null
acceptedGeometryRef.current = null
holdNativeOrigin(null)
presentIntentRef.current = null
setReadPositionReady(false)
return owner.epoch
- }, [cancelFrame, clearBudget, clearOlderMeasurementAnchor, holdNativeOrigin, setOwnerKind, setPaginationDirection, setReadPositionReady])
+ }, [cancelFrame, clearMeasurementAnchor, holdNativeOrigin, observePageBody, setOwnerKind, setPaginationDirection, setReadPositionReady])
const retireInitialPosition = useCallback(() => {
initialRetiredRef.current = true
entryResolvedRef.current = true
}, [])
- const releasePosition = useCallback((userHandover = false) => {
+ const releasePosition = useCallback((userHandover = false, outcome: PositionOutcome = userHandover ? "user-cancelled" : "cancelled") => {
+ lateNewRef.current.allowed = false
const intent = semanticIntentRef.current
const cancelledTarget = positionKind.get() === "target"
? intent?.notifyTarget ? intent.id
@@ -277,23 +303,9 @@ export function useScrollAnchor({
positionedTargetRef.current = targetIntentRef.current
if (cancelledTarget) onTargetCancelledRef.current?.(cancelledTarget)
if (userHandover) userInputRef.current.handover = true
- settlePresentation()
+ settlePresentation(outcome)
scheduleGeometryRef.current()
}, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
- const armBudget = useCallback(() => {
- if (!positionOwnerRef.current.active || !contextRef.current.visible
- || (positionKind.get() === "initial" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending")) return
- if (initialDeadlineRef.current?.handle) return
- const epoch = positionOwnerRef.current.epoch
- const at = initialDeadlineRef.current?.at ?? Date.now() + INITIAL_POSITION_TIMEOUT_MS
- const handle = window.setTimeout(() => {
- if (!positionOwnerRef.current.active || positionOwnerRef.current.epoch !== epoch) return
- releasePosition()
- }, Math.max(0, at - Date.now()))
- initialDeadlineRef.current = { handle, at }
- }, [positionKind, releasePosition])
-
-
const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {
const root = scrollRef.current
const native = virtualizerRef.current
@@ -306,9 +318,10 @@ export function useScrollAnchor({
if (item?.kind !== "message" || item.key !== key
|| !wrapper || !body || body.dataset.msgId !== item.m.id) return null
const rect = wrapper.getBoundingClientRect()
+ const bodyRect = body.getBoundingClientRect()
const offset = rect.top - root.getBoundingClientRect().top
- if (rect.height <= 0 || Math.abs(offset + root.scrollTop - row.start) > 1) return null
- const bodyInset = body.getBoundingClientRect().top - rect.top
+ if (rect.height <= 0 || bodyRect.height <= 0 || Math.abs(offset + root.scrollTop - row.start) > 1) return null
+ const bodyInset = bodyRect.top - rect.top
return { viewportOffset: offset + bodyInset, bodyInset }
}, [])
const refreshPendingPageAnchor = useCallback(() => {
@@ -331,6 +344,8 @@ export function useScrollAnchor({
if (offset !== null) Object.assign(anchor, offset)
}, [positionKind, readPageMessageGeometry])
const awaitingTarget = !!scrollToMessageId && positionedTargetRef.current !== scrollToMessageId
+ const pendingLateNew = visible && initialScrollReady && !!newDividerBefore && entryResolvedRef.current
+ && lateNewRef.current.allowed && !lateNewRef.current.consumed && (ownerKind === "idle" || ownerKind === "initial")
const getItemKey = useCallback((index: number) => items[index].key, [items])
const estimateSize = useCallback((index: number) => estimateRowHeight(items[index], !!hasMoreOlder), [items, hasMoreOlder])
// eslint-disable-next-line react-hooks/incompatible-library -- supported TanStack Virtual imperative adapter
@@ -338,7 +353,10 @@ export function useScrollAnchor({
...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,
directDomUpdates: false,
useFlushSync: true,
- initialRect: { width: 0, height: items.reduce((size, item) => size + estimateRowHeight(item, !!hasMoreOlder), shortGap + tailPaddingEnd) },
+ initialRect: initialSnapshot ? { width: initialSnapshot.width, height: initialSnapshot.height }
+ : { width: 0, height: items.reduce((size, item) => size + estimateRowHeight(item, !!hasMoreOlder), shortGap + tailPaddingEnd) },
+ initialOffset: initialSnapshot?.offset ?? 0,
+ initialMeasurementsCache: initialSnapshot?.measurements ?? [],
count: items.length,
getScrollElement: () => scrollRef.current,
estimateSize,
@@ -351,10 +369,10 @@ export function useScrollAnchor({
},
getItemKey,
scrollPaddingStart: scrollPaddingStartRef.current,
- anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit
+ anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit && !pendingLateNew
&& (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",
followOnAppend: visible && !entryChanged && ownerKind === "idle" && readPositionReady && dataState === "ready" && !awaitingTarget
- && !pendingLocalSubmit && !followSuspended && !hasMoreNewer
+ && !pendingLocalSubmit && !pendingLateNew && !followSuspended && !hasMoreNewer
&& !isFetchingOlder && !isFetchingNewer && paginationDirection === null
&& (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,
scrollEndThreshold: 1,
@@ -367,9 +385,9 @@ export function useScrollAnchor({
virtualizerRef.current = virtualizer
useLayoutEffect(() => { refreshPendingPageAnchor() })
useLayoutEffect(() => {
- const anchor = olderMeasurementAnchorRef.current
- if (anchor && !items.some(item => item.key === anchor.key)) clearOlderMeasurementAnchor()
- }, [clearOlderMeasurementAnchor, items])
+ const anchor = measurementAnchorRef.current
+ if (anchor && !items.some(item => item.key === anchor.key)) clearMeasurementAnchor()
+ }, [clearMeasurementAnchor, items])
const readGeometry = useCallback((viewportTransition = false): Geometry | null => {
const root = scrollRef.current
@@ -410,6 +428,49 @@ export function useScrollAnchor({
isScrolling: native.isScrolling,
}
}, [followSuspension, nativeOrigin])
+ const hasCommittedRows = useCallback(() => {
+ const root = scrollRef.current
+ const native = virtualizerRef.current
+ const committed = committedRowsRef.current
+ const layout = committed?.layout
+ const rect = native?.scrollRect
+ const rows = native?.getVirtualItems()
+ return !!root && !!native && committed?.native === native && committed.entry === positionEntryRef.current
+ && committed.items === currentItemsRef.current && native.scrollElement === root && root.isConnected
+ && !!layout && !!rect && root.clientHeight > 0 && root.clientWidth > 0
+ && rect.width === root.clientWidth && rect.height === root.clientHeight
+ && layout.totalSize === native.getTotalSize() && layout.scrollMargin === native.options.scrollMargin
+ && !!rows && layout.rows.length === rows.length && rows.length > 0
+ && layout.rows.every((row, index) => {
+ const current = rows[index]
+ return row.key === current.key && row.index === current.index
+ && row.start === current.start && row.size === current.size
+ && row.end === current.end && row.lane === current.lane
+ })
+ }, [])
+ const savePosition = useCallback((geometry: Geometry) => {
+ const { scope, fingerprint: currentFingerprint } = snapshotContextRef.current
+ const native = virtualizerRef.current
+ const committed = committedRowsRef.current
+ if (!scope || !native || !positionOwnerRef.current.active || !contextRef.current.visible
+ || positionKind.get() !== "idle" || geometry.epoch !== positionOwnerRef.current.epoch
+ || geometry.isScrolling || paginationRef.current || contextRef.current.dataState === "error"
+ || committed?.items !== currentItemsRef.current || committed.layout.totalSize !== native.getTotalSize()
+ || native.options.count !== currentItemsRef.current.length
+ || currentItemsRef.current.some((item, index) => native.options.getItemKey(index) !== item.key)) return
+ const previous = savedPositionRef.current
+ if (previous?.scope === scope && previous.fingerprint === currentFingerprint
+ && previous.geometry.scrollTop === geometry.scrollTop && previous.geometry.total === geometry.total
+ && previous.geometry.clientWidth === geometry.clientWidth && previous.geometry.clientHeight === geometry.clientHeight) return
+ saveVirtualListPosition(scope, {
+ version: 1, fingerprint: currentFingerprint, offset: geometry.scrollTop,
+ width: geometry.clientWidth, height: geometry.clientHeight,
+ paddingStart: native.options.paddingStart ?? 0, paddingEnd: geometry.paddingEnd,
+ anchorKey: geometry.key, anchorOffset: geometry.itemStart - geometry.scrollTop,
+ measurements: native.takeSnapshot(), at: Date.now(),
+ })
+ savedPositionRef.current = { scope, fingerprint: currentFingerprint, geometry }
+ }, [positionKind])
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
const epoch = positionOwnerRef.current.epoch
@@ -421,38 +482,32 @@ export function useScrollAnchor({
const root = scrollRef.current
const native = virtualizerRef.current
if (!intent || intent.epoch !== owner.epoch || !root || !native) return
- if (positionKind.get() === "initial" && !contextRef.current.initialScrollReady) return
- const pendingEnd = intent.pendingInitialEnd
- if (pendingEnd) {
- const deadline = initialDeadlineRef.current
- if (!deadline || Date.now() >= deadline.at) return
- if (pendingEnd.root !== root || Math.abs(root.scrollTop - pendingEnd.scrollTop) > 1) {
- releasePosition()
+ if (intent.type === "unread" && contextRef.current.newDividerBefore !== intent.id) {
+ releasePosition()
+ return
+ }
+ const index = intent.type === "end" ? currentItemsRef.current.length - 1
+ : intent.type === "restore" ? currentItemsRef.current.findIndex(item => item.key === intent.id)
+ : intent.id ? intent.type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
+ : findMessageIndex(currentItemsRef.current, intent.id) : null
+ if (index === null || index < 0) {
+ if (intent.type !== "end" && contextRef.current.dataState === "ready") releasePosition()
+ return
+ }
+ if ((positionKind.get() === "initial" || positionKind.get() === "late-new") && !contextRef.current.initialScrollReady) return
+ if (!intent.issued) {
+ if (intent.origin && (intent.origin.root !== root || Math.abs(root.scrollTop - intent.origin.offset) > 1)) {
+ releasePosition(true)
return
}
- const committed = committedRowsRef.current
- const layout = committed?.layout
- const rect = native.scrollRect
- const rows = native.getVirtualItems()
- const matches = committed?.native === native && committed.entry === positionEntryRef.current
- && committed.items === currentItemsRef.current && native.scrollElement === root && root.isConnected
- && layout && rect && root.clientHeight > 0 && root.clientWidth > 0
- && rect.width === root.clientWidth && rect.height === root.clientHeight
- && layout.totalSize === native.getTotalSize() && layout.scrollMargin === native.options.scrollMargin
- && layout.rows.length === rows.length && rows.length > 0
- && layout.rows.every((row, index) => {
- const current = rows[index]
- return row.key === current.key && row.index === current.index
- && row.start === current.start && row.size === current.size
- && row.end === current.end && row.lane === current.lane
- })
- if (!matches) {
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- return
+ if (!hasCommittedRows()) return
+ if (intent.type === "end") native.scrollToEnd({ behavior: intent.behavior })
+ else {
+ intent.index = index
+ native.scrollToIndex(index, { align: intent.type === "restore" ? "start" : "center", behavior: intent.behavior })
}
- intent.pendingInitialEnd = null
- initialEndIssuedRef.current = true
- native.scrollToEnd({ behavior: intent.behavior })
+ intent.issued = true
+ intent.origin = null
}
const viewport = root.getBoundingClientRect()
if (root.clientHeight <= 0 || root.clientWidth <= 0 || viewport.height <= 0 || viewport.width <= 0) return
@@ -467,11 +522,16 @@ export function useScrollAnchor({
&& Math.abs(Math.max(0, root.scrollHeight - root.clientHeight) - root.scrollTop) <= 1
&& !!rect && rect.height > 0 && !!wrapper && wrapper.height > 0
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
+ } else if (intent.type === "restore") {
+ if (index !== intent.index) {
+ intent.index = index
+ native.scrollToIndex(index, { align: "start", behavior: intent.behavior })
+ }
+ const targetOffset = native.getOffsetForIndex(index, "start")?.[0]
+ landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1 && readGeometry() !== null
+ && (currentItemsRef.current[index]?.kind !== "message" || readPageMessageGeometry(intent.id!) !== null)
} else if (intent.id) {
- const index = intent.type === "unread"
- ? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
- : findMessageIndex(currentItemsRef.current, intent.id)
- if (index !== null && index !== intent.index) {
+ if (index !== intent.index) {
intent.index = index
native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
}
@@ -485,30 +545,32 @@ export function useScrollAnchor({
const body = row?.getBoundingClientRect()
const wrapper = row?.closest("[data-index]")?.getBoundingClientRect()
if (rect && body && wrapper && wrapper.height > 0 && rect.height > 0 && body.height > 0) {
- const targetOffset = index === null ? undefined : native.getOffsetForIndex(index, "center")?.[0]
+ const targetOffset = native.getOffsetForIndex(index, "center")?.[0]
landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
&& body.bottom > viewport.top + 1 && body.top < viewport.bottom - 1
}
}
if (landed) {
- const initial = positionKind.get() === "initial"
+ const initial = positionKind.get() === "initial" || positionKind.get() === "late-new"
if (initial && contextRef.current.dataState === "pending") setFollowSuspended(true)
const geometry = readGeometry()
- if (!geometry) {
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- return
- }
+ if (!geometry) return
if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
settlePresentation()
if (!initial && contextRef.current.dataState === "pending") return
acceptedGeometryRef.current = geometry
+ if (intent.type === "restore") {
+ native.cancelScroll()
+ clearMeasurementAnchor()
+ scrollPaddingStartRef.current = 0
+ native.setOptions({ ...native.options, scrollPaddingStart: 0 })
+ }
semanticIntentRef.current = null
setOwnerKind("idle")
setReadPositionReady(true)
setResumeValidated(true)
retireInitialPosition()
- clearBudget()
if (intent.notifyTarget && intent.id) {
positionedTargetRef.current = intent.id
onTargetPositionedRef.current?.(intent.id)
@@ -516,39 +578,47 @@ export function useScrollAnchor({
scheduleGeometryRef.current()
return
}
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [clearMeasurementAnchor, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, readPageMessageGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
const onRowsLayoutCommit = useCallback((layout: VirtualRowsLayoutSnapshot | null) => {
committedRowsRef.current = layout ? { layout, native: virtualizer, entry: positionEntry, items } : null
- if (layout && positionOwnerRef.current.active && semanticIntentRef.current?.pendingInitialEnd) scheduleInitialPositionSettled()
- }, [items, positionEntry, scheduleInitialPositionSettled, virtualizer])
+ observePageBody()
+ if (layout && positionOwnerRef.current.active && semanticIntentRef.current) scheduleInitialPositionSettled()
+ if (layout && paginationRef.current) scheduleGeometryRef.current()
+ }, [items, observePageBody, positionEntry, scheduleInitialPositionSettled, virtualizer])
const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {
const owner = positionOwnerRef.current
if (!owner.active || !contextRef.current.visible) return
- const index = type === "end" ? currentItemsRef.current.length - 1
+ const index = type === "restore" ? currentItemsRef.current.findIndex(item => item.key === id)
+ : type === "end" ? currentItemsRef.current.length - 1
: id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id)
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,
- awaitingData: positionKind.get() === "initial" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending",
+ awaitingData: positionKind.get() === "initial" || positionKind.get() === "late-new" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending",
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
- pendingInitialEnd: type === "end" && positionKind.get() === "initial" && !loadedTailPresent && !initialEndIssuedRef.current
- ? { root: scrollRef.current, scrollTop: scrollRef.current?.scrollTop ?? 0 } : null,
+ issued: false,
+ origin: positionKind.get() === "initial" && type !== "restore" && !initialSnapshot ? { root: scrollRef.current, offset: scrollRef.current?.scrollTop ?? 0 } : null,
}
if (semanticIntentRef.current.awaitingData) return
- if (type === "end") {
- if (!semanticIntentRef.current.pendingInitialEnd) virtualizerRef.current?.scrollToEnd({ behavior })
+ if (type === "end" && loadedTailPresent) {
+ virtualizerRef.current?.scrollToEnd({ behavior })
+ semanticIntentRef.current.issued = true
}
- else if (index !== null) {
- virtualizerRef.current?.scrollToIndex(index, { align: "center", behavior })
+ if (type === "restore" && restorationRef.current) {
+ scrollPaddingStartRef.current = restorationRef.current.anchorOffset
+ const native = virtualizerRef.current
+ if (native) {
+ measurementAnchorRef.current = { key: id!, epoch: owner.epoch }
+ native.shouldAdjustScrollPositionOnItemSizeChange = adjustAnchoredMeasurement
+ native.setOptions({ ...native.options, scrollPaddingStart: scrollPaddingStartRef.current })
+ }
}
- armBudget()
scheduleInitialPositionSettled()
- }, [armBudget, positionKind, scheduleInitialPositionSettled])
+ }, [adjustAnchoredMeasurement, initialSnapshot, positionKind, scheduleInitialPositionSettled])
useLayoutEffect(() => {
const owner = positionOwnerRef.current
@@ -556,28 +626,23 @@ export function useScrollAnchor({
const intent = semanticIntentRef.current
if (intent && intent.epoch !== owner.epoch) {
intent.epoch = owner.epoch
- if (intent.pendingInitialEnd) scheduleInitialPositionSettled()
- else startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
+ startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
} else if (positionKind.get() === "present" && presentIntentRef.current !== null) {
presentIntentRef.current.epoch = owner.epoch
}
if (acceptedGeometryRef.current) acceptedGeometryRef.current.epoch = owner.epoch
- if (positionKind.get() === "initial" || semanticIntentRef.current) armBudget()
return () => {
owner.active = false
owner.epoch += 1
virtualizerRef.current?.cancelScroll()
- clearOlderMeasurementAnchor()
+ clearMeasurementAnchor()
paginationRef.current = null
+ observePageBody()
cancelFrame()
- if (initialDeadlineRef.current) {
- window.clearTimeout(initialDeadlineRef.current.handle)
- initialDeadlineRef.current.handle = 0
- }
if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)
geometryFrameRef.current = null
}
- }, [armBudget, cancelFrame, clearOlderMeasurementAnchor, positionKind, scheduleInitialPositionSettled, startIntent])
+ }, [cancelFrame, clearMeasurementAnchor, observePageBody, positionKind, scheduleInitialPositionSettled, startIntent])
useLayoutEffect(() => {
const update = () => setDocumentVisible(document.visibilityState !== "hidden")
@@ -588,13 +653,14 @@ export function useScrollAnchor({
useLayoutEffect(() => {
if (!visible) {
+ if (entryActivationRef.current.seen) lateNewRef.current.allowed = false
setResumeValidated(false)
if (entryActivationRef.current.seen && positionKind.get() !== "idle") releasePosition()
positionOwnerRef.current.active = false
virtualizerRef.current?.cancelScroll()
cancelFrame()
- clearBudget()
paginationRef.current = null
+ observePageBody()
setPaginationDirection(null)
if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)
geometryFrameRef.current = null
@@ -603,7 +669,7 @@ export function useScrollAnchor({
if (!readReady.get() || readGeometry()) setResumeValidated(true)
scheduleGeometryRef.current()
}
- }, [cancelFrame, clearBudget, positionKind, readGeometry, readReady, releasePosition, setPaginationDirection, visible])
+ }, [cancelFrame, observePageBody, positionKind, readGeometry, readReady, releasePosition, setPaginationDirection, visible])
useLayoutEffect(() => {
if (committedEntry === positionEntry) return
@@ -611,15 +677,16 @@ export function useScrollAnchor({
claimPosition("initial")
entryResolvedRef.current = false
initialRetiredRef.current = false
- initialEndIssuedRef.current = false
- initialPositionSettledRef.current = false
+ setPositionOutcome("pending")
+ restorationRef.current = null
+ lateNewRef.current = { allowed: true, consumed: false }
targetIntentRef.current = null
positionedTargetRef.current = null
consumedPresentVersionRef.current = presentVersion ?? 0
consumedLocalSubmitVersionRef.current = localSubmitVersion ?? 0
userInputRef.current.handover = false
setFollowSuspended(false)
- }, [claimPosition, committedEntry, localSubmitVersion, positionEntry, presentVersion, setFollowSuspended])
+ }, [claimPosition, committedEntry, localSubmitVersion, positionEntry, presentVersion, setFollowSuspended, setPositionOutcome])
useLayoutEffect(() => {
const target = scrollToMessageId ?? null
@@ -639,7 +706,7 @@ export function useScrollAnchor({
useLayoutEffect(() => {
const intent = semanticIntentRef.current
- if (visible && intent?.awaitingData && (positionKind.get() === "initial" ? initialScrollReady : dataState === "ready")) {
+ if (visible && intent?.awaitingData && (positionKind.get() === "initial" || positionKind.get() === "late-new" ? initialScrollReady : dataState === "ready")) {
startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
}
}, [dataState, initialScrollReady, positionKind, startIntent, visible])
@@ -672,16 +739,84 @@ export function useScrollAnchor({
acceptedGeometryRef.current = {
...next, isScrolling: next.isScrolling && unchangedPosition ? previous.isScrolling : next.isScrolling,
}
+ savePosition(acceptedGeometryRef.current)
if (readReady.get()) setResumeValidated(true)
holdNativeOrigin(next.scrollTop <= 1 && !next.pinEligible ? currentItemsRef.current[0]?.key ?? null : null)
}
- }, [holdNativeOrigin, positionKind, readReady])
+ }, [holdNativeOrigin, positionKind, readReady, savePosition])
+
+ const reconcilePage = useCallback(() => {
+ const page = paginationRef.current
+ const native = virtualizerRef.current
+ if (!page || !native) return null
+ const finish = () => {
+ if (page.restoringBody) native.cancelScroll()
+ clearMeasurementAnchor()
+ scrollPaddingStartRef.current = 0
+ native.setOptions({ ...native.options, scrollPaddingStart: 0 })
+ paginationRef.current = null
+ observePageBody()
+ setPaginationDirection(null)
+ return null
+ }
+ const context = contextRef.current
+ if (context.dataState === "empty" || context.dataState === "error") return finish()
+ if (page.receipt) {
+ const result = page.receipt.result
+ if (!result) return false
+ if (result.status !== "success" || result.window === page.receipt.before
+ || context.messageWindow !== result.window && context.messageWindow !== page.receipt.before) return finish()
+ if (context.messageWindow !== result.window || context.dataState === "pending"
+ || currentItemsRef.current === page.receipt.beforeItems) return false
+ } else if (page.phase !== "settling") {
+ const fetching = page.direction === "older" ? context.isFetchingOlder : context.isFetchingNewer
+ if (fetching) { page.phase = "fetching"; return false }
+ if (page.phase !== "fetching") return false
+ }
+ if (!hasCommittedRows()) return false
+ if (page.phase !== "settling" || page.restoringBody && page.bodyItems !== currentItemsRef.current) {
+ page.phase = "settling"
+ const anchor = page.anchor
+ const items = currentItemsRef.current
+ if (anchor && anchor.epoch === positionOwnerRef.current.epoch && positionKind.get() === "idle"
+ && items.find(item => item.kind === "message")?.key !== anchor.firstKey) {
+ const index = items.findIndex(item => item.key === anchor.key)
+ const item = items[index]
+ const bodyInset = item?.kind === "message" ? item.paddingTop ?? anchor.bodyInset : anchor.bodyInset
+ if (index >= 0 && (anchor.header || bodyInset !== anchor.bodyInset)) {
+ measurementAnchorRef.current = { key: anchor.key, epoch: anchor.epoch }
+ native.shouldAdjustScrollPositionOnItemSizeChange = adjustAnchoredMeasurement
+ scrollPaddingStartRef.current = anchor.viewportOffset - bodyInset
+ native.setOptions({ ...native.options, scrollPaddingStart: scrollPaddingStartRef.current })
+ const offset = native.getOffsetForIndex(index, "start")?.[0]
+ if (offset !== undefined) {
+ acceptedGeometryRef.current = null
+ holdNativeOrigin(null)
+ page.restoringBody = true
+ page.bodyItems = items
+ native.scrollToOffset(offset, { behavior: "auto" })
+ return true
+ }
+ }
+ }
+ }
+ if (!readGeometry()) return false
+ if (page.restoringBody && page.anchor) {
+ if (!currentItemsRef.current.some(item => item.key === page.anchor?.key)) return finish()
+ const body = readPageMessageGeometry(page.anchor.key)
+ if (!body || Math.abs(body.viewportOffset - page.anchor.viewportOffset) > 1) return false
+ }
+ if (native.isScrolling) return false
+ return finish()
+ }, [adjustAnchoredMeasurement, clearMeasurementAnchor, hasCommittedRows, holdNativeOrigin, observePageBody, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
const reconcileGeometry = useCallback((viewportOnly = false) => {
const root = scrollRef.current
const native = virtualizerRef.current
const owner = positionOwnerRef.current
if (!owner.active || !root || !native) return false
+ const page = reconcilePage()
+ if (page !== null) return page
if (viewportOnly && (positionKind.get() !== "idle"
|| acceptedGeometryRef.current?.epoch !== owner.epoch
|| (acceptedGeometryRef.current.clientHeight === root.clientHeight
@@ -757,14 +892,8 @@ export function useScrollAnchor({
if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })
else if (readReady.get()) setResumeValidated(true)
}
- if (paginationRef.current?.phase === "settling") {
- paginationRef.current = null
- setPaginationDirection(null)
- clearOlderMeasurementAnchor()
- }
-
return false
- }, [claimPosition, clearOlderMeasurementAnchor, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, retireInitialPosition, setPaginationDirection, setReadPositionReady, setShortGap, startIntent])
+ }, [claimPosition, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcilePage, retireInitialPosition, setReadPositionReady, setShortGap, startIntent])
const reconcileViewport = useCallback(() => {
const intent = semanticIntentRef.current
const root = scrollRef.current
@@ -772,14 +901,16 @@ export function useScrollAnchor({
if (intent && root && native && intent.epoch === positionOwnerRef.current.epoch
&& (intent.viewport.width !== root.clientWidth || intent.viewport.height !== root.clientHeight)) {
intent.viewport = { width: root.clientWidth, height: root.clientHeight }
- if (intent.type !== "end" && intent.index !== null && root.clientHeight > 0) {
- native.scrollToIndex(intent.index, { align: "center", behavior: intent.behavior })
- }
+ intent.issued = false
scheduleInitialPositionSettled()
}
- if (intent?.loadedTailPresent) scheduleInitialPositionSettled()
+ if (intent) scheduleInitialPositionSettled()
+ if (positionKind.get() === "idle") {
+ const geometry = readGeometry()
+ if (geometry) savePosition(geometry)
+ }
reconcileGeometry(true)
- }, [reconcileGeometry, scheduleInitialPositionSettled])
+ }, [positionKind, readGeometry, reconcileGeometry, savePosition, scheduleInitialPositionSettled])
const reconcileGeometryRef = useRef(reconcileGeometry)
useLayoutEffect(() => {
reconcileGeometryRef.current = reconcileGeometry
@@ -802,8 +933,6 @@ export function useScrollAnchor({
if (!root) return
const inputOwner = userInputRef.current
const onScroll = () => {
- const pendingEnd = semanticIntentRef.current?.pendingInitialEnd
- if (pendingEnd?.root === root && Math.abs(root.scrollTop - pendingEnd.scrollTop) > 1) releasePosition()
const previous = acceptedGeometryRef.current
const native = virtualizerRef.current
if (positionKind.get() === "idle" && readReady.get()
@@ -824,7 +953,7 @@ export function useScrollAnchor({
holdNativeOrigin(null)
}
reconcileGeometry(true)
- if (semanticIntentRef.current?.loadedTailPresent) scheduleInitialPositionSettled()
+ if (semanticIntentRef.current) scheduleInitialPositionSettled()
const next = readGeometry()
if (next && native?.isAtEnd(1) && Math.abs(Math.max(0, next.scrollHeight - next.clientHeight) - next.scrollTop) <= 1
&& !userInputRef.current.touch && userInputRef.current.pointers.size === 0
@@ -893,7 +1022,9 @@ export function useScrollAnchor({
root.ownerDocument.addEventListener("pointercancel", onPointerUp)
root.ownerDocument.defaultView?.addEventListener("blur", onBlur)
const ro = new ResizeObserver(() => { reconcileViewportRef.current(); scheduleGeometry() })
+ geometryObserverRef.current = ro
ro.observe(root)
+ observePageBody()
const footer = root.closest<HTMLElement>('[data-slot="community-conversation-surface"]')
?.querySelector<HTMLElement>('[data-slot="community-conversation-footer"]')
const mo = footer && typeof MutationObserver !== "undefined"
@@ -911,14 +1042,16 @@ export function useScrollAnchor({
root.ownerDocument.removeEventListener("pointercancel", onPointerUp)
root.ownerDocument.defaultView?.removeEventListener("blur", onBlur)
ro.disconnect()
+ geometryObserverRef.current = null
+ observedPageBodyRef.current = null
mo?.disconnect()
inputOwner.touch = false
inputOwner.pointers.clear()
}
- }, [holdNativeOrigin, nativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
+ }, [holdNativeOrigin, nativeOrigin, observeGeometry, observePageBody, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
const capturePageAnchor = useCallback((direction: "older" | "newer") => {
- clearOlderMeasurementAnchor()
+ clearMeasurementAnchor()
let anchor: NonNullable<typeof paginationRef.current>["anchor"]
if (positionKind.get() === "idle") {
const geometry = readGeometry()
@@ -938,16 +1071,18 @@ export function useScrollAnchor({
}
}
paginationRef.current = { direction, phase: "pending", anchor }
+ observePageBody()
const page = paginationRef.current
setPaginationDirection(direction)
return (request: MessageRequest | void) => {
if (paginationRef.current !== page || !request) return
if (!request.accepted) {
paginationRef.current = null
+ observePageBody()
setPaginationDirection(null)
return
}
- const receipt: NonNullable<typeof page.receipt> = { before: contextRef.current.messageWindow }
+ const receipt: NonNullable<typeof page.receipt> = { before: contextRef.current.messageWindow, beforeItems: currentItemsRef.current }
page.receipt = receipt
const complete = (result: MessageRequestResult) => {
if (!positionOwnerRef.current.active || paginationRef.current !== page) return
@@ -956,54 +1091,10 @@ export function useScrollAnchor({
}
void request.completed.then(complete, () => complete({ status: "error" }))
}
- }, [clearOlderMeasurementAnchor, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
+ }, [clearMeasurementAnchor, observePageBody, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
const captureOlderPageAnchor = useCallback(() => capturePageAnchor("older"), [capturePageAnchor])
const captureNewerPageAnchor = useCallback(() => capturePageAnchor("newer"), [capturePageAnchor])
- useLayoutEffect(() => {
- const page = paginationRef.current
- if (!page || page.phase === "settling") return
- if (page.receipt) {
- const result = page.receipt.result
- if (!result) return
- if (dataState === "error" || result.status !== "success" || result.window === page.receipt.before
- || messageWindow !== result.window && messageWindow !== page.receipt.before) {
- paginationRef.current = null
- setPaginationDirection(null)
- return
- }
- if (messageWindow !== result.window || dataState === "pending") return
- } else {
- const fetching = page.direction === "older" ? isFetchingOlder : isFetchingNewer
- if (fetching) { page.phase = "fetching"; return }
- if (page.phase !== "fetching") return
- }
- page.phase = "settling"
- let restoringBody = false
- if (page.anchor && page.anchor.epoch === positionOwnerRef.current.epoch
- && positionKind.get() === "idle"
- && items.find(item => item.kind === "message")?.key !== page.anchor.firstKey) {
- const index = items.findIndex(item => item.key === page.anchor?.key)
- const item = items[index]
- const native = virtualizerRef.current
- const bodyInset = item?.kind === "message" ? item.paddingTop ?? page.anchor.bodyInset : page.anchor.bodyInset
- if (index >= 0 && native && (page.anchor.header || bodyInset !== page.anchor.bodyInset)) {
- olderMeasurementAnchorRef.current = { key: page.anchor.key, epoch: page.anchor.epoch }
- native.shouldAdjustScrollPositionOnItemSizeChange = adjustOlderMeasurement
- scrollPaddingStartRef.current = page.anchor.viewportOffset - bodyInset
- native.setOptions({ ...native.options, scrollPaddingStart: scrollPaddingStartRef.current })
- acceptedGeometryRef.current = null
- holdNativeOrigin(null)
- native.scrollToIndex(index, { align: "start" })
- restoringBody = true
- }
- }
- if (!restoringBody) {
- paginationRef.current = null
- setPaginationDirection(null)
- }
- scheduleInitialPositionSettled()
- scheduleGeometry()
- }, [adjustOlderMeasurement, dataState, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, messageWindow, positionKind, requestRevision, scheduleGeometry, scheduleInitialPositionSettled, setPaginationDirection])
+ useLayoutEffect(() => { scheduleGeometry() }, [dataState, isFetchingNewer, isFetchingOlder, messageWindow, requestRevision, scheduleGeometry])
const requestPresentPosition = useCallback((request?: MessageRequest | void) => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
@@ -1072,7 +1163,6 @@ export function useScrollAnchor({
intent.fetching = true
return
}
- if (intent.fetching) armBudget()
if (intent.fetching && hasMoreNewer) {
releasePosition()
return
@@ -1083,24 +1173,51 @@ export function useScrollAnchor({
retireInitialPosition()
setFollowSuspended(false)
startIntent("end", null)
- }, [armBudget, dataState, hasMessages, hasMoreNewer, isFetchingNewer, messageWindow, positionKind, presentVersion, releasePosition, requestRevision, retireInitialPosition, setFollowSuspended, setReadPositionReady, startIntent])
+ }, [dataState, hasMessages, hasMoreNewer, isFetchingNewer, messageWindow, positionKind, presentVersion, releasePosition, requestRevision, retireInitialPosition, setFollowSuspended, setReadPositionReady, startIntent])
const virtualItems = virtualizer.getVirtualItems()
useLayoutEffect(() => {
- if (!visible || positionKind.get() === "idle") return
+ const late = lateNewRef.current
+ if (!late.allowed || late.consumed || !newDividerBefore || !entryResolvedRef.current
+ || !visible || !initialScrollReady || !hasMessages
+ || positionKind.get() !== "idle" && positionKind.get() !== "initial"
+ || findMountScrollTargetIndex(items, newDividerBefore) === null) return
+ late.consumed = true
+ claimPosition("late-new")
+ startIntent("unread", newDividerBefore)
+ }, [claimPosition, hasMessages, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, startIntent, visible])
+ useLayoutEffect(() => {
+ if (!visible) return
if (dataState === "error" || dataState === "empty") {
- releasePosition()
+ lateNewRef.current.allowed = false
+ if (positionKind.get() === "idle") return
+ releasePosition(false, dataState)
if (dataState === "empty") setReadPositionReady(true)
return
}
+ if (positionKind.get() === "idle") return
if (dataState === "pending" && !initialScrollReady) return
if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) return
- armBudget()
if (!entryResolvedRef.current) {
+ const snapshot = restorationRef.current
+ const root = scrollRef.current
+ if (snapshot && (!root || root.clientWidth <= 0 || root.clientHeight <= 0)) return
entryResolvedRef.current = true
- startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
+ if (newDividerBefore) lateNewRef.current.consumed = true
+ if (snapshot && snapshot.fingerprint === fingerprint && snapshot.width === root?.clientWidth
+ && snapshot.height === root.clientHeight && snapshot.paddingEnd === tailPaddingEnd
+ && items.some(item => item.key === snapshot.anchorKey)) startIntent("restore", String(snapshot.anchorKey))
+ else {
+ if (snapshot) {
+ restorationRef.current = null
+ virtualizer.setOptions({ ...virtualizer.options, initialMeasurementsCache: [] })
+ virtualizer.measure()
+ scrollRef.current?.querySelectorAll<HTMLElement>("[data-index]").forEach(element => virtualizer.measureElement(element))
+ }
+ startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
+ }
} else scheduleInitialPositionSettled()
- }, [armBudget, dataState, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])
+ }, [dataState, fingerprint, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, tailPaddingEnd, virtualItems, virtualizer, visible])
const scrollToBottom = useCallback(() => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
@@ -1123,11 +1240,11 @@ export function useScrollAnchor({
: -1
const belowCount = root && virtualizer.isAtEnd(MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX)
? 0 : computeBelowCount(items, lastVisibleIndex)
- const pageReceipt = paginationRef.current?.receipt
- const paginationRequestPending = !!pageReceipt && (!pageReceipt.result || pageReceipt.result.status === "success" && messageWindow !== pageReceipt.result.window)
+ const paginationRequestPending = paginationDirection !== null
return {
scrollRef, virtualizer, onRowsLayoutCommit, readPositionReady: active && visible && dataState !== "pending" && dataState !== "error" && resumeValidated && !entryChanged && readPositionReady, paginationEnabled: active && visible && dataState !== "pending" && dataState !== "error" && !entryChanged && ownerKind === "idle" && !awaitingTarget, belowCount,
paginationRequestPending,
+ positionOutcome,
scrollToBottom, requestPresentPosition, jumpTo,
captureOlderPageAnchor, captureNewerPageAnchor,
}
diff --git a/src/web/src/lib/community/virtual-list-position.test.ts b/src/web/src/lib/community/virtual-list-position.test.ts
new file mode 100644
index 000000000..4cdde203d
--- /dev/null
+++ b/src/web/src/lib/community/virtual-list-position.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureChannelMetadataToken } from "./conversation-qualification"
+import { retireCommunityAccount } from "./account-cache-lifecycle"
+import { retireCommunityChannelReading } from "@/lib/community-db/sync"
+import { shouldDehydrateCommunityQuery } from "@/lib/query-persister"
+import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "./virtual-list-position"
+
+const snapshot = (fingerprint = "rows"): VirtualListPositionSnapshot => ({
+ version: 1, fingerprint, offset: 300, width: 320, height: 500, paddingStart: 0, paddingEnd: 48,
+ anchorKey: "m3", anchorOffset: -20, at: Date.now(), measurements: [{ key: "m3", index: 3, start: 280, end: 380, size: 100, lane: 0 }],
+})
+
+describe("account-owned virtual layout lifetime", () => {
+ it("isolates accounts, conversations, list shapes and tags without storing message bodies", async () => {
+ const alice = await createCommunityQueryOwner("alice")
+ const bob = await createCommunityQueryOwner("bob")
+ const base: VirtualListPositionScope = { proof: captureChannelMetadataToken(alice.client, "A"), kind: "messages", tag: null }
+ const rows = [{ key: "m1", content: "Private message text", grouped: false }]
+ const fingerprint = virtualListLayoutFingerprint(rows)
+ saveVirtualListPosition(base, snapshot(fingerprint))
+ expect(readVirtualListPosition(base, fingerprint)?.offset).toBe(300)
+ for (const scope of [
+ { ...base, proof: captureChannelMetadataToken(bob.client, "A") },
+ { ...base, proof: captureChannelMetadataToken(alice.client, "B") },
+ { ...base, kind: "forum" as const }, { ...base, tag: "bug" },
+ ]) expect(readVirtualListPosition(scope, fingerprint)).toBeNull()
+ expect(readVirtualListPosition(base, virtualListLayoutFingerprint([{ ...rows[0], grouped: true }]))).toBeNull()
+ expect(JSON.stringify(alice.client.getQueryData(virtualListPositionKey(base)))).not.toContain("Private message text")
+ const query = alice.client.getQueryCache().find({ queryKey: virtualListPositionKey(base), exact: true })!
+ expect(shouldDehydrateCommunityQuery(query)).toBe(false)
+ })
+
+ it("expires layout records and bounds the number and size of retained lists", async () => {
+ const { client } = await createCommunityQueryOwner()
+ const scopes = Array.from({ length: 33 }, (_, index): VirtualListPositionScope => ({ proof: captureChannelMetadataToken(client, `c${index}`), kind: "messages", tag: null }))
+ for (const scope of scopes) saveVirtualListPosition(scope, snapshot())
+ expect(client.getQueryCache().findAll({ predicate: query => query.queryKey[3] === "virtual-position" })).toHaveLength(32)
+ expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
+ saveVirtualListPosition(scopes[32], { ...snapshot(), measurements: Array.from({ length: 2049 }, () => snapshot().measurements[0]) })
+ expect(readVirtualListPosition(scopes[32], "rows")).toBeNull()
+ saveVirtualListPosition(scopes[0], { ...snapshot(), measurements: Array.from({ length: 2049 }, () => snapshot().measurements[0]) })
+ expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
+ saveVirtualListPosition(scopes[0], { ...snapshot(), at: Date.now() - 300001 })
+ expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()
+ })
+
+ it("uses the existing account and channel retirement fences for stale capture callbacks", async () => {
+ const { client, registry } = await createCommunityQueryOwner()
+ const scope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }
+ saveVirtualListPosition(scope, snapshot())
+ retireCommunityChannelReading(registry, "A", { reason: "read-denied", serverId: null })
+ expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()
+ saveVirtualListPosition(scope, snapshot())
+ expect(readVirtualListPosition(scope, "rows")).toBeNull()
+ retireCommunityAccount(registry)
+ saveVirtualListPosition(scope, snapshot())
+ expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()
+ })
+})
diff --git a/src/web/src/lib/community/virtual-list-position.ts b/src/web/src/lib/community/virtual-list-position.ts
new file mode 100644
index 000000000..60fccc297
--- /dev/null
+++ b/src/web/src/lib/community/virtual-list-position.ts
@@ -0,0 +1,75 @@
+import { hashKey } from "@tanstack/react-query"
+import type { VirtualItem } from "@tanstack/react-virtual"
+import { isChannelMetadataTokenCurrent, type captureChannelMetadataToken } from "./conversation-qualification"
+
+export type VirtualListPositionScope = {
+ proof: ReturnType<typeof captureChannelMetadataToken>
+ kind: "messages" | "forum"
+ tag: string | null
+}
+
+export type VirtualListPositionSnapshot = {
+ version: 1
+ fingerprint: string
+ offset: number
+ width: number
+ height: number
+ paddingStart: number
+ paddingEnd: number
+ anchorKey: VirtualItem["key"]
+ anchorOffset: number
+ measurements: VirtualItem[]
+ at: number
+}
+
+const POSITION_GC_MS = 5 * 60 * 1000
+const MAX_POSITION_LISTS = 32
+const MAX_POSITION_MEASUREMENTS = 2048
+
+export function virtualListPositionKey({ proof, kind, tag }: VirtualListPositionScope) {
+ const channelId = proof.channelId!
+ const parentId = proof.channelLineage?.parentChannelId
+ return ["community", "channel", channelId, "virtual-position", proof.viewerId, kind, tag,
+ proof.accountEpoch, proof.accessEpoch, proof.ownerGeneration,
+ proof.channelScopes.get(channelId)?.generation ?? 0,
+ parentId ?? null, parentId ? proof.channelScopes.get(parentId)?.generation ?? 0 : 0] as const
+}
+
+export function virtualListLayoutFingerprint(rows: readonly unknown[]): string {
+ const value = hashKey(rows)
+ let first = 2166136261
+ let second = 0x9e3779b9
+ for (let index = 0; index < value.length; index++) {
+ const code = value.charCodeAt(index)
+ first = Math.imul(first ^ code, 16777619)
+ second = Math.imul(second ^ code, 0x85ebca6b)
+ }
+ return `${value.length}:${first >>> 0}:${second >>> 0}`
+}
+
+function current(scope: VirtualListPositionScope) {
+ return !!scope.proof.viewerId && !!scope.proof.channelId && isChannelMetadataTokenCurrent(scope.proof)
+}
+
+export function readVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string) {
+ if (!scope || !current(scope)) return null
+ const value = scope.proof.queryClient.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(scope))
+ return value?.version === 1 && value.fingerprint === fingerprint && Date.now() - value.at < POSITION_GC_MS ? value : null
+}
+
+export function saveVirtualListPosition(scope: VirtualListPositionScope | undefined, value: VirtualListPositionSnapshot) {
+ if (!scope || !current(scope) || value.width <= 0 || value.height <= 0
+ || !Number.isFinite(value.offset) || value.offset < 0 || !value.measurements.length) return
+ const client = scope.proof.queryClient
+ if (value.measurements.length > MAX_POSITION_MEASUREMENTS) {
+ client.removeQueries({ queryKey: virtualListPositionKey(scope), exact: true })
+ return
+ }
+ client.getQueryCache().build<VirtualListPositionSnapshot>(client, {
+ queryKey: virtualListPositionKey(scope), gcTime: POSITION_GC_MS,
+ }).setData(value)
+ const records = client.getQueryCache().findAll({ predicate: query => query.queryKey[0] === "community"
+ && query.queryKey[1] === "channel" && query.queryKey[3] === "virtual-position" })
+ .sort((left, right) => left.state.dataUpdatedAt - right.state.dataUpdatedAt)
+ for (const query of records.slice(0, Math.max(0, records.length - MAX_POSITION_LISTS))) client.getQueryCache().remove(query)
+}
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 2dc206e39..122f4ea1e 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -1,5 +1,5 @@
import { COMMUNITY_CONTRACT_VERSION } from "@alook/shared"
-import type { Locator, Page, Request, Route } from "@playwright/test"
+import type { ElementHandle, Locator, Page, Request, Route } from "@playwright/test"
import type { TiptapEditorHTMLElement } from "@tiptap/react"
import { test, expect } from "./_fixtures/case-fixture"
import {
@@ -94,6 +94,125 @@ function expectStableScroller(before: ScrollerGeometry, after: ScrollerGeometry)
}
}
+async function sampleReadingPosition(scroller: Locator) {
+ return scroller.evaluate((element) => {
+ const viewport = element.getBoundingClientRect()
+ const content = element.querySelector<HTMLElement>("[data-message-list-content]")
+ const message = Array.from(element.querySelectorAll<HTMLElement>("[data-msg-id]"))
+ .find(row => {
+ const rect = row.getBoundingClientRect()
+ return rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom
+ })
+ return {
+ ready: content?.dataset.readPositionReady === "true"
+ && content.dataset.initialPositionPhase === "revealed" && content.getAttribute("aria-hidden") === "false",
+ mediaReady: document.fonts.status === "loaded"
+ && Array.from(element.querySelectorAll("img")).every(image => image.complete),
+ clientWidth: element.clientWidth,
+ clientHeight: element.clientHeight,
+ scrollHeight: element.scrollHeight,
+ scrollTop: element.scrollTop,
+ anchor: message ? {
+ id: message.dataset.msgId!,
+ key: message.closest<HTMLElement>("[data-message-row-key]")!.dataset.messageRowKey!,
+ offset: message.getBoundingClientRect().top - viewport.top,
+ } : null,
+ rows: Array.from(element.querySelectorAll<HTMLElement>("[data-message-row-key]"))
+ .filter(row => {
+ const rect = row.getBoundingClientRect()
+ return rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom
+ }).map(row => {
+ const message = row.querySelector<HTMLElement>("[data-msg-id]")
+ const body = message?.querySelector<HTMLElement>("[data-community-message-body]")
+ if (message && !body) throw new Error(`Missing fixture message body: ${message.dataset.msgId}`)
+ return {
+ key: row.dataset.messageRowKey!, height: row.getBoundingClientRect().height,
+ id: message?.dataset.msgId ?? null,
+ text: body ? body.textContent : row.textContent,
+ paragraphs: body ? Array.from(body.querySelectorAll("p"), paragraph => paragraph.textContent) : null,
+ }
+ }),
+ }
+ })
+}
+
+type ReadingPosition = Awaited<ReturnType<typeof sampleReadingPosition>>
+type ReadingRoot = ElementHandle<HTMLElement | SVGElement>
+
+async function settledReadingPosition(scroller: Locator): Promise<ReadingPosition> {
+ let previous = "", stableSince = 0
+ let settled: ReadingPosition | null = null
+ await expect.poll(async () => {
+ const current = await sampleReadingPosition(scroller)
+ const signature = JSON.stringify(current)
+ if (signature !== previous) {
+ previous = signature
+ stableSince = Date.now()
+ }
+ if (!current.ready || !current.mediaReady || !current.anchor || Date.now() - stableSince < 400) return false
+ settled = current
+ return true
+ }, { timeout: 10_000, intervals: [100] }).toBe(true)
+ return settled!
+}
+
+async function readingRoot(scroller: Locator): Promise<ReadingRoot> {
+ const root = await scroller.elementHandle()
+ expect(root).not.toBeNull()
+ return root!
+}
+
+async function expectReadingRootDetached(root: ReadingRoot): Promise<void> {
+ await expect.poll(() => root.evaluate(element => element.isConnected)).toBe(false)
+}
+
+async function expectReadingRootRecreated(previous: ReadingRoot, scroller: Locator): Promise<void> {
+ const current = await readingRoot(scroller)
+ expect(await current.evaluate((element, old) => element.isConnected && element !== old, previous)).toBe(true)
+ await current.dispose()
+ await previous.dispose()
+}
+
+async function expectReadingRootRetained(previous: ReadingRoot, scroller: Locator): Promise<void> {
+ const current = await readingRoot(scroller)
+ expect(await current.evaluate((element, old) => element.isConnected && element === old, previous)).toBe(true)
+ await current.dispose()
+ await previous.dispose()
+}
+
+async function expectReadingPositionRestored(scroller: Locator, before: ReadingPosition, fixture: { id: string; paragraphs: readonly string[] }): Promise<void> {
+ const after = await settledReadingPosition(scroller)
+ expect(after.anchor?.id).toBe(before.anchor?.id)
+ expect(after.anchor?.key).toBe(before.anchor?.key)
+ expect(Math.abs(after.anchor!.offset - before.anchor!.offset), "restored message offset within its viewport").toBeLessThanOrEqual(1)
+ for (const key of ["clientWidth", "clientHeight", "scrollHeight", "scrollTop"] as const) {
+ expect(Math.abs(after[key] - before[key]), `qualified snapshot ${key}`).toBeLessThanOrEqual(1)
+ }
+ expect(after.rows.map(({ key, id, text }) => ({ key, id, text }))).toEqual(before.rows.map(({ key, id, text }) => ({ key, id, text })))
+ for (const position of [before, after]) {
+ const body = position.rows.find(row => row.id === fixture.id)
+ expect(body, `visible fixture message ${fixture.id}`).toBeDefined()
+ expect(body?.paragraphs).toEqual(fixture.paragraphs)
+ }
+ for (let index = 0; index < before.rows.length; index += 1) {
+ expect(Math.abs(after.rows[index].height - before.rows[index].height), `restored row ${before.rows[index].key}`).toBeLessThanOrEqual(1)
+ }
+}
+
+async function expectCanonicalTail(scroller: Locator, messageId: string): Promise<void> {
+ await expect.poll(() => scroller.evaluate((element, messageId) => {
+ const content = element.querySelector<HTMLElement>("[data-message-list-content]")
+ const body = Array.from(element.querySelectorAll<HTMLElement>("[data-msg-id]"))
+ .find(row => row.dataset.msgId === messageId)
+ const rect = body?.getBoundingClientRect(), viewport = element.getBoundingClientRect()
+ return {
+ ready: content?.dataset.readPositionReady === "true" && content.dataset.initialPositionPhase === "revealed",
+ visible: !!rect && rect.height > 0 && rect.bottom > viewport.top && rect.top < viewport.bottom,
+ atEnd: Math.abs(element.scrollHeight - element.clientHeight - element.scrollTop) <= 1,
+ }
+ }, messageId)).toEqual({ ready: true, visible: true, atEnd: true })
+}
+
async function clickAuthoritativeOwnerChannelRow(page: Page, channelId: string): Promise<void> {
const row = page.getByTestId(tid.channelRow(channelId))
await expect(row).toBeEnabled({ timeout: 20_000 })
@@ -357,7 +476,7 @@ function trackSurfaceGets(page: Page, channelId: string): SurfaceGetTracker {
return tracker
}
-async function expectRetainedMountGets(
+async function expectReturnReadsAndGets(
page: Page,
channelId: string,
departureReadState: ReadState,
@@ -435,10 +554,8 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await seedJoinServer("alice", "bob", serverId)
const channelBobMessageId = await seedMessage("bob", channelId, `channel **target** ${stamp}`)
const channelBobSecondMessageId = await seedMessage("bob", channelId, `channel _alternate_ ${stamp}`)
- await seedMessage("alice", channelId, Array.from(
- { length: 80 },
- (_, index) => `scroll restoration line ${index} ${stamp}`,
- ).join("\n\n"))
+ const channelScrollLines = Array.from({ length: 80 }, (_, index) => `scroll restoration line ${index} ${stamp}`)
+ const channelScrollMessageId = await seedMessage("alice", channelId, channelScrollLines.join("\n\n"))
const openerId = await seedMessage("alice", channelId, `thread opener ${stamp}`)
const threadId = await seedThread("alice", openerId, `mobile-thread-${stamp}`)
const threadBobMessageId = await seedMessage("bob", threadId, `thread **target** ${stamp}`)
@@ -446,10 +563,8 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
for (let index = 0; index < 24; index += 1) {
await seedMessage(index % 2 === 0 ? "alice" : "bob", dmId, `dm scroll row ${index} ${stamp}`)
}
- await seedMessage("bob", dmId, Array.from(
- { length: 70 },
- (_, index) => `dm scroll line ${index} ${stamp}`,
- ).join("\n\n"))
+ const dmScrollLines = Array.from({ length: 70 }, (_, index) => `dm scroll line ${index} ${stamp}`)
+ const dmScrollMessageId = await seedMessage("bob", dmId, dmScrollLines.join("\n\n"))
const bobInfo = await memberInfo("alice", serverId, userId("bob"))
const aliceInfo = await memberInfo("alice", serverId, userId("alice"))
const replyAuthorMention = `@${bobInfo.name}#${bobInfo.discriminator}`
@@ -969,6 +1084,20 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
expect(await latestSeq(alice.page, dmId)).toBe(beforeDmTypingSeq)
const dmScroller = alice.page.getByTestId(tid.messageScroller)
+ await test.step("qualify a fresh DM entry after the sender-confirmed read projection", async () => {
+ const confirmed = await settledReadState(alice.page, dmId)
+ expect(confirmed.lastReadMessageId).toBe(dmReplyPayload.message.id)
+ expect(confirmed.lastReadSeq).toBe(beforeDmTypingSeq)
+ const gets = trackSurfaceGets(alice.page, dmId)
+ await alice.page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe("/c/me")
+ await alice.page.getByTestId(tid.dmRow(dmId)).click()
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await expectCanonicalTail(dmScroller, dmReplyPayload.message.id)
+ await expect(dmScroller.locator("[data-new-divider]")).toHaveCount(0)
+ await expectReturnReadsAndGets(alice.page, dmId, confirmed, gets)
+ gets.stop()
+ })
await expect.poll(() => dmScroller.evaluate((element) => (
element.scrollHeight - element.clientHeight
))).toBeGreaterThan(1600)
@@ -979,38 +1108,43 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
})
expect(departedDmScrollTop).toBe(900)
const dmReadState = await settledReadState(alice.page, dmId)
+ const dmReadingPosition = await settledReadingPosition(dmScroller)
+ expect(Math.abs(dmReadingPosition.scrollTop - departedDmScrollTop)).toBeLessThanOrEqual(1)
+ expect(dmReadingPosition.scrollHeight - dmReadingPosition.clientHeight - dmReadingPosition.scrollTop).toBeGreaterThan(1)
+ const departedDmRoot = await readingRoot(dmScroller)
const dmReturnGets = trackSurfaceGets(alice.page, dmId)
await alice.page.getByRole("button", { name: "Back" }).click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe("/c/me")
+ await expectReadingRootDetached(departedDmRoot)
await alice.page.getByTestId(tid.dmRow(dmId)).click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
- await expect(alice.page.getByTestId(tid.message(dmReadState.lastReadMessageId!))).toBeVisible()
- await expectRetainedMountGets(alice.page, dmId, dmReadState, dmReturnGets)
- expect(Math.abs(await dmScroller.evaluate((element) => element.scrollTop) - departedDmScrollTop))
- .toBeGreaterThan(50)
+ await expectReadingPositionRestored(dmScroller, dmReadingPosition, { id: dmScrollMessageId, paragraphs: dmScrollLines })
+ await expectReadingRootRecreated(departedDmRoot, dmScroller)
+ await expectReturnReadsAndGets(alice.page, dmId, dmReadState, dmReturnGets)
dmReturnGets.stop()
- const departedDmReloadScrollTop = await dmScroller.evaluate((element) => {
- element.scrollTop = 700
- element.dispatchEvent(new Event("scroll"))
- return element.scrollTop
+ await test.step("DM reload creates a new document and lands at its confirmed canonical tail", async () => {
+ const departedDmReloadScrollTop = await dmScroller.evaluate((element) => {
+ element.scrollTop = 700
+ element.dispatchEvent(new Event("scroll"))
+ return element.scrollTop
+ })
+ expect(departedDmReloadScrollTop).toBe(700)
+ const beforeReload = await settledReadingPosition(dmScroller)
+ expect(beforeReload.scrollHeight - beforeReload.clientHeight - beforeReload.scrollTop).toBeGreaterThan(1)
+ const dmReloadReadState = await settledReadState(alice.page, dmId)
+ expect(dmReloadReadState.lastReadMessageId).toBe(dmReplyPayload.message.id)
+ expect(dmReloadReadState.lastReadSeq).toBe(beforeDmTypingSeq)
+ const documentTimeOrigin = await alice.page.evaluate(() => performance.timeOrigin)
+ const dmReloadGets = trackSurfaceGets(alice.page, dmId)
+ await alice.page.reload({ waitUntil: "commit" })
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
+ expect(await alice.page.evaluate(() => performance.timeOrigin)).toBeGreaterThan(documentTimeOrigin)
+ await expectCanonicalTail(dmScroller, dmReplyPayload.message.id)
+ await expectReturnReadsAndGets(alice.page, dmId, dmReloadReadState, dmReloadGets)
+ dmReloadGets.stop()
+ expect(await latestSeq(alice.page, dmId)).toBe(beforeDmTypingSeq)
})
- expect(departedDmReloadScrollTop).toBe(700)
- const dmReloadReadState = await settledReadState(alice.page, dmId)
- const dmReloadGets = trackSurfaceGets(alice.page, dmId)
- await alice.page.reload({ waitUntil: "commit" })
- await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/me/${dmId}`)
- const reloadedDmReadMessage = alice.page.getByTestId(tid.message(dmReloadReadState.lastReadMessageId!))
- await expect(async () => {
- expect(await reloadedDmReadMessage.count()).toBe(1)
- expect(await reloadedDmReadMessage.isVisible()).toBe(true)
- }).toPass({ timeout: 10_000 })
- await expectRetainedMountGets(alice.page, dmId, dmReloadReadState, dmReloadGets)
- expect(Math.abs(
- await dmScroller.evaluate((element) => element.scrollTop) - departedDmReloadScrollTop,
- )).toBeGreaterThan(50)
- expect(await latestSeq(alice.page, dmId)).toBe(beforeDmTypingSeq)
- dmReloadGets.stop()
await alice.page.emulateMedia({ reducedMotion: "reduce" })
await alice.page.evaluate(() => {
@@ -1057,20 +1191,27 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
})
expect(readingPosition).toBe(2200)
const channelReadState = await settledReadState(alice.page, channelId)
+ const channelSequence = await latestSeq(alice.page, channelId)
+ expect(channelReadState.lastReadSeq).toBe(channelSequence)
+ const channelReadingPosition = await settledReadingPosition(scroller)
+ expect(Math.abs(channelReadingPosition.scrollTop - readingPosition)).toBeLessThanOrEqual(1)
+ expect(channelReadingPosition.scrollHeight - channelReadingPosition.clientHeight - channelReadingPosition.scrollTop).toBeGreaterThan(1)
+ const departedChannelRoot = await readingRoot(scroller)
const channelReturnGets = trackSurfaceGets(alice.page, channelId)
await alice.page.getByRole("banner").getByRole("button", { name: "Back" }).click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ await expectReadingRootDetached(departedChannelRoot)
await clickAuthoritativeOwnerChannelRow(alice.page, channelId)
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
await expect(composerEditable(alice.page)).toContainText(navigationDraft)
- await expect(alice.page.getByTestId(tid.message(channelReadState.lastReadMessageId!))).toBeVisible()
- expect(Math.abs(await scroller.evaluate((element) => element.scrollTop) - readingPosition))
- .toBeGreaterThan(50)
- await expectRetainedMountGets(alice.page, channelId, channelReadState, channelReturnGets)
+ await expectReadingPositionRestored(scroller, channelReadingPosition, { id: channelScrollMessageId, paragraphs: channelScrollLines })
+ await expectReadingRootRecreated(departedChannelRoot, scroller)
+ await expectReturnReadsAndGets(alice.page, channelId, channelReadState, channelReturnGets)
channelReturnGets.stop()
+ expect(await latestSeq(alice.page, channelId)).toBe(channelSequence)
})
-test("mobile thread return uses server read state instead of tab-local pixel memory", async ({ caseActors }) => {
+test("mobile thread return recreates its list and restores the qualified reading anchor", async ({ caseActors }) => {
const actors = await caseActors(["alice"])
const { asUser } = actors
const { seedChannel, seedMessage, seedServer, seedThread } = actors.seed
@@ -1091,10 +1232,8 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
for (let index = 0; index < 24; index += 1) {
await seedMessage("alice", threadId, `thread scroll row ${index} ${stamp}`)
}
- await seedMessage("alice", threadId, Array.from(
- { length: 70 },
- (_, index) => `thread scroll line ${index} ${stamp}`,
- ).join("\n\n"))
+ const threadScrollLines = Array.from({ length: 70 }, (_, index) => `thread scroll line ${index} ${stamp}`)
+ const threadScrollMessageId = await seedMessage("alice", threadId, threadScrollLines.join("\n\n"))
const threadReplyId = await seedMessage("alice", threadId, `scroll thread reply ${stamp}`)
const alice = await asUser("alice")
@@ -1125,9 +1264,11 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
if (await scrollToPresent.isVisible()) await scrollToPresent.click()
const threadIndicator = alice.page.getByTestId(tid.threadIndicator(openerId))
await expect(threadIndicator).toBeVisible()
+ const parentRoot = await readingRoot(scroller)
await threadIndicator.click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)
await expect(alice.page.getByTestId(tid.message(threadReplyId))).toBeVisible()
+ expect(await parentRoot.evaluate(element => element.isConnected)).toBe(true)
const threadScroller = alice.page.getByTestId(tid.threadSplitPanel).getByTestId(tid.messageScroller)
await expect.poll(() => threadScroller.evaluate((element) => (
element.scrollHeight - element.clientHeight
@@ -1139,15 +1280,89 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
})
expect(departedThreadScrollTop).toBe(900)
const threadReadState = await settledReadState(alice.page, threadId)
+ expect(threadReadState.lastReadMessageId).toBe(threadReplyId)
+ const threadReadingPosition = await settledReadingPosition(threadScroller)
+ expect(Math.abs(threadReadingPosition.scrollTop - departedThreadScrollTop)).toBeLessThanOrEqual(1)
+ expect(threadReadingPosition.scrollHeight - threadReadingPosition.clientHeight - threadReadingPosition.scrollTop).toBeGreaterThan(1)
+ const departedThreadRoot = await readingRoot(threadScroller)
const threadReturnGets = trackSurfaceGets(alice.page, threadId)
await alice.page.goBack({ waitUntil: "commit" })
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
await expect(composerEditable(alice.page)).toContainText(draft)
+ await expectReadingRootDetached(departedThreadRoot)
+ await expectReadingRootRetained(parentRoot, scroller)
await alice.page.goForward({ waitUntil: "commit" })
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)
- await expect(alice.page.getByTestId(tid.message(threadReadState.lastReadMessageId!))).toBeVisible()
- await expectRetainedMountGets(alice.page, threadId, threadReadState, threadReturnGets)
- expect(Math.abs(await threadScroller.evaluate((element) => element.scrollTop) - departedThreadScrollTop))
- .toBeGreaterThan(50)
+ await expectReadingPositionRestored(threadScroller, threadReadingPosition, { id: threadScrollMessageId, paragraphs: threadScrollLines })
+ await expectReadingRootRecreated(departedThreadRoot, threadScroller)
+ await expectReturnReadsAndGets(alice.page, threadId, threadReadState, threadReturnGets)
threadReturnGets.stop()
})
+
+test("mobile width change invalidates a previously qualified snapshot and falls back to its canonical tail", async ({ caseActors }) => {
+ test.setTimeout(120_000)
+ const actors = await caseActors(["alice"])
+ const { seedChannel, seedMessage, seedServer } = actors.seed
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Mobile-width-${stamp}`)
+ const channelId = await seedChannel("alice", serverId, "width-fallback")
+ for (let index = 0; index < 24; index += 1) {
+ await seedMessage("alice", channelId, `width row ${index} ${stamp}`)
+ }
+ const widthScrollLines = Array.from({ length: 80 }, (_, index) => `width layout line ${index} ${stamp}`)
+ const widthScrollMessageId = await seedMessage("alice", channelId, widthScrollLines.join("\n\n"))
+ const tailId = await seedMessage("alice", channelId, `width canonical tail ${stamp}`)
+ const alice = await actors.asUser("alice")
+ await alice.page.setViewportSize({ width: 390, height: 844 })
+ const href = `/c/channels/${serverId}/${channelId}`
+ await gotoAfterUserWsAuth(alice.page, href)
+ await ignoreNextDevToolsPointerCapture(alice.page)
+ const scroller = alice.page.getByTestId(tid.messageScroller)
+ await expectCanonicalTail(scroller, tailId)
+ const sequence = await latestSeq(alice.page, channelId)
+ const read = await settledReadState(alice.page, channelId)
+ expect(read.lastReadMessageId).toBe(tailId)
+ expect(read.lastReadSeq).toBe(sequence)
+ await expect.poll(() => scroller.evaluate(element => element.scrollHeight - element.clientHeight)).toBeGreaterThan(2200)
+ await scroller.evaluate(element => {
+ element.scrollTop = 1200
+ element.dispatchEvent(new Event("scroll"))
+ })
+ const departure = await settledReadingPosition(scroller)
+ expect(departure.scrollTop).toBe(1200)
+ expect(departure.scrollHeight - departure.clientHeight - departure.scrollTop).toBeGreaterThan(1)
+
+ await test.step("the unchanged viewport recreates the node and restores its qualified anchor", async () => {
+ const original = await readingRoot(scroller)
+ const gets = trackSurfaceGets(alice.page, channelId)
+ await alice.page.getByRole("banner").getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ await expectReadingRootDetached(original)
+ await clickAuthoritativeOwnerChannelRow(alice.page, channelId)
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(href)
+ await expectReadingPositionRestored(scroller, departure, { id: widthScrollMessageId, paragraphs: widthScrollLines })
+ await expectReadingRootRecreated(original, scroller)
+ await expectReturnReadsAndGets(alice.page, channelId, read, gets)
+ gets.stop()
+ })
+
+ await test.step("a changed viewport rejects that snapshot and lands on the confirmed read tail", async () => {
+ const qualified = await settledReadingPosition(scroller)
+ expect(qualified.clientWidth).toBe(departure.clientWidth)
+ const original = await readingRoot(scroller)
+ const gets = trackSurfaceGets(alice.page, channelId)
+ await alice.page.getByRole("banner").getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ await expectReadingRootDetached(original)
+ await alice.page.setViewportSize({ width: 430, height: 844 })
+ await clickAuthoritativeOwnerChannelRow(alice.page, channelId)
+ await expect.poll(() => new URL(alice.page.url()).pathname).toBe(href)
+ await expectCanonicalTail(scroller, tailId)
+ expect(await scroller.evaluate(element => element.clientWidth)).not.toBe(qualified.clientWidth)
+ await expectReadingRootRecreated(original, scroller)
+ await expectReturnReadsAndGets(alice.page, channelId, read, gets)
+ gets.stop()
+ })
+ expect(await settledReadState(alice.page, channelId)).toEqual(read)
+ expect(await latestSeq(alice.page, channelId)).toBe(sequence)
+})
diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.ts
index d9a9719ba..56a1a27a4 100644
--- a/src/web/src/test/message-scroll-fixture.ts
+++ b/src/web/src/test/message-scroll-fixture.ts
@@ -26,7 +26,7 @@ let scrollCalls: number[]
let pendingScrollEvents: Set<HTMLElement>
let scrollDescriptor: PropertyDescriptor | undefined
-const ROOT_SELECTOR = '[data-testid="scroll"], [data-testid="community-message-scroller"]'
+const ROOT_SELECTOR = '[data-testid="scroll"], [data-testid="community-message-scroller"], [data-testid="community-forum-post-list"]'
function isScrollRoot(node: HTMLElement) { return node.matches(ROOT_SELECTOR) }
function rootFor(node: HTMLElement) { return node.closest<HTMLElement>(ROOT_SELECTOR) }
function deliverScrollEvents() {
@@ -205,7 +205,8 @@ export function installMessageScrollFixture() {
})
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(function (this: HTMLElement) {
return isScrollRoot(this)
- ? Math.max(this.clientHeight, Number.parseFloat(this.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height ?? "0") || 0)
+ ? Math.max(this.clientHeight, Number.parseFloat(this.querySelector<HTMLElement>('[data-message-list-content]')?.style.height
+ || this.querySelector<HTMLElement>('[data-message-list-content] > div')?.style.height || "0") || 0)
: rowGeometry(this).height
})
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {