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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions dashboard/e2e/review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,101 @@ test('a text file opens in a tab of its own from the toolbar', async () => {
}
});

test('a markdown file shows rendered, with its images and diagrams', async () => {
const base = reviewWorkspace();
stub.review(
BOX,
reviewWorkspace({
files: {
...base.files,
'app/doc/guide.md':
'# Guide\n\n![a chart](../img/chart.svg)\n\n```mermaid\nflowchart LR\n A --> B\n```\n',
'app/img/chart.svg':
'<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20"/></svg>',
},
}),
);
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);

// A relative path starts from the directory of the file.
const image = page.getByAltText('a chart');
await expect.poll(() => image.isVisible()).toBe(true);
expect(await image.getAttribute('src')).toContain('path=%2Fworkspace%2Fapp%2Fimg%2Fchart.svg');
expect(await image.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(40);
await image.click();
const zoomed = page.locator('[data-slot="image-zoom-content"]');
await expect.poll(() => zoomed.isVisible()).toBe(true);
await page.keyboard.press('Escape');
await expect.poll(() => zoomed.count()).toBe(0);

await expect.poll(() => page.locator('.aui-md-mermaid img').isVisible()).toBe(true);
await shoot(page, 'review-markdown-desktop');

await page.getByRole('button', { name: 'Show the source' }).click();
await expect.poll(() => page.getByText('# Guide').isVisible()).toBe(true);

// Edit mode leaves the preview and hides its button.
await page.getByRole('button', { name: 'Show the rendered file' }).click();
await page.getByRole('button', { name: 'Edit this file' }).click();
await expect.poll(() => page.getByRole('textbox').isVisible()).toBe(true);
expect(await page.getByRole('button', { name: 'Show the rendered file' }).count()).toBe(0);
expect(errors).toEqual([]);
} finally {
await close();
}
});

test('an image opens in the lightbox from the toolbar', async () => {
const base = reviewWorkspace();
stub.review(
BOX,
reviewWorkspace({
files: {
...base.files,
'notes/chart.svg':
'<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20"/></svg>',
},
}),
);
const { page, errors, close } = await openPage(
stub.url,
`/boxes/${BOX}/review?path=notes%2Fchart.svg`,
'dark',
'desktop',
);
try {
await expect.poll(() => page.getByText('<svg').isVisible()).toBe(true);
await page.getByTitle('Show the image').click();
const zoomed = page.locator('[data-slot="image-zoom-content"]');
await expect.poll(() => zoomed.isVisible()).toBe(true);
expect(await zoomed.getAttribute('src')).toMatch(
/\/files\/raw\?path=%2Fworkspace%2Fnotes%2Fchart\.svg&view=\d+$/,
);
expect(await zoomed.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBe(40);
await page.keyboard.press('Escape');
await expect.poll(() => zoomed.count()).toBe(0);

// A file of another type has no preview.
await page.getByRole('button', { name: /^notes/ }).click();
await page.getByRole('button', { name: /todo\.txt/ }).click();
await expect.poll(() => page.getByText('plain text, no grammar').isVisible()).toBe(true);
expect(await page.getByTitle('Show the image').count()).toBe(0);
expect(await page.getByRole('button', { name: 'Show the rendered file' }).count()).toBe(0);
expect(errors).toEqual([]);
} finally {
await close();
}
});

test('a file past the line limit is one plain block with nothing to tap', async () => {
// Long enough that a row per line gives tens of thousands of elements, which
// freezes a phone. One line changed, so the toolbar has something to count.
Expand Down
16 changes: 10 additions & 6 deletions dashboard/src/components/assistant-ui/elements/markdown-text.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { filePath, fileUrl } from "@/lib/files";
import { cn } from "@/lib/utils";

/** The props of {@link MarkdownText}: the text part props and extra markdown components. */
/** The props of {@link MarkdownText}: the text part props, extra markdown components and the base directory. */
type MarkdownTextProps = Partial<TextMessagePartProps> & {
/** Components that replace the default components for some elements. */
components?: Parameters<typeof memoizeMarkdownComponents>[0];
/** Boxes edit: the absolute directory in the box where a relative path starts. The default is the workspace. */
baseDir?: string;
};

/**
Expand Down Expand Up @@ -57,16 +59,17 @@ const useShallowStable = <T extends Record<string, unknown> | undefined>(
* file in the box loads the file from the box.
*
* @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.
*/
const MarkdownTextImpl: FC<MarkdownTextProps> = ({ components }) => {
const MarkdownTextImpl: FC<MarkdownTextProps> = ({ components, baseDir }) => {
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
// own, and the browser loads the files again.
const [view] = useState(() => ++views);
const urlTransform = useMemo(
() => urlTransformFor(boxId, view),
[boxId, view],
() => urlTransformFor(boxId, view, baseDir),
[boxId, view, baseDir],
);
const stableComponents = useShallowStable(components);
const markdownComponents = useMemo(() => {
Expand Down Expand Up @@ -104,13 +107,14 @@ let views = 0;
*
* @param boxId The id of the box, or undefined outside the view of a box.
* @param view The number of the view of the message, for the file URLs.
* @param baseDir The absolute directory in the box where a relative path starts, or undefined for the workspace.
* @returns The filter.
*/
const urlTransformFor =
(boxId: string | undefined, view: number): UrlTransform =>
(boxId: string | undefined, view: number, baseDir?: string): UrlTransform =>
(url, key) => {
if (key === "src" && /^data:image\//i.test(url)) return url;
const path = boxId && filePath(url);
const path = boxId && filePath(url, baseDir);
return path ? fileUrl(boxId, path, view) : defaultUrlTransform(url);
};

Expand Down
32 changes: 32 additions & 0 deletions dashboard/src/components/review/MarkdownPreview.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { TextMessagePartProvider } from '@assistant-ui/react';
import { MarkdownText } from '@/components/assistant-ui/elements/markdown-text';
import { WORKSPACE_DIR } from '@/lib/files';

/**
* 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.
*/
export function MarkdownPreview({
path,
content,
}: {
/** The workspace-relative path of the file. */
path: string;
/** The markdown text. */
content: string;
}) {
// A relative path in the file starts from the directory of the file.
const baseDir = `${WORKSPACE_DIR}/${path}`.replace(/\/[^/]*$/, '');
return (
// The container lets a wide table or code block grow to the width of the pane.
<div data-slot="review-preview" className="@container min-h-0 flex-1 overflow-auto">
<div className="mx-auto w-full max-w-[44rem] px-4 py-4">
<TextMessagePartProvider text={content}>
<MarkdownText baseDir={baseDir} />
</TextMessagePartProvider>
</div>
</div>
);
}
44 changes: 43 additions & 1 deletion dashboard/src/components/review/ReviewToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import {
ChevronDown,
ChevronUp,
ExternalLink,
Eye,
GitCompare,
MessageSquare,
Pencil,
Undo2,
WrapText,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ImageZoom } from '@/components/assistant-ui/elements/image';
import { Button, buttonVariants } from '@/components/ui/button';
import { cn } from '@/lib/utils';

/**
Expand All @@ -26,12 +28,16 @@ import { cn } from '@/lib/utils';
* @param dirty True when there are unsaved changes.
* @param busy True while a write is in flight.
* @param openHref The URL that serves the bytes of the file, or null for a file with none.
* @param preview The kind of preview of the file, or null when the file has none or the pane is in edit mode.
* @param previewing True while the pane shows the rendered markdown.
* @param imageSrc The URL of the image for the lightbox.
* @param onWrap Called when the user toggles wrapping.
* @param onStepChange Called with -1 for the previous change or 1 for the next.
* @param onStepComment Called with -1 for the previous comment or 1 for the next.
* @param onEdit Called when the user switches edit mode on or off.
* @param onSave Called when the user saves the file.
* @param onRevert Called when the user discards the unsaved changes.
* @param onPreview Called when the user switches the markdown preview on or off.
*/
export function ReviewToolbar({
changeCount,
Expand All @@ -43,12 +49,16 @@ export function ReviewToolbar({
dirty,
busy,
openHref,
preview,
previewing,
imageSrc,
onWrap,
onStepChange,
onStepComment,
onEdit,
onSave,
onRevert,
onPreview,
}: {
/** The number of changes in the file. */
changeCount: number;
Expand All @@ -68,6 +78,12 @@ export function ReviewToolbar({
busy: boolean;
/** The URL that serves the bytes of the file, or null for a file with none. */
openHref: string | null;
/** The kind of preview of the file, or null when the file has none or the pane is in edit mode. */
preview: 'image' | 'markdown' | null;
/** True while the pane shows the rendered markdown. */
previewing: boolean;
/** The URL of the image for the lightbox. */
imageSrc: string;
/** Called when the user toggles wrapping. */
onWrap: () => void;
/** Called with -1 for the previous change or 1 for the next. */
Expand All @@ -80,6 +96,8 @@ export function ReviewToolbar({
onSave: () => void;
/** Called when the user discards the unsaved changes. */
onRevert: () => void;
/** Called when the user switches the markdown preview on or off. */
onPreview: () => void;
}) {
return (
<div className="flex shrink-0 items-center gap-1 border-b px-2 py-1 text-xs">
Expand All @@ -100,6 +118,30 @@ export function ReviewToolbar({
/>
<span className="flex-1" />

{preview === 'image' ? (
<ImageZoom src={imageSrc} alt="" inline>
<span
className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}
title="Show the image"
>
<Eye />
</span>
</ImageZoom>
) : preview === 'markdown' ? (
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-pressed={previewing}
onClick={onPreview}
title={previewing ? 'Show the source' : 'Show the rendered file'}
aria-label={previewing ? 'Show the source' : 'Show the rendered file'}
className={cn(previewing && 'bg-accent text-accent-foreground')}
>
<Eye />
</Button>
) : null}

{/* A plain link, so the browser handles the file by its type. */}
{openHref ? (
<Button asChild variant="ghost" size="icon-sm">
Expand Down
26 changes: 25 additions & 1 deletion dashboard/src/lib/files.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { filePath, fileUrl, workspaceFileUrl } from './files.ts';
import { filePath, fileUrl, previewKind, workspaceFileUrl } from './files.ts';

test('a file is fetched by its path in the box, from its box', () => {
assert.equal(
Expand Down Expand Up @@ -28,6 +28,30 @@ test('an absolute path and a relative path name a file in the box', () => {
assert.equal(filePath('notes.md#usage'), '/workspace/notes.md');
});

test('a relative path starts from the base directory, and dot parts are resolved', () => {
assert.equal(
filePath('img/chart.png', '/workspace/repo/doc'),
'/workspace/repo/doc/img/chart.png',
);
assert.equal(
filePath('../img/chart.png', '/workspace/repo/doc'),
'/workspace/repo/img/chart.png',
);
assert.equal(filePath('/tmp/chart.png', '/workspace/repo/doc'), '/tmp/chart.png');
assert.equal(filePath('docs/./a//b.png'), '/workspace/docs/a/b.png');
assert.equal(filePath('../../../chart.png'), '/chart.png');
});

test('images and markdown files have a preview', () => {
assert.equal(previewKind('doc/chart.PNG'), 'image');
assert.equal(previewKind('logo.svg'), 'image');
assert.equal(previewKind('README.md'), 'markdown');
assert.equal(previewKind('notes.markdown'), 'markdown');
assert.equal(previewKind('main.ts'), null);
assert.equal(previewKind('Makefile'), null);
assert.equal(previewKind('.md/notes'), null);
});

test('a URL with a scheme, or without a path, names no file', () => {
for (const url of [
'https://example.com/chart.png',
Expand Down
Loading
Loading