Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

test(plan): pin the thread walker to one editor scroll per step (#21437)

boojackd5b0b59d7b0e
diff --git a/frontend/src/components/monaco/MonacoViewZone.test.tsx b/frontend/src/components/monaco/MonacoViewZone.test.tsx
index ab6472d48c..dec3c56804 100644
--- a/frontend/src/components/monaco/MonacoViewZone.test.tsx
+++ b/frontend/src/components/monaco/MonacoViewZone.test.tsx
@@ -1,46 +1,47 @@
-import { act } from "react";
+import { act, useContext, useEffect } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, test, vi } from "vitest";
-import { MonacoViewZone } from "./MonacoViewZone";
+import { fakeEditorLayout, lineTop } from "@/test-utils/monacoLayout";
+import { MonacoViewZone, MonacoViewZoneRevealContext } from "./MonacoViewZone";
import type { IStandaloneCodeEditor } from "./types";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
-function fakeEditor() {
- const zones = new Map<
- string,
- {
- afterLineNumber: number;
- domNode: HTMLElement;
- onDomNodeTop?: (top: number) => void;
- }
- >();
+type FakeZone = {
+ afterLineNumber: number;
+ domNode: HTMLElement;
+ heightInPx: number;
+ onDomNodeTop?: (top: number) => void;
+};
+
+function fakeEditor(layoutOptions: { scrollTop?: number } = {}) {
+ const zones = new Map<string, FakeZone>();
let nextId = 0;
const widgets = new Set<{ getDomNode: () => HTMLElement }>();
+ const layout = fakeEditorLayout(
+ () =>
+ Array.from(zones, ([id, zone]) => ({
+ id,
+ afterLineNumber: zone.afterLineNumber,
+ height: zone.heightInPx,
+ })),
+ layoutOptions
+ );
const editor = {
+ ...layout,
addOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {
widgets.add(widget);
},
removeOverlayWidget: (widget: { getDomNode: () => HTMLElement }) => {
widgets.delete(widget);
},
- getLayoutInfo: () => ({
- contentLeft: 52,
- width: 800,
- verticalScrollbarWidth: 14,
- minimap: { minimapWidth: 0 },
- }),
onDidLayoutChange: () => ({ dispose: vi.fn() }),
getModel: () => ({}),
changeViewZones: (
callback: (accessor: {
- addZone: (zone: {
- afterLineNumber: number;
- domNode: HTMLElement;
- onDomNodeTop?: (top: number) => void;
- }) => string;
+ addZone: (zone: FakeZone) => string;
removeZone: (id: string) => void;
layoutZone: (id: string) => void;
}) => void
@@ -57,7 +58,20 @@ function fakeEditor() {
layoutZone: vi.fn(),
}),
};
- return { editor: editor as unknown as IStandaloneCodeEditor, widgets, zones };
+ // A sibling zone Monaco stacks before the component's, after the same line.
+ const addZoneBefore = (afterLineNumber: number, height: number) =>
+ zones.set(`sibling-${nextId++}`, {
+ afterLineNumber,
+ domNode: document.createElement("div"),
+ heightInPx: height,
+ });
+ return {
+ addZoneBefore,
+ editor: editor as unknown as IStandaloneCodeEditor,
+ scroll: layout.setScrollTop,
+ widgets,
+ zones,
+ };
}
describe("MonacoViewZone", () => {
@@ -104,44 +118,94 @@ describe("MonacoViewZone", () => {
});
});
+// Monaco parks the widget of a zone outside the rendered viewport far above
+// the page, so the reveal must not depend on where the widget is.
+const WIDGET_TOP = -1_000_000;
-afterEach(() => vi.unstubAllGlobals());
+afterEach(() => vi.restoreAllMocks());
+
+// Positions the widget off screen and the target `offset` px into it.
+function stubRects(target: HTMLElement, offset: number, height: number) {
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
+ function (this: HTMLElement) {
+ return this === target
+ ? new DOMRect(0, WIDGET_TOP + offset, 700, height)
+ : new DOMRect(0, WIDGET_TOP, 800, 0);
+ }
+ );
+}
test.each([
- { name: "already visible", top: 150, height: 100, expected: undefined },
- { name: "below the viewport", top: 480, height: 120, expected: 208 },
- { name: "above the viewport", top: 50, height: 120, expected: 42 },
- { name: "taller than the viewport", top: 450, height: 600, expected: 442 },
-])("reveals $name with minimal editor scrolling", ({top, height, expected}) => {
- const frames = new Map<number, FrameRequestCallback>();
- let nextFrame = 0;
- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++nextFrame, callback); return nextFrame; });
- vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
- const runFrame = () => { const queued = [...frames.values()]; frames.clear(); act(() => queued.forEach(callback => callback(0))); };
- const host = document.createElement("div");
- host.getBoundingClientRect = () => new DOMRect(0, 100, 800, 400);
+ { name: "already visible", line: 4, height: 100, scrollTop: 50, expected: undefined },
+ // Minimal scrolling: the box lands against the nearer edge, 8px in.
+ { name: "below the viewport", line: 20, height: 120, scrollTop: 50, expected: lineTop(21) + 120 + 8 - 400 },
+ { name: "above the viewport", line: 4, height: 120, scrollTop: 300, expected: lineTop(5) - 8 },
+ { name: "taller than the viewport", line: 4, height: 600, scrollTop: 300, expected: lineTop(5) - 8 },
+])("reveals a zone $name with one editor scroll", ({line, height, scrollTop, expected}) => {
+ const {editor, scroll} = fakeEditor({scrollTop});
const target = document.createElement("div");
- target.getBoundingClientRect = () => new DOMRect(0, top, 700, height);
+ stubRects(target, 0, height);
const revealTarget = {current: target};
- const {editor} = fakeEditor();
- const scroll = vi.fn();
- Object.assign(editor, {getDomNode: () => host, getScrollTop: () => 100, setScrollTop: scroll});
const root = createRoot(document.createElement("div"));
- const render = (key: string, text = "comment") => act(() => root.render(<MonacoViewZone afterLineNumber={4} editor={editor} revealKey={key} revealTarget={revealTarget}>{text}</MonacoViewZone>));
+ const render = (key: string, text = "comment") => act(() => root.render(<MonacoViewZone afterLineNumber={line} editor={editor} revealKey={key} revealTarget={revealTarget}>{text}</MonacoViewZone>));
render("first");
- runFrame();
- expect(scroll).not.toHaveBeenCalled();
- runFrame();
if (expected === undefined) expect(scroll).not.toHaveBeenCalled();
else expect(scroll).toHaveBeenCalledExactlyOnceWith(expected);
// Typing/rerendering the same comment must not pull the reader back.
scroll.mockClear();
render("first", "longer comment");
- runFrame(); runFrame();
expect(scroll).not.toHaveBeenCalled();
- render("second");
- runFrame();
act(() => root.unmount());
- runFrame();
expect(scroll).not.toHaveBeenCalled();
});
+
+test("reveals from the first line of the range the content is about", () => {
+ // Line 12's zone is in view; lines 9-11 above it are scrolled past.
+ const {editor, scroll} = fakeEditor({scrollTop: 250});
+ const target = document.createElement("div");
+ stubRects(target, 0, 100);
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<MonacoViewZone afterLineNumber={12} editor={editor} revealKey="a" revealTarget={{current: target}}>comment</MonacoViewZone>));
+ expect(scroll).not.toHaveBeenCalled();
+ act(() => root.render(<MonacoViewZone afterLineNumber={12} editor={editor} revealFromLine={9} revealKey="b" revealTarget={{current: target}}>comment</MonacoViewZone>));
+ expect(scroll).toHaveBeenCalledExactlyOnceWith(lineTop(9) - 8);
+ act(() => root.unmount());
+});
+
+test("content revealing a part of itself scrolls to that part, not to the range", () => {
+ const {editor, scroll} = fakeEditor({scrollTop: 250});
+ const footer = document.createElement("div");
+ stubRects(footer, 320, 40);
+ function Footer() {
+ const reveal = useContext(MonacoViewZoneRevealContext);
+ useEffect(() => reveal?.(footer), [reveal]);
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<MonacoViewZone afterLineNumber={12} editor={editor} revealFromLine={9}><Footer /></MonacoViewZone>));
+ // The footer (296 + 320 → 616..656) crosses the 250..650 viewport's bottom.
+ expect(scroll).toHaveBeenCalledExactlyOnceWith(lineTop(13) + 320 + 40 + 8 - 400);
+ act(() => root.unmount());
+});
+
+test("a range taller than the viewport keeps its last line and the top of the content in view", () => {
+ const {editor, scroll} = fakeEditor();
+ const target = document.createElement("div");
+ stubRects(target, 0, 100);
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<MonacoViewZone afterLineNumber={40} editor={editor} revealFromLine={1} revealKey="a" revealTarget={{current: target}}>comment</MonacoViewZone>));
+ // The whole content (100px) peeks above the bottom inset.
+ expect(scroll).toHaveBeenCalledExactlyOnceWith(lineTop(41) + 100 + 8 - 400);
+ act(() => root.unmount());
+});
+
+test("accounts for sibling zones stacked before it and the target's offset in the content", () => {
+ const {addZoneBefore, editor, scroll} = fakeEditor({scrollTop: 600});
+ addZoneBefore(4, 50);
+ const target = document.createElement("div");
+ stubRects(target, 30, 100);
+ const root = createRoot(document.createElement("div"));
+ act(() => root.render(<MonacoViewZone afterLineNumber={4} editor={editor} revealKey="a" revealTarget={{current: target}}>comment</MonacoViewZone>));
+ expect(scroll).toHaveBeenCalledExactlyOnceWith(lineTop(5) + 50 + 30 - 8);
+ act(() => root.unmount());
+});
diff --git a/frontend/src/components/monaco/MonacoViewZone.tsx b/frontend/src/components/monaco/MonacoViewZone.tsx
index cf6da16d11..1ecc4805d8 100644
--- a/frontend/src/components/monaco/MonacoViewZone.tsx
+++ b/frontend/src/components/monaco/MonacoViewZone.tsx
@@ -14,6 +14,9 @@ export const MonacoViewZoneRevealContext = createContext<
((target: HTMLElement) => void) | undefined
>(undefined);
+// Breathing room kept between a revealed box and the viewport edges, in px.
+const REVEAL_INSET = 8;
+
// Hosts interactive React content between two editor lines the way VS Code's
// ZoneWidget does: a view zone reserves the vertical space (the zone layer
// sits under the text layer, so it cannot take clicks), and an overlay widget
@@ -23,12 +26,16 @@ export function MonacoViewZone({
afterLineNumber,
children,
editor,
+ revealFromLine,
revealKey,
revealTarget,
}: {
afterLineNumber: number;
children: ReactNode;
editor: IStandaloneCodeEditor;
+ // The first line to keep in view with the revealed content, for content
+ // that discusses the lines above it.
+ revealFromLine?: number;
// Reveal once on opening/changing content, never on every resize or keystroke.
revealKey?: unknown;
revealTarget?: RefObject<HTMLElement | null>;
@@ -39,7 +46,15 @@ export function MonacoViewZone({
return node;
}, []);
const contentRef = useRef<HTMLDivElement>(null);
- const revealFrame = useRef<number | undefined>(undefined);
+ const zoneRef = useRef<{
+ id: string;
+ afterLineNumber: number;
+ fit: () => void;
+ }>(undefined);
+ const revealFromLineRef = useRef(revealFromLine);
+ useLayoutEffect(() => {
+ revealFromLineRef.current = revealFromLine;
+ }, [revealFromLine]);
useLayoutEffect(() => {
const content = contentRef.current;
@@ -89,12 +104,14 @@ export function MonacoViewZone({
// render, so the first frame never shows the content over the lines
// below it at a placeholder height.
fit();
+ zoneRef.current = { id: zoneId, afterLineNumber, fit };
const observer = new ResizeObserver(fit);
if (content) observer.observe(content);
return () => {
observer.disconnect();
layoutSubscription.dispose();
+ zoneRef.current = undefined;
// The editor may already be disposed when the host unmounts.
if (!editor.getModel()) return;
editor.removeOverlayWidget(widget);
@@ -102,38 +119,57 @@ export function MonacoViewZone({
};
}, [afterLineNumber, editor, widgetNode]);
+ // Scrolls the editor once, synchronously, so the target (and the lines from
+ // `fromLine` above it) is in view. Positions come from the editor's layout
+ // rather than the DOM: Monaco places a zone's widget only when the zone is
+ // inside the rendered viewport and only on its next render, and the scroll
+ // must land before that render to avoid a visible jump.
+ // Content revealing a part of itself, such as a reply form, passes no line.
const reveal = useCallback(
- (target: HTMLElement) => {
- if (revealFrame.current !== undefined)
- cancelAnimationFrame(revealFrame.current);
- // Wait for the zone height to include newly opened forms.
- revealFrame.current = requestAnimationFrame(() => {
- revealFrame.current = requestAnimationFrame(() => {
- const host = editor.getDomNode();
- if (!host || !editor.getModel()) return;
- const bounds = target.getBoundingClientRect();
- const viewport = host.getBoundingClientRect();
- if (!bounds.height || !viewport.height) return;
- const top = viewport.top + 8;
- const bottom = viewport.bottom - 8;
- const delta =
- bounds.height > bottom - top || bounds.top < top
- ? bounds.top - top
- : Math.max(0, bounds.bottom - bottom);
- if (delta) editor.setScrollTop(editor.getScrollTop() + delta);
- });
- });
+ (target: HTMLElement, fromLine?: number) => {
+ const zone = zoneRef.current;
+ if (!zone || !editor.getModel()) return;
+ // The zone may not have caught up with content that just grew.
+ zone.fit();
+ const rect = target.getBoundingClientRect();
+ const viewportHeight = editor.getLayoutInfo().height;
+ if (!rect.height || !viewportHeight) return;
+
+ const targetTop =
+ zoneTopOffset(editor, zone.afterLineNumber, zone.id) +
+ rect.top -
+ widgetNode.getBoundingClientRect().top;
+ const targetBottom = targetTop + rect.height;
+ const boxTop =
+ (fromLine === undefined
+ ? targetTop
+ : Math.min(targetTop, editor.getTopForLineNumber(fromLine))) -
+ REVEAL_INSET;
+ const boxBottom = targetBottom + REVEAL_INSET;
+
+ const scrollTop = editor.getScrollTop();
+ const viewportBottom = scrollTop + viewportHeight;
+ if (boxTop >= scrollTop && boxBottom <= viewportBottom) return;
+ if (boxBottom - boxTop > viewportHeight) {
+ // Anchor the top of the box, but keep enough of the target itself in
+ // view that a long range does not push it off the bottom.
+ const peek = Math.min(rect.height, viewportHeight / 3);
+ editor.setScrollTop(
+ Math.max(boxTop, targetTop + peek + REVEAL_INSET - viewportHeight)
+ );
+ return;
+ }
+ editor.setScrollTop(
+ boxTop < scrollTop ? boxTop : boxBottom - viewportHeight
+ );
},
- [editor]
+ [editor, widgetNode]
);
useLayoutEffect(() => {
const target = revealTarget?.current ?? contentRef.current;
- if (revealKey !== undefined && target) reveal(target);
- return () => {
- if (revealFrame.current !== undefined)
- cancelAnimationFrame(revealFrame.current);
- };
+ if (revealKey !== undefined && target)
+ reveal(target, revealFromLineRef.current);
}, [reveal, revealKey, revealTarget]);
return createPortal(
@@ -145,3 +181,29 @@ export function MonacoViewZone({
widgetNode
);
}
+
+// The editor widget lists its zones in layout order, but the method is not
+// on the public editor interface.
+type WhitespaceLister = IStandaloneCodeEditor & {
+ getWhitespaces: () => {
+ id: string;
+ afterLineNumber: number;
+ height: number;
+ }[];
+};
+
+// The top of the zone within the editor's scrollable content: the bottom of
+// its line, plus the zones Monaco stacks before it after that same line.
+function zoneTopOffset(
+ editor: IStandaloneCodeEditor,
+ afterLineNumber: number,
+ zoneId: string
+): number {
+ let top = editor.getBottomForLineNumber(afterLineNumber);
+ for (const whitespace of (editor as WhitespaceLister).getWhitespaces()) {
+ if (whitespace.afterLineNumber !== afterLineNumber) continue;
+ if (whitespace.id === zoneId) break;
+ top += whitespace.height;
+ }
+ return top;
+}
diff --git a/frontend/src/components/monaco/core.ts b/frontend/src/components/monaco/core.ts
index ba569e80f2..e68d69f711 100644
--- a/frontend/src/components/monaco/core.ts
+++ b/frontend/src/components/monaco/core.ts
@@ -186,6 +186,8 @@ export const defaultEditorOptions =
codeLens: false,
scrollbar: {
alwaysConsumeMouseWheel: false,
+ // A thin strip rather than Monaco's 14px block.
+ verticalScrollbarSize: 8,
},
inlineSuggest: {
showToolbar: "never",
@@ -223,6 +225,8 @@ export const defaultDiffEditorOptions =
codeLens: false,
scrollbar: {
alwaysConsumeMouseWheel: false,
+ // A thin strip rather than Monaco's 14px block.
+ verticalScrollbarSize: 8,
},
inlineSuggest: {
showToolbar: "never",
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
index 1b82919422..80cf06d74b 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadWalker.tsx
@@ -4,7 +4,7 @@ import { Button } from "@/components/ui/button";
// Touch has no hover and keeps focus on the tapped arrow, so coarse pointers
// get no ring: the flash on the target card is the feedback there.
-// Size comes from the shared "sm" button, whose 28px height is the strip's.
+// The strip takes its height from the shared "sm" buttons.
const ARROW_CLASS =
"rounded-none border-l border-control-border text-control-light hover:text-control focus-visible:ring-inset focus-visible:ring-offset-0 pointer-coarse:focus-visible:ring-0";
@@ -35,7 +35,7 @@ export function StatementThreadWalker({
.join(" · ");
return (
<div
- className="flex h-7 items-stretch overflow-hidden rounded-sm border border-control-border bg-background text-xs shadow-sm pointer-coarse:shadow-none"
+ className="flex items-stretch overflow-hidden rounded-sm border border-control-border bg-background text-xs shadow-sm pointer-coarse:shadow-none"
data-testid="thread-walker"
title={title}
>
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
index 537e198131..70a1ffccfe 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.test.tsx
@@ -8,6 +8,7 @@ import type {
IStandaloneCodeEditor,
MonacoModule,
} from "@/components/monaco/types";
+import { fakeEditorLayout, lineTop } from "@/test-utils/monacoLayout";
import { PositionSchema } from "@/types/proto-es/v1/common_pb";
import {
IssueComment_ThreadState,
@@ -239,7 +240,7 @@ function createFakeEditor(lineMaxColumn = 20) {
up: [],
leave: [],
};
- const zones = new Map<string, { afterLineNumber: number; domNode: HTMLElement }>();
+ const zones = new Map<string, { afterLineNumber: number; domNode: HTMLElement; heightInPx: number }>();
const widgets = new Set<{ getDomNode: () => HTMLElement }>();
let zoneSeq = 0;
// The DOM hit test used by the drag; tests set the line the pointer is on.
@@ -258,6 +259,9 @@ function createFakeEditor(lineMaxColumn = 20) {
const domNode = document.createElement("div");
document.body.append(domNode);
domNode.scrollIntoView = vi.fn();
+ const layout = fakeEditorLayout(() =>
+ Array.from(zones, ([id, zone]) => ({ id, afterLineNumber: zone.afterLineNumber, height: zone.heightInPx }))
+ );
const subscribe = (key: string) => (handler: MouseHandler) => {
handlers[key].push(handler);
return {
@@ -276,12 +280,7 @@ function createFakeEditor(lineMaxColumn = 20) {
widgets.delete(widget);
},
getContribution: () => mocks.findController,
- getLayoutInfo: () => ({
- contentLeft: 52,
- width: 800,
- verticalScrollbarWidth: 14,
- minimap: { minimapWidth: 0 },
- }),
+ ...layout,
getTargetAtClientPoint: () =>
pointer.line === undefined
? null
@@ -289,7 +288,7 @@ function createFakeEditor(lineMaxColumn = 20) {
onDidLayoutChange: () => ({ dispose: vi.fn() }),
changeViewZones: (
callback: (accessor: {
- addZone: (zone: { afterLineNumber: number; domNode: HTMLElement }) => string;
+ addZone: (zone: { afterLineNumber: number; domNode: HTMLElement; heightInPx: number }) => string;
removeZone: (id: string) => void;
layoutZone: (id: string) => void;
}) => void
@@ -327,8 +326,6 @@ function createFakeEditor(lineMaxColumn = 20) {
onMouseLeave: subscribe("leave"),
onMouseMove: subscribe("move"),
onMouseUp: subscribe("up"),
- revealLineInCenter: vi.fn(),
- revealLineNearTop: vi.fn(),
};
const fire = (key: string, line: number | undefined, type: number, detail?: Record<string, unknown>) => {
const event = {
@@ -360,6 +357,8 @@ function createFakeEditor(lineMaxColumn = 20) {
return {
editor: editor as unknown as IStandaloneCodeEditor,
decorations,
+ scroll: layout.scroll,
+ setScrollTop: layout.setScrollTop,
pressEscape: () => act(() => {
domNode.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
}),
@@ -413,8 +412,16 @@ beforeEach(() => {
afterEach(() => {
act(() => root.unmount());
document.body.replaceChildren();
+ vi.restoreAllMocks();
});
+// Gives every element a 100px box so the zones' reveals have something to
+// measure; jsdom lays nothing out.
+const giveElementsHeight = () =>
+ vi
+ .spyOn(HTMLElement.prototype, "getBoundingClientRect")
+ .mockReturnValue(new DOMRect(0, 0, 700, 100));
+
const mount = (editor: IStandaloneCodeEditor) =>
act(() =>
root.render(
@@ -834,7 +841,7 @@ describe("StatementThreadsLayer", () => {
expect((hosted(fake.widgets, "[data-testid='saved-draft']") as HTMLInputElement)?.value).toBe("");
});
- test("a focus request expands the thread, reveals its line, and is cleared", () => {
+ test("a focus request expands the thread, reveals it from its first line, and is cleared", () => {
mocks.comments = [
threadRoot("first", 3, 4, { createdAt: 2 }),
threadRoot("target", 10, 12, { createdAt: 5 }),
@@ -844,13 +851,12 @@ describe("StatementThreadsLayer", () => {
specId: "spec-1",
nonce: 7,
};
+ giveElementsHeight();
const fake = createFakeEditor();
+ fake.scroll.top = 600;
mount(fake.editor);
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/target`);
- expect(
- (fake.editor as unknown as { revealLineInCenter: ReturnType<typeof vi.fn> })
- .revealLineInCenter
- ).toHaveBeenCalledWith(10);
+ expect(fake.setScrollTop).toHaveBeenCalledExactlyOnceWith(lineTop(10) - 8);
expect(mocks.clearThreadFocus).toHaveBeenCalledWith(7);
});
test("the walker steps through unresolved threads in editor order and wraps", () => {
@@ -859,6 +865,7 @@ describe("StatementThreadsLayer", () => {
threadRoot("done", 5, 5, { createdAt: 2, resolved: true }),
threadRoot("c", 7, 8, { createdAt: 3 }),
];
+ giveElementsHeight();
const fake = createFakeEditor();
mount(fake.editor);
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/a`);
@@ -869,15 +876,24 @@ describe("StatementThreadsLayer", () => {
"plan.review.thread.walker.count:2"
);
+ // Scrolled past the threads: a step scrolls the editor exactly once, to
+ // the target's first line, and brings the editor onto the page.
+ fake.scroll.top = 600;
+ fake.setScrollTop.mockClear();
pressWalker(fake.widgets, "next");
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/c`);
expect(zoneAfter(fake.zones)).toEqual([8]);
- expect(fake.editor.revealLineNearTop).toHaveBeenLastCalledWith(7);
+ expect(fake.setScrollTop).toHaveBeenCalledExactlyOnceWith(lineTop(7) - 8);
expect(fake.editor.getDomNode()?.scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });
+ fake.setScrollTop.mockClear();
pressWalker(fake.widgets, "next");
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/a`);
+ expect(fake.setScrollTop).toHaveBeenCalledExactlyOnceWith(lineTop(2) - 8);
+ // Stepping onto a thread already in view leaves the scroll alone.
+ fake.setScrollTop.mockClear();
pressWalker(fake.widgets, "previous");
expect(cardRoot(fake.widgets)).toBe(`${ISSUE}/issueComments/c`);
+ expect(fake.setScrollTop).not.toHaveBeenCalled();
// Closing the open line leaves no current thread: down starts over, up ends.
fake.fire("down", 8, MouseTargetType.GUTTER_GLYPH_MARGIN);
diff --git a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
index f709e0fde3..b7708f7ee1 100644
--- a/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
+++ b/frontend/src/routes/project/plan-detail/components/threads/StatementThreadsLayer.tsx
@@ -157,14 +157,27 @@ export function StatementThreadsLayer({
setExpandedRoots(new Set(firstToExpand(markersByLine.get(line))));
}, [editorThreads, markersByLine]);
+ // Bumped by every open gesture, so the zone reveals the thread again even
+ // when the same one is reopened.
+ const [openNonce, setOpenNonce] = useState(0);
const openThreads = useCallback(
(line: number | undefined, roots: Iterable<string>) => {
initialExpansionAppliedRef.current = true;
setOpenLine(line);
setExpandedRoots(new Set(roots));
+ setOpenNonce((nonce) => nonce + 1);
},
[]
);
+ const openEntries = useMemo(
+ () => (openLine !== undefined ? (markersByLine.get(openLine) ?? []) : []),
+ [markersByLine, openLine]
+ );
+ const expandedEntry = useMemo(
+ () =>
+ openEntries.find((entry) => expandedRoots.has(entry.thread.root.name)),
+ [expandedRoots, openEntries]
+ );
// Keep drafts across card collapses and closing/reopening a gutter group.
const [replyDrafts, setReplyDrafts] = useState<Record<string, string>>({});
@@ -218,7 +231,8 @@ export function StatementThreadsLayer({
openThreads(target.range.endLine, [target.thread.root.name]);
setSelection(undefined);
setFlashRoot(target.thread.root.name);
- editor.revealLineNearTop(target.range.startLine);
+ // The thread's zone scrolls the editor when it opens; this only brings
+ // the editor itself onto the page.
editor.getDomNode()?.scrollIntoView({ block: "nearest" });
setWalkerAnnouncement(
t("plan.review.thread.walker.position", { index: index + 1, count })
@@ -246,7 +260,6 @@ export function StatementThreadsLayer({
return;
}
openThreads(target.range.endLine, [target.thread.root.name]);
- editor.revealLineInCenter(target.range.startLine);
editor
.getDomNode()
?.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -287,11 +300,6 @@ export function StatementThreadsLayer({
const lineClasses = new Map<number, string>(
commentedLines.map((line) => [line, "bb-thread-line--passive"])
);
- const activeThread = editorThreads.find(
- (entry) =>
- entry.range.endLine === openLine &&
- expandedRoots.has(entry.thread.root.name)
- );
// A pending selection replaces the reading highlight; open composers
// keep theirs beside it, and win where they overlap.
const pendingSelection = canCreate ? selection : undefined;
@@ -300,8 +308,8 @@ export function StatementThreadsLayer({
lineClasses.set(line, className);
}
};
- if (activeThread && !pendingSelection) {
- paint(activeThread.range, "bb-thread-line");
+ if (expandedEntry && !pendingSelection) {
+ paint(expandedEntry.range, "bb-thread-line");
}
for (const composer of composers.values()) {
paint(composer.range, "bb-thread-line--selecting");
@@ -369,8 +377,7 @@ export function StatementThreadsLayer({
commentedLines,
composers,
editor,
- editorThreads,
- expandedRoots,
+ expandedEntry,
markersByLine,
monacoModule,
openLine,
@@ -601,9 +608,6 @@ export function StatementThreadsLayer({
openThreads(line, [created.name]);
};
- const openEntries: EditorThread[] =
- openLine !== undefined ? (markersByLine.get(openLine) ?? []) : [];
-
return (
<>
{visitableThreads.length > 0 && !findWidgetVisible && (
@@ -621,7 +625,8 @@ export function StatementThreadsLayer({
<MonacoViewZone
afterLineNumber={openLine}
editor={editor}
- revealKey={expandedRoots.size > 0 ? expandedRoots : undefined}
+ revealFromLine={expandedEntry?.range.startLine}
+ revealKey={expandedEntry ? openNonce : undefined}
revealTarget={expandedThreadRef}
>
<div className="py-2 pr-2">
@@ -652,6 +657,7 @@ export function StatementThreadsLayer({
afterLineNumber={line}
editor={editor}
key={line}
+ revealFromLine={composer.range.startLine}
revealKey={composer.revealNonce}
>
<div className="py-2 pr-2">
diff --git a/frontend/src/test-utils/monacoLayout.ts b/frontend/src/test-utils/monacoLayout.ts
new file mode 100644
index 0000000000..7e487030d2
--- /dev/null
+++ b/frontend/src/test-utils/monacoLayout.ts
@@ -0,0 +1,47 @@
+import { vi } from "vitest";
+
+// Vertical layout for a fake Monaco editor: 24px lines under 8px padding,
+// with view zones stacked after their line in insertion order.
+export const LINE_HEIGHT = 24;
+export const PADDING_TOP = 8;
+
+export const lineTop = (lineNumber: number) =>
+ PADDING_TOP + (lineNumber - 1) * LINE_HEIGHT;
+
+export type FakeWhitespace = {
+ id: string;
+ afterLineNumber: number;
+ height: number;
+};
+
+// The layout getters MonacoViewZone reveals through, over the zones the
+// fake editor currently holds. `scroll.top` is readable and settable.
+export function fakeEditorLayout(
+ whitespaces: () => FakeWhitespace[],
+ { scrollTop = 0, viewportHeight = 400 } = {}
+) {
+ const scroll = { top: scrollTop };
+ const before = (lineNumber: number) =>
+ whitespaces()
+ .filter((zone) => zone.afterLineNumber < lineNumber)
+ .reduce((sum, zone) => sum + zone.height, 0);
+ return {
+ scroll,
+ getLayoutInfo: () => ({
+ contentLeft: 52,
+ height: viewportHeight,
+ width: 800,
+ verticalScrollbarWidth: 14,
+ minimap: { minimapWidth: 0 },
+ }),
+ getScrollTop: () => scroll.top,
+ setScrollTop: vi.fn((top: number) => {
+ scroll.top = top;
+ }),
+ getTopForLineNumber: (lineNumber: number) =>
+ lineTop(lineNumber) + before(lineNumber),
+ getBottomForLineNumber: (lineNumber: number) =>
+ lineTop(lineNumber) + LINE_HEIGHT + before(lineNumber),
+ getWhitespaces: whitespaces,
+ };
+}
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
index 256a587399..72ebff694e 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts
@@ -1248,3 +1248,84 @@ test.describe.skip("Inline comment threads: ranges, shared markers, walker detai
await expect(planPage.inlineComposer).toHaveCount(0);
});
});
+
+// Inline comment threads, third pass: the editor scroll a walker step makes.
+// A thread taller than the editor's viewport used to be revealed twice, by
+// the walker and then by its zone, so the editor jumped and jumped back.
+// Gated off with the feature: inlineThreadsEnabled() is false in the embedded
+// binary this suite runs against, so the thread UI is absent by design.
+// Re-enable together with the gate in src/utils/featureGates.ts.
+test.describe.skip("Inline comment threads: walker scrolls the editor once (CUJ N)", () => {
+ test.describe.configure({ mode: "serial" });
+ let planId: string;
+ let shortRootName = "";
+ const stamp = Date.now();
+ const shortRoot = `N short root line 1 ${stamp}`;
+ const longRoot = `N long root lines 4-7 ${stamp}`;
+ const longBody = [longRoot]
+ .concat(
+ Array.from({ length: 40 }, (_, i) => `Paragraph ${i + 1} of a review note taller than the editor.`),
+ )
+ .join("\n\n");
+
+ const expectLineAtTop = async (lineNumber: number) => {
+ const offset = await planPage.statementLineOffset(lineNumber);
+ expect(offset).toBeGreaterThanOrEqual(0);
+ expect(offset).toBeLessThan(24);
+ };
+ const stepTo = (root: string) => async () => {
+ await planPage.threadWalkerNext.click();
+ await expect(planPage.threadCardIn("changes", root)).toBeVisible({ timeout: 10_000 });
+ };
+
+ test.beforeAll(async () => {
+ await setupApproval(ONE_STEP_RULE);
+ const seeded = await seedReviewPlan(env, page, {
+ prefix: "E2E Review N",
+ sql: [1, 2, 3, 4, 5, 6, 7]
+ .map((n) => `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_n${n}_${stamp} TEXT;`)
+ .join("\n"),
+ });
+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);
+ planId = seeded.planId;
+ const plan = await env.api.getPlan(seeded.planName);
+ const spec = plan.specs?.[0];
+ const specId = spec?.id ?? "";
+ const sheetSha256 = spec?.changeDatabaseConfig?.sheet?.split("/").pop() ?? "";
+ expect(specId).not.toBe("");
+ expect(sheetSha256).toMatch(/^[0-9a-f]{64}$/);
+ const anchor = (startLine: number, endLine: number) => ({
+ statementAnchor: { spec: specId, sheetSha256, startLine, endLine },
+ });
+ const short = await env.api.createIssueComment(seeded.issueName, shortRoot, anchor(1, 1));
+ shortRootName = short.name;
+ await env.api.createIssueComment(seeded.issueName, longBody, anchor(4, 7));
+ await goReview(planId);
+ await planPage.expandSection("Changes");
+ });
+
+ test("a step onto a thread taller than the editor scrolls once, to the thread's first line", async () => {
+ await expect(planPage.threadCardIn("changes", shortRoot)).toBeVisible({ timeout: 15_000 });
+ expect(await planPage.countStatementEditorScrolls(stepTo(longRoot))).toBe(1);
+ // Line 4 sits at the top of the viewport with the card below it.
+ await expectLineAtTop(4);
+ await expect(planPage.statementLineNumber(7)).toBeVisible();
+ });
+
+ test("stepping away from a scrolled card and back scrolls once each way", async () => {
+ await planPage.scrollStatementEditorPastLine(4);
+ expect(await planPage.countStatementEditorScrolls(stepTo(shortRoot))).toBe(1);
+ await expect(planPage.statementLineNumber(1)).toBeVisible();
+ expect(await planPage.countStatementEditorScrolls(stepTo(longRoot))).toBe(1);
+ await expectLineAtTop(4);
+ });
+
+ test("stepping onto the only thread scrolls once from the bottom and not at all once in place", async () => {
+ await env.api.setIssueCommentThreadState(shortRootName, "RESOLVED");
+ await expect(planPage.threadWalker).toContainText("1", { timeout: 15_000 });
+ await planPage.scrollStatementEditorPastLine(4);
+ expect(await planPage.countStatementEditorScrolls(stepTo(longRoot))).toBe(1);
+ await expectLineAtTop(4);
+ expect(await planPage.countStatementEditorScrolls(stepTo(longRoot))).toBe(0);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
index 55969abe24..befce646d9 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
@@ -389,6 +389,68 @@ export class PlanDetailPage {
);
}
+ // The offset of a line's number cell from the statement editor's top edge.
+ // Monaco renders only the lines in view, so an unrendered line counts as
+ // scrolled above.
+ async statementLineOffset(lineNumber: number): Promise<number> {
+ const cell = this.statementLineNumber(lineNumber);
+ if ((await cell.count()) === 0) return Number.NEGATIVE_INFINITY;
+ const [editorBox, lineBox] = await Promise.all([
+ this.statementEditor.boundingBox(),
+ cell.boundingBox(),
+ ]);
+ if (!editorBox || !lineBox) return Number.NEGATIVE_INFINITY;
+ return lineBox.y - editorBox.y;
+ }
+
+ // Wheel the statement editor down until the line is scrolled above its top.
+ async scrollStatementEditorPastLine(lineNumber: number): Promise<void> {
+ await this.statementEditor.hover({ position: { x: 300, y: 60 } });
+ await expect
+ .poll(async () => {
+ await this.page.mouse.wheel(0, 240);
+ return this.statementLineOffset(lineNumber);
+ })
+ .toBeLessThan(0);
+ }
+
+ // How many times the statement editor scrolled while `step` ran, counted
+ // once the editor has stayed still for ten frames. Monaco writes every
+ // scroll as the `top` of its lines layer.
+ async countStatementEditorScrolls(step: () => Promise<void>): Promise<number> {
+ type ScrollLog = { tops: string[]; observer: MutationObserver };
+ await this.statementEditor.evaluate((node) => {
+ const lines = node.querySelector<HTMLElement>(".lines-content");
+ if (!lines) throw new Error("statement editor has no lines layer");
+ const host = window as unknown as { __bbScrollLog?: ScrollLog };
+ host.__bbScrollLog?.observer.disconnect();
+ const tops = [lines.style.top];
+ const observer = new MutationObserver(() => {
+ if (lines.style.top !== tops[tops.length - 1]) tops.push(lines.style.top);
+ });
+ observer.observe(lines, { attributes: true, attributeFilter: ["style"] });
+ host.__bbScrollLog = { tops, observer };
+ });
+ await step();
+ return this.page.evaluate(
+ () =>
+ new Promise<number>((resolve) => {
+ const log = (window as unknown as { __bbScrollLog?: ScrollLog }).__bbScrollLog;
+ if (!log) throw new Error("no scroll log is recording");
+ let seen = log.tops.length;
+ let still = 0;
+ const tick = () => {
+ if (log.tops.length === seen) still += 1;
+ else [seen, still] = [log.tops.length, 0];
+ if (still < 10) return requestAnimationFrame(tick);
+ log.observer.disconnect();
+ resolve(log.tops.length - 1);
+ };
+ requestAnimationFrame(tick);
+ }),
+ );
+ }
+
// Scroll the editor clear of the sticky page header, which otherwise
// intercepts pointer actions on its top lines. The dashboard body, not the
// window, owns the page scroll, so walk up to the nearest scrolling