diff --git a/dashboard/e2e/review.test.ts b/dashboard/e2e/review.test.ts index c3a947d7..4dbfd953 100644 --- a/dashboard/e2e/review.test.ts +++ b/dashboard/e2e/review.test.ts @@ -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'; @@ -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 { + 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( diff --git a/dashboard/src/components/review/CodePane.tsx b/dashboard/src/components/review/CodePane.tsx index c6efd1c5..96b923b3 100644 --- a/dashboard/src/components/review/CodePane.tsx +++ b/dashboard/src/components/review/CodePane.tsx @@ -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; } /** @@ -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. */ @@ -180,6 +183,7 @@ export function CodePane({
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. diff --git a/dashboard/src/components/review/CommentComposer.tsx b/dashboard/src/components/review/CommentComposer.tsx index d2c589a1..5f87496c 100644 --- a/dashboard/src/components/review/CommentComposer.tsx +++ b/dashboard/src/components/review/CommentComposer.tsx @@ -139,6 +139,8 @@ 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, @@ -146,6 +148,7 @@ export function ComposerSheet({ busy, onSave, onCancel, + onCover, }: { /** The line or the block being commented on, or null when the sheet is closed. */ composing: Composing | null; @@ -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(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 ( - (open ? undefined : onCancel())}> + (next ? undefined : onCancel())}> {/* The sheet has no description. An explicit undefined tells Radix the - omission is deliberate. */} - + omission is deliberate. The backdrop is light, so the commented text + above the sheet stays readable. */} + {initial === '' ? `Comment on ${range}` : `Edit the comment on ${range}`} diff --git a/dashboard/src/components/review/MarkdownPreview.tsx b/dashboard/src/components/review/MarkdownPreview.tsx index 6d9944cc..a17180e8 100644 --- a/dashboard/src/components/review/MarkdownPreview.tsx +++ b/dashboard/src/components/review/MarkdownPreview.tsx @@ -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. */ @@ -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(/\/[^/]*$/, ''); @@ -253,6 +256,7 @@ export function MarkdownPreview({
0 ? { paddingBottom: bottomInset } : undefined} className="@container min-h-0 flex-1 overflow-auto" > diff --git a/dashboard/src/components/ui/sheet.tsx b/dashboard/src/components/ui/sheet.tsx index e027f765..9fd653e0 100644 --- a/dashboard/src/components/ui/sheet.tsx +++ b/dashboard/src/components/ui/sheet.tsx @@ -86,6 +86,7 @@ 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({ @@ -93,16 +94,19 @@ function SheetContent({ children, side = 'right', showCloseButton = true, + overlayClassName, ...props }: React.ComponentProps & { /** 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 ( - + ([]); + /** 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(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(null); @@ -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), @@ -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]); @@ -529,7 +565,7 @@ export function BoxReview() { return (
{/* The header stays while editing, because the toolbar under it holds Save. */} - +
{/* Below md with a file open, back returns to the file list. Otherwise it leaves the review. */} @@ -761,6 +797,7 @@ export function BoxReview() { onShowHunk={showHunk} renderUnderBlock={underBlock} onBlocks={setBlocks} + bottomInset={bottomInset} /> ) : ( )} @@ -810,6 +848,7 @@ export function BoxReview() { } }} onCancel={() => compose(null)} + onCover={setCover} /> {confirmDelete !== null && file ? ( @@ -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(`[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. *