diff --git a/dashboard/e2e/orchestrator.ts b/dashboard/e2e/orchestrator.ts index b47404f..1608c19 100644 --- a/dashboard/e2e/orchestrator.ts +++ b/dashboard/e2e/orchestrator.ts @@ -452,10 +452,11 @@ export interface TestOrchestrator { * * @param boxId The box id. * @param path The path of the file, relative to the workspace. - * @param line The line number of the comment. + * @param line The line number of the comment, or the first line of its block. * @param text The text of the comment. + * @param endLine The last line of the block, or 0 for a comment on one line. */ - comment(boxId: string, path: string, line: number, text: string): Promise; + comment(boxId: string, path: string, line: number, text: string, endLine?: number): Promise; /** * Reads the comments on one file through the real API. * @@ -1298,11 +1299,12 @@ export async function startOrchestrator( write: (boxId, path, content) => writeFile(workspaceOf(boxId), path, content), read: (boxId, path) => readFileSync(join(workspaceOf(boxId), path), 'utf8'), hasReview: (boxId) => existsSync(join(workspaceOf(boxId), 'REVIEW.md')), - comment: async (boxId, path, line, text) => { + comment: async (boxId, path, line, text, endLine = 0) => { await setup('PUT', `/api/boxes/${boxId}/review/annotations`, { path, line, comment: text, + ...(endLine > 0 ? { endLine } : {}), }); }, comments: async (boxId, path) => { diff --git a/dashboard/e2e/review.test.ts b/dashboard/e2e/review.test.ts index 3de8a7c..c3a947d 100644 --- a/dashboard/e2e/review.test.ts +++ b/dashboard/e2e/review.test.ts @@ -296,6 +296,199 @@ test('a text file opens in a tab of its own from the toolbar', async () => { } }); +/** A markdown file for the rendered view, with a changed paragraph and a list. */ +const GUIDE = [ + '# Guide', + '', + 'First paragraph line one', + 'line two of first paragraph', + '', + 'Second paragraph changed', + '', + '- item one', + '- item two', + '', + 'Last paragraph', + '', +].join('\n'); + +/** + * Makes a workspace with the guide, where the second paragraph changed since the commit. + * + * @returns The workspace. + */ +function guideWorkspace(): ReturnType { + const base = reviewWorkspace(); + return reviewWorkspace({ + files: { ...base.files, 'app/doc/guide.md': GUIDE }, + committed: { + ...base.committed, + 'app/doc/guide.md': GUIDE.replace('Second paragraph changed', 'Second paragraph original'), + }, + }); +} + +test('a block of the rendered file is commented on, marked and stepped to', async () => { + stub.review(BOX, guideWorkspace()); + const { page, errors, close } = await openPage( + stub.url, + `/boxes/${BOX}/review?path=app%2Fdoc%2Fguide.md`, + 'dark', + 'desktop', + ); + try { + await expect.poll(() => page.getByText('# Guide').isVisible()).toBe(true); + await page.getByRole('button', { name: 'Show the rendered file' }).click(); + await expect.poll(() => page.getByRole('heading', { name: 'Guide' }).isVisible()).toBe(true); + + // The changed paragraph is one changed block, with a marker that opens its hunk. + await expect.poll(() => page.getByLabel('1 change').isVisible()).toBe(true); + await page.getByRole('button', { name: 'Show the change at line 6' }).click(); + await expect.poll(() => page.getByText('Second paragraph original').isVisible()).toBe(true); + await page.keyboard.press('Escape'); + await expect.poll(() => page.getByText('Second paragraph original').count()).toBe(0); + + // A tap on a paragraph comments the whole paragraph. + await page.getByText('First paragraph line one').click(); + await expect + .poll(() => page.getByRole('textbox', { name: 'Comment on lines 3 to 4' }).isVisible()) + .toBe(true); + await page + .getByRole('textbox', { name: 'Comment on lines 3 to 4' }) + .fill('about the first paragraph'); + await page.getByRole('button', { name: 'Comment', exact: true }).click(); + await expect.poll(() => stub.reviewCalls.length).toBe(1); + expect(stub.reviewCalls[0]).toMatchObject({ + method: 'PUT', + body: { path: 'app/doc/guide.md', line: 3, endLine: 4, comment: 'about the first paragraph' }, + }); + // The card names the lines, under the paragraph, and REVIEW.md holds the range. + await expect.poll(() => page.getByText('about the first paragraph').isVisible()).toBe(true); + expect(await page.getByText('Lines 3 to 4').count()).toBe(1); + expect(stub.read(BOX, 'REVIEW.md')).toContain('#### Line 3 to 4\n'); + await expect.poll(() => page.getByLabel('1 comment').isVisible()).toBe(true); + expect(await page.getByRole('button', { name: 'Next comment' }).isDisabled()).toBe(false); + await shoot(page, 'review-rendered-comment-desktop'); + + // A heading is one line, so its comment is a line comment. A tap on a list + // item comments the item, and not the whole list. + await page.getByRole('heading', { name: 'Guide' }).click(); + await expect + .poll(() => page.getByRole('textbox', { name: 'Comment on line 1' }).isVisible()) + .toBe(true); + await page.getByText('item two').click(); + await expect + .poll(() => page.getByRole('textbox', { name: 'Comment on line 9' }).isVisible()) + .toBe(true); + await page.keyboard.press('Escape'); + + // The source view shows the card under the first line of the block and marks + // every row of the block. + await page.getByRole('button', { name: 'Show the source' }).click(); + await expect.poll(() => page.getByText('# Guide').isVisible()).toBe(true); + await expect.poll(() => page.getByText('Lines 3 to 4').isVisible()).toBe(true); + for (const line of [3, 4]) { + expect(await page.locator(`[data-line="${line}"]`).getAttribute('class')).toContain( + 'bg-primary/8', + ); + } + expect(await page.locator('[data-line="5"]').getAttribute('class')).not.toContain( + 'bg-primary/8', + ); + expect(errors).toEqual([]); + } finally { + await close(); + } +}); + +test('a block comment on a phone goes through the sheet', async () => { + stub.review(BOX, guideWorkspace()); + const { page, errors, close } = await openPage( + stub.url, + `/boxes/${BOX}/review?path=app%2Fdoc%2Fguide.md`, + ); + try { + await expect.poll(() => page.getByText('# Guide').isVisible()).toBe(true); + await page.getByRole('button', { name: 'Show the rendered file' }).click(); + await page.getByText('Last paragraph').click(); + await expect.poll(() => page.getByText('Comment on line 11').isVisible()).toBe(true); + await page.getByRole('textbox', { name: 'Comment on line 11' }).fill('the end'); + await page.getByRole('button', { name: 'Comment', exact: true }).click(); + await expect.poll(() => page.getByText('the end').isVisible()).toBe(true); + expect((await stub.comments(BOX, 'app/doc/guide.md'))[0]).toMatchObject({ + line: 11, + endLine: 0, + comment: 'the end', + }); + expect(errors).toEqual([]); + } finally { + await close(); + } +}); + +test('the place of the reader survives the switch of the view, and a reopen', async () => { + // Paragraphs on the odd lines, long enough to scroll. + const paragraphs = Array.from({ length: 300 }, (_, i) => `Paragraph ${i + 1}`).join('\n\n'); + stub.review(BOX, { + files: { 'long.md': `${paragraphs}\n`, 'short.ts': 'const one = 1;\n' }, + repos: [''], + }); + + const { page, errors, close } = await openPage( + stub.url, + `/boxes/${BOX}/review?path=long.md`, + 'dark', + 'desktop', + ); + try { + const pane = page.locator('[data-slot="review-code-pane"]'); + const preview = page.locator('[data-slot="review-preview"]'); + await expect.poll(() => pane.isVisible()).toBe(true); + await pane.evaluate((el) => { + el.scrollTop = 2000; + }); + /** + * Reads the line at the top of a scroller. The rows of the rendered view are + * nested, so the test measures them against the scroller. + * + * @param scroller The scroller. + * @returns The line of the topmost row, or null when no row is in view. + */ + const topLine = (scroller: typeof pane): Promise => + scroller.evaluate((el) => { + const top = Math.round(el.getBoundingClientRect().top); + for (const row of el.querySelectorAll('[data-line]')) { + if (Math.round(row.getBoundingClientRect().bottom) > top) return Number(row.dataset.line); + } + return null; + }); + const before = (await topLine(pane))!; + expect(before).toBeGreaterThan(1); + // A blank line between two paragraphs lands on the paragraph after it. + const block = before % 2 === 1 ? before : before + 1; + + await page.getByRole('button', { name: 'Show the rendered file' }).click(); + await expect.poll(() => preview.isVisible()).toBe(true); + await expect.poll(() => topLine(preview)).toBe(block); + + await page.getByRole('button', { name: 'Show the source' }).click(); + await expect.poll(() => pane.isVisible()).toBe(true); + expect(await topLine(pane)).toBe(block); + + // The file reopens in the view it was left in, at the same place. + await page.getByRole('button', { name: 'Show the rendered file' }).click(); + await expect.poll(() => preview.isVisible()).toBe(true); + await page.getByRole('button', { name: /short\.ts/ }).click(); + await expect.poll(() => page.getByText('const one = 1;').isVisible()).toBe(true); + await page.getByRole('button', { name: /long\.md/ }).click(); + await expect.poll(() => preview.isVisible()).toBe(true); + await expect.poll(() => topLine(preview)).toBe(block); + 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/assistant-ui/elements/markdown-text.tsx b/dashboard/src/components/assistant-ui/elements/markdown-text.tsx index 3f9631b..60b9811 100644 --- a/dashboard/src/components/assistant-ui/elements/markdown-text.tsx +++ b/dashboard/src/components/assistant-ui/elements/markdown-text.tsx @@ -20,6 +20,7 @@ import { MermaidDiagram } from "@/components/assistant-ui/elements/mermaid-diagr import { TooltipIconButton } from "@/components/assistant-ui/elements/tooltip-icon-button"; import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard"; import { filePath, fileUrl } from "@/lib/files"; +import { rehypeBlocks } from "@/lib/markdown-blocks"; import { cn } from "@/lib/utils"; /** The props of {@link MarkdownText}: the text part props, extra markdown components and the base directory. */ @@ -28,6 +29,8 @@ type MarkdownTextProps = Partial & { components?: Parameters[0]; /** Boxes edit: the absolute directory in the box where a relative path starts. The default is the workspace. */ baseDir?: string; + /** Boxes edit: true to give each block its source lines and to wrap each top level block in a div. */ + blocks?: boolean; }; /** @@ -60,8 +63,13 @@ const useShallowStable = | undefined>( * * @param components Components that replace the default components for some elements. * @param baseDir The absolute directory in the box where a relative path starts. The default is the workspace. + * @param blocks True to give each block its source lines and to wrap each top level block in a div. */ -const MarkdownTextImpl: FC = ({ components, baseDir }) => { +const MarkdownTextImpl: FC = ({ + components, + baseDir, + blocks = false, +}) => { const { id: boxId } = useParams(); // Boxes edit: the browser keeps an image of the page in memory, whatever // the cache headers say. So each view of the message gets file URLs of its @@ -83,6 +91,7 @@ const MarkdownTextImpl: FC = ({ components, baseDir }) => { return ( = { +export const CHANGE: Record = { added: { bar: 'bg-ok', row: 'bg-ok/8' }, modified: { bar: 'bg-warn', row: 'bg-warn/8' }, }; @@ -67,9 +68,9 @@ export interface CodePaneProps { deletions: Map; /** The hunk index of each line, by line number, for the gutter to open. */ hunkByLine: Map; - /** The comments, by line number. */ + /** The comments, by line number. A comment on a block is on its first line. */ annotations: Map; - /** The line whose composer is open, or null. */ + /** The line whose composer is open, or the first line of the block, or null. */ composing: number | null; /** True to wrap long lines, false to scroll them sideways. */ wrap: boolean; @@ -120,8 +121,6 @@ export function CodePane({ onShowHunk, renderUnderLine, }: CodePaneProps) { - /** The path this pane has already positioned, so a poll does not re-do it. */ - const positioned = useRef(null); const editing = edit !== null; /** The shown text, which is the buffer while editing and the file otherwise. */ const source = edit ? edit.text : content; @@ -130,18 +129,19 @@ export function CodePane({ /** * Puts each file back where it was left, and every file this review has not - * opened at the top. + * opened at the top. When the pane leaves the file, it records the place. * * It runs before paint, so the reader never sees the offset of the previous file. - * It positions each path once, so a poll that refetches the open file keeps - * the place of the reader. + * The view mounts the pane once per file, and the effect positions the file once, + * so a poll that refetches the open file keeps the place of the reader. */ useLayoutEffect(() => { const element = scrollRef.current; - if (!element || positioned.current === path) return; - positioned.current = path; - element.scrollTop = recallScroll(path); - }, [scrollRef, path, content]); + if (!element) return; + const anchor = recallScroll(path); + element.scrollTop = anchor ? (scrollForAnchor(rowOffsets(element), anchor) ?? 0) : 0; + return () => rememberScroll(path, anchorAt(rowOffsets(element), element.scrollTop)); + }, [scrollRef, path]); /** Brings the line that prev/next asked for into the middle of the pane. */ useEffect(() => { @@ -151,14 +151,16 @@ export function CodePane({ ?.scrollIntoView({ block: 'center' }); }, [scrollRef, scrollTo]); - /** Records where the reader is, for the next time they open this file. */ - useEffect(() => { - const element = scrollRef.current; - if (!element) return; - const onScroll = (): void => rememberScroll(path, element.scrollTop); - element.addEventListener('scroll', onScroll, { passive: true }); - return () => element.removeEventListener('scroll', onScroll); - }, [scrollRef, path]); + /** The comment on a block, by each line of the block after its first. These rows get its marker. */ + const inBlock = useMemo(() => { + const map = new Map(); + for (const annotation of annotations.values()) { + for (let line = annotation.line + 1; line <= annotation.endLine; line++) { + map.set(line, annotation); + } + } + return map; + }, [annotations]); const lines = useMemo(() => (tooLong ? [] : splitLines(source)), [source, tooLong]); /** The lines that the tokens describe. They are the lines of the file until the user types. */ @@ -210,7 +212,7 @@ export function CodePane({ text={text} tokens={tokenLines[index] === text ? (tokens?.[index] ?? null) : null} change={diffLines[String(index + 1)]} - annotation={annotations.get(index + 1)} + annotation={annotations.get(index + 1) ?? inBlock.get(index + 1)} composing={composing === index + 1} hunkIndex={hunkByLine.get(index + 1)} deletionHunk={deletions.get(index + 1)} @@ -239,7 +241,7 @@ export function CodePane({ * @param text The text of the line. * @param tokens The colours of the line, or null while it renders plain. * @param change The kind of change on the line, or undefined when the line did not change. - * @param annotation The comment on the line, if any. + * @param annotation The comment on the line, or the comment on the block that holds the line, if any. * @param composing True while the composer is open on the line. * @param hunkIndex The hunk of the line, or undefined when the line is in no hunk. * @param deletionHunk The hunk of the lines deleted after this line, or undefined for none. @@ -272,7 +274,7 @@ const Row = memo(function Row({ tokens: Token[] | null; /** The kind of change on the line, or undefined when the line did not change. */ change: ReviewLineChange | undefined; - /** The comment on the line, if any. */ + /** The comment on the line, or the comment on the block that holds the line, if any. */ annotation: ReviewAnnotation | undefined; /** True while the composer is open on the line. */ composing: boolean; @@ -486,7 +488,7 @@ function Gutter({ * @param event The click on the code of the line. * @returns True when the click selected text. */ -function selecting(event: React.MouseEvent): boolean { +export function selecting(event: React.MouseEvent): boolean { if (event.detail > 1) return true; const selection = window.getSelection(); return selection !== null && !selection.isCollapsed; diff --git a/dashboard/src/components/review/CommentCard.tsx b/dashboard/src/components/review/CommentCard.tsx index ce68902..c98cb36 100644 --- a/dashboard/src/components/review/CommentCard.tsx +++ b/dashboard/src/components/review/CommentCard.tsx @@ -1,20 +1,23 @@ import { Pencil, Trash2 } from 'lucide-react'; import { Button } from '@/components/ui/button'; +import { lineRange } from '@/lib/lines'; import type { ReviewAnnotation } from '../../../../shared/types.ts'; /** - * One comment, as a card under the line it is about. + * One comment, as a card under the line or the block it is about. * * The agent can write into REVIEW.md, so the comment renders as a text node only. * * @param annotation The comment to show. * @param busy True while a write is in flight, so a double tap cannot act twice. + * @param showLine True to name the line of a comment on one line. A comment on a block always names its lines. * @param onEdit Called when the user asks to edit the comment. * @param onDelete Called when the user asks to delete the comment. */ export function CommentCard({ annotation, busy, + showLine = false, onEdit, onDelete, }: { @@ -22,13 +25,19 @@ export function CommentCard({ annotation: ReviewAnnotation; /** True while a write is in flight, so a double tap cannot act twice. */ busy: boolean; + /** True to name the line of a comment on one line. A comment on a block always names its lines. */ + showLine?: boolean; /** Called when the user asks to edit the comment. */ onEdit: () => void; /** Called when the user asks to delete the comment. */ onDelete: () => void; }) { + const range = lineRange(annotation.line, annotation.endLine); return (
+ {annotation.endLine > 0 || showLine ? ( +

{range}

+ ) : null}

{annotation.comment}

@@ -38,7 +47,7 @@ export function CommentCard({ size="icon-sm" disabled={busy} onClick={onEdit} - aria-label={`Edit the comment on line ${annotation.line}`} + aria-label={`Edit the comment on ${range}`} title="Edit" > @@ -49,7 +58,7 @@ export function CommentCard({ size="icon-sm" disabled={busy} onClick={onDelete} - aria-label={`Delete the comment on line ${annotation.line}`} + aria-label={`Delete the comment on ${range}`} title="Delete" > diff --git a/dashboard/src/components/review/CommentComposer.tsx b/dashboard/src/components/review/CommentComposer.tsx index eae697b..d2c589a 100644 --- a/dashboard/src/components/review/CommentComposer.tsx +++ b/dashboard/src/components/review/CommentComposer.tsx @@ -1,6 +1,8 @@ import { useEffect, useRef, useState } from 'react'; import { Button } from '@/components/ui/button'; import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'; +import { lineRange } from '@/lib/lines'; +import type { Composing } from '../../stores/review.ts'; /** * The save shortcut as the hint shows it: ⌘↵ on Apple platforms, Ctrl+↵ @@ -15,7 +17,8 @@ const SAVE_KEY = /mac|iphone|ipad|ipod/i.test( /** * The form that both composer layouts render. * - * @param line The line being commented on. + * @param line The line being commented on, or the first line of the block. + * @param endLine The last line of the block, or 0 for one line. * @param initial The existing comment when editing, or '' when writing a new one. * @param busy Disables the buttons while a write is in flight. * @param autoFocus Focuses the textarea on mount and whenever the line changes. @@ -24,14 +27,17 @@ const SAVE_KEY = /mac|iphone|ipad|ipod/i.test( */ function Form({ line, + endLine, initial, busy, autoFocus, onSave, onCancel, }: { - /** The line being commented on. */ + /** The line being commented on, or the first line of the block. */ line: number; + /** The last line of the block, or 0 for one line. */ + endLine: number; /** The existing comment when editing, or '' when writing a new one. */ initial: string; /** Disables the buttons while a write is in flight. */ @@ -45,6 +51,7 @@ function Form({ }) { const [text, setText] = useState(initial); const field = useRef(null); + const range = lineRange(line, endLine); // The composer stays mounted when it moves to another line, so it resets the text. useEffect(() => { @@ -75,8 +82,8 @@ function Form({ if (event.key === 'Escape') onCancel(); }} rows={3} - placeholder={`Comment on line ${line}…`} - aria-label={`Comment on line ${line}`} + placeholder={`Comment on ${range}…`} + aria-label={`Comment on ${range}`} className="w-full resize-y rounded-md border bg-background px-2 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring" />
@@ -97,11 +104,13 @@ function Form({ /** * The composer inline below the line, for wide screens. * - * @param props The line, the existing comment, the busy flag and the callbacks. + * @param props The line or the block, the existing comment, the busy flag and the callbacks. */ export function InlineComposer(props: { - /** The line being commented on. */ + /** The line being commented on, or the first line of the block. */ line: number; + /** The last line of the block, or 0 for one line. */ + endLine: number; /** The existing comment when editing, or '' when writing a new one. */ initial: string; /** Disables the buttons while a write is in flight. */ @@ -125,21 +134,21 @@ export function InlineComposer(props: { * The view picks this or {@link InlineComposer} with a media query, because the * sheet renders into a portal that a CSS breakpoint on a wrapper cannot hide. * - * @param line The line being commented on, or null when the sheet is closed. + * @param composing The line or the block being commented on, or null when the sheet is closed. * @param initial The existing comment when editing, or '' when writing a new one. * @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. */ export function ComposerSheet({ - line, + composing, initial, busy, onSave, onCancel, }: { - /** The line being commented on, or null when the sheet is closed. */ - line: number | null; + /** The line or the block being commented on, or null when the sheet is closed. */ + composing: Composing | null; /** The existing comment when editing, or '' when writing a new one. */ initial: string; /** Disables the buttons while a write is in flight. */ @@ -149,20 +158,22 @@ export function ComposerSheet({ /** Called when the user cancels or dismisses the sheet. */ onCancel: () => void; }) { + const range = composing ? lineRange(composing.line, composing.endLine) : ''; return ( - (open ? undefined : onCancel())}> + (open ? undefined : onCancel())}> {/* The sheet has no description. An explicit undefined tells Radix the omission is deliberate. */} - {initial === '' ? `Comment on line ${line}` : `Edit the comment on line ${line}`} + {initial === '' ? `Comment on ${range}` : `Edit the comment on ${range}`}
- {line === null ? null : ( + {composing === null ? null : (
; + /** The workspace-relative path of the file. It keys the remembered scroll position. */ + path: string; + /** The markdown text. */ + content: string; + /** Changed lines, keyed by line number as the API sends them. */ + diffLines: Record; + /** The hunk index of each deletion marker, by the line it sits after. 0 is the top. */ + deletions: Map; + /** The hunk index of each line, by line number. */ + hunkByLine: Map; + /** The lines that have a comment, in order. A comment on a block counts on its first line. */ + commentedLines: number[]; + /** The line or the block that the composer is open on, or null. */ + composing: Composing | null; + /** A line to scroll to once, when prev/next asks for it. */ + scrollTo: ScrollTarget | null; + /** Called with the lines of a block when the user taps it. */ + onSelectBlock: (line: number, endLine: number) => void; + /** Called with the hunk index when the user taps the change marker of a block. */ + onShowHunk: (hunkIndex: number) => void; + /** Renders the cards and the composer below a block, for the comments on its lines. */ + renderUnderBlock: (line: number, endLine: number) => React.ReactNode; + /** Called with the blocks of the file, in order, when they are rendered. */ + onBlocks: (blocks: Block[]) => void; +} + +/** What the frame of a block needs from the pane. */ +interface BlockContextValue { + /** The change in a range of lines, and the hunk of the first changed line. */ + changeIn: (line: number, endLine: number) => { change?: ReviewLineChange; hunk?: number }; + /** True when a line of the range has a comment. */ + commentedIn: (line: number, endLine: number) => boolean; + /** True when the composer is open on a line of the range. */ + composingIn: (line: number, endLine: number) => boolean; + /** Called with the lines of a block when the user taps it. */ + onSelectBlock: (line: number, endLine: number) => void; + /** Called with the hunk index when the user taps the change marker of a block. */ + onShowHunk: (hunkIndex: number) => void; + /** Renders the cards and the composer below a block. */ + renderUnder: (line: number, endLine: number) => React.ReactNode; + /** Registers a rendered block. The returned function removes it. */ + register: (block: Block) => () => void; +} + +const BlockContext = createContext(null); + +/** The top padding of a block by its tag. A heading gets the space that it has in a message. */ +const SPACE_ABOVE: Record = { + h1: 'pt-5', + h2: 'pt-5', + h3: 'pt-4', + h4: 'pt-3.5', + h5: 'pt-3', + h6: 'pt-3', +}; + +/** The reading column of a block. */ +const COLUMN = 'mx-auto w-full max-w-[55rem] px-4'; + +/** The components of the renderer that the pane replaces. One object, so the renderer keeps its memo. */ +const components = { div: BlockFrame }; /** * The pane that shows a markdown file of the review rendered, as the thread shows a message. * - * @param path The workspace-relative path of the file. - * @param content The markdown text. + * Each top level block of the file knows its source lines, so the pane can mark a changed block, show the + * comments on its lines under it and open the composer for it. The pane keeps the place of the reader like + * the code pane does, with the line at the top of the pane. + * + * @param props The props of the pane. */ export function MarkdownPreview({ + scrollRef, path, content, -}: { - /** The workspace-relative path of the file. */ - path: string; - /** The markdown text. */ - content: string; -}) { + diffLines, + deletions, + hunkByLine, + commentedLines, + composing, + scrollTo, + onSelectBlock, + onShowHunk, + renderUnderBlock, + onBlocks, +}: MarkdownPreviewProps) { // A relative path in the file starts from the directory of the file. const baseDir = `${WORKSPACE_DIR}/${path}`.replace(/\/[^/]*$/, ''); + + /** The rendered blocks, by their lines. The renderer defers its work, so they arrive after the mount. */ + const blocks = useRef(new Map()); + /** Counts the changes of the block set, so an effect can act on them. */ + const [generation, setGeneration] = useState(0); + const register = useCallback((block: Block) => { + const key = `${block.line}-${block.endLine}`; + blocks.current.set(key, block); + setGeneration((n) => n + 1); + return () => { + blocks.current.delete(key); + setGeneration((n) => n + 1); + }; + }, []); + + /** The blocks in order, for the toolbar. The generation stands for the block set. */ + const ordered = useMemo( + () => [...blocks.current.values()].sort((a, b) => a.line - b.line), + [generation], + ); + useEffect(() => onBlocks(ordered), [onBlocks, ordered]); + + /** The scroll position that the pane set last, to tell a scroll of the reader from a layout change. */ + const placed = useRef(null); + + /** + * Puts the file back where the reader left it, once the blocks are rendered. + * + * The view mounts the pane once per file, and the pane positions the file once, + * so a poll that refetches the open file keeps the place of the reader. + */ + const positioned = useRef(false); + useLayoutEffect(() => { + const element = scrollRef.current; + if (!element || positioned.current || ordered.length === 0) return; + positioned.current = true; + const anchor = recallScroll(path); + element.scrollTop = anchor ? (scrollNearAnchor(rowOffsets(element), anchor) ?? 0) : 0; + placed.current = element.scrollTop; + }, [scrollRef, path, ordered]); + + /** + * Records the place of the reader when the pane leaves the file. A pane that + * has not positioned the file yet has no place to record. + */ + useLayoutEffect(() => { + const element = scrollRef.current; + if (!element) return; + return () => { + if (positioned.current) { + rememberScroll(path, anchorAt(rowOffsets(element), element.scrollTop)); + } + }; + }, [scrollRef, path]); + + /** + * Images and diagrams get their height after the first paint, which moves the + * blocks below them. The pane restores the place of the reader after each + * such change, until the reader scrolls. + */ + useEffect(() => { + const element = scrollRef.current; + const inner = element?.firstElementChild; + if (!element || !inner || !positioned.current) return; + const anchor = recallScroll(path); + if (!anchor) return; + const observer = new ResizeObserver(() => { + if (placed.current === null || element.scrollTop !== placed.current) { + observer.disconnect(); + return; + } + element.scrollTop = scrollNearAnchor(rowOffsets(element), anchor) ?? element.scrollTop; + placed.current = element.scrollTop; + }); + observer.observe(inner); + return () => observer.disconnect(); + }, [scrollRef, path, ordered]); + + /** Brings the block that prev/next asked for into the middle of the pane. */ + useEffect(() => { + if (!scrollTo) return; + scrollRef.current + ?.querySelector(`[data-block][data-line="${scrollTo.line}"]`) + ?.scrollIntoView({ block: 'center' }); + }, [scrollRef, scrollTo]); + + const context = useMemo( + () => ({ + changeIn: (line, endLine) => { + let change: ReviewLineChange | undefined; + let hunk: number | undefined; + // A deletion at the top of the file belongs to the first block. + if (line === 1 && deletions.has(0)) { + change = 'modified'; + hunk = deletions.get(0); + } + for (let at = line; at <= endLine; at++) { + const kind = diffLines[String(at)]; + const deletion = deletions.get(at); + if (kind) { + change = change && change !== kind ? 'modified' : kind; + hunk ??= hunkByLine.get(at); + } + if (deletion !== undefined) { + change = 'modified'; + hunk ??= deletion; + } + } + return { change, hunk }; + }, + commentedIn: (line, endLine) => commentedLines.some((at) => at >= line && at <= endLine), + composingIn: (line, endLine) => + composing !== null && composing.line >= line && composing.line <= endLine, + onSelectBlock, + onShowHunk, + renderUnder: renderUnderBlock, + register, + }), + [ + diffLines, + deletions, + hunkByLine, + commentedLines, + composing, + onSelectBlock, + onShowHunk, + renderUnderBlock, + register, + ], + ); + return ( // The container lets a wide table or code block grow to the width of the pane. -
-
+
+ - + + +
+ ); +} + +/** + * The frame of one top level block: the change marker, the block in the reading + * column and the comments on its lines under it. + * + * The renderer gives the frame the tag and the lines of the block as data + * attributes. A div without them is not a block and renders as it is. + * + * @param props The attributes of the div and the block inside it. + */ +function BlockFrame({ + children, + className, + ...props +}: React.ComponentProps<'div'> & { + 'data-block'?: string; + 'data-line'?: number | string; + 'data-line-end'?: number | string; +}) { + const context = useContext(BlockContext); + const tag = props['data-block']; + const line = Number(props['data-line']); + const endLine = Number(props['data-line-end']); + const isBlock = context !== null && tag !== undefined && line > 0 && endLine >= line; + + useLayoutEffect(() => { + if (!isBlock) return; + return context.register({ line, endLine }); + }, [isBlock, context, line, endLine]); + + if (!isBlock) { + return ( +
+ {children} +
+ ); + } + + const { change, hunk } = context.changeIn(line, endLine); + const active = context.commentedIn(line, endLine) || context.composingIn(line, endLine); + const under = context.renderUnder(line, endLine); + + /** Opens the composer for the innermost block under a tap, unless the tap hit a control inside the block. */ + const select = (event: React.SyntheticEvent): void => { + const target = event.target; + if (!(target instanceof Element)) return; + const control = target.closest('a, button, [role="button"], input, textarea'); + if (control && control !== event.currentTarget) return; + const block = target.closest('[data-line]'); + const start = Number(block?.dataset.line); + const end = Number(block?.dataset.lineEnd); + if (start > 0 && end >= start) context.onSelectBlock(start, end); + }; + + return ( +
+ + {/* Tapping the block starts a comment, as tapping a line of code does. A + button element would make the text unselectable, so a div takes the role. */} + {/* biome-ignore lint/a11y/useSemanticElements: a button element would make the text unselectable */} +
{ + if (!selecting(event)) select(event); + }} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + select(event); + } + }} + className={cn( + COLUMN, + 'pb-1.5 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset', + SPACE_ABOVE[tag] ?? 'pt-1.5', + // The frame spaces the blocks, so the block keeps no margin of its own. + '[&>*]:my-0!', + )} + > + {children}
+ {under ?
{under}
: null}
); } + +/** + * The change marker at the left edge of a block, which opens the hunk of the change. + * + * It is a button only where there is a hunk to open. + * + * @param line The first line of the block. + * @param change The kind of change in the block, or undefined when the block did not change. + * @param hunk The hunk of the first change in the block, or undefined when the block is in no hunk. + * @param onShowHunk Called with the hunk index when the user taps the marker. + */ +function Marker({ + line, + change, + hunk, + onShowHunk, +}: { + /** The first line of the block. */ + line: number; + /** The kind of change in the block, or undefined when the block did not change. */ + change: ReviewLineChange | undefined; + /** The hunk of the first change in the block, or undefined when the block is in no hunk. */ + hunk: number | undefined; + /** Called with the hunk index when the user taps the marker. */ + onShowHunk: (hunkIndex: number) => void; +}) { + if (!change) return null; + const bar = ( + + ); + if (hunk === undefined) return bar; + return ( + + ); +} diff --git a/dashboard/src/lib/anchor.test.ts b/dashboard/src/lib/anchor.test.ts index 9535f07..ab1cfc9 100644 --- a/dashboard/src/lib/anchor.test.ts +++ b/dashboard/src/lib/anchor.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; -import { anchorAt, type RowOffset, scrollForAnchor } from './anchor.ts'; +import { anchorAt, type RowOffset, scrollForAnchor, scrollNearAnchor } from './anchor.ts'; /** * Builds rows of equal height, with extra height after the given lines. @@ -57,8 +57,25 @@ test('a line that is gone moves nobody anywhere', () => { assert.equal(scrollForAnchor(rows(10, 20), { line: 40, offset: 0 }), null); }); -test('an empty pane has no anchor to take', () => { - assert.equal(anchorAt([], 0), null); +test('a line between or inside blocks lands on the block that holds it or follows it', () => { + // Paragraphs on lines 1 to 2, 4 to 6 and 9, with blank lines between them. + const blocks: RowOffset[] = [ + { line: 1, top: 0, end: 2 }, + { line: 4, top: 50, end: 6 }, + { line: 9, top: 120 }, + ]; + assert.equal(scrollNearAnchor(blocks, { line: 4, offset: 7 }), 57); + assert.equal(scrollNearAnchor(blocks, { line: 5, offset: 7 }), 50); + assert.equal(scrollNearAnchor(blocks, { line: 3, offset: 7 }), 50); + assert.equal(scrollNearAnchor(blocks, { line: 8, offset: 0 }), 120); + assert.equal(scrollNearAnchor(blocks, { line: 10, offset: 0 }), null); + assert.equal(scrollNearAnchor(blocks, { line: 0, offset: 30 }), 30); +}); + +test('a pane without rows keeps its scroll position as the anchor', () => { + const anchor = anchorAt([], 300); + assert.deepEqual(anchor, { line: 0, offset: 300 }); + assert.equal(scrollForAnchor([], anchor), 300); }); test('a scroller above its first row does not scroll past the top coming back', () => { diff --git a/dashboard/src/lib/anchor.ts b/dashboard/src/lib/anchor.ts index 8860712..e889edb 100644 --- a/dashboard/src/lib/anchor.ts +++ b/dashboard/src/lib/anchor.ts @@ -8,15 +8,17 @@ /** One rendered line and where its row starts in the scroller. */ export interface RowOffset { - /** The line number. */ + /** The line number. For a block of lines, its first line. */ line: number; /** Distance from the top of the scrolled content to the top of the row. */ top: number; + /** The last line of a block of lines, or undefined for a row of one line. */ + end?: number; } /** The scroll position of a pane, as a line and an offset into that line. */ export interface ScrollAnchor { - /** The line number. */ + /** The line number, or 0 for a pane without rows, where the offset is the scroll position. */ line: number; /** * The distance from the top of the row of the line to the top of the pane. @@ -35,11 +37,11 @@ export interface ScrollAnchor { * * @param rows The rows in the order they are rendered. * @param scrollTop The scroll position of the scroller. - * @returns The anchor, or null when there are no rows. + * @returns The anchor. Without rows, it is line 0 with the scroll position as the offset. */ -export function anchorAt(rows: RowOffset[], scrollTop: number): ScrollAnchor | null { +export function anchorAt(rows: RowOffset[], scrollTop: number): ScrollAnchor { const first = rows[0]; - if (!first) return null; + if (!first) return { line: 0, offset: scrollTop }; let standing = first; for (const row of rows) { if (row.top > scrollTop) break; @@ -59,25 +61,48 @@ export function anchorAt(rows: RowOffset[], scrollTop: number): ScrollAnchor | n * @returns The scroll position, or null when the line is gone. */ export function scrollForAnchor(rows: RowOffset[], anchor: ScrollAnchor): number | null { + if (anchor.line === 0) return Math.max(0, anchor.offset); const row = rows.find((r) => r.line === anchor.line); if (!row) return null; return Math.max(0, row.top + anchor.offset); } +/** + * Computes the scroll position that brings an anchor into view in a pane of blocks. + * + * A line of the anchor that is no row lands at the top of the block that holds + * it, or of the first block after it. + * + * @param rows The blocks of the pane, with their last lines. + * @param anchor The anchor to restore. + * @returns The scroll position, or null when no block is at or after the line. + */ +export function scrollNearAnchor(rows: RowOffset[], anchor: ScrollAnchor): number | null { + const exact = scrollForAnchor(rows, anchor); + if (exact !== null) return exact; + const holder = rows.find((r) => r.line <= anchor.line && anchor.line <= (r.end ?? r.line)); + const row = holder ?? rows.find((r) => r.line > anchor.line); + return row ? row.top : null; +} + /** * Reads the rows of a scroller from its `[data-line]` elements. * - * Uses `offsetTop` because it is measured against the scrolled content and - * does not change when the scroller scrolls. + * The top of a row is measured from the top of the scrolled content, whatever + * the row is nested in, and rounded to whole pixels like a scroll position. * - * @param scroller The scroller of the code pane. + * @param scroller The scroller of the pane. * @returns The rows in the order they are rendered. */ export function rowOffsets(scroller: HTMLElement): RowOffset[] { const rows: RowOffset[] = []; + const origin = scroller.getBoundingClientRect().top - scroller.scrollTop; for (const element of scroller.querySelectorAll('[data-line]')) { const line = Number(element.dataset.line); - if (Number.isInteger(line)) rows.push({ line, top: element.offsetTop }); + const end = Number(element.dataset.lineEnd); + if (!Number.isInteger(line)) continue; + const top = Math.round(element.getBoundingClientRect().top - origin); + rows.push(end > line ? { line, top, end } : { line, top }); } return rows; } diff --git a/dashboard/src/lib/lines.ts b/dashboard/src/lib/lines.ts new file mode 100644 index 0000000..6b4a851 --- /dev/null +++ b/dashboard/src/lib/lines.ts @@ -0,0 +1,10 @@ +/** + * Names a line or a block of lines, for a label. + * + * @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 "line 12" for one line, or "lines 10 to 14" for a block. + */ +export function lineRange(line: number, endLine: number): string { + return endLine > 0 ? `lines ${line} to ${endLine}` : `line ${line}`; +} diff --git a/dashboard/src/lib/markdown-blocks.test.ts b/dashboard/src/lib/markdown-blocks.test.ts new file mode 100644 index 0000000..e0c13b3 --- /dev/null +++ b/dashboard/src/lib/markdown-blocks.test.ts @@ -0,0 +1,85 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { rehypeBlocks } from './markdown-blocks.ts'; + +/** A hast node, as the tests build it. */ +interface Node { + type: string; + tagName?: string; + value?: string; + properties?: Record; + children?: Node[]; + position?: { start: { line: number }; end: { line: number } }; +} + +/** + * Makes an element with a position. + * + * @param tagName The tag. + * @param start The first source line. + * @param end The last source line. + * @param children The children. + * @returns The element. + */ +function element(tagName: string, start: number, end: number, children: Node[] = []): Node { + return { + type: 'element', + tagName, + properties: {}, + children, + position: { start: { line: start }, end: { line: end } }, + }; +} + +test('each top level element is wrapped in a block with its lines', () => { + const tree: Node = { + type: 'root', + children: [ + element('h1', 1, 1, [{ type: 'text', value: 'Title' }]), + { type: 'text', value: '\n' }, + element('p', 3, 4, [{ type: 'text', value: 'two lines' }]), + ], + }; + rehypeBlocks()(tree); + + assert.equal(tree.children?.length, 3); + const [heading, newline, paragraph] = tree.children as Node[]; + assert.equal(newline?.type, 'text'); + assert.equal(heading?.tagName, 'div'); + assert.deepEqual(heading?.properties, { dataBlock: 'h1', dataLine: 1, dataLineEnd: 1 }); + assert.equal(heading?.children?.[0]?.tagName, 'h1'); + assert.deepEqual(heading?.children?.[0]?.properties, { dataLine: 1, dataLineEnd: 1 }); + assert.deepEqual(paragraph?.properties, { dataBlock: 'p', dataLine: 3, dataLineEnd: 4 }); +}); + +test('nested blocks get their lines, and inline elements do not', () => { + const link = element('a', 6, 6, [{ type: 'text', value: 'link' }]); + const inner = element('p', 6, 6, [link]); + const item = element('li', 5, 6, [{ type: 'text', value: 'item' }, inner]); + const list = element('ul', 5, 6, [item]); + const tree: Node = { type: 'root', children: [list] }; + rehypeBlocks()(tree); + + assert.deepEqual(list.properties, { dataLine: 5, dataLineEnd: 6 }); + assert.deepEqual(item.properties, { dataLine: 5, dataLineEnd: 6 }); + assert.deepEqual(inner.properties, { dataLine: 6, dataLineEnd: 6 }); + assert.deepEqual(link.properties, {}); +}); + +test('an element without a position keeps its properties and gets no lines', () => { + const paragraph: Node = { + type: 'element', + tagName: 'p', + properties: { className: ['kept'] }, + children: [], + }; + const tree: Node = { type: 'root', children: [paragraph] }; + rehypeBlocks()(tree); + + assert.deepEqual(paragraph.properties, { className: ['kept'] }); + assert.deepEqual(tree.children?.[0]?.properties, { + dataBlock: 'p', + dataLine: undefined, + dataLineEnd: undefined, + }); +}); diff --git a/dashboard/src/lib/markdown-blocks.ts b/dashboard/src/lib/markdown-blocks.ts new file mode 100644 index 0000000..4846154 --- /dev/null +++ b/dashboard/src/lib/markdown-blocks.ts @@ -0,0 +1,96 @@ +/** + * A rehype plugin that gives the blocks of a rendered markdown file their source lines, so the review can + * address a block like a row of the code pane. + */ + +/** The tags of the block elements that get their source lines. */ +const BLOCK_TAGS = new Set([ + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'p', + 'li', + 'tr', + 'blockquote', + 'hr', + 'pre', + 'ul', + 'ol', + 'table', +]); + +/** The part of a hast node that the plugin reads and writes. */ +interface Node { + type: string; + tagName?: string; + properties?: Record; + children?: Node[]; + position?: { start: { line: number }; end: { line: number } }; +} + +/** + * Makes the transformer of the plugin. + * + * Every block element gets `data-line` with its first source line and `data-line-end` with its last one. + * Each element at the top of the tree is wrapped in a div with `data-block` set to the tag of the element and + * the same two attributes, so one component can render the frame of every block. + * + * @returns The transformer, which changes the tree in place. + */ +export function rehypeBlocks(): (tree: unknown) => void { + return (tree) => { + const root = tree as Node; + if (!root.children) return; + mark(root.children); + root.children = root.children.map((child) => (child.type === 'element' ? wrap(child) : child)); + }; +} + +/** + * Writes the source lines of each block element in a subtree. + * + * @param nodes The nodes to walk. + */ +function mark(nodes: Node[]): void { + for (const node of nodes) { + if (node.type !== 'element') continue; + if (node.tagName && BLOCK_TAGS.has(node.tagName)) + Object.assign(node, { properties: lines(node) }); + if (node.children) mark(node.children); + } +} + +/** + * Gives the properties of an element with its source lines added. + * + * @param node The element. + * @returns The properties, with the lines when the element has a position. + */ +function lines(node: Node): Record { + const properties = { ...node.properties }; + if (node.position) { + properties.dataLine = node.position.start.line; + properties.dataLineEnd = node.position.end.line; + } + return properties; +} + +/** + * Wraps a top level element in the block div. + * + * @param node The element. + * @returns The div, with the element as its only child. + */ +function wrap(node: Node): Node { + const { dataLine, dataLineEnd } = lines(node); + return { + type: 'element', + tagName: 'div', + properties: { dataBlock: node.tagName, dataLine, dataLineEnd }, + children: [node], + position: node.position, + }; +} diff --git a/dashboard/src/stores/review.test.ts b/dashboard/src/stores/review.test.ts index 0c83609..9a64c87 100644 --- a/dashboard/src/stores/review.test.ts +++ b/dashboard/src/stores/review.test.ts @@ -14,8 +14,10 @@ import { newReview, open, recallScroll, + recallView, refresh, rememberScroll, + rememberView, saveComment, saveFile, setBase, @@ -267,17 +269,24 @@ test('opening a different box discards the previous one', async () => { assert.equal(useReview.getState().boxId, 'other'); }); -test('how far a file was read is remembered per file', () => { - rememberScroll('a.ts', 420); - assert.equal(recallScroll('a.ts'), 420); - // A file this review has not opened starts at the top. - assert.equal(recallScroll('b.ts'), 0); +test('where a file was left, and how it was shown, is remembered per file', () => { + rememberScroll('a.ts', { line: 12, offset: 4 }); + assert.deepEqual(recallScroll('a.ts'), { line: 12, offset: 4 }); + assert.equal(recallView('a.ts'), false); + rememberView('a.ts', true); + assert.equal(recallView('a.ts'), true); + assert.deepEqual(recallScroll('a.ts'), { line: 12, offset: 4 }); + // A file this review has not opened starts at the top, as source. + assert.equal(recallScroll('b.ts'), null); + assert.equal(recallView('b.ts'), false); }); test('a new box starts every file at the top again', () => { - rememberScroll('a.ts', 420); + rememberScroll('a.ts', { line: 12, offset: 4 }); + rememberView('a.ts', true); open('another-box'); - assert.equal(recallScroll('a.ts'), 0); + assert.equal(recallScroll('a.ts'), null); + assert.equal(recallView('a.ts'), false); }); test('a refresh refetches the tree and the open file', async () => { @@ -327,7 +336,7 @@ test('a refresh while a write is in flight is skipped', async () => { test('a refresh while a composer is open is skipped', async () => { await loadTree(); - useReview.setState({ composing: 4 }); + useReview.setState({ composing: { line: 4, endLine: 0 } }); const before = requested.length; await refresh(); // A refetch would drop the text that the reader types. @@ -359,15 +368,15 @@ test('a comment shows before the server confirms it', async () => { answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'saved', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'saved', outdated: false }], }; const pending = saveComment('a.ts', 2, 'saved'); assert.deepEqual(useReview.getState().file?.annotations, [ - { line: 2, comment: 'saved', outdated: false }, + { line: 2, endLine: 0, comment: 'saved', outdated: false }, ]); await pending; assert.deepEqual(useReview.getState().file?.annotations, [ - { line: 2, comment: 'saved', outdated: false }, + { line: 2, endLine: 0, comment: 'saved', outdated: false }, ]); assert.equal(useReview.getState().saving, false); assert.equal(useReview.getState().composing, null); @@ -391,7 +400,7 @@ test('the tree badge follows a comment without refetching the tree', async () => answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'x', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'x', outdated: false }], }; await saveComment('a.ts', 2, 'x'); assert.equal(hits('/review/dir'), before); @@ -404,7 +413,7 @@ test('deleting the last comment clears the badge', async () => { await loadFile('a.ts'); answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'x', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'x', outdated: false }], }; await saveComment('a.ts', 2, 'x'); @@ -420,7 +429,7 @@ test('a comment deeper in the tree lights the folders above it', async () => { await loadDir('src'); answers['/review/annotations'] = { path: 'src/deep.ts', - annotations: [{ line: 1, comment: 'x', outdated: false }], + annotations: [{ line: 1, endLine: 0, comment: 'x', outdated: false }], }; await saveComment('src/deep.ts', 1, 'x'); @@ -435,13 +444,13 @@ test('editing an existing comment replaces it rather than adding one', async () await loadFile('a.ts'); answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'first', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'first', outdated: false }], }; await saveComment('a.ts', 2, 'first'); answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'second', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'second', outdated: false }], }; await saveComment('a.ts', 2, 'second'); assert.equal(useReview.getState().file?.annotations.length, 1); @@ -453,7 +462,7 @@ test('a new review clears the comments and reloads the tree', async () => { await loadFile('a.ts'); answers['/review/annotations'] = { path: 'a.ts', - annotations: [{ line: 2, comment: 'x', outdated: false }], + annotations: [{ line: 2, endLine: 0, comment: 'x', outdated: false }], }; await saveComment('a.ts', 2, 'x'); const before = hits('/review/dir'); @@ -571,7 +580,7 @@ test('saving anyway reads what is on disk first, then writes over it', async () test('an outdated comment is carried through as such', async () => { await loadTree(); answers['/review/file'] = file({ - annotations: [{ line: 2, comment: 'about the old code', outdated: true }], + annotations: [{ line: 2, endLine: 0, comment: 'about the old code', outdated: true }], }); await loadFile('a.ts'); // The server runs the drift check, and the store carries the flag through. diff --git a/dashboard/src/stores/review.ts b/dashboard/src/stores/review.ts index e107287..b9541a0 100644 --- a/dashboard/src/stores/review.ts +++ b/dashboard/src/stores/review.ts @@ -9,6 +9,7 @@ import type { ReviewFileResponse, } from '../../../shared/types.ts'; import { ApiError, api } from '../api.ts'; +import type { ScrollAnchor } from '../lib/anchor.ts'; import { type Token, tokenizeLines } from '../lib/highlight.ts'; import { refetchOnVisible } from '../lib/poll.ts'; @@ -22,6 +23,22 @@ export interface OpenFile extends ReviewFileResponse { tokens: Token[][] | null; } +/** The line or the block of lines that the composer is open on. */ +export interface Composing { + /** The line, or the first line of the block. */ + line: number; + /** The last line of the block, or 0 for one line. */ + endLine: number; +} + +/** The place where the reader left a file. */ +interface ReadingPlace { + /** The scroll anchor of the pane, or null when the pane was never left. */ + anchor: ScrollAnchor | null; + /** True when the file was shown rendered. */ + rendered: boolean; +} + /** The state that the review view renders. */ export interface ReviewState { /** The box the store holds, or null before the first `open`. */ @@ -43,8 +60,8 @@ export interface ReviewState { loadingFile: boolean; /** The last error message, or null. The view shows it in place of the pane. */ error: string | null; - /** The line whose composer is open, or null. */ - composing: number | null; + /** The line or the block that the composer is open on, or null. */ + composing: Composing | null; /** True while an annotation write is in flight. */ saving: boolean; /** @@ -75,31 +92,51 @@ const EMPTY: ReviewState = { export const useReview = create(() => EMPTY); /** - * The scroll offset of each file, by path. + * The place where the reader left each file, by path. * * The map is outside the state, so a scroll does not render the view again. * {@link open} clears it when the store changes to another box. */ -const scrollOffsets = new Map(); +const places = new Map(); + +/** + * Records the scroll anchor of a file, when the pane leaves it. + * + * @param path The path of the file. + * @param anchor The scroll anchor of the pane. + */ +export function rememberScroll(path: string, anchor: ScrollAnchor): void { + places.set(path, { rendered: false, ...places.get(path), anchor }); +} /** - * Records the scroll offset of a file. + * Reads the scroll anchor where the reader left a file. * * @param path The path of the file. - * @param offset The scroll offset in pixels. + * @returns The anchor, or null for a file that this review has not left. */ -export function rememberScroll(path: string, offset: number): void { - scrollOffsets.set(path, offset); +export function recallScroll(path: string): ScrollAnchor | null { + return places.get(path)?.anchor ?? null; } /** - * Reads the last scroll offset of a file. + * Records whether a file is shown rendered. * * @param path The path of the file. - * @returns The offset in pixels, or 0 for a file that this review has not opened. + * @param rendered True when the file is shown rendered. */ -export function recallScroll(path: string): number { - return scrollOffsets.get(path) ?? 0; +export function rememberView(path: string, rendered: boolean): void { + places.set(path, { anchor: null, ...places.get(path), rendered }); +} + +/** + * Reads whether a file was last shown rendered. + * + * @param path The path of the file. + * @returns True when the file was shown rendered. A file that this review has not opened shows as source. + */ +export function recallView(path: string): boolean { + return places.get(path)?.rendered ?? false; } /** @@ -130,7 +167,7 @@ function get(): ReviewState { */ export function open(boxId: string): void { if (get().boxId === boxId) return; - scrollOffsets.clear(); + places.clear(); set({ ...EMPTY, boxId }); } @@ -299,12 +336,12 @@ export function setDirty(dirty: boolean): void { } /** - * Opens or closes the composer on one line. + * Opens or closes the composer on one line or one block of lines. * - * @param line The line of the composer, or null to close it. + * @param composing The line or the block of the composer, or null to close it. */ -export function compose(line: number | null): void { - set({ composing: line }); +export function compose(composing: Composing | null): void { + set({ composing }); } /** The result of a save. A conflict is the only failure that the reviewer can resolve. */ @@ -354,10 +391,16 @@ export async function saveFile( * the previous list. * * @param path The path of the file. - * @param line The line of the comment. + * @param line The line of the comment, or the first line of its block. * @param comment The text of the comment. + * @param endLine The last line of the block, or 0 for a comment on one line. */ -export async function saveComment(path: string, line: number, comment: string): Promise { +export async function saveComment( + path: string, + line: number, + comment: string, + endLine = 0, +): Promise { const { boxId, file } = get(); if (!boxId) return; const previous = file?.annotations ?? []; @@ -366,13 +409,14 @@ export async function saveComment(path: string, line: number, comment: string): if (file && file.path === path) { const optimistic = [ ...previous.filter((a) => a.line !== line), - { line, comment: comment.trim(), outdated: false }, + { line, endLine, comment: comment.trim(), outdated: false }, ].sort((a, b) => a.line - b.line); set({ file: { ...file, annotations: optimistic }, composing: null }); } try { - const answer = await api.setAnnotation(boxId, { path, line, comment }); + const body = endLine > 0 ? { path, line, endLine, comment } : { path, line, comment }; + const answer = await api.setAnnotation(boxId, body); applyAnnotations(path, answer.annotations, countDelta(previous, answer.annotations)); set({ saving: false, error: null }); } catch (err) { diff --git a/dashboard/src/views/BoxReview.tsx b/dashboard/src/views/BoxReview.tsx index ffdf393..0518d3d 100644 --- a/dashboard/src/views/BoxReview.tsx +++ b/dashboard/src/views/BoxReview.tsx @@ -9,7 +9,7 @@ import { CodePane, type ScrollTarget } from '@/components/review/CodePane'; import { CommentCard } from '@/components/review/CommentCard'; import { ComposerSheet, InlineComposer } from '@/components/review/CommentComposer'; import { HunkSheet } from '@/components/review/HunkSheet'; -import { MarkdownPreview } from '@/components/review/MarkdownPreview'; +import { type Block, MarkdownPreview } from '@/components/review/MarkdownPreview'; import { ReviewToolbar } from '@/components/review/ReviewToolbar'; import { ReviewTree } from '@/components/review/ReviewTree'; import { Shelf } from '@/components/Shelf'; @@ -36,7 +36,9 @@ import { loadTree, newReview, open as openReview, + recallView, refreshOnReturn, + rememberView, saveComment, saveFile, setBase, @@ -81,6 +83,8 @@ export function BoxReview() { const [scrollTo, setScrollTo] = useState(null); /** True while the pane shows a markdown file rendered. */ const [previewing, setPreviewing] = useState(false); + /** The blocks of the rendered file, in order, once the pane has rendered them. */ + const [blocks, setBlocks] = useState([]); 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); @@ -133,10 +137,12 @@ export function BoxReview() { return refreshOnReturn(); }, [id]); - // The URL decides which file is open. The hunk sheet and the preview close with their file. + // The URL decides which file is open. The hunk sheet closes with its file, and + // a file opens in the view it was last shown in. useEffect(() => { setHunk(null); - setPreviewing(false); + setBlocks([]); + setPreviewing(path ? recallView(path) : false); if (path) void loadFile(path); else closeFile(); }, [path]); @@ -238,9 +244,11 @@ export function BoxReview() { } else { setConflict(false); edit.stop(); + // The file goes back to the view it was shown in before the edit. + if (path) setPreviewing(recallView(path)); } }, - [edit], + [edit, path], ); const editing = edit.text !== null; @@ -254,8 +262,15 @@ export function BoxReview() { * everything past where the read stopped. */ const editable = file !== null && !file.deleted && !file.binary && !file.truncated && !tooLong; - /** The kind of preview that the toolbar offers. Edit mode has none. */ - const preview = file && !file.deleted && !editing ? previewKind(file.path) : null; + /** + * The kind of preview that the toolbar offers. Edit mode has none, and a markdown file past + * the line limit has none, because its comments need the rows of the code pane. + */ + const preview = useMemo(() => { + if (!file || file.deleted || editing) return null; + const kind = previewKind(file.path); + return kind === 'markdown' && tooLong ? null : kind; + }, [file, editing, tooLong]); /** True while the pane shows the rendered markdown instead of the code. */ const rendered = previewing && preview === 'markdown'; /** The absolute path of the open file in the box, or null. */ @@ -309,7 +324,25 @@ export function BoxReview() { * pane's rows are memoized against typing. */ const selectLine = useCallback((line: number) => { - compose(useReview.getState().composing === line ? null : line); + const current = useReview.getState().composing; + compose(current?.line === line && current.endLine === 0 ? null : { line, endLine: 0 }); + }, []); + + /** + * Opens or closes the composer on a block of the rendered file. + * + * A block whose first line already has a comment opens that comment, because + * REVIEW.md holds one comment per line. + */ + const selectBlock = useCallback((line: number, endLine: number) => { + const { composing: current, file: open } = useReview.getState(); + if (current?.line === line) { + compose(null); + return; + } + const existing = open?.annotations.find((a) => a.line === line); + // A block of one line is a line comment. + compose({ line, endLine: existing ? existing.endLine : endLine > line ? endLine : 0 }); }, []); /** Opens the hunk sheet for a hunk index of the open file. */ @@ -360,6 +393,13 @@ export function BoxReview() { () => (file?.annotations ?? []).map((a) => a.line).sort((a, b) => a - b), [file?.annotations], ); + /** The first lines of the blocks of the rendered file that hold a change, in order. */ + const changedBlocks = useMemo(() => blocksWith(blocks, changedLines), [blocks, changedLines]); + /** The first lines of the blocks of the rendered file that hold a comment, in order. */ + const commentedBlocks = useMemo( + () => blocksWith(blocks, commentedLines), + [blocks, commentedLines], + ); /** * Renders the comment card and the inline composer under a line. @@ -371,7 +411,7 @@ export function BoxReview() { (line: number) => { if (!file) return null; const annotation = annotations.get(line); - const open = composing === line; + const open = composing?.line === line ? composing : null; if (!annotation && !open) return null; return (
@@ -379,7 +419,7 @@ export function BoxReview() { compose(line)} + onEdit={() => compose({ line, endLine: annotation.endLine })} // Asks first, because a deleted comment has no undo and the bin // sits close to the pencil. onDelete={() => setConfirmDelete(line)} @@ -390,9 +430,53 @@ export function BoxReview() { {open && wide ? ( void saveComment(file.path, line, comment)} + onSave={(comment) => void saveComment(file.path, line, comment, open.endLine)} + onCancel={() => compose(null)} + /> + ) : null} +
+ ); + }, + [file, annotations, composing, saving, wide], + ); + + /** + * Renders the comment cards and the inline composer under a block of the + * rendered file, for the comments on its lines. + * + * The pane calls it for every block. It returns null for a block without either. + */ + const underBlock = useCallback( + (line: number, endLine: number) => { + if (!file) return null; + const open = + composing && composing.line >= line && composing.line <= endLine ? composing : null; + const cards = file.annotations.filter( + (a) => a.line >= line && a.line <= endLine && a.line !== open?.line, + ); + if (cards.length === 0 && !open) return null; + return ( +
+ {cards.map((annotation) => ( + compose({ line: annotation.line, endLine: annotation.endLine })} + onDelete={() => setConfirmDelete(annotation.line)} + /> + ))} + {open && wide ? ( + void saveComment(file.path, open.line, comment, open.endLine)} onCancel={() => compose(null)} /> ) : null} @@ -571,10 +655,11 @@ export function BoxReview() { {file ? ( <> setWrap((w) => !w)} - onStepChange={(direction) => step(changedLines, direction)} - onStepComment={(direction) => step(commentedLines, direction)} + onStepChange={(direction) => + step(rendered ? changedBlocks : changedLines, direction) + } + onStepComment={(direction) => + step(rendered ? commentedBlocks : commentedLines, direction) + } onEdit={() => { if (editing) guard(() => switchMode(false)); else { @@ -598,9 +687,8 @@ export function BoxReview() { onSave={() => save(false)} onRevert={edit.revert} onPreview={() => { - // An open composer belongs to the code. - compose(null); - setPreviewing((on) => !on); + rememberView(file.path, !previewing); + setPreviewing(!previewing); }} /> {file.deleted ? ( @@ -655,10 +743,28 @@ export function BoxReview() { ) : null} + {/* Each pane is mounted once per file, so it records the place of + the reader while the rows of the file are still there. */} {rendered ? ( - + ) : ( { - if (file && composing !== null) void saveComment(file.path, composing, comment); + if (file && composing !== null) { + void saveComment(file.path, composing.line, comment, composing.endLine); + } }} onCancel={() => compose(null)} /> @@ -759,6 +867,19 @@ export function BoxReview() { /** Counts the image URLs of the lightbox, so each new URL differs from the earlier ones. */ let imageViews = 0; +/** + * Picks the blocks that hold one of the given lines. + * + * @param blocks The blocks of the rendered file, in order. + * @param lines The lines, in order. + * @returns The first line of each block that holds one of the lines, in order. + */ +function blocksWith(blocks: Block[], lines: number[]): number[] { + return blocks + .filter((block) => lines.some((line) => line >= block.line && line <= block.endLine)) + .map((block) => block.line); +} + /** * Checks if a click is a plain left click. A modified click opens a tab or a * window and leaves the buffer here untouched. diff --git a/doc/rest.md b/doc/rest.md index 169f79e..eb499f4 100644 --- a/doc/rest.md +++ b/doc/rest.md @@ -118,8 +118,9 @@ name. `PUT …/review/file` accepts a `ReviewFileBody` with `path`, `content`, and the `hash` the file was read at. A save over an edit the agent made in the meantime is refused with a 412; the reviewer can then save anyway or drop the changes. -`PUT …/review/annotations` accepts a `ReviewAnnotationBody` with `path`, `line`, and `comment`, and creates or replaces -the comment on that line. `REVIEW.md` holds at most one comment per line. DELETE removes it. +`PUT …/review/annotations` accepts a `ReviewAnnotationBody` with `path`, `line`, `comment` and an optional `endLine` +for a comment on a block of lines, and creates or replaces the comment on that line. `REVIEW.md` holds at most one +comment per line, and a comment on a block counts on its first line. DELETE removes it. `PUT …/review/base` accepts `{ "rev": "…" }` and compares the whole review against that revision. `null` or absent clears the base back to each repository's own HEAD. The answer says where the expression resolved in each repository. diff --git a/doc/review.md b/doc/review.md index 332af83..9fd89c9 100644 --- a/doc/review.md +++ b/doc/review.md @@ -31,9 +31,10 @@ The review has commenting and editing modes. It opens in commenting mode. ### Commenting -Select a source line to open the comment form. Write the comment, then select **Comment** or press `Ctrl`/`Cmd`+`Enter` -to save it. Use the buttons on an existing comment card to edit or delete it. Comments are saved in the `REVIEW.md` file -at the workspace root. +Select a source line to open the comment form. In a rendered markdown file, select a block, such as a paragraph or a +list item, to comment on all lines of the block. Write the comment, then select **Comment** or press +`Ctrl`/`Cmd`+`Enter` to save it. Use the buttons on an existing comment card to edit or delete it. Comments are saved in +the `REVIEW.md` file at the workspace root. When the review was opened from a thread and has comments, select **Hand to agent** to switch back to the thread with a prepared prompt that asks the agent to read your review. @@ -57,8 +58,9 @@ The review code lives in `orchestrator/src/review/`. There is no annotation table. Every mutation reads, parses, applies, serializes and writes the whole `REVIEW.md` under a per-box lock. The write sends the hash that was read. When the agent changed the file in between, the [file service](files.md) refuses the write, and the mutation is read and applied once more. Writes are atomic and keep -the file's permissions. The format matches the desktop [`review`](https://github.com/splitbrain/review) tool byte for -byte — the test fixtures are files that tool wrote. +the file's permissions. The format is the format of the desktop [`review`](https://github.com/splitbrain/review) tool, +and the test fixtures are files that tool wrote. A comment on a block of lines has the heading `#### Line 10 to 14`. The +desktop tool reads it as a comment on line 10 and drops the range when it writes the file. ### One workspace, many repositories @@ -92,9 +94,9 @@ offers. The orchestrator caps file reads at 2 MiB; a NUL byte marks a file as bi ### Drift -Each comment stores three lines of context above and below its line. The drift check compares the stored context with -the current source: an exact match elsewhere relocates the comment, no match marks it `(outdated)`. Drift runs when a -reader arrives, on every file view, and after every comment write. +Each comment stores three lines of context above and below its line, or above and below its block. The drift check +compares the stored context with the current source: an exact match elsewhere relocates the comment, no match marks it +`(outdated)`. Drift runs when a reader arrives, on every file view, and after every comment write. ### Editing diff --git a/orchestrator/src/app.ts b/orchestrator/src/app.ts index 4075c44..ad86c63 100644 --- a/orchestrator/src/app.ts +++ b/orchestrator/src/app.ts @@ -887,13 +887,19 @@ export function buildApp(cfg: Config, db: Db, opts: BuildOptions = {}): Orchestr ); /** - * Creates or replaces the comment on one line. REVIEW.md holds at most one + * Creates or replaces the comment on one line or one block of lines. REVIEW.md holds at most one * comment per line. */ app.put('/api/boxes/:id/review/annotations', async (req) => { const { id } = req.params as { id: string }; const body = parseBody(reviewAnnotationBody, req.body); - const annotations = await review.setAnnotation(id, body.path, body.line, body.comment); + const annotations = await review.setAnnotation( + id, + body.path, + body.line, + body.comment, + body.endLine ?? 0, + ); return { path: body.path, annotations } satisfies ReviewAnnotationsResponse; }); diff --git a/orchestrator/src/bodies.ts b/orchestrator/src/bodies.ts index 0fc1648..97f23ca 100644 --- a/orchestrator/src/bodies.ts +++ b/orchestrator/src/bodies.ts @@ -92,13 +92,14 @@ export const reviewFileBody = z.object({ }); /** - * The body of PUT /api/boxes/:id/review/annotations, with the comment on one line. + * The body of PUT /api/boxes/:id/review/annotations, with the comment on one line or one block of lines. * - * `line` is coerced, so a line number in a string also works. + * `line` and `endLine` are coerced, so a line number in a string also works. */ export const reviewAnnotationBody = z.object({ path: filled, line: z.coerce.number(), + endLine: z.coerce.number().optional(), comment: z.string(), }); diff --git a/orchestrator/src/review/routes.test.ts b/orchestrator/src/review/routes.test.ts index a9f128a..68d9c70 100644 --- a/orchestrator/src/review/routes.test.ts +++ b/orchestrator/src/review/routes.test.ts @@ -813,7 +813,9 @@ describe('saving a file', () => { hash, }); // The drift check moves the comment with its line. - assert.deepEqual(body.annotations, [{ line: 4, comment: 'this one', outdated: false }]); + assert.deepEqual(body.annotations, [ + { line: 4, endLine: 0, comment: 'this one', outdated: false }, + ]); }); test('a file the review cannot show cannot be saved either', async () => { @@ -905,7 +907,7 @@ describe('annotations', () => { }); assert.equal(status, 200); assert.deepEqual(body.annotations, [ - { line: 3, comment: 'this needs a name', outdated: false }, + { line: 3, endLine: 0, comment: 'this needs a name', outdated: false }, ]); const written = readFileSync(join(ws, 'REVIEW.md'), 'utf8'); @@ -924,8 +926,8 @@ describe('annotations', () => { const { body } = await get('/api/boxes/bbb/review/file?path=code.ts'); assert.deepEqual(body.annotations, [ - { line: 2, comment: 'second', outdated: false }, - { line: 5, comment: 'fifth', outdated: false }, + { line: 2, endLine: 0, comment: 'second', outdated: false }, + { line: 5, endLine: 0, comment: 'fifth', outdated: false }, ]); const listing = await openDir('bbb'); @@ -939,7 +941,9 @@ describe('annotations', () => { commentable('ccc'); await put('ccc', { path: 'code.ts', line: 3, comment: 'first' }); const { body } = await put('ccc', { path: 'code.ts', line: 3, comment: 'second' }); - assert.deepEqual(body.annotations, [{ line: 3, comment: 'second', outdated: false }]); + assert.deepEqual(body.annotations, [ + { line: 3, endLine: 0, comment: 'second', outdated: false }, + ]); }); test('a comment is deleted, and the last one takes the file with it', async () => { @@ -953,7 +957,7 @@ describe('annotations', () => { }); assert.equal(first.statusCode, 200); assert.deepEqual((first.json() as ReviewAnnotationsResponse).annotations, [ - { line: 4, comment: 'y', outdated: false }, + { line: 4, endLine: 0, comment: 'y', outdated: false }, ]); await orchestrator.app.inject({ @@ -992,13 +996,36 @@ describe('annotations', () => { ); const { body } = await put('eee', { path: 'code.ts', line: 6, comment: 'written by the API' }); assert.deepEqual(body.annotations, [ - { line: 1, comment: 'written by the agent', outdated: false }, - { line: 6, comment: 'written by the API', outdated: false }, + { line: 1, endLine: 0, comment: 'written by the agent', outdated: false }, + { line: 6, endLine: 0, comment: 'written by the API', outdated: false }, ]); // The start date of the review stays, and does not change to today. assert.match(readFileSync(join(ws, 'REVIEW.md'), 'utf8'), /_Started: 2020-01-01_/); }); + test('a comment on a block is written with its range, and refused past the file', async () => { + const ws = commentable('ggg'); + const { status, body } = await put('ggg', { + path: 'code.ts', + line: 2, + endLine: 4, + comment: 'about the block', + }); + assert.equal(status, 200); + assert.deepEqual(body.annotations, [ + { line: 2, endLine: 4, comment: 'about the block', outdated: false }, + ]); + const written = readFileSync(join(ws, 'REVIEW.md'), 'utf8'); + assert.match(written, /#### Line 2 to 4\n/); + // The context holds the block and three lines around it, clamped to the file. + assert.match(written, /1: one\n2: two\n3: three\n4: four\n5: five\n6: six\n/); + + const past = await put('ggg', { path: 'code.ts', line: 2, endLine: 9, comment: 'x' }); + assert.equal(past.status, 400); + const before = await put('ggg', { path: 'code.ts', line: 4, endLine: 2, comment: 'x' }); + assert.equal(before.status, 400); + }); + test('a comment survives its code moving', async () => { const ws = commentable('fff'); await put('fff', { path: 'code.ts', line: 3, comment: 'about three' }); @@ -1006,7 +1033,9 @@ describe('annotations', () => { write(ws, 'code.ts', 'new\nnew\none\ntwo\nthree\nfour\nfive\nsix\n'); const { body } = await get('/api/boxes/fff/review/file?path=code.ts'); - assert.deepEqual(body.annotations, [{ line: 5, comment: 'about three', outdated: false }]); + assert.deepEqual(body.annotations, [ + { line: 5, endLine: 0, comment: 'about three', outdated: false }, + ]); // Relocation is persisted, so the agent reads the right line too. assert.match(readFileSync(join(ws, 'REVIEW.md'), 'utf8'), /#### Line 5/); }); @@ -1017,7 +1046,9 @@ describe('annotations', () => { write(ws, 'code.ts', 'completely\ndifferent\ncontent\n'); const { body } = await get('/api/boxes/ggg/review/file?path=code.ts'); - assert.deepEqual(body.annotations, [{ line: 3, comment: 'about three', outdated: true }]); + assert.deepEqual(body.annotations, [ + { line: 3, endLine: 0, comment: 'about three', outdated: true }, + ]); assert.match(readFileSync(join(ws, 'REVIEW.md'), 'utf8'), /#### Line 3 \(outdated\)/); }); @@ -1065,7 +1096,9 @@ describe('annotations', () => { assert.equal(body.binary, true); // The listing counts the comment, so the file view shows it too. The // reviewer reads and deletes it there. - assert.deepEqual(body.annotations, [{ line: 3, comment: 'about three', outdated: false }]); + assert.deepEqual(body.annotations, [ + { line: 3, endLine: 0, comment: 'about three', outdated: false }, + ]); }); test('a comment on a file the change deleted comes back with it', async () => { @@ -1078,7 +1111,9 @@ describe('annotations', () => { const { body } = await get('/api/boxes/nnn/review/file?path=code.ts'); assert.equal(body.deleted, true); - assert.deepEqual(body.annotations, [{ line: 3, comment: 'about three', outdated: true }]); + assert.deepEqual(body.annotations, [ + { line: 3, endLine: 0, comment: 'about three', outdated: true }, + ]); }); test('bad input is refused before REVIEW.md is touched', async () => { @@ -1089,7 +1124,7 @@ describe('annotations', () => { { path: 'code.ts', line: 1.5, comment: 'x' }, { path: 'code.ts', line: 1, comment: ' ' }, { path: 'code.ts', line: 1, comment: 'x'.repeat(20_001) }, - { line: 1, comment: 'x' }, + { line: 1, endLine: 0, comment: 'x' }, ]) { const res = await orchestrator.app.inject({ method: 'PUT', diff --git a/orchestrator/src/review/service.ts b/orchestrator/src/review/service.ts index d688daa..3e1d21b 100644 --- a/orchestrator/src/review/service.ts +++ b/orchestrator/src/review/service.ts @@ -418,26 +418,32 @@ export class ReviewService { } /** - * Adds or replaces the comment on one line. + * Adds or replaces the comment on one line or one block of lines. * * @param id The box id. * @param relPath The workspace-relative path of the file. - * @param line The line number, starting at 1. + * @param line The line number, starting at 1. For a block, its first line. * @param comment The comment. The method trims it. + * @param endLine The last line of a block, or 0 for a comment on one line. * @returns The comments of the file after the drift check. - * @throws {HttpError} 400 for a line that is not a positive integer or a comment that is empty or longer - * than 20000 characters, 404 for a path that the review does not offer, 409 for a deleted file or when - * REVIEW.md changes during both write attempts. + * @throws {HttpError} 400 for a line that is not a positive integer, an end line that is not an integer at or + * past the line and inside the file, or a comment that is empty or longer than 20000 characters, 404 for a + * path that the review does not offer, 409 for a deleted file or when REVIEW.md changes during both write + * attempts. */ async setAnnotation( id: string, relPath: string, line: number, comment: string, + endLine = 0, ): Promise { if (!Number.isInteger(line) || line < 1) { throw new HttpError(400, 'line must be a positive integer'); } + if (!Number.isInteger(endLine) || (endLine !== 0 && endLine < line)) { + throw new HttpError(400, 'endLine must be 0 or a line at or past line'); + } const text = comment.trim(); if (text === '') throw new HttpError(400, 'comment is required'); if (text.length > 20_000) throw new HttpError(400, 'comment is too long'); @@ -449,9 +455,10 @@ export class ReviewService { throw new HttpError(409, 'This file was deleted, so there is no line to comment on.'); } const source = fileLines((await box.files.read(relPath, MAX_FILE_BYTES)).content); + if (endLine > source.length) throw new HttpError(400, 'endLine is past the end of the file'); await this.mutate(id, box.files, relPath, (review) => { - setAnnotation(review, relPath, line, text, source); + setAnnotation(review, relPath, line, text, source, endLine); }); return this.drifted(id, box.files, relPath); } @@ -920,9 +927,14 @@ function failedCondition(err: unknown): boolean { * @returns The annotations in line order. */ function toAnnotations( - annotations: Map, + annotations: Map, ): ReviewAnnotation[] { return [...annotations.entries()] .sort(([a], [b]) => a - b) - .map(([line, ann]) => ({ line, comment: ann.comment, outdated: ann.outdated })); + .map(([line, ann]) => ({ + line, + endLine: ann.endLine, + comment: ann.comment, + outdated: ann.outdated, + })); } diff --git a/orchestrator/src/review/store.test.ts b/orchestrator/src/review/store.test.ts index 65eb645..1e61c66 100644 --- a/orchestrator/src/review/store.test.ts +++ b/orchestrator/src/review/store.test.ts @@ -191,6 +191,21 @@ describe('parseReview', () => { assert.equal(normal.data.get('test.go')?.get(5)?.outdated, false); }); + test('reads the range of a block comment, with and without the outdated marker', () => { + const head = '# Code Review\n\n_Started: 2026-03-22_\n\n---\n\n## `doc.md`\n\n'; + const block = parseReview(`${head}#### Line 5 to 9\n\nAbout this paragraph\n`); + assert.equal(block.data.get('doc.md')?.get(5)?.endLine, 9); + assert.equal(block.data.get('doc.md')?.get(5)?.outdated, false); + const outdated = parseReview(`${head}#### Line 5 to 9 (outdated)\n\nAbout this paragraph\n`); + assert.equal(outdated.data.get('doc.md')?.get(5)?.endLine, 9); + assert.equal(outdated.data.get('doc.md')?.get(5)?.outdated, true); + // A range that ends on its first line is a line comment. + const one = parseReview(`${head}#### Line 5 to 5\n\nAbout this heading\n`); + assert.equal(one.data.get('doc.md')?.get(5)?.endLine, 0); + const line = parseReview(`${head}#### Line 5\n\nAbout this line\n`); + assert.equal(line.data.get('doc.md')?.get(5)?.endLine, 0); + }); + test('an empty document is an empty review', () => { const review = parseReview(''); assert.equal(review.data.size, 0); @@ -273,6 +288,30 @@ describe('a comment survives a write and a read', () => { }); } + test('a block comment keeps its range and holds the block in its context', () => { + const source = lines('l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\nl10\nl11\nl12\n'); + const review = emptyReview('2026-08-31'); + setAnnotation(review, 'doc.md', 5, 'about the block', source, 8); + const text = serializeReview(review); + assert.ok(text.includes('\n#### Line 5 to 8\n\nabout the block\n')); + assert.ok( + text.includes('2: l2\n3: l3\n4: l4\n5: l5\n6: l6\n7: l7\n8: l8\n9: l9\n10: l10\n11: l11\n'), + ); + assert.ok(!text.includes('\n1: l1\n')); + assert.ok(!text.includes('\n12: l12\n')); + const back = parseReview(text).data.get('doc.md')?.get(5); + assert.equal(back?.endLine, 8); + assert.deepEqual(back?.context, source.slice(1, 11)); + assert.equal(back?.contextFrom, 2); + }); + + test('a block that ends on its first line is written as a line comment', () => { + const review = emptyReview('2026-08-31'); + setAnnotation(review, 'doc.md', 2, 'about the heading', lines('l1\nl2\nl3\n'), 2); + assert.ok(serializeReview(review).includes('\n#### Line 2\n\n')); + assert.equal(review.data.get('doc.md')?.get(2)?.endLine, 0); + }); + test('neighbouring annotations stay separated', () => { const review = emptyReview('2026-08-31'); setAnnotation( @@ -429,7 +468,7 @@ function annotated( contextFrom: number, outdated = false, ): Map { - return new Map([[line, { comment: 'test comment', context, contextFrom, outdated }]]); + return new Map([[line, { comment: 'test comment', endLine: 0, context, contextFrom, outdated }]]); } describe('checkDrift', () => { @@ -470,7 +509,7 @@ describe('checkDrift', () => { test('an annotation with no context adopts the current source', () => { const anns = new Map([ - [1, { comment: 'no context', context: [], contextFrom: 0, outdated: false }], + [1, { comment: 'no context', endLine: 0, context: [], contextFrom: 0, outdated: false }], ]); assert.equal(checkDrift(anns, ['line1', 'line2']), true); const ann = anns.get(1)!; @@ -546,6 +585,23 @@ describe('checkDrift', () => { assert.equal(reloaded.data.get('test.go')?.get(4)?.outdated, true); }); + test('a block comment moves with its block, and an edit inside the block outdates it', () => { + const review = emptyReview('2026-08-31'); + const before = ['l1', 'A', 'B', 'C', 'l5', 'l6', 'l7']; + setAnnotation(review, 'doc.md', 2, 'about A to C', before, 4); + const anns = review.data.get('doc.md')!; + + // Two lines inserted at the top move the block down. + assert.equal(checkDrift(anns, ['n1', 'n2', ...before]), true); + assert.equal(anns.get(4)?.endLine, 6); + assert.equal(anns.get(4)?.outdated, false); + + const edited = ['n1', 'n2', 'l1', 'A', 'CHANGED', 'C', 'l5', 'l6', 'l7']; + assert.equal(checkDrift(anns, edited), true); + assert.equal(anns.get(4)?.outdated, true); + assert.equal(anns.get(4)?.endLine, 6); + }); + test('a context longer than the file matches nothing', () => { const anns = annotated(1, ['a', 'b'], 1); assert.equal(checkDrift(anns, ['a']), true); @@ -569,8 +625,8 @@ describe('checkDrift', () => { // Both comments are about the same code, so both find line 8. The one // that has to move must not overwrite the one already there. const anns = new Map([ - [5, { comment: 'moves', context: ['dup'], contextFrom: 5, outdated: false }], - [8, { comment: 'stays', context: ['dup'], contextFrom: 8, outdated: false }], + [5, { comment: 'moves', endLine: 0, context: ['dup'], contextFrom: 5, outdated: false }], + [8, { comment: 'stays', endLine: 0, context: ['dup'], contextFrom: 8, outdated: false }], ]); const source = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'dup', 'h']; assert.equal(checkDrift(anns, source), true); @@ -579,6 +635,7 @@ describe('checkDrift', () => { // keeps the context position that it was written with. assert.deepEqual(anns.get(5), { comment: 'moves', + endLine: 0, context: ['dup'], contextFrom: 5, outdated: true, @@ -591,8 +648,8 @@ describe('checkDrift', () => { test('a refused annotation moves when its target line is free again', () => { const anns = new Map([ - [5, { comment: 'moves', context: ['dup'], contextFrom: 5, outdated: false }], - [8, { comment: 'stays', context: ['dup'], contextFrom: 8, outdated: false }], + [5, { comment: 'moves', endLine: 0, context: ['dup'], contextFrom: 5, outdated: false }], + [8, { comment: 'stays', endLine: 0, context: ['dup'], contextFrom: 8, outdated: false }], ]); const source = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'dup', 'h']; checkDrift(anns, source); @@ -600,6 +657,7 @@ describe('checkDrift', () => { assert.equal(checkDrift(anns, source), true); assert.deepEqual(anns.get(8), { comment: 'moves', + endLine: 0, context: ['dup'], contextFrom: 8, outdated: false, @@ -610,8 +668,8 @@ describe('checkDrift', () => { // One line inserted at the top moves both comments down by one, so each // lands on the line the other is leaving. const anns = new Map([ - [1, { comment: 'first', context: ['one'], contextFrom: 1, outdated: false }], - [2, { comment: 'second', context: ['two'], contextFrom: 2, outdated: false }], + [1, { comment: 'first', endLine: 0, context: ['one'], contextFrom: 1, outdated: false }], + [2, { comment: 'second', endLine: 0, context: ['two'], contextFrom: 2, outdated: false }], ]); assert.equal(checkDrift(anns, ['inserted', 'one', 'two']), true); assert.equal(anns.size, 2); @@ -624,9 +682,9 @@ describe('checkDrift', () => { // the target of 'second', so 'second' stays on line 2, which is the target // of 'first'. No annotation moves, and all three stay. const anns = new Map([ - [1, { comment: 'first', context: ['aa'], contextFrom: 1, outdated: false }], - [2, { comment: 'second', context: ['bb'], contextFrom: 2, outdated: false }], - [3, { comment: 'third', context: ['bb'], contextFrom: 3, outdated: false }], + [1, { comment: 'first', endLine: 0, context: ['aa'], contextFrom: 1, outdated: false }], + [2, { comment: 'second', endLine: 0, context: ['bb'], contextFrom: 2, outdated: false }], + [3, { comment: 'third', endLine: 0, context: ['bb'], contextFrom: 3, outdated: false }], ]); checkDrift(anns, ['w', 'aa', 'bb', 'cc']); assert.deepEqual( diff --git a/orchestrator/src/review/store.ts b/orchestrator/src/review/store.ts index dd55420..24adbaf 100644 --- a/orchestrator/src/review/store.ts +++ b/orchestrator/src/review/store.ts @@ -21,6 +21,8 @@ const CONTEXT_MARKER = 'context'; export interface Annotation { /** The comment of the reviewer, trimmed. */ comment: string; + /** The last line of a comment on a block of lines, or 0 for a comment on one line. */ + endLine: number; /** The stored context lines, without their line-number prefix. */ context: string[]; /** The first line number of the context block, or 0 when none is stored. */ @@ -42,8 +44,8 @@ export interface Review { /** Matches a file section heading, which holds the path in backticks. */ const FILE_HEADER = /^## `(.+)`$/; -/** Matches an annotation heading with its line number and an optional marker. */ -const LINE_HEADER = /^#### Line (\d+)(.*)$/; +/** Matches an annotation heading with its line number, an optional last line of a block and an optional marker. */ +const LINE_HEADER = /^#### Line (\d+)(?: to (\d+))?(.*)$/; /** Matches one numbered source line of a context block. */ const CONTEXT_LINE = /^(\d+):(?: (.*))?$/; /** Matches the line that records the date the review was started. */ @@ -93,6 +95,7 @@ export function parseReview(text: string): Review { let started = ''; let currentFile = ''; let currentLine = 0; + let currentEnd = 0; let outdated = false; let body: string[] = []; let collecting = false; @@ -104,7 +107,9 @@ export function parseReview(text: string): Review { const { comment, context, contextFrom } = splitBody(body, marked); if (comment !== '' && currentFile !== '') { const forFile = data.get(currentFile); - if (forFile) forFile.set(currentLine, { comment, context, contextFrom, outdated }); + if (forFile) { + forFile.set(currentLine, { comment, endLine: currentEnd, context, contextFrom, outdated }); + } } body = []; collecting = false; @@ -128,7 +133,8 @@ export function parseReview(text: string): Review { if (lineHeader && currentFile !== '') { save(); currentLine = Number(lineHeader[1]); - outdated = (lineHeader[2] ?? '').includes('outdated'); + currentEnd = blockEnd(currentLine, Number(lineHeader[2] ?? 0)); + outdated = (lineHeader[3] ?? '').includes('outdated'); collecting = true; continue; } @@ -360,9 +366,8 @@ export function serializeReview(review: Review): string { out.push('\n---\n\n', `## \`${path}\`\n`); for (const [lineNum, ann] of [...lines].sort((a, b) => a[0] - b[0])) { - out.push( - ann.outdated ? `\n#### Line ${lineNum} (outdated)\n\n` : `\n#### Line ${lineNum}\n\n`, - ); + const range = ann.endLine > 0 ? ` to ${ann.endLine}` : ''; + out.push(`\n#### Line ${lineNum}${range}${ann.outdated ? ' (outdated)' : ''}\n\n`); const { text, openFence } = escapeComment(ann.comment); out.push(text); if (ann.context.length > 0) { @@ -534,27 +539,40 @@ export function todayStamp(now: Date = new Date()): string { } /** - * Gives the lines around a line. + * Gives the last line of a block for an annotation. A block that ends on its first line is one line. + * + * @param line The first line of the block. + * @param endLine The last line of the block, or 0 for one line. + * @returns The last line, or 0 for a block of one line. + */ +export function blockEnd(line: number, endLine: number): number { + return endLine > line ? endLine : 0; +} + +/** + * Gives the lines around a line or a block of lines. * * @param lines The lines of the file. * @param lineNum The line number, starting at 1. * @param radius The number of lines above and below. + * @param endLine The last line of a block, or 0 for one line. The lines of the block are part of the context. * @returns The lines and the line number of the first line. A line out of range gives no lines and 0. */ export function contextAround( lines: string[], lineNum: number, radius: number = CONTEXT_RADIUS, + endLine = 0, ): { context: string[]; from: number } { if (lineNum < 1 || lineNum > lines.length) return { context: [], from: 0 }; const start = Math.max(lineNum - radius, 1); - const end = Math.min(lineNum + radius, lines.length); + const end = Math.min(Math.max(lineNum, endLine) + radius, lines.length); return { context: lines.slice(start - 1, end), from: start }; } /** - * Adds or replaces the comment on one line of one file. The annotation stores - * the source lines around the line, so the drift check can follow the code + * Adds or replaces the comment on one line or one block of lines of one file. The annotation stores + * the source lines around the line or the block, so the drift check can follow the code * when it moves. * * @param review The review to change. @@ -562,6 +580,7 @@ export function contextAround( * @param line The line number, starting at 1. * @param comment The comment. * @param sourceLines The current lines of the file, or null for an annotation without context. + * @param endLine The last line of a block, or 0 for a comment on one line. */ export function setAnnotation( review: Review, @@ -569,6 +588,7 @@ export function setAnnotation( line: number, comment: string, sourceLines: string[] | null, + endLine = 0, ): void { let lines = review.data.get(file); if (!lines) { @@ -577,12 +597,13 @@ export function setAnnotation( } const ann: Annotation = { comment: comment.trim(), + endLine: blockEnd(line, endLine), context: [], contextFrom: 0, outdated: false, }; if (sourceLines) { - const { context, from } = contextAround(sourceLines, line, CONTEXT_RADIUS); + const { context, from } = contextAround(sourceLines, line, CONTEXT_RADIUS, ann.endLine); ann.context = context; ann.contextFrom = from; } @@ -663,7 +684,7 @@ export function checkDrift( for (const [lineNum, ann] of annotations) { if (ann.context.length === 0) { // Without stored context, the annotation takes the context of the current source. - const { context, from } = contextAround(sourceLines, lineNum, CONTEXT_RADIUS); + const { context, from } = contextAround(sourceLines, lineNum, CONTEXT_RADIUS, ann.endLine); if (context.length > 0) { ann.context = context; ann.contextFrom = from; @@ -739,6 +760,7 @@ function relocate(annotations: Map, relocations: Relocation[ let changed = moves.size > 0; for (const r of relocations) { if (moves.has(r.oldLine)) { + if (r.ann.endLine > 0) r.ann.endLine += r.newLine - r.oldLine; r.ann.contextFrom = r.newFrom; r.ann.outdated = false; } else if (!r.ann.outdated) { diff --git a/shared/types.ts b/shared/types.ts index cbadde5..83a1ba9 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -973,10 +973,12 @@ export interface ReviewDirResponse extends ReviewFacts { truncated: boolean; } -/** One comment on one line, as the API reports it. */ +/** One comment on one line or one block of lines, as the API reports it. */ export interface ReviewAnnotation { - /** The line the comment is on, counted from 1. */ + /** The line the comment is on, counted from 1. For a block, its first line. */ line: number; + /** The last line of a block, or 0 for a comment on one line. */ + endLine: number; /** The text of the comment. */ comment: string; /** True when the code that the comment was written for is gone. */ @@ -1066,8 +1068,10 @@ export interface ReviewAnnotationsResponse { export interface ReviewAnnotationBody { /** The path of the file, relative to the workspace. */ path: string; - /** The line to comment on. */ + /** The line to comment on. For a block, its first line. */ line: number; + /** The last line of a block, or 0 or absent for a comment on one line. */ + endLine?: number; /** The text of the comment. */ comment: string; }