Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep message scroll position stable (#1134)

Gener7ea9ec180db5
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 06cd69003..9cbe4c04c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -356,8 +356,8 @@ importers:
specifier: 0.11.2
'@tanstack/react-virtual':
- specifier: 3.14.22
+ specifier: 3.14.24
'@tanstack/store':
specifier: 0.11.2
version: 0.11.2
@@ -3639,8 +3639,8 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-zNiB9IF3prySTfAUrj9tPHjD/lonBYkfxrPP4v4ITUx+qwHajJR5cY/xirjvwc+KWkur10GX3TpsbKh7JkD8Lw==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-JoNsByXR68fNlB2NZuT3bSk8uYBxuOWl6YNJ7djTrw7IMwBWuaOtffxj/TcuMa80WmL6byb+80i1NEM/8Qmocw==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
@@ -3648,8 +3648,8 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-sJ4mjol8uQsHV0gOJzzjwXfh2Fwm+Sz0+8deqiTm4jGbMdjzNSW+xZCFm0kUa870uhd8yi+DpKnZb5Kc4apa0Q==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-gxy5SvH0mFRJ0YujtrflB/1HAu9Wn1KGvL0bjZfQkYVVMsIpQiwcf1mR06/ViN4NjllUb4HNCjqE9FGwgTvMCQ==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-Syiaf3w69dFyYv4o2mqJ1/2VtBJTNq5Hu5cVXfnzOuJKFpUojukQR13ZW+5NvdMJM7GFHeNPmveMNhoIubiFyA==}
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}
@@ -12871,15 +12871,15 @@ snapshots:
react-dom: 19.3.1([email protected])
use-sync-external-store: 1.6.0([email protected])
dependencies:
- '@tanstack/virtual-core': 3.19.7
+ '@tanstack/virtual-core': 3.19.9
react: 19.3.1
react-dom: 19.3.1([email protected])
'@tanstack/[email protected]': {}
- '@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
'@tauri-apps/[email protected]': {}
diff --git a/src/web/package.json b/src/web/package.json
index 20e116e69..c68d66c25 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -68,7 +68,7 @@
"@tanstack/react-query": "5.104.5",
"@tanstack/react-query-persist-client": "5.104.5",
"@tanstack/react-store": "0.11.2",
- "@tanstack/react-virtual": "3.14.22",
+ "@tanstack/react-virtual": "3.14.24",
"@tanstack/store": "0.11.2",
"@tauri-apps/plugin-clipboard-manager": "^2.5.0",
"@tiptap/extension-list": "^3.32.0",
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 739ce8a7d..7b07bbdd5 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
@@ -268,6 +268,7 @@ describe("useMessageListController", () => {
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: undefined,
edge: "start",
+ preloadWithinViewport: true,
},
{
virtualizer: mocks.virtualizer,
@@ -281,6 +282,7 @@ describe("useMessageListController", () => {
onBeforeLoad: mocks.captureNewerPageAnchor,
onLoad: undefined,
edge: "end",
+ preloadWithinViewport: true,
},
])
expect(latest.scrollRef).toBe(mocks.scrollRef)
@@ -430,6 +432,7 @@ describe("useMessageListController", () => {
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: loadOlder,
edge: "start",
+ preloadWithinViewport: true,
},
{
virtualizer: mocks.virtualizer,
@@ -443,6 +446,7 @@ describe("useMessageListController", () => {
onBeforeLoad: mocks.captureNewerPageAnchor,
onLoad: loadNewer,
edge: "end",
+ preloadWithinViewport: true,
},
])
expect(latest.pillCount).toBe(9)
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 e03b70ac0..2b1dd11fc 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -154,6 +154,7 @@ export function useMessageListController({
onLoad: onLoadOlder,
edge: "start",
requestKey: messageWindow,
+ preloadWithinViewport: true,
})
useVirtualCursorPagination({
virtualizer,
@@ -167,6 +168,7 @@ export function useMessageListController({
onLoad: onLoadNewer,
edge: "end",
requestKey: messageWindow,
+ preloadWithinViewport: true,
})
const jumpClearTimerRef = useRef<number | null>(null)
diff --git a/src/web/src/components/community/messages/message-list.pending-scroll.dom.test.ts b/src/web/src/components/community/messages/message-list.pending-scroll.dom.test.ts
index 10ea7334d..a9eace3b6 100644
--- a/src/web/src/components/community/messages/message-list.pending-scroll.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list.pending-scroll.dom.test.ts
@@ -49,6 +49,75 @@ function messageOffset(root: HTMLElement, id: string) {
}
describe("MessageList continuous input through an accepted page", () => {
+ it.each(["response-first", "rows-first"])("captures a first body reached after early prefetch (%s)", async order => {
+ let messages = Array.from({ length: 50 }, (_, index) => message(index + 40))
+ const before = {}, received = {}
+ let complete!: (result: MessageRequestResult) => void
+ const completed = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ const older = vi.fn(() => ({ accepted: true as const, completed }))
+ const view = (window = before, fetching = false) => React.createElement(MessageList, {
+ channel: "general", messages, messageWindow: window, initialScrollReady: true,
+ initialPositionMessageId: "m65", positionDataState: "ready", hasMore: true,
+ hasMoreNewer: true, isFetchingOlder: fetching, onLoadOlder: older, onOpenThread: vi.fn(),
+ })
+ const renderer = render(view())
+ resize()
+ const root = renderer.getByTestId(tid.messageScroller)
+ fireEvent.wheel(root, { deltaY: -20 })
+ act(() => root.scrollTo({ top: root.clientHeight }))
+ resize(0)
+ runFrames(1)
+ expect(older).toHaveBeenCalledOnce()
+ const native = anchorState.current!.virtualizer
+ const trace: Array<Record<string, unknown>> = []
+ const record = (phase: string) => trace.push({ phase, top: root.scrollTop, height: root.scrollHeight, total: native.getTotalSize(),
+ nativeOffset: native.scrollOffset, body: messageOffset(root, "m40"), pending: anchorState.current!.paginationRequestPending,
+ row: native.getVirtualItems().find(row => row.key === "msg:id:m40"), writes: [...anchorState.nativeWrites] })
+ onTestFinished(() => {
+ if (process.env.ALOOK_SCROLL_TRACE === "1") process.stdout.write(`MESSAGE_LATE_FIRST_BODY_TRACE ${JSON.stringify({ order, trace })}\n`)
+ })
+ expect(native.getVirtualItemForOffset(root.scrollTop)?.key).not.toBe("msg:id:m40")
+ renderer.rerender(view(before, true))
+ const first = native.getVirtualItems().find(row => row.key === "msg:id:m40")!
+ expect(first).toBeDefined()
+ fireEvent.wheel(root, { deltaY: -20 })
+ act(() => root.scrollTo({ top: first.start + 20 }))
+ resize(0)
+ runFrames(1)
+ expect(native.getVirtualItemForOffset(root.scrollTop)?.key).toBe("msg:id:m40")
+ const bodyInset = () => {
+ const body = root.querySelector<HTMLElement>('[data-msg-id="m40"]')!
+ return body.getBoundingClientRect().top - body.closest("[data-index]")!.getBoundingClientRect().top
+ }
+ const top = messageOffset(root, "m40")!
+ record("first-body-before-publication")
+ const inset = bodyInset()
+ expect(inset).toBeGreaterThan(0)
+ const publish = () => { messages = [...Array.from({ length: 39 }, (_, index) => message(index + 1)), ...messages] }
+ if (order === "rows-first") {
+ publish()
+ renderer.rerender(view(before, true))
+ resize(0)
+ expect.soft(messageOffset(root, "m40")).toBeCloseTo(top, 0)
+ runFrames(1)
+ record("rows-before-receipt")
+ expect.soft(messageOffset(root, "m40")).toBeCloseTo(top, 0)
+ expect(anchorState.current!.paginationRequestPending).toBe(true)
+ }
+ await act(async () => { complete({ status: "success", window: received }) })
+ if (order === "response-first") publish()
+ renderer.rerender(view(received))
+ resize(0)
+ record("response-measured")
+ expect.soft(messageOffset(root, "m40")).toBeCloseTo(top, 0)
+ runFrames()
+ record("response-frames")
+ expect(bodyInset()).toBe(inset / 2)
+ expect(messageOffset(root, "m40")).toBeCloseTo(top, 0)
+ expect(anchorState.current!.paginationRequestPending).toBe(false)
+ expect(older).toHaveBeenCalledOnce()
+ })
+
it.each([
["older", "response-first", "edge"], ["older", "rows-first", "edge"],
["newer", "response-first", "edge"], ["newer", "rows-first", "edge"],
@@ -106,6 +175,15 @@ describe("MessageList continuous input through an accepted page", () => {
expect(load).toHaveBeenCalledOnce()
record("accepted-page")
renderer.rerender(view(before, true))
+ if (direction === "newer" && position === "edge") {
+ const measuredEnd = root.scrollHeight - root.clientHeight
+ fireEvent.wheel(root, { deltaY: measuredEnd - root.scrollTop })
+ act(() => root.scrollTo({ top: measuredEnd }))
+ resize(0)
+ runFrames(1)
+ record("measured-edge-precondition")
+ expect(root.scrollHeight - root.clientHeight - root.scrollTop).toBeLessThanOrEqual(1)
+ }
for (let step = 1; step <= 3; step++) {
const delta = (direction === "older" ? -1 : 1) * (position === "edge" ? 30 : -120)
const previous = root.scrollTop
diff --git a/src/web/src/hooks/community/use-scroll-anchor.measure-commit.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.measure-commit.dom.test.ts
index c5b09d046..426ef062e 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.measure-commit.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.measure-commit.dom.test.ts
@@ -1,11 +1,57 @@
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
-import { screen } from "@/test/react-dom-harness"
-import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import { act, fireEvent, screen } from "@/test/react-dom-harness"
+import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
beforeEach(installMessageScrollFixture)
afterEach(restoreMessageScrollFixture)
describe("native row measurement commits the matching viewport geometry", () => {
+ it.each([false, true])("preserves a reading row through repeated above-fold growth during backward input (StrictMode=%s)", strict => {
+ const h = mount({ items: Array.from({ length: 50 }, (_, i) => message(`m${i}`)), hasMoreOlder: false }, strict)
+ h.move(700)
+ fireEvent.wheel(h.root, { deltaY: -150 })
+ act(() => h.root.scrollTo({ top: 550 }))
+ resize(0)
+ const native = scrollFixture.latest.virtualizer
+ expect(native.scrollDirection).toBe("backward")
+ const anchor = native.getVirtualItemForOffset(h.root.scrollTop + 1)
+ const above = native.getVirtualItems().find(row => String(row.key).startsWith("msg:") && row.end <= h.root.scrollTop)
+ if (!anchor || !above) throw new Error("Measured reading and above-fold rows are required")
+ const readingId = String(anchor.key).slice(4)
+ const growingId = String(above.key).slice(4)
+ expect(native.itemSizeCache.has(above.key)).toBe(true)
+ const before = { top: bodyTop(h.root, readingId), offset: h.root.scrollTop }
+ let growth = 0
+ for (const delta of [100, 80]) {
+ growth += delta
+ scrollFixture.bodyHeights.set(growingId, above.size + growth)
+ resize(0)
+ expect(bodyTop(h.root, readingId)).toBeCloseTo(before.top, 0)
+ expect(h.root.scrollTop).toBeCloseTo(before.offset + growth, 0)
+ runFrames(1)
+ }
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it.each(["spanning", "below"])("keeps the reading point when a %s row grows during backward input", location => {
+ const h = mount({ items: Array.from({ length: 50 }, (_, i) => message(`m${i}`)), hasMoreOlder: false })
+ h.move(700)
+ fireEvent.wheel(h.root, { deltaY: -150 })
+ act(() => h.root.scrollTo({ top: 550 }))
+ resize(0)
+ const native = scrollFixture.latest.virtualizer
+ expect(native.scrollDirection).toBe("backward")
+ const reading = native.getVirtualItemForOffset(h.root.scrollTop + 1)!
+ const growing = location === "spanning" ? reading : native.getVirtualItems().find(row => row.start >= h.root.scrollTop + h.root.clientHeight)!
+ expect(growing).toBeDefined()
+ const readingId = String(reading.key).slice(4)
+ const before = { top: bodyTop(h.root, readingId), offset: h.root.scrollTop }
+ scrollFixture.bodyHeights.set(String(growing.key).slice(4), growing.size + 80)
+ resize(0)
+ expect(bodyTop(h.root, readingId)).toBeCloseTo(before.top, 0)
+ expect(h.root.scrollTop).toBeCloseTo(before.offset, 0)
+ })
+
it.each([
["tail", false], ["reader", false], ["tail", true], ["reader", true],
] as const)("keeps %s geometry coherent before observer delivery returns (StrictMode=%s)", (position, strict) => {
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 99b31c1b6..de8858bd4 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
@@ -19,6 +19,35 @@ function failedInitialReader(onInitialPositionSettled?: () => void) {
}
describe("locked native adapter and existing message scroll owner", () => {
+ it.each([0, 0.5, 1, 2])("does not follow a tail resize after upward takeover at %spx from the end", distance => {
+ const h = mount()
+ h.move(h.root.scrollHeight - h.root.clientHeight - distance)
+ const native = scrollFixture.latest.virtualizer
+ fireEvent.wheel(h.root, { deltaY: -20 })
+ expect(native.options.followOnAppend).toBe(false)
+ const before = h.root.scrollTop
+ expect(h.root.scrollHeight - h.root.clientHeight - before).toBeCloseTo(distance, 1)
+ scrollFixture.bodyHeights.set("m13", 200)
+ resize(0)
+ expect(h.root.scrollTop).toBeCloseTo(before, 1)
+ })
+
+ it("restores native tail eligibility before a peer append in the same React commit", () => {
+ const h = mount()
+ const native = scrollFixture.latest.virtualizer
+ fireEvent.wheel(h.root, { deltaY: -20 })
+ expect(native.options.scrollEndThreshold).toBe(-1)
+ const end = vi.spyOn(native, "scrollToEnd")
+ act(() => {
+ fireEvent.wheel(h.root, { deltaY: 20 })
+ h.stage({ items: [...h.input.items, message("received-with-resume")] })
+ })
+ resize()
+ expect(end).toHaveBeenCalledOnce()
+ expect(native.options.scrollEndThreshold).toBe(1)
+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)
+ })
+
it("hands a pending native tail command to real upward intent before exact one-pixel positioning", () => {
const h = mount()
const native = scrollFixture.latest.virtualizer
@@ -843,7 +872,6 @@ describe("locked native adapter and existing message scroll owner", () => {
h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
expect(bodyTop(h.root, input === "wheel" ? "m3" : "m8")).toBe(before)
expect(index).not.toHaveBeenCalled()
- expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
})
it("returns to native measurement policy when the header-fold restore settles", () => {
const h = mount()
@@ -868,12 +896,10 @@ describe("locked native adapter and existing message scroll owner", () => {
const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
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)
@@ -906,7 +932,6 @@ describe("locked native adapter and existing message scroll owner", () => {
resize(2)
h.stage({ items: h.input.items.filter(item => item.m.id !== "m0") })
resize(0)
- expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
runFrames()
const readingTop = bodyTop(h.root, "older-29")
const nextTop = bodyTop(h.root, "m1")
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 255408be4..2119e2b76 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -233,7 +233,15 @@ export function useScrollAnchor({
positionScopeRef.current = positionScope
}, [items, positionEntry, positionScope, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, onUserTakeover, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
const followSuspension = useCreateAtom(false)
- const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
+ const [followSuspended, writeFollowSuspended] = useAtom(followSuspension)
+ const setFollowSuspended = useCallback((suspended: boolean) => {
+ const native = virtualizerRef.current
+ const scrollEndThreshold = suspended ? -1 : 1
+ if (native && native.options.scrollEndThreshold !== scrollEndThreshold) {
+ native.setOptions({ ...native.options, scrollEndThreshold })
+ }
+ writeFollowSuspended(suspended)
+ }, [writeFollowSuspended])
const acceptedGeometryRef = useRef<Geometry | null>(null)
const geometryFrameRef = useRef<number | null>(null)
const geometryObserverRef = useRef<ResizeObserver | null>(null)
@@ -259,7 +267,6 @@ export function useScrollAnchor({
}, [presentation, setPositionOutcome])
const clearMeasurementAnchor = useCallback(() => {
measurementAnchorRef.current = null
- if (virtualizerRef.current) virtualizerRef.current.shouldAdjustScrollPositionOnItemSizeChange = undefined
}, [])
const observePageBody = useCallback(() => {
const observer = geometryObserverRef.current
@@ -273,13 +280,16 @@ export function useScrollAnchor({
observedPageBodyRef.current = body
if (body) observer.observe(body)
}, [])
- const adjustAnchoredMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item) => {
+ const adjustMeasurement = useCallback<NonNullable<ReactVirtualizer<HTMLDivElement, Element>["shouldAdjustScrollPositionOnItemSizeChange"]>>((item, _delta, native) => {
const anchor = measurementAnchorRef.current
const owner = positionOwnerRef.current
const ownsAnchor = positionKind.get() === "idle"
const index = anchor && anchor.epoch === owner.epoch && owner.active && ownsAnchor
? currentItemsRef.current.findIndex(row => row.key === anchor.key) : -1
- return item.index < index
+ if (index >= 0) return item.index < index
+ const offset = native.scrollOffset ?? 0
+ const measured = native.itemSizeCache.get(item.key)
+ return measured === undefined ? item.start < offset : item.start + measured <= offset
}, [positionKind])
const beginPosition = useCallback((kind: Kind) => {
const epoch = positionOwnerRef.current.epoch
@@ -338,7 +348,6 @@ export function useScrollAnchor({
claimPosition("idle", preservePage)
if (keepMeasurement && measurement && native) {
measurementAnchorRef.current = { key: measurement.key, epoch: positionOwnerRef.current.epoch }
- native.shouldAdjustScrollPositionOnItemSizeChange = adjustAnchoredMeasurement
}
if (userHandover && wasReadable) setReadPositionReady(true)
retireInitialPosition()
@@ -350,7 +359,7 @@ export function useScrollAnchor({
}
settlePresentation(outcome)
scheduleGeometryRef.current()
- }, [adjustAnchoredMeasurement, claimPosition, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
+ }, [claimPosition, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {
const root = scrollRef.current
const native = virtualizerRef.current
@@ -369,13 +378,32 @@ export function useScrollAnchor({
const bodyInset = bodyRect.top - rect.top
return { viewportOffset: offset + bodyInset, bodyInset }
}, [])
+ const readFirstPageAnchor = useCallback(() => {
+ const native = virtualizerRef.current
+ const offset = native?.scrollOffset ?? 0
+ const fold = native?.getVirtualItemForOffset(offset)
+ const first = currentItemsRef.current.find(item => item.kind === "message")
+ const header = !!fold && currentItemsRef.current[fold.index]?.kind !== "message"
+ if (!native || !fold || !first || !header && String(fold.key) !== first.key) return
+ const message = native.getVirtualItems().find(item => currentItemsRef.current[item.index]?.kind === "message" && item.end > offset)
+ const geometry = message && readPageMessageGeometry(String(message.key))
+ if (!message || !geometry) return
+ return { key: String(message.key), ...geometry, header, firstKey: first.key, epoch: positionOwnerRef.current.epoch }
+ }, [readPageMessageGeometry])
const refreshPendingPageAnchor = useCallback(() => {
const page = paginationRef.current
const anchor = page?.anchor
- if (!page || page.phase === "settling" || !anchor
- || !positionOwnerRef.current.active || anchor.epoch !== positionOwnerRef.current.epoch
- || positionKind.get() !== "idle"
- || currentItemsRef.current.find(item => item.kind === "message")?.key !== anchor.firstKey) return
+ if (!page || page.phase === "settling" || !positionOwnerRef.current.active || positionKind.get() !== "idle") return
+ const first = currentItemsRef.current.find(item => item.kind === "message")
+ if (!anchor) {
+ const beforeFirst = page.receipt?.beforeItems.find(item => item.kind === "message")
+ if (page.direction === "older" && page.receipt && first?.key === beforeFirst?.key) {
+ page.anchor = readFirstPageAnchor()
+ observePageBody()
+ }
+ return
+ }
+ if (anchor.epoch !== positionOwnerRef.current.epoch || first?.key !== anchor.firstKey) return
const native = virtualizerRef.current
const fold = native?.getVirtualItemForOffset(native.scrollOffset ?? 0)
if (fold && currentItemsRef.current[fold.index]?.kind === "message") {
@@ -387,7 +415,7 @@ export function useScrollAnchor({
if (fold) anchor.header = currentItemsRef.current[fold.index]?.kind !== "message"
const offset = readPageMessageGeometry(anchor.key)
if (offset !== null) Object.assign(anchor, offset)
- }, [positionKind, readPageMessageGeometry])
+ }, [observePageBody, positionKind, readFirstPageAnchor, readPageMessageGeometry])
const awaitingTarget = !!scrollToMessageId && positionedTargetRef.current !== scrollToMessageId
const pendingLateNew = visible && initialScrollReady && !!newDividerBefore && entryResolvedRef.current
&& lateNewRef.current.allowed && !lateNewRef.current.consumed && (ownerKind === "idle" || ownerKind === "initial")
@@ -439,7 +467,7 @@ export function useScrollAnchor({
&& !pendingLocalSubmit && !pendingLateNew && !followSuspended && !hasMoreNewer
&& !isFetchingOlder && !isFetchingNewer && paginationDirection === null
&& (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,
- scrollEndThreshold: 1,
+ scrollEndThreshold: followSuspended ? -1 : 1,
scrollMargin: 0,
paddingStart: shortGap,
paddingEnd: tailPaddingEnd,
@@ -447,6 +475,7 @@ export function useScrollAnchor({
onChange: () => { refreshPendingPageAnchor(); reconcileViewportRef.current(); scheduleGeometryRef.current() },
})
virtualizerRef.current = virtualizer
+ virtualizer.shouldAdjustScrollPositionOnItemSizeChange = adjustMeasurement
useLayoutEffect(() => { refreshPendingPageAnchor() })
useLayoutEffect(() => {
const anchor = measurementAnchorRef.current
@@ -820,6 +849,7 @@ export function useScrollAnchor({
}
if (!hasCommittedRows()) return false
if (page.phase !== "settling" || page.restoringBody && page.bodyItems !== currentItemsRef.current) {
+ if (!readGeometry()) return false
page.phase = "settling"
const anchor = page.anchor
const items = currentItemsRef.current
@@ -830,7 +860,6 @@ export function useScrollAnchor({
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]
@@ -853,7 +882,7 @@ export function useScrollAnchor({
}
if (native.isScrolling || page.receipt && !page.receipt.result) return false
return finish()
- }, [adjustAnchoredMeasurement, clearMeasurementAnchor, hasCommittedRows, holdNativeOrigin, observePageBody, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
+ }, [clearMeasurementAnchor, hasCommittedRows, holdNativeOrigin, observePageBody, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
const reconcileGeometry = useCallback((viewportOnly = false) => {
const root = scrollRef.current
@@ -1097,19 +1126,7 @@ export function useScrollAnchor({
if (positionKind.get() === "idle") {
const geometry = readGeometry()
if (geometry) acceptedGeometryRef.current = geometry
- const native = virtualizerRef.current
- const offset = native?.scrollOffset ?? 0
- const fold = native?.getVirtualItemForOffset(offset)
- const first = currentItemsRef.current.find(item => item.kind === "message")
- const header = !!fold && currentItemsRef.current[fold.index]?.kind !== "message"
- if (direction === "older" && fold && (header || String(fold.key) === first?.key)) {
- const message = native?.getVirtualItems().find(item => currentItemsRef.current[item.index]?.kind === "message" && item.end > offset)
- const viewportOffset = message && readPageMessageGeometry(String(message.key))
- if (message && first && viewportOffset !== null && viewportOffset !== undefined) anchor = {
- key: String(message.key), ...viewportOffset, header,
- firstKey: first.key, epoch: positionOwnerRef.current.epoch,
- }
- }
+ if (direction === "older") anchor = readFirstPageAnchor()
}
paginationRef.current = { direction, phase: "pending", anchor }
observePageBody()
@@ -1132,7 +1149,7 @@ export function useScrollAnchor({
}
void request.completed.then(complete, () => complete({ status: "error" }))
}
- }, [clearMeasurementAnchor, observePageBody, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
+ }, [clearMeasurementAnchor, observePageBody, positionKind, readFirstPageAnchor, readGeometry, setPaginationDirection])
const captureOlderPageAnchor = useCallback(() => capturePageAnchor("older"), [capturePageAnchor])
const captureNewerPageAnchor = useCallback(() => capturePageAnchor("newer"), [capturePageAnchor])
useLayoutEffect(() => { scheduleGeometry() }, [dataState, isFetchingNewer, isFetchingOlder, messageWindow, requestRevision, scheduleGeometry])
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
index 95cdb1d33..5e3866a35 100644
--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
@@ -1,7 +1,7 @@
import { createElement } from "react"
import { describe, expect, it, vi } from "vitest"
import type { VirtualItem } from "@tanstack/react-virtual"
-import { render } from "@/test/react-dom-harness"
+import { fireEvent, render } from "@/test/react-dom-harness"
import { useVirtualCursorPagination } from "./use-virtual-cursor-pagination"
type Props = Parameters<typeof useVirtualCursorPagination>[0]
@@ -26,6 +26,81 @@ describe.each(["start", "end"] as const)("native virtual cursor pagination (%s)"
}
const boundary = edge === "start" ? [0, 1] : [8, 9]
+ function viewportFixture(distance: number, indices = [4, 5], overrides: Partial<Props> = {}, contentHeight = 5000) {
+ const root = document.createElement("div")
+ Object.defineProperties(root, {
+ clientHeight: { value: 500, configurable: true },
+ scrollHeight: { value: contentHeight, configurable: true },
+ })
+ const move = (next: number) => { root.scrollTop = edge === "start" ? next : contentHeight - 500 - next; fireEvent.scroll(root) }
+ move(distance)
+ const f = fixture({ preloadWithinViewport: true, virtualizer: { getVirtualItems: () => range(...indices), scrollElement: root }, ...overrides })
+ return { ...f, root, move }
+ }
+
+ it("preloads one viewport away while the virtual range stays inside one tall row", () => {
+ const f = viewportFixture(501)
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.move(500)
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ f.move(499)
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ expect(f.onBeforeLoad.mock.invocationCallOrder[0]).toBeLessThan(f.onLoad.mock.invocationCallOrder[0])
+ })
+
+ it("does not use a distant overscan boundary as the pixel preload threshold", () => {
+ const f = viewportFixture(2000, boundary)
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.move(500)
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("deduplicates a pending window while the visible boundary keys change", () => {
+ const indices = [4, 5]
+ const f = viewportFixture(400, indices, { requestKey: {} })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ indices.splice(0, 2, 2, 3)
+ f.move(300)
+ indices.splice(0, 2, 0, 1)
+ f.move(200)
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ expect(f.onBeforeLoad).toHaveBeenCalledOnce()
+ f.rerender({ requestKey: {} })
+ expect(f.onLoad).toHaveBeenCalledTimes(2)
+ })
+
+ it("uses physical start distance when one tall virtual row occupies both edges", () => {
+ const f = viewportFixture(400, [0], { count: 1, hasMoreAtStart: true })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ if (edge === "end") expect(f.root.scrollTop).toBeGreaterThan(f.root.clientHeight)
+ })
+
+ it("keeps eligibility, fetch and error gates on pixel scroll events and removes the listener", () => {
+ const f = viewportFixture(400, [4, 5], { enabled: false })
+ f.move(300)
+ f.rerender({ enabled: true, isFetching: true })
+ f.move(200)
+ f.rerender({ enabled: true, isFetching: false, isError: true })
+ f.move(100)
+ expect(f.onLoad).not.toHaveBeenCalled()
+ f.rerender({ enabled: true, isFetching: false, isError: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ f.view.unmount()
+ f.move(2000)
+ f.move(0)
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ })
+
+ it("prioritizes the older side of a short pixel preload window", () => {
+ const f = viewportFixture(100, [4, 5], { hasMoreAtStart: true }, 700)
+ f.move(100)
+ expect(f.onLoad).toHaveBeenCalledTimes(edge === "start" ? 1 : 0)
+ if (edge === "end") {
+ f.rerender({ hasMoreAtStart: false })
+ expect(f.onLoad).toHaveBeenCalledOnce()
+ }
+ })
+
it("loads when the native range reaches the boundary, with anchor capture first", () => {
const f = fixture()
expect(f.onLoad).not.toHaveBeenCalled()
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
index 672f6740a..55206c4cf 100644
--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
@@ -6,9 +6,9 @@ import type { MessageRequest } from "@/lib/community/message-position"
export function useVirtualCursorPagination({
virtualizer, count, enabled = true, hasMore, hasMoreAtStart, isFetching, isError,
- onBeforeLoad, onLoad, edge, requestKey,
+ onBeforeLoad, onLoad, edge, requestKey, preloadWithinViewport = false,
}: {
- virtualizer: { getVirtualItems: () => VirtualItem[] }
+ virtualizer: { getVirtualItems: () => VirtualItem[]; scrollElement?: HTMLElement | null }
count: number
enabled?: boolean
hasMore?: boolean
@@ -19,21 +19,40 @@ export function useVirtualCursorPagination({
onLoad?: () => MessageRequest | void
edge: "start" | "end"
requestKey?: object
+ preloadWithinViewport?: boolean
}) {
const virtualItems = virtualizer.getVirtualItems()
+ const scrollElement = virtualizer.scrollElement
const attempted = useRef<{ count: number; key: VirtualItem["key"]; window?: object; legacy: boolean } | null>(null)
useEffect(() => {
- const boundary = edge === "start" ? virtualItems[0] : virtualItems.at(-1)
- if (isFetching && attempted.current?.legacy) attempted.current = null
- if (!enabled || !boundary || count === 0 || !hasMore || isFetching || isError || !onLoad) return
- if (edge === "start" ? boundary.index > 0 : boundary.index < count - 1) { attempted.current = null; return }
- if (edge === "end" && hasMoreAtStart && virtualItems[0]?.index === 0) return
- if (attempted.current?.count === count && attempted.current.key === boundary.key && attempted.current.window === requestKey) return
- const attempt = { count, key: boundary.key, window: requestKey, legacy: false }
- attempted.current = attempt
- const receive = onBeforeLoad?.()
- const request = onLoad()
- attempt.legacy = !request
- receive?.(request)
- }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isError, onBeforeLoad, onLoad, requestKey, virtualItems])
+ const root = preloadWithinViewport ? virtualizer.scrollElement : null
+ const load = () => {
+ const rows = virtualizer.getVirtualItems()
+ const boundary = edge === "start" ? rows[0] : rows.at(-1)
+ if (isFetching && attempted.current?.legacy) attempted.current = null
+ if (!enabled || !boundary || count === 0 || !hasMore || isFetching || isError || !onLoad) return
+ let atStart = rows[0]?.index === 0
+ let nearEdge = edge === "start" ? boundary.index === 0 : boundary.index === count - 1
+ if (preloadWithinViewport) {
+ if (!root || root.clientHeight <= 0) return
+ const start = Math.max(0, root.scrollTop)
+ const end = Math.max(0, root.scrollHeight - root.clientHeight - root.scrollTop)
+ atStart = start <= root.clientHeight
+ nearEdge = (edge === "start" ? start : end) <= root.clientHeight
+ }
+ if (!nearEdge) { attempted.current = null; return }
+ if (edge === "end" && hasMoreAtStart && atStart) return
+ const key = preloadWithinViewport ? edge : boundary.key
+ if (attempted.current?.count === count && attempted.current.key === key && attempted.current.window === requestKey) return
+ const attempt = { count, key, window: requestKey, legacy: false }
+ attempted.current = attempt
+ const receive = onBeforeLoad?.()
+ const request = onLoad()
+ attempt.legacy = !request
+ receive?.(request)
+ }
+ load()
+ root?.addEventListener("scroll", load, { passive: true })
+ return () => root?.removeEventListener("scroll", load)
+ }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isError, onBeforeLoad, onLoad, preloadWithinViewport, requestKey, scrollElement, virtualItems, virtualizer])
}
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index 12a4e448e..ef70cf00b 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -1,4 +1,4 @@
-import { communityFixtureFetch } from "./_fixtures/business-contract"
+import { communityFixtureFetch, confirmCommunityFixtureApiResponse, CURRENT_COMMUNITY_FIXTURE_HEADERS } from "./_fixtures/business-contract"
import type { CommunityConversationEntryRead } from "@alook/shared"
import type { Locator, Page, Route, TestInfo } from "@playwright/test"
import { test, expect, type CaseActors } from "./_fixtures/case-fixture"
@@ -95,6 +95,23 @@ function estimatePlainMessage(content: string): number {
return 24 + Math.min(Math.max(1, Math.ceil(content.length / 55)) * 20, 400)
}
+async function seedResizableHtmlPreview(page: Page, channelId: string) {
+ const html = '<!doctype html><html><body><div id="content" style="height:160px">Asynchronous content</div><script>addEventListener("message",event=>{if(event.source===parent&&event.data?.type==="scroll-fixture-height"&&Number.isFinite(event.data.height))document.getElementById("content").style.height=event.data.height+"px"})</script></body></html>'
+ const upload = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/attachments`, {
+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
+ multipart: { file: { name: "scroll-resize.html", mimeType: "text/html", buffer: Buffer.from(html) } },
+ }))
+ expect(upload.status()).toBe(200)
+ const attachmentId = (await upload.json() as { id: string }).id
+ const posted = await confirmCommunityFixtureApiResponse(page.request.post(`/api/community/channels/${channelId}/messages`, {
+ headers: CURRENT_COMMUNITY_FIXTURE_HEADERS,
+ data: { content: `[alook-html-preview](${attachmentId})`, attachments: [attachmentId] },
+ }))
+ expect(posted.status()).toBe(201)
+ const messageId = (await posted.json() as { message: { id: string } }).message.id
+ return { messageId, attachmentId }
+}
+
async function seedProfile(
actors: CaseActors,
channelId: string,
@@ -154,11 +171,11 @@ async function setReadCheckpoint(actors: CaseActors, channelId: string, messageI
expect(response.ok).toBe(true)
}
-function identity(channelId: string) {
+function identity(channelId: string, viewport = VIEWPORT) {
return createScrollTraceIdentity({
account: "alice",
channel: channelId,
- viewport: { ...VIEWPORT, dpr: 1 },
+ viewport: { ...viewport, dpr: 1 },
})
}
@@ -585,6 +602,130 @@ function tracedAsUser(actors: CaseActors): CaseActors["asUser"] {
}
test.describe("message scroll characterization", () => {
+ test("measured reaction updates above the fold preserve reading during repeated controlled backward input", async ({ caseActors }, testInfo) => {
+ test.setTimeout(120_000)
+ const actors = await caseActors(["alice"])
+ const serverId = await actors.seed.seedServer("alice", `Measured reactions ${Date.now()}`)
+ const channelId = await actors.seed.seedChannel("alice", serverId, "measured-reactions")
+ const { page } = await tracedAsUser(actors)("alice")
+ await page.setViewportSize({ width: 390, height: 800 })
+ await seedProfile(actors, channelId, 4, false, "alice")
+ const messageId = await actors.seed.seedMessage("alice", channelId, "A measured historical message")
+ await seedProfile(actors, channelId, 24, false, "alice")
+ const reactionFrame = (frame: Parameters<typeof communityFrameEvents>[0]) => communityFrameEvents(frame).some(event =>
+ event.type === "community:reaction.add" && event.messageId === messageId)
+ const proxy = await proxyCommunityWebSockets(page.context(), { decide: frame => reactionFrame(frame) ? "hold" : "forward" })
+ const batches = [["πŸ‘", "❀️", "πŸ˜‚", "πŸŽ‰", "πŸ‘€"], ["πŸš€", "βœ…", "πŸ”₯", "πŸ’―", "πŸ€”"]]
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const scroller = page.getByTestId(tid.messageScroller)
+ await scroller.evaluate(element => { element.scrollTop = 0; element.dispatchEvent(new Event("scroll")) })
+ await expect(page.getByTestId(tid.message(messageId))).toHaveCount(1)
+ await scroller.evaluate((element, id) => {
+ const row = element.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)
+ if (!row) throw new Error("The measured reaction message is required")
+ element.scrollTop += row.getBoundingClientRect().bottom - element.getBoundingClientRect().top + 256
+ element.dispatchEvent(new Event("scroll"))
+ }, messageId)
+ await waitForCommittedGeometry(scroller)
+ await installScrollTraceInCurrentDocument(page)
+ await startScrollTrace(page, { scenario: "measured-reactions-backward-growth", identity: identity(channelId, { width: 390, height: 800 }) })
+ await beginScrollTraceAnalysis(page, "above-fold-repeated-growth", { commandDirection: "backward" })
+ const samples: Array<{ at: number; rowHeight: number }> = []
+ let trace: ScrollTraceResult | undefined
+ try {
+ for (const [round, emojis] of batches.entries()) {
+ for (const emoji of emojis) await actors.seed.seedReaction("alice", messageId, emoji)
+ await expect.poll(() => proxy.frames.flatMap(communityFrameEvents).filter(event =>
+ event.type === "community:reaction.add" && event.messageId === messageId).length).toBe((round + 1) * 5)
+ await markScrollTrace(page, `stimulus:reactions-${round}`, { detail: { input: "controlled-wheel-and-scroll", emojis } })
+ const before = await scroller.evaluate((element, growingId) => {
+ element.dispatchEvent(new WheelEvent("wheel", { deltaY: -1, bubbles: true }))
+ element.scrollTop -= 1
+ element.dispatchEvent(new Event("scroll"))
+ const top = element.getBoundingClientRect().top
+ const growing = element.querySelector<HTMLElement>(`[data-msg-id="${growingId}"]`)
+ const reader = Array.from(element.querySelectorAll<HTMLElement>("[data-msg-id]"))
+ .find(row => row.getBoundingClientRect().bottom > top + 1)
+ const wrapper = growing?.closest<HTMLElement>("[data-index]")
+ if (!growing || !reader || !wrapper) throw new Error("Mounted growth and reading rows are required")
+ return { id: reader.dataset.msgId!, top: reader.getBoundingClientRect().top - top,
+ growingBottom: wrapper.getBoundingClientRect().bottom - top, scrollTop: element.scrollTop,
+ rowHeight: wrapper.getBoundingClientRect().height, at: performance.now() }
+ }, messageId)
+ expect(before.growingBottom).toBeLessThan(0)
+ samples.push({ at: before.at, rowHeight: before.rowHeight })
+ expect(proxy.releaseHeld(reactionFrame)).toBeGreaterThan(0)
+ await expect.poll(() => page.getByTestId(tid.message(messageId)).evaluate(element => element.closest("[data-index]")!.getBoundingClientRect().height))
+ .toBeGreaterThan(before.rowHeight)
+ await advanceScrollTraceFrame(scroller)
+ const after = await page.getByTestId(tid.message(before.id)).evaluate(element => {
+ const root = element.closest<HTMLElement>("[data-message-scroller-boundary]")?.querySelector<HTMLElement>("[data-pagination-enabled]")
+ if (!root) throw new Error("The reading scroller is required")
+ return element.getBoundingClientRect().top - root.getBoundingClientRect().top
+ })
+ await markScrollTrace(page, `observed:reactions-${round}`, { detail: { before, after } })
+ expect.soft(Math.abs(after - before.top), `Reading drift after reaction batch ${round}`).toBeLessThanOrEqual(1)
+ }
+ } finally {
+ await endScrollTraceAnalysis(page, "above-fold-repeated-growth")
+ trace = await finishAndAttach(page, testInfo)
+ }
+ if (!trace) throw new Error("The reaction-growth trace is required")
+ for (const sample of samples) {
+ const measurement = trace.measurements.find(row => row.id === messageId && row.timestamp >= sample.at && row.height > sample.rowHeight + 1)
+ expect(measurement, "A real growing-row measurement must precede the 150ms backward reset").toBeDefined()
+ expect(measurement!.timestamp - sample.at).toBeLessThan(150)
+ }
+ })
+
+ test("controlled upward release before native movement prevents HTML tail resize follow", async ({ caseActors }, testInfo) => {
+ test.setTimeout(120_000)
+ const actors = await caseActors(["alice"])
+ const serverId = await actors.seed.seedServer("alice", `Released HTML ${Date.now()}`)
+ const channelId = await actors.seed.seedChannel("alice", serverId, "released-html")
+ const { page } = await tracedAsUser(actors)("alice")
+ await page.setViewportSize(VIEWPORT)
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ await seedProfile(actors, channelId, 24, false, "alice")
+ const { attachmentId } = await seedResizableHtmlPreview(page, channelId)
+ const scroller = page.getByTestId(tid.messageScroller)
+ const iframe = page.getByTestId(tid.htmlPreviewFrame(attachmentId))
+ await expect(page.getByTestId(tid.htmlPreview(attachmentId))).toHaveAttribute("data-html-preview-status", "ready")
+ await expect(iframe).toHaveCSS("height", "160px")
+ await installScrollTraceInCurrentDocument(page)
+ await startScrollTrace(page, { scenario: "released-html-tail-growth", identity: identity(channelId) })
+ try {
+ for (const distance of [0, 1, 2]) {
+ await iframe.evaluate(element => (element as HTMLIFrameElement).contentWindow?.postMessage({ type: "scroll-fixture-height", height: 160 }, "*"))
+ await expect(iframe).toHaveCSS("height", "160px")
+ await establishScrollDistancePrecondition(scroller, `released-tail-${distance}`, distance, 0.05)
+ await beginScrollTraceAnalysis(page, `released-tail-${distance}`)
+ try {
+ const before = await scroller.evaluate((element, frameId) => {
+ const frame = element.querySelector<HTMLIFrameElement>(`[data-testid="${frameId}"]`)
+ if (!frame?.contentWindow) throw new Error("A real mounted HTML preview is required")
+ const wheel = new WheelEvent("wheel", { deltaY: -20, bubbles: true })
+ element.dispatchEvent(wheel)
+ const result = { top: element.scrollTop, distance: element.scrollHeight - element.clientHeight - element.scrollTop,
+ trusted: wheel.isTrusted }
+ frame.contentWindow.postMessage({ type: "scroll-fixture-height", height: 260 }, "*")
+ return result
+ }, tid.htmlPreviewFrame(attachmentId))
+ await markScrollTrace(page, `stimulus:released-tail-${distance}`, { detail: before })
+ await expect(iframe).toHaveCSS("height", "260px")
+ await advanceScrollTraceFrame(scroller)
+ const after = await scroller.evaluate(element => element.scrollTop)
+ await markScrollTrace(page, `observed:released-tail-${distance}`, { detail: { before, after } })
+ expect.soft(Math.abs(after - before.top), `Released reader movement at ${distance}px`).toBeLessThanOrEqual(1)
+ } finally {
+ await endScrollTraceAnalysis(page, `released-tail-${distance}`)
+ }
+ }
+ } finally {
+ await finishAndAttach(page, testInfo)
+ }
+ })
+
test("cold and warm loading, older prepend, and jump-to-present remain observable", async ({ caseActors }, testInfo) => {
test.setTimeout(180_000)
const actors = await caseActors(["alice", "bob", "carol"])