diff --git a/apps/app/src/components/thread/timeline/ThreadTimelineRows.system-summary.test.tsx b/apps/app/src/components/thread/timeline/ThreadTimelineRows.system-summary.test.tsx index 791174b3c5e..5d9d59faf2f 100644 --- a/apps/app/src/components/thread/timeline/ThreadTimelineRows.system-summary.test.tsx +++ b/apps/app/src/components/thread/timeline/ThreadTimelineRows.system-summary.test.tsx @@ -1,6 +1,12 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { MemoryRouter } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -8,11 +14,12 @@ import type { TimelineRow } from "@bb/server-contract"; import { ThreadTitleMentionResourcesProvider } from "@/components/thread/ThreadTitleMentions"; import { systemRow } from "@/test/fixtures/thread-timeline-rows"; import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures"; +import { installFakeFlowLayout } from "@/test/fake-flow-layout"; import { ThreadTimelineRows } from "./ThreadTimelineRows"; -function renderRow(row: TimelineRow) { - return render( - +function rowTree(row: TimelineRow, queryClient = new QueryClient()) { + return ( + - , + ); } +function renderRow(row: TimelineRow) { + return render(rowTree(row)); +} + beforeEach(() => { vi.stubGlobal("ResizeObserver", undefined); }); @@ -159,3 +170,85 @@ describe("system summary overflow", () => { expect(screen.queryByRole("button", { name: "Show more" })).toBeNull(); }); }); + +describe("pending system detail scrolling", () => { + const LINE_HEIGHT = 100; + const DETAIL_HEIGHT = 100; + + it("keeps an expanded pending detail at its end while it streams, holds a reader who scrolled up, and follows again once they reach the new end", async () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + const layout = installFakeFlowLayout({ + heightOf: (element) => + element.tagName === "PRE" + ? (element.textContent ?? "").split("\n").length * LINE_HEIGHT + : null, + scrollElement: () => + document.querySelector("[data-detail-scroll-area]"), + viewportHeight: DETAIL_HEIGHT, + }); + try { + const pendingRow = (lineCount: number) => + systemRow({ + detail: Array.from( + { length: lineCount }, + (_, index) => `line ${index + 1}`, + ).join("\n"), + status: "pending", + }); + const settle = async () => { + await act(async () => { + layout.flushResizeObservers(); + await vi.advanceTimersByTimeAsync(50); + }); + await act(async () => { + await vi.advanceTimersByTimeAsync(4_000); + layout.flushResizeObservers(); + }); + }; + const queryClient = new QueryClient(); + const view = render(rowTree(pendingRow(10), queryClient)); + const stream = async (lineCount: number) => { + view.rerender(rowTree(pendingRow(lineCount), queryClient)); + await settle(); + }; + + fireEvent.click( + screen.getByRole("button", { name: /Provisioned thread/u }), + ); + await settle(); + expect(layout.maxScrollTop()).toBe(900); + expect(layout.scrollTop).toBe(900); + + act(() => layout.layoutScrollTo(500)); + await stream(11); + expect(layout.scrollTop).toBe(1_000); + + act(() => layout.userScrollTo(500)); + await settle(); + await stream(12); + expect(layout.maxScrollTop()).toBe(1_100); + expect(layout.scrollTop).toBe(500); + + act(() => layout.userScrollTo(1_000)); + await settle(); + await stream(13); + expect(layout.scrollTop).toBe(1_000); + + act(() => layout.userScrollTo(1_200)); + await settle(); + await stream(14); + expect(layout.scrollTop).toBe(1_300); + } finally { + layout.restore(); + vi.useRealTimers(); + } + }); +}); diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx index 13ea6a19109..3755e697959 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.test.tsx @@ -59,7 +59,9 @@ function setup({ ), initiallyAttached: attached, }); - let disconnect = rootPending ? () => undefined : keeper.connect(scrollElement); + let disconnect = rootPending + ? () => undefined + : keeper.connect(scrollElement); cleanups.push(layout.restore, () => disconnect()); const connectRoot = () => { rootReady = true; @@ -111,8 +113,13 @@ function setup({ const top = topOf(key); return top < VIEWPORT_HEIGHT && top + heightOf(key) > 0; }); + const extent = () => layout.maxScrollTop() + VIEWPORT_HEIGHT; + const totalHeight = (itemKeys: string[]) => + itemKeys.reduce((sum, key) => sum + heightOf(key), 0) + + 8 * (itemKeys.length - 1); return { connectRoot, + extent, heightOf, keeper, layout, @@ -120,6 +127,7 @@ function setup({ measurements, mounted, topOf, + totalHeight, view, visibleKeys, }; @@ -227,16 +235,23 @@ describe("TimelineWindowedItems", () => { expect(harness.visibleKeys().length).toBeGreaterThan(3); }); - it("renders every row while the scrollport has no usable geometry, and windows once it does", () => { + it("renders every row while the scrollport has no usable geometry, then windows once it does with spacers sized from the heights it measured", () => { const harness = setup({ attached: false, viewportHeight: 0 }); - render(harness.view(keys(300)), { container: harness.list }); + const itemKeys = keys(300); + render(harness.view(itemKeys), { container: harness.list }); expect(harness.mounted().length).toBe(300); harness.layout.setViewportHeight(VIEWPORT_HEIGHT); act(() => harness.keeper.reconcile()); + act(() => harness.layout.flushResizeObservers()); expect(harness.mounted().length).toBeLessThan(50); expect(harness.visibleKeys().length).toBeGreaterThan(3); + expect(harness.extent()).toBe(harness.totalHeight(itemKeys)); + for (let step = 0; step < 11; step += 1) { + act(() => harness.layout.userScrollTo(harness.layout.scrollTop + 200)); + } + expect(harness.extent()).toBe(harness.totalHeight(itemKeys)); }); it("starts at the end of the list when pinned to the bottom", () => { @@ -329,12 +344,55 @@ describe("TimelineWindowedItems", () => { expect(harness.mounted().length).toBe(300); }); - it("mounts a bounded window of a long history", () => { + it("mounts a bounded window of a long history and replaces it when the reader scrolls away", () => { const harness = setup({ attached: true }); - render(harness.view(keys(1_000)), { container: harness.list }); + const itemKeys = keys(1_000); + render(harness.view(itemKeys), { container: harness.list }); expect(harness.mounted().length).toBeLessThan(40); expect(harness.layout.scrollTop).toBe(harness.layout.maxScrollTop()); + + act(() => harness.layout.userScrollTo(6_000)); + + expect(harness.mounted()).not.toContain(itemKeys.at(-1)); + expect(harness.mounted().length).toBeLessThan(40); + expect(harness.visibleKeys().length).toBeGreaterThan(3); + }); + + it("shows the rows at a target the keeper scrolls to before any scroll event arrives", () => { + const harness = setup({ attached: true }); + render(harness.view(keys(400)), { container: harness.list }); + expect(harness.mounted()).not.toContain("row-0"); + + act(() => harness.keeper.scrollTo(0, "instant")); + + expect(harness.layout.scrollTop).toBe(0); + expect(harness.topOf("row-0")).toBe(0); + const visible = harness.visibleKeys(); + const last = visible.at(-1) ?? ""; + expect(harness.topOf(last) + harness.heightOf(last)).toBeGreaterThanOrEqual( + VIEWPORT_HEIGHT, + ); + }); + + it("re-measures a row that remounts taller than the thread remembered, so the scroll extent stays exact after it unmounts again", () => { + const harness = setup({ attached: true }); + const itemKeys = keys(200); + for (const key of itemKeys) + harness.measurements.set(key, harness.heightOf(key)); + harness.measurements.set("row-100", harness.heightOf("row-100") - 30); + render(harness.view(itemKeys), { container: harness.list }); + expect(harness.mounted()).not.toContain("row-100"); + + act(() => + harness.layout.userScrollTo(harness.totalHeight(itemKeys.slice(0, 100))), + ); + act(() => harness.layout.flushResizeObservers()); + expect(harness.visibleKeys()).toContain("row-100"); + act(() => harness.layout.userScrollTo(harness.layout.maxScrollTop())); + + expect(harness.mounted()).not.toContain("row-100"); + expect(harness.extent()).toBe(harness.totalHeight(itemKeys)); }); it("keeps forced and interacted rows mounted outside the window", () => { diff --git a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx index c75ca4bf142..072809e47c4 100644 --- a/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx +++ b/apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx @@ -182,6 +182,19 @@ function sameKeys(left: ReadonlySet, right: ReadonlySet) { return true; } +function knownHeights( + itemKeys: readonly string[], + measurements: ReadonlyMap, + rendered: ReadonlyMap, +): Map { + const heights = new Map(); + for (const key of itemKeys) { + const height = measurements.get(key) ?? rendered.get(key); + if (height !== undefined) heights.set(key, height); + } + return heights; +} + function spacerHeight(model: LayoutModel, first: number, last: number) { const top = model.offsets[first] ?? 0; const bottom = (model.offsets[last] ?? 0) + (model.heights[last] ?? 0); @@ -428,6 +441,16 @@ export function TimelineWindowedItems({ if (scrollRoot !== null) { const usable = scrollRoot.clientHeight > 0; if (usable !== live.scrollRootUsable) { + if (usable && live.scrollRootUsable === false) { + setWindowState((current) => ({ + keys: current.keys, + heights: knownHeights( + live.itemKeys, + measurements, + current.heights, + ), + })); + } live.scrollRootUsable = usable; setScrollRootUsable(usable); } @@ -473,12 +496,11 @@ export function TimelineWindowedItems({ const heldKey = heldKeyOf(positionKeeper); if (heldKey !== null && live.indexByKey.has(heldKey)) keys.add(heldKey); if (sameKeys(keys, live.windowKeys) || !takeFrameUpdate()) return; - const heights = new Map(); - for (const key of live.itemKeys) { - const height = - measurements.get(key) ?? live.renderedHeights.get(key); - if (height !== undefined) heights.set(key, height); - } + const heights = knownHeights( + live.itemKeys, + measurements, + live.renderedHeights, + ); const apply = () => setWindowState({ keys, heights }); if (urgent && uncovered) { flushSync(apply); diff --git a/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx b/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx index a50e97fcdff..dd5442d10fd 100644 --- a/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx +++ b/apps/app/src/components/ui/bottom-anchored-scroll-body.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom -import { act, cleanup, render } from "@testing-library/react"; +import { act, cleanup, render, screen } from "@testing-library/react"; import { getDefaultStore } from "jotai"; import { useContext, useEffect, useState } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -11,6 +11,7 @@ import { type BottomAnchorContextValue, } from "@/components/ui/bottom-anchored-scroll-body"; import { TimelineWindowedItems } from "@/components/thread/timeline/TimelineWindowedItems"; +import { scrollPageToTop } from "@/lib/page-scroll-to-top"; import { threadTimelineScrollAnchorAtomFamily } from "@/lib/thread-timeline-scroll-anchor"; import { installFakeFlowLayout } from "@/test/fake-flow-layout"; @@ -124,7 +125,15 @@ function setup(threadId: string, keys: string[]) { top: row.getBoundingClientRect().top, })) .find((row) => row.top >= 0)?.key ?? ""; - return { layout, topOf, firstVisible, view }; + const scrollElement = document.querySelector( + "[data-page-scroll-viewport]", + ); + if (scrollElement === null) throw new Error("no scroll element"); + return { layout, topOf, firstVisible, view, scrollElement }; +} + +function savedAnchor(threadId: string) { + return getDefaultStore().get(threadTimelineScrollAnchorAtomFamily(threadId)); } describe("BottomAnchoredScrollBody", () => { @@ -172,6 +181,45 @@ describe("BottomAnchoredScrollBody", () => { expect(handles.bottomAnchor?.isAtBottom).toBe(false); }); + it("keeps an explicit jump to the end when the saved row it was waiting for arrives afterwards", () => { + const keysA = rowKeys("thread-a", 120); + const first = setup("thread-a", keysA); + act(() => first.layout.userScrollTo(400)); + first.view.unmount(); + + const second = setup("thread-a", keysA.slice(60)); + expect(second.layout.scrollTop).toBe(second.layout.maxScrollTop()); + act(() => handles.bottomAnchor?.scrollToBottom()); + act(() => second.view.rerender()); + act(() => second.layout.flushResizeObservers()); + + expect(second.layout.scrollTop).toBe(second.layout.maxScrollTop()); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + }); + + it("stays at the end and keeps following new content when the saved row never loads", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + getDefaultStore().set(threadTimelineScrollAnchorAtomFamily("thread-a"), { + rowId: "thread-a:row-gone", + offsetWithinRow: 20, + atBottom: false, + }); + const { layout, view } = setup("thread-a", rowKeys("thread-a", 60)); + expect(layout.scrollTop).toBe(layout.maxScrollTop()); + + act(() => vi.advanceTimersByTime(1_500)); + act(() => layout.flushResizeObservers()); + act(() => + view.rerender( + , + ), + ); + act(() => layout.flushResizeObservers()); + + expect(layout.scrollTop).toBe(layout.maxScrollTop()); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + }); + it("saves the end when the timeline unmounts during a transient off-bottom layout", () => { const keysA = rowKeys("thread-a", 60); const first = setup("thread-a", keysA); @@ -182,29 +230,26 @@ describe("BottomAnchoredScrollBody", () => { first.view.unmount(); - expect( - getDefaultStore().get(threadTimelineScrollAnchorAtomFamily("thread-a")), - ).toEqual({ rowId: "", offsetWithinRow: 0, atBottom: true }); + expect(savedAnchor("thread-a")).toEqual({ + rowId: "", + offsetWithinRow: 0, + atBottom: true, + }); }); it("saves the row the reader scrolled to when the timeline unmounts before the scroll event lands", () => { const keysA = rowKeys("thread-a", 120); const first = setup("thread-a", keysA); - const scrollElement = document.querySelector( - "[data-page-scroll-viewport]", - ); - if (scrollElement === null) throw new Error("no scroll element"); const target = first.layout.maxScrollTop() - 2_000; - scrollElement.dispatchEvent(new WheelEvent("wheel", { deltaY: -2_000 })); + first.scrollElement.dispatchEvent( + new WheelEvent("wheel", { deltaY: -2_000 }), + ); first.layout.bounceTo(target); const reader = first.firstVisible(); const before = first.topOf(reader); first.view.unmount(); - const saved = getDefaultStore().get( - threadTimelineScrollAnchorAtomFamily("thread-a"), - ); - expect(saved?.atBottom).toBe(false); + expect(savedAnchor("thread-a")?.atBottom).toBe(false); const second = setup("thread-a", keysA); expect(second.topOf(reader)).toBe(before); @@ -222,26 +267,111 @@ describe("BottomAnchoredScrollBody", () => { expect(handles.bottomAnchor?.isAtBottom).toBe(true); }); - it("follows a scroll made without input when nothing changed size, such as find in page", () => { - vi.useFakeTimers({ - toFake: ["setTimeout", "clearTimeout", "performance"], - }); - const { layout, topOf, firstVisible } = setup( - "thread-a", - rowKeys("thread-a", 60), - ); - act(() => layout.userScrollTo(layout.maxScrollTop() - 1_500)); - act(() => vi.advanceTimersByTime(500)); + it("keeps following new content when the reader wheels back to the end and keeps wheeling there", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const keys = rowKeys("thread-a", 60); + const { layout, view, scrollElement } = setup("thread-a", keys); + const end = layout.maxScrollTop(); + act(() => layout.userScrollTo(end - 500)); + act(() => layout.userScrollTo(end)); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); - act(() => layout.layoutScrollTo(layout.scrollTop - 300)); - const reader = firstVisible(); - const before = topOf(reader); + act(() => { + scrollElement.dispatchEvent(new WheelEvent("wheel", { deltaY: 200 })); + }); + const grown = rowKeys("thread-a", 61); + act(() => view.rerender()); + act(() => { + scrollElement.dispatchEvent(new Event("scroll")); + }); act(() => layout.flushResizeObservers()); - expect(layout.scrollTop).toBe(layout.maxScrollTop() - 1_800); - expect(topOf(reader)).toBe(before); + expect(layout.maxScrollTop()).toBe(end + 8 + heightOf(grown.at(-1) ?? "")); + expect(layout.scrollTop).toBe(layout.maxScrollTop()); + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + view.unmount(); + expect(savedAnchor("thread-a")).toEqual({ + rowId: "", + offsetWithinRow: 0, + atBottom: true, + }); }); + it("detaches from new content when a header tap scrolls the timeline to the top", () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] }); + const keys = rowKeys("thread-a", 60); + const { layout, view, topOf, scrollElement } = setup("thread-a", keys); + const header = document.createElement("header"); + scrollElement.parentElement?.prepend(header); + scrollElement.getClientRects = () => + [new DOMRect(0, 0, 400, VIEWPORT_HEIGHT)] as unknown as DOMRectList; + const nativeScrollTo = vi.fn(); + scrollElement.scrollTo = nativeScrollTo; + expect(handles.bottomAnchor?.isAtBottom).toBe(true); + + act(() => scrollPageToTop(header)); + expect(nativeScrollTo).toHaveBeenCalledWith({ top: 0, behavior: "smooth" }); + for (const top of [layout.maxScrollTop() - 300, 800, 0]) { + act(() => layout.layoutScrollTo(top)); + } + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + + act(() => + view.rerender( + , + ), + ); + act(() => layout.flushResizeObservers()); + expect(layout.scrollTop).toBe(0); + expect(topOf(keys[0] ?? "")).toBe(0); + view.unmount(); + expect(savedAnchor("thread-a")).toEqual({ + rowId: keys[0], + offsetWithinRow: 0, + atBottom: false, + }); + }); + + it.each([ + { delivery: "its scroll event arrives first", reRendersFirst: false }, + { + delivery: "the timeline re-renders before its scroll event", + reRendersFirst: true, + }, + ])( + "follows a scroll made without input when nothing changed size, such as find in page, when $delivery", + ({ reRendersFirst }) => { + vi.useFakeTimers({ + toFake: ["setTimeout", "clearTimeout", "performance"], + }); + const keys = rowKeys("thread-a", 60); + const { layout, topOf, firstVisible, view, scrollElement } = setup( + "thread-a", + keys, + ); + act(() => layout.userScrollTo(layout.maxScrollTop() - 1_500)); + act(() => vi.advanceTimersByTime(500)); + const fromEnd = layout.maxScrollTop() - layout.scrollTop + 300; + + layout.bounceTo(layout.scrollTop - 300); + const reader = firstVisible(); + const before = topOf(reader); + if (reRendersFirst) { + act(() => + view.rerender(), + ); + } + act(() => { + scrollElement.dispatchEvent(new Event("scroll")); + }); + act(() => layout.flushResizeObservers()); + + expect(layout.maxScrollTop() - layout.scrollTop).toBe(fromEnd); + expect(topOf(reader)).toBe(before); + expect(handles.bottomAnchor?.isAtBottom).toBe(false); + }, + ); + it("treats a scroll without input that comes with a size change as layout, so it neither detaches nor moves the reader", () => { vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"], @@ -297,6 +427,12 @@ describe("BottomAnchoredScrollBody", () => { expect(handles.bottomAnchor?.isAtBottom).toBe(true); }); + it("renders the composer inside the timeline's scroll area, so wheel and gutter scrolling over it scroll the timeline", () => { + const { scrollElement } = setup("thread-a", rowKeys("thread-a", 5)); + + expect(scrollElement.contains(screen.getByText("composer"))).toBe(true); + }); + it("holds a collapsing row's bottom edge when the reader holds it", () => { const keys = rowKeys("thread-a", 60); const { layout, topOf, firstVisible } = setup("thread-a", keys); diff --git a/apps/app/src/components/ui/scroll-position-keeper.test.ts b/apps/app/src/components/ui/scroll-position-keeper.test.ts index f327aaa3cf7..4055d9959b1 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.test.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.test.ts @@ -36,15 +36,15 @@ function createTimeline( deferWrites = false, attached = false, footerTop = null, + floor = true, }: { deferWrites?: boolean; attached?: boolean; footerTop?: number | null; + floor?: boolean; } = {}, ) { const scrollElement = document.createElement("div"); - const scrollContent = document.createElement("div"); - const floor = document.createElement("div"); const content = document.createElement("div"); const list = document.createElement("div"); list.setAttribute("data-timeline-row-list", "top-level"); @@ -52,8 +52,14 @@ function createTimeline( items.setAttribute("data-timeline-items", ""); list.append(items); content.append(list); - scrollContent.append(floor, content); - scrollElement.append(scrollContent); + const floorElement = floor ? document.createElement("div") : null; + if (floorElement === null) { + scrollElement.append(content); + } else { + const scrollContent = document.createElement("div"); + scrollContent.append(floorElement, content); + scrollElement.append(scrollContent); + } document.body.append(scrollElement); const layout = installFakeFlowLayout({ scrollElement, @@ -83,7 +89,7 @@ function createTimeline( bottomThresholdPx: 4, deferWritesWhileScrolling: deferWrites, getContentElement: () => content, - getFloorElement: () => floor, + getFloorElement: () => floorElement, getFooterElement: () => (footerTop === null ? null : footer), getScrollElement: () => scrollElement, getTopLevelRows: () => @@ -97,23 +103,22 @@ function createTimeline( previousRestore?.(); }; - const topOf = (id: string) => { - const element = elements.get(id); - if (element === undefined) throw new Error(`No row ${id}`); - return element.getBoundingClientRect().top; + const element = (id: string) => { + const found = elements.get(id); + if (found === undefined) throw new Error(`No row ${id}`); + return found; }; return { content, + element, keeper, layout, scrollElement, setRows, - topOf, + topOf: (id: string) => element(id).getBoundingClientRect().top, resize(id: string, height: number) { - const element = elements.get(id); - if (element === undefined) throw new Error(`No row ${id}`); - setFakeHeight(element, height); + setFakeHeight(element(id), height); }, userScrollTo(top: number) { layout.userScrollTo(top); @@ -135,6 +140,17 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(false); }); + it("keeps native scroll anchoring off on the root while attached, detached, and back at the end", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + expect(timeline.scrollElement.style.overflowAnchor).toBe("none"); + timeline.userScrollTo(timeline.layout.maxScrollTop() - 800); + expect(timeline.keeper.isAttached()).toBe(false); + expect(timeline.scrollElement.style.overflowAnchor).toBe("none"); + timeline.keeper.scrollToBottom(); + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.scrollElement.style.overflowAnchor).toBe("none"); + }); + it("drives each reconcile to the same intent, so a clamped intermediate correction is not counted twice", () => { const rows = rowsOf(10); const timeline = createTimeline(rows); @@ -170,6 +186,40 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(true); }); + it("attaches a detached reader whose finger is down when content shrinks and clamps them onto the end", () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "requestAnimationFrame", + "cancelAnimationFrame", + "performance", + ], + }); + const rows = rowsOf(10); + const timeline = createTimeline(rows, { attached: true }); + timeline.userScrollTo(1_300); + vi.advanceTimersByTime(500); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.setRows(rows.slice(0, 8)); + timeline.layout.flushResizeObservers(); + if (timeline.layout.takeClamp()) { + timeline.scrollElement.dispatchEvent(new Event("scroll")); + } + vi.advanceTimersToNextFrame(); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + timeline.setRows([...rows.slice(0, 8), { id: "row-new", height: 250 }]); + timeline.layout.flushResizeObservers(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + it("attaches when a row collapses onto the end right after a touch drag, while fling momentum still counts as the reader's", () => { vi.useFakeTimers({ toFake: [ @@ -247,6 +297,32 @@ describe("ScrollPositionKeeper", () => { }, ); + it("stays attached when a shrink clamps the scroll during a touch before the resize is observed, and follows the regrowth", () => { + const rows = [...rowsOf(9), { id: "last", height: 1_200 }]; + const timeline = createTimeline(rows, { attached: true, floor: false }); + timeline.layout.flushResizeObservers(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + timeline.resize("last", 400); + expect(timeline.layout.takeClamp()).toBe(true); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.keeper.savedPosition()).toEqual({ + rowId: "", + offsetWithinRow: 0, + atBottom: true, + }); + + timeline.layout.flushResizeObservers(); + timeline.resize("last", 650); + timeline.layout.flushResizeObservers(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchend")); + expect(timeline.keeper.isAttached()).toBe(true); + }); + it("keeps an attached view at the end when it scrolls without input or a size change", () => { const timeline = createTimeline(rowsOf(10), { attached: true }); @@ -274,6 +350,36 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.hasUserScrolled()).toBe(false); }); + it("keeps a wheel scroll whose scroll event has not arrived when a layout reconcile runs first", () => { + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(900); + + timeline.scrollElement.dispatchEvent( + new WheelEvent("wheel", { deltaY: -200 }), + ); + timeline.layout.bounceTo(700); + timeline.keeper.reconcile(); + expect(timeline.layout.scrollTop).toBe(700); + + timeline.scrollElement.dispatchEvent(new Event("scroll")); + expect(timeline.layout.scrollTop).toBe(700); + }); + + it("follows a detached view's scroll without input, such as find in page, when a layout reconcile runs before its scroll event", () => { + vi.useFakeTimers({ + toFake: ["setTimeout", "clearTimeout", "performance"], + }); + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(900); + vi.advanceTimersByTime(500); + + timeline.layout.bounceTo(700); + timeline.keeper.reconcile(); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + + expect(timeline.layout.scrollTop).toBe(700); + }); + it("follows a scroll without input while the window find bar is open, and keeps the end again once the window has focus", () => { const timeline = createTimeline(rowsOf(10), { attached: true }); @@ -299,6 +405,32 @@ describe("ScrollPositionKeeper", () => { expect(timeline.layout.scrollTop).toBe(400); }); + it("ignores scroll keys typed into an editable control, so a scroll that follows still counts as layout", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const textarea = document.createElement("textarea"); + const button = document.createElement("button"); + timeline.content.append(textarea, button); + + for (const key of ["End", "ArrowUp", "PageUp", " "]) { + textarea.dispatchEvent( + new KeyboardEvent("keydown", { key, bubbles: true }), + ); + } + timeline.layout.layoutScrollTo(400); + + expect(timeline.keeper.isAttached()).toBe(true); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.hasUserScrolled()).toBe(false); + + button.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowUp", bubbles: true }), + ); + timeline.layout.layoutScrollTo(400); + + expect(timeline.keeper.isAttached()).toBe(false); + expect(timeline.layout.scrollTop).toBe(400); + }); + it("follows content that stays shrunk to the new end", () => { vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"], @@ -375,6 +507,21 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("row-3")).toBe(before); }); + it("keeps an attached view at the end within the resize callback when the viewport gets shorter", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + timeline.layout.flushResizeObservers(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + + timeline.layout.setViewportHeight(300); + expect(timeline.layout.scrollTop).toBeLessThan( + timeline.layout.maxScrollTop(), + ); + timeline.layout.flushResizeObservers(); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + it("saves a detached reader who sits at the end as at the bottom", () => { const rows = rowsOf(10); const timeline = createTimeline(rows); @@ -465,6 +612,42 @@ describe("ScrollPositionKeeper", () => { expect(timeline.layout.scrollTop).toBe(400); }); + it("stays attached when revealing a row that is already visible at the end", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const row = timeline.element("row-9"); + row.scrollIntoView = () => undefined; + + timeline.keeper.revealElement(row, { block: "nearest" }); + expect(timeline.keeper.isAttached()).toBe(true); + + timeline.setRows(rowsOf(11)); + timeline.keeper.reconcile(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + + it("keeps a revealed row at the top when a row above it resizes before the reveal's scroll event, and tells windowed lists at once", () => { + const timeline = createTimeline(rowsOf(10), { attached: true }); + const onPositionChange = vi.fn(); + timeline.keeper.registerList({ itemAt: () => null, onPositionChange }); + const target = timeline.element("row-2"); + target.scrollIntoView = () => { + timeline.scrollElement.scrollTop = 400; + }; + + timeline.keeper.revealElement(target, { block: "start" }); + expect(onPositionChange).toHaveBeenCalled(); + expect(timeline.topOf("row-2")).toBe(0); + expect(timeline.keeper.isAttached()).toBe(false); + + timeline.resize("row-1", 260); + timeline.layout.flushResizeObservers(); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + + expect(timeline.topOf("row-2")).toBe(0); + expect(timeline.keeper.isAttached()).toBe(false); + }); + it("shifts content above an attached toggle by exactly the height change", () => { const timeline = createTimeline(rowsOf(10), { attached: true }); const lastBottom = () => timeline.topOf("row-9") + 200; @@ -528,7 +711,9 @@ describe("ScrollPositionKeeper", () => { expect(timeline.keeper.isAttached()).toBe(false); timeline.userScrollTo(max - 200); expect(timeline.keeper.isAttached()).toBe(false); - timeline.userScrollTo(max); + timeline.userScrollTo(max - 6); + expect(timeline.keeper.isAttached()).toBe(false); + timeline.userScrollTo(max - 3); expect(timeline.keeper.isAttached()).toBe(true); }); @@ -627,6 +812,32 @@ describe("ScrollPositionKeeper", () => { expect(timeline.topOf("after-0")).toBe(before); }); + it("anchors a nested row that is the first to start in a viewport its parent row covers", () => { + const timeline = createTimeline([ + { id: "turn", height: 0, children: rowsOf(5, 300, "step") }, + ...rowsOf(5), + ]); + timeline.userScrollTo(250); + const before = timeline.topOf("step-1"); + + timeline.setRows([ + { + id: "turn", + height: 0, + children: [ + { id: "step-0", height: 500 }, + ...rowsOf(5, 300, "step").slice(1), + ], + }, + ...rowsOf(5), + ]); + timeline.keeper.reconcile(); + + expect(before).toBe(50); + expect(timeline.topOf("step-1")).toBe(before); + expect(timeline.layout.scrollTop).toBe(450); + }); + it("anchors the row the reader can see, not one hidden behind the composer", () => { const timeline = createTimeline(rowsOf(10, 450), { footerTop: 300 }); timeline.userScrollTo(1_000); @@ -732,6 +943,24 @@ describe("ScrollPositionKeeper", () => { expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); }); + it("jumps to the end and stays attached as content grows while the reader's finger is still down", () => { + const timeline = createTimeline(rowsOf(10)); + timeline.userScrollTo(400); + expect(timeline.keeper.isAttached()).toBe(false); + timeline.scrollElement.dispatchEvent(new TouchEvent("touchstart")); + + timeline.keeper.scrollToBottom(); + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + + timeline.setRows(rowsOf(11)); + timeline.scrollElement.dispatchEvent(new Event("scroll")); + timeline.layout.flushResizeObservers(); + + expect(timeline.layout.scrollTop).toBe(timeline.layout.maxScrollTop()); + expect(timeline.keeper.isAttached()).toBe(true); + }); + it("does not count a send button's jump to the end as the reader's gesture when the button handles pointerup itself", () => { const timeline = createTimeline(rowsOf(10)); timeline.userScrollTo(200); diff --git a/apps/app/src/components/ui/scroll-position-keeper.ts b/apps/app/src/components/ui/scroll-position-keeper.ts index 83934233192..eeda95447cd 100644 --- a/apps/app/src/components/ui/scroll-position-keeper.ts +++ b/apps/app/src/components/ui/scroll-position-keeper.ts @@ -542,13 +542,30 @@ export class ScrollPositionKeeper { if (widthChanged) this.keepAnchorVisible(scrollElement); this.reconciledWidth = width; const previous = this.ownScrollTop; - if ( + const movement = + previous !== null && Math.abs(scrollTop - previous) >= MIN_WRITE_PX + ? scrollTop - previous + : 0; + const clampedToEnd = previous !== null && - Math.abs(scrollTop - previous) >= MIN_WRITE_PX && + previous > max + 0.5 && + Math.abs(scrollTop - max) < 1; + const navigated = + movement !== 0 && + !this.isInputSession() && + this.followsUnexplainedScroll() && + !clampedToEnd; + if (navigated) { + this.userScrolled = true; + this.pendingRestore = null; + this.scrollMovedAt = window.performance.now(); + this.setPosition(this.capture(scrollElement) ?? FREE); + } else if ( + movement !== 0 && this.position.kind === "anchor" && this.isInputSession() ) { - this.position.offset -= scrollTop - previous; + this.position.offset -= movement; this.scrollMovedAt = window.performance.now(); } this.ownScrollTop = scrollTop; @@ -585,7 +602,7 @@ export class ScrollPositionKeeper { this.scheduleClampSettle(); } } - if (restored) this.attachIfAtEnd(scrollElement); + if (restored || navigated) this.attachIfAtEnd(scrollElement); else this.scheduleAttachAtEnd(scrollElement); if (notify) this.notifyLists(urgent); } diff --git a/apps/app/src/test/fake-flow-layout.ts b/apps/app/src/test/fake-flow-layout.ts index 650a737aa73..050d83febc5 100644 --- a/apps/app/src/test/fake-flow-layout.ts +++ b/apps/app/src/test/fake-flow-layout.ts @@ -285,6 +285,8 @@ export function installFakeFlowLayout({ observerSnapshot = heights; try { measureContentHeight(heights); + const scrollElement = resolveScrollElement(); + if (scrollElement !== null) heights.set(scrollElement, viewportHeight); for (const observer of [...observers]) { const entries: ResizeObserverEntry[] = []; for (const target of observer.targets) { diff --git a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx index 742b4b4b482..b06194b61d1 100644 --- a/apps/app/src/views/thread-detail/thread-opening.model.test.tsx +++ b/apps/app/src/views/thread-detail/thread-opening.model.test.tsx @@ -13,7 +13,7 @@ import { ThreadTimelineSurface } from "@/components/thread/timeline/ThreadTimeli import { useThreadTimelineController } from "@/components/thread/timeline/useThreadTimelineController"; import { sdk } from "@/lib/sdk"; import { makeThreadListEntry } from "@bb/test-helpers/domain-fixtures"; -import { threadListQueryKey } from "@/hooks/queries/query-keys"; +import { threadListQueryKey, threadQueryKey } from "@/hooks/queries/query-keys"; import { installFakeFlowLayout } from "@/test/fake-flow-layout"; import { makeThreadResponse, @@ -127,6 +127,30 @@ function Host({ shown }: { shown: boolean }) { let restoreLayout: (() => void) | null = null; +function getScrollElement() { + return document.querySelector("[data-page-scroll-viewport]"); +} + +function installOpeningLayout( + viewportHeight: number, + heightOfRow: (id: string) => number, +) { + const layout = installFakeFlowLayout({ + heightOf: (element) => { + if (element.hasAttribute("data-scroll-landmark-id")) return 24; + const rowId = element.getAttribute("data-timeline-row-id"); + if (rowId === null) return null; + return element.parentElement?.closest("[data-timeline-row-id]") + ? null + : heightOfRow(rowId); + }, + scrollElement: getScrollElement, + viewportHeight, + }); + restoreLayout = layout.restore; + return layout; +} + beforeEach(() => { vi.useFakeTimers({ toFake: [ @@ -291,21 +315,7 @@ async function runSeed(seed: number): Promise { }), ); - const getScrollElement = () => - document.querySelector("[data-page-scroll-viewport]"); - const layout = installFakeFlowLayout({ - heightOf: (element) => { - if (element.hasAttribute("data-scroll-landmark-id")) return 24; - const rowId = element.getAttribute("data-timeline-row-id"); - if (rowId === null) return null; - return element.parentElement?.closest("[data-timeline-row-id]") - ? null - : heightOfRow(rowId); - }, - scrollElement: getScrollElement, - viewportHeight, - }); - restoreLayout = layout.restore; + const layout = installOpeningLayout(viewportHeight, heightOfRow); const log: string[] = [ `seed ${seed} ${compact ? "phone" : "desktop"} viewport=${viewportHeight} segments=${segmentCount}`, @@ -553,4 +563,84 @@ describe("thread opening model", () => { } }, ); + + it("keeps a read thread at the end when a live reply adds NEW above the view", async () => { + const rows = Array.from({ length: 12 }, (_, index) => + conversationRow({ + id: `msg-${index + 1}`, + role: "assistant", + seq: index + 1, + createdAt: (index + 1) * 1_000, + startedAt: (index + 1) * 1_000, + text: `reply ${index + 1}`, + threadId: THREAD_ID, + turnId: `turn-${index + 1}`, + }), + ); + const readThread = makeThreadResponse({ + id: THREAD_ID, + lastReadAt: 6_500, + latestAttentionAt: 6_500, + status: "idle", + }); + vi.mocked(sdk.threads.get).mockResolvedValue(readThread); + vi.mocked(sdk.threads.timeline).mockResolvedValue( + makeThreadTimelineResponse({ rows, maxSeq: rows.length }), + ); + vi.mocked(sdk.threads.markRead).mockResolvedValue({ + ...readThread, + lastReadAt: 12_000, + latestAttentionAt: 12_000, + }); + const layout = installOpeningLayout(600, () => 150); + const { wrapper: Wrapper, queryClient } = createQueryClientTestHarness(); + render( + + + + + , + ); + const settle = async () => { + for (let index = 0; index < 3; index += 1) { + await act(async () => { + layout.flushResizeObservers(); + await vi.advanceTimersByTimeAsync(50); + }); + } + await act(async () => { + await vi.advanceTimersByTimeAsync(4_000); + layout.flushResizeObservers(); + }); + }; + const divider = () => + document.querySelector( + "[data-testid=thread-unread-divider]", + ); + const attached = () => + document.querySelector("[data-scroll-attached]") !== null; + await settle(); + expect(divider()).toBeNull(); + expect(layout.scrollTop).toBeGreaterThan(0); + expect(layout.maxScrollTop() - layout.scrollTop).toBeLessThanOrEqual( + THRESHOLD_PX, + ); + expect(attached()).toBe(true); + + await act(async () => { + queryClient.setQueryData(threadQueryKey(THREAD_ID), { + ...readThread, + latestAttentionAt: 12_000, + }); + }); + await settle(); + + const shown = divider(); + expect(shown).not.toBeNull(); + expect(shown!.getBoundingClientRect().top).toBeLessThan(0); + expect(layout.maxScrollTop() - layout.scrollTop).toBeLessThanOrEqual( + THRESHOLD_PX, + ); + expect(attached()).toBe(true); + }); }); diff --git a/docs/timeline-pagination.md b/docs/timeline-pagination.md index 604491b2910..b8b920c00d1 100644 --- a/docs/timeline-pagination.md +++ b/docs/timeline-pagination.md @@ -360,11 +360,15 @@ Every layout change is reconciled before paint. Triggers are ResizeObservers on the root, its content, and every mounted row, plus each windowed list's layout effect after a commit. Within one reconciliation: -1. A scroll the owner did not make is folded into the position as the reader's - movement, before the layout is read. Changes that landed in the same forced - layout are therefore not mistaken for scrolling. They are reconciled against - the moved position first. Only then, if the anchor has left the viewport, - the owner picks a new anchor where the reader now is. +1. A scroll the owner did not make is folded into the position before the + layout is read, even when its scroll event has not arrived yet. During an + input session it is the reader's movement: changes that landed in the same + forced layout are reconciled against the moved position, and only if the + anchor has left the viewport does the owner pick a new anchor where the + reader now is. Outside one, a view that follows navigation (see above) + takes its position from where the scroll left it, so a re-render between + find in page and its scroll event does not undo the jump. A clamp onto the + end of shrunken content is layout, not navigation. 2. Windowed lists render the rows around a row key, never around a raw `scrollTop`. A prepend keeps the same rows mounted, and the owner's anchor row is always mounted. @@ -386,7 +390,8 @@ mount, the owner takes its position from them. Lists of 20 or more items are windowed everywhere except iOS WebKit (Safari and the mobile app's WKWebView), where every row stays mounted. Every row also mounts while the scroll root has no height, for example in a hidden pane, and -windowing resumes once it has one. Rows stay in normal flow between spacers whose +windowing resumes once it has one, with spacers sized from the heights measured +meanwhile, so the scroll extent stays exact. Rows stay in normal flow between spacers whose heights come from the measurements the thread retains, so rows never overlap and a row resize needs no positioning pass. The thread retains the 2,000 most recent measurements; a spacer keeps the height it last rendered for a row whose