Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
// @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";
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(
<QueryClientProvider client={new QueryClient()}>
function rowTree(row: TimelineRow, queryClient = new QueryClient()) {
return (
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<ThreadTimelineRows
timelineRows={[row]}
threadRuntimeDisplayStatus="idle"
workspaceRootPath={undefined}
/>
</MemoryRouter>
</QueryClientProvider>,
</QueryClientProvider>
);
}

function renderRow(row: TimelineRow) {
return render(rowTree(row));
}

beforeEach(() => {
vi.stubGlobal("ResizeObserver", undefined);
});
Expand Down Expand Up @@ -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<HTMLElement>("[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();
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -111,15 +113,21 @@ 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,
list,
measurements,
mounted,
topOf,
totalHeight,
view,
visibleKeys,
};
Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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", () => {
Expand Down
34 changes: 28 additions & 6 deletions apps/app/src/components/thread/timeline/TimelineWindowedItems.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,19 @@ function sameKeys(left: ReadonlySet<string>, right: ReadonlySet<string>) {
return true;
}

function knownHeights(
itemKeys: readonly string[],
measurements: ReadonlyMap<string, number>,
rendered: ReadonlyMap<string, number>,
): Map<string, number> {
const heights = new Map<string, number>();
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);
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<string, number>();
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);
Expand Down
Loading
Loading