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
71 changes: 71 additions & 0 deletions dashboard/e2e/review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* much that a test on one does not cover the other.
*/

import type { Page } from 'playwright';
import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest';
import { closeBrowser, openPage, shoot } from './browser.ts';
import { DEFAULT_BOX, startOrchestrator, type TestOrchestrator } from './orchestrator.ts';
Expand Down Expand Up @@ -489,6 +490,76 @@ test('the place of the reader survives the switch of the view, and a reopen', as
}
});

/**
* Measures how far the bottom of an element sits above the top of the comment sheet.
*
* @param page The page.
* @param selector The selector of the element.
* @returns The distance in pixels. A negative distance means the sheet covers the element.
*/
async function gapAboveSheet(page: Page, selector: string): Promise<number> {
return page.evaluate((sel) => {
const element = [...document.querySelectorAll(sel)].at(-1);
const sheet = document.querySelector('[data-slot="sheet-content"]');
if (!element || !sheet) return Number.NaN;
return sheet.getBoundingClientRect().top - element.getBoundingClientRect().bottom;
}, selector);
}

test('on a phone, a line near the end scrolls above the comment sheet', async () => {
stub.review(BOX, {
files: {
'long.ts': Array.from({ length: 80 }, (_, i) => `const line${i + 1} = ${i};`).join('\n'),
},
repos: [''],
});
const { page, errors, close } = await openPage(stub.url, `/boxes/${BOX}/review?path=long.ts`);
try {
const pane = page.locator('[data-slot="review-code-pane"]');
await expect.poll(() => pane.isVisible()).toBe(true);
await pane.evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
await page.locator('[data-line="79"] code').click();
await expect.poll(() => page.getByText('Comment on line 79').isVisible()).toBe(true);
// The line sits just above the sheet, even though no line follows to scroll into.
await expect.poll(() => gapAboveSheet(page, '[data-line="79"]')).toBeGreaterThanOrEqual(0);
// The header hides while the sheet is open, and the line stays above the sheet as the pane grows.
await expect.poll(() => page.locator('[data-slot="shelf"]').getAttribute('data-away')).toBe('');
await page.waitForTimeout(500);
expect(await gapAboveSheet(page, '[data-line="79"]')).toBeLessThan(20);
await shoot(page, 'review-sheet-line-phone', 'viewport');
expect(errors).toEqual([]);
} finally {
await close();
}
});

test('on a phone, the end of a block scrolls above the comment sheet', async () => {
const paragraphs = Array.from({ length: 40 }, (_, i) => `Paragraph ${i + 1}`).join('\n\n');
stub.review(BOX, { files: { 'long.md': `${paragraphs}\n` }, repos: [''] });
const { page, errors, close } = await openPage(stub.url, `/boxes/${BOX}/review?path=long.md`);
try {
await expect.poll(() => page.locator('[data-slot="review-code-pane"]').isVisible()).toBe(true);
await page.getByRole('button', { name: 'Show the rendered file' }).click();
const preview = page.locator('[data-slot="review-preview"]');
await expect.poll(() => page.getByText('Paragraph 1', { exact: true }).isVisible()).toBe(true);
await preview.evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
await page.getByText('Paragraph 39', { exact: true }).click();
await expect.poll(() => page.getByText('Comment on line 77').isVisible()).toBe(true);
// The frame of the block, with its tinted background, ends just above the sheet.
const frame = '[data-block][data-line="77"]';
await expect.poll(() => gapAboveSheet(page, frame)).toBeGreaterThanOrEqual(0);
await page.waitForTimeout(500);
expect(await gapAboveSheet(page, frame)).toBeLessThan(20);
expect(errors).toEqual([]);
} finally {
await close();
}
});

test('a markdown file shows rendered, with its images and diagrams', async () => {
const base = reviewWorkspace();
stub.review(
Expand Down
4 changes: 4 additions & 0 deletions dashboard/src/components/review/CodePane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ export interface CodePaneProps {
onShowHunk: (hunkIndex: number) => void;
/** Renders the card and the composer below a line. */
renderUnderLine?: (line: number) => React.ReactNode;
/** The height in pixels at the bottom of the pane that a sheet covers, so the last line can scroll above it. */
bottomInset?: number;
}

/**
Expand Down Expand Up @@ -120,6 +122,7 @@ export function CodePane({
onSelectLine,
onShowHunk,
renderUnderLine,
bottomInset = 0,
}: CodePaneProps) {
const editing = edit !== null;
/** The shown text, which is the buffer while editing and the file otherwise. */
Expand Down Expand Up @@ -180,6 +183,7 @@ export function CodePane({
<div
ref={scrollRef}
data-slot="review-code-pane"
style={bottomInset > 0 ? { paddingBottom: bottomInset } : undefined}
className={cn(
// 16px on a phone, because Safari zooms the page when a smaller control
// takes focus. Both modes use the same size, so a switch moves nothing.
Expand Down
59 changes: 56 additions & 3 deletions dashboard/src/components/review/CommentComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,16 @@ export function InlineComposer(props: {
* @param busy Disables the buttons while a write is in flight.
* @param onSave Called with the trimmed comment when the user saves.
* @param onCancel Called when the user cancels or dismisses the sheet.
* @param onCover Called with the top edge of the area that the sheet and the keyboard cover, or with null when the
* sheet closes.
*/
export function ComposerSheet({
composing,
initial,
busy,
onSave,
onCancel,
onCover,
}: {
/** The line or the block being commented on, or null when the sheet is closed. */
composing: Composing | null;
Expand All @@ -157,13 +160,63 @@ export function ComposerSheet({
onSave: (comment: string) => void;
/** Called when the user cancels or dismisses the sheet. */
onCancel: () => void;
/**
* Called with the top edge of the area that the sheet and the keyboard cover, in pixels from the top of the
* layout viewport, or with null when the sheet closes.
*/
onCover: (top: number | null) => void;
}) {
const range = composing ? lineRange(composing.line, composing.endLine) : '';
const open = composing !== null;
/** The panel of the open sheet. Radix mounts it in a portal after the sheet opens, and unmounts it after it closes. */
const [panel, setPanel] = useState<HTMLDivElement | null>(null);

/**
* Reports the covered area while the panel is on screen. The panel slides in, and the keyboard opens after it
* and shrinks the visible area, so the sheet measures again after each of them.
*/
useEffect(() => {
const element = panel;
if (!element) {
onCover(null);
return;
}
let frame = 0;
const measure = (): void => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const viewport = window.visualViewport;
const visibleBottom = viewport ? viewport.offsetTop + viewport.height : window.innerHeight;
onCover(Math.min(element.getBoundingClientRect().top, visibleBottom));
});
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(element);
element.addEventListener('animationend', measure);
window.visualViewport?.addEventListener('resize', measure);
window.visualViewport?.addEventListener('scroll', measure);
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
element.removeEventListener('animationend', measure);
window.visualViewport?.removeEventListener('resize', measure);
window.visualViewport?.removeEventListener('scroll', measure);
};
}, [panel, onCover]);

return (
<Sheet open={composing !== null} onOpenChange={(open) => (open ? undefined : onCancel())}>
<Sheet open={open} onOpenChange={(next) => (next ? undefined : onCancel())}>
{/* The sheet has no description. An explicit undefined tells Radix the
omission is deliberate. */}
<SheetContent side="bottom" className="gap-0" aria-describedby={undefined}>
omission is deliberate. The backdrop is light, so the commented text
above the sheet stays readable. */}
<SheetContent
ref={setPanel}
side="bottom"
className="gap-0"
overlayClassName="bg-black/25"
aria-describedby={undefined}
>
<SheetHeader className="pb-2">
<SheetTitle className="text-sm">
{initial === '' ? `Comment on ${range}` : `Edit the comment on ${range}`}
Expand Down
4 changes: 4 additions & 0 deletions dashboard/src/components/review/MarkdownPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export interface MarkdownPreviewProps {
renderUnderBlock: (line: number, endLine: number) => React.ReactNode;
/** Called with the blocks of the file, in order, when they are rendered. */
onBlocks: (blocks: Block[]) => void;
/** The height in pixels at the bottom of the pane that a sheet covers, so the last block can scroll above it. */
bottomInset?: number;
}

/** What the frame of a block needs from the pane. */
Expand Down Expand Up @@ -114,6 +116,7 @@ export function MarkdownPreview({
onShowHunk,
renderUnderBlock,
onBlocks,
bottomInset = 0,
}: MarkdownPreviewProps) {
// A relative path in the file starts from the directory of the file.
const baseDir = `${WORKSPACE_DIR}/${path}`.replace(/\/[^/]*$/, '');
Expand Down Expand Up @@ -253,6 +256,7 @@ export function MarkdownPreview({
<div
ref={scrollRef}
data-slot="review-preview"
style={bottomInset > 0 ? { paddingBottom: bottomInset } : undefined}
className="@container min-h-0 flex-1 overflow-auto"
>
<BlockContext.Provider value={context}>
Expand Down
6 changes: 5 additions & 1 deletion dashboard/src/components/ui/sheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,27 @@ function SheetOverlay({
* @param children The content of the panel.
* @param side The edge of the screen that the panel slides in from.
* @param showCloseButton True to show the close button at the top right corner.
* @param overlayClassName Extra classes for the backdrop.
* @param props The other props of the Radix dialog content.
*/
function SheetContent({
className,
children,
side = 'right',
showCloseButton = true,
overlayClassName,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
/** The edge of the screen that the panel slides in from. */
side?: 'top' | 'right' | 'bottom' | 'left';
/** True to show the close button at the top right corner. */
showCloseButton?: boolean;
/** Extra classes for the backdrop. */
overlayClassName?: string;
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetOverlay className={overlayClassName} />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
Expand Down
61 changes: 60 additions & 1 deletion dashboard/src/views/BoxReview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { stagePrompt } from '@/lib/staged-prompt';
import { cn } from '@/lib/utils';
import type { ReviewDiffHunk, ReviewRepo } from '../../../shared/types.ts';
import {
type Composing,
closeFile,
compose,
deleteComment,
Expand Down Expand Up @@ -85,6 +86,13 @@ export function BoxReview() {
const [previewing, setPreviewing] = useState(false);
/** The blocks of the rendered file, in order, once the pane has rendered them. */
const [blocks, setBlocks] = useState<Block[]>([]);
/** The top edge of the area that the comment sheet and the keyboard cover, or null while the sheet is closed. */
const [cover, setCover] = useState<number | null>(null);
/**
* The composer that the view scrolled above the sheet, and the scroll position it set, to tell a scroll of the
* reader from its own.
*/
const sheetScroll = useRef<{ composing: Composing; top: number } | null>(null);
const [confirmNew, setConfirmNew] = useState(false);
/** The line of the comment that a tap on a bin wants to remove, or null. */
const [confirmDelete, setConfirmDelete] = useState<number | null>(null);
Expand Down Expand Up @@ -345,6 +353,31 @@ export function BoxReview() {
compose({ line, endLine: existing ? existing.endLine : endLine > line ? endLine : 0 });
}, []);

/** The height at the bottom of the pane that the sheet covers. The pane fills the screen down to its bottom. */
const bottomInset = cover === null ? 0 : Math.max(0, window.innerHeight - cover);

/**
* Scrolls the commented line or block above the sheet, with its end just above
* the top of the sheet. It runs again when the covered area changes and when
* the pane resizes as the header hides, until the reader scrolls the pane.
*/
useLayoutEffect(() => {
const pane = paneRef.current;
if (cover === null || !composing || wide || !pane) return;
const place = (): void => {
const last = sheetScroll.current;
if (last?.composing === composing && Math.abs(pane.scrollTop - last.top) > 1) return;
const target = commentedElement(pane, composing.line, composing.endLine);
if (!target) return;
pane.scrollTop += target.getBoundingClientRect().bottom - (cover - SHEET_GAP);
sheetScroll.current = { composing, top: pane.scrollTop };
};
place();
const observer = new ResizeObserver(place);
observer.observe(pane);
return () => observer.disconnect();
}, [cover, composing, wide]);

/** Opens the hunk sheet for a hunk index of the open file. */
const showHunk = useCallback(
(index: number) => setHunk(file?.diff.hunks[index] ?? null),
Expand Down Expand Up @@ -518,6 +551,9 @@ export function BoxReview() {
'[data-slot="review-code-pane"], [data-slot="review-preview"]',
);

/** True while the header is out of the way. It hides while the comment sheet is open, to give the text room. */
const shelfAway = cover !== null || (away && !editing);

// Shows the header again when the open file or the pane changes. Below md, the list's
// only way out is the button in that header.
useEffect(reset, [reset, path, rendered]);
Expand All @@ -529,7 +565,7 @@ export function BoxReview() {
return (
<div ref={container} className="flex h-dvh flex-col">
{/* The header stays while editing, because the toolbar under it holds Save. */}
<Shelf away={away && !editing}>
<Shelf away={shelfAway}>
<header className="flex shrink-0 items-center gap-2 border-b px-3 py-2">
{/* Below md with a file open, back returns to the file list.
Otherwise it leaves the review. */}
Expand Down Expand Up @@ -761,6 +797,7 @@ export function BoxReview() {
onShowHunk={showHunk}
renderUnderBlock={underBlock}
onBlocks={setBlocks}
bottomInset={bottomInset}
/>
) : (
<CodePane
Expand All @@ -781,6 +818,7 @@ export function BoxReview() {
onSelectLine={selectLine}
onShowHunk={showHunk}
renderUnderLine={underLine}
bottomInset={bottomInset}
/>
)}
</>
Expand Down Expand Up @@ -810,6 +848,7 @@ export function BoxReview() {
}
}}
onCancel={() => compose(null)}
onCover={setCover}
/>

{confirmDelete !== null && file ? (
Expand Down Expand Up @@ -867,6 +906,26 @@ export function BoxReview() {
/** Counts the image URLs of the lightbox, so each new URL differs from the earlier ones. */
let imageViews = 0;

/** The space in pixels between the commented text and the top of the comment sheet. */
const SHEET_GAP = 8;

/**
* Finds the element of a commented line or block in a pane.
*
* Nested blocks of the rendered view share a first line. The outermost element with the same range wins, which is
* the frame of a top level block, and else the innermost element on the line.
*
* @param pane The scroller of the pane.
* @param line The line, or the first line of the block.
* @param endLine The last line of the block, or 0 for one line.
* @returns The element, or null when the pane does not show the line.
*/
function commentedElement(pane: HTMLElement, line: number, endLine: number): HTMLElement | null {
const candidates = [...pane.querySelectorAll<HTMLElement>(`[data-line="${line}"]`)];
const end = String(endLine > 0 ? endLine : line);
return candidates.find((el) => el.dataset.lineEnd === end) ?? candidates.at(-1) ?? null;
}

/**
* Picks the blocks that hold one of the given lines.
*
Expand Down
Loading