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
46 changes: 46 additions & 0 deletions dashboard/e2e/ux.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,52 @@ test('a mermaid block shows its source while streaming, then a diagram that open
}
});

// A code block gets syntax colours once the message is complete. A block in a
// language without a grammar stays plain.
test('a code block shows plain text while streaming, then syntax colours', async () => {
const code = '```ts\nconst answer: number = 42;\n```';
const plain = '```klingon\nqaplah\n```';
await start({
prompts: [
{
match: () => true,
updates: reply(`here it is\n\n${code}\n\nand another\n\n${plain}\n`),
hold: true,
},
],
});

const { page, errors, close } = await openPage(
stub.url,
`/boxes/${BOX.id}/threads/${BOX.threadId}`,
);
try {
const input = page.getByLabel('Message input');
await input.fill('show me code');
await input.press('Control+Enter');

const block = page.locator('.aui-md-pre code').first();
await expect
.poll(() => block.textContent(), { timeout: 10_000 })
.toBe('const answer: number = 42;\n');
expect(await block.locator('span').count()).toBe(0);

stub.gateway.release();
await expect.poll(() => block.locator('span').count(), { timeout: 10_000 }).toBeGreaterThan(1);
// The text stays the same, and a keyword gets a colour of its own.
expect(await block.textContent()).toBe('const answer: number = 42;\n');
const colours = await block
.locator('span')
.evaluateAll((spans) => new Set(spans.map((span) => getComputedStyle(span).color)).size);
expect(colours).toBeGreaterThan(1);
expect(await page.locator('.aui-md-pre code').last().locator('span').count()).toBe(0);
await shoot(page, 'code-block-phone');
expect(errors).toEqual([]);
} finally {
await close();
}
});

test('the mode switcher lists the advertised modes and sets one', async () => {
await start({
modes: {
Expand Down
72 changes: 72 additions & 0 deletions dashboard/src/components/assistant-ui/elements/code-highlight.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"use client";

import { type CSSProperties, type FC, Fragment, useEffect, useState } from "react";
import { useAuiState } from "@assistant-ui/react";
import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown";

import { type Token, tokenizeLines } from "@/lib/highlight";

/**
* Shows a code block with syntax colouring.
*
* While the message is still streaming, the block shows plain text, so a
* growing block is not tokenized again for each change. The block also stays
* plain when no grammar exists for its language, or when the code is too long
* to tokenize.
*
* @param code The code of the block.
* @param language The language from the info string of the code fence.
* @param components The Pre and Code components that show the code.
*/
export const CodeHighlight: FC<SyntaxHighlighterProps> = ({
code,
language,
components: { Pre, Code },
}) => {
const streaming = useAuiState((s) => s.part.status.type === "running");
const [result, setResult] = useState<{
code: string;
language: string;
lines: Token[][] | null;
}>();

useEffect(() => {
if (streaming) return;
let current = true;
tokenizeLines(code, language).then(
(lines) => current && setResult({ code, language, lines }),
);
return () => {
current = false;
};
}, [code, language, streaming]);

// A result for other code or another language is stale.
const lines =
result?.code === code && result.language === language
? result.lines
: null;

return (
// Pre renders again only for a new markdown node, so the key makes it show the colours.
<Pre key={lines ? "highlighted" : "plain"}>
<Code>
{lines
? lines.map((tokens, i) => (
// biome-ignore lint/suspicious/noArrayIndexKey: lines have no id, and the block is replaced whole
<Fragment key={i}>
{i > 0 && "\n"}
{tokens.map((token, j) => (
// The span carries both theme colours, and the stylesheet picks one.
// biome-ignore lint/suspicious/noArrayIndexKey: tokens have no id, and a line is replaced whole
<span key={j} style={token.style as CSSProperties}>
{token.content}
</span>
))}
</Fragment>
))
: code}
</Code>
</Pre>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { useParams } from "react-router";
import type { TextMessagePartProps } from "@assistant-ui/react";
import { CheckIcon, CopyIcon } from "lucide-react";

import { CodeHighlight } from "@/components/assistant-ui/elements/code-highlight";
import { ImageZoom } from "@/components/assistant-ui/elements/image";
import { MermaidDiagram } from "@/components/assistant-ui/elements/mermaid-diagram";
import { TooltipIconButton } from "@/components/assistant-ui/elements/tooltip-icon-button";
Expand Down Expand Up @@ -379,4 +380,6 @@ const defaultComponents = memoizeMarkdownComponents({
);
},
CodeHeader,
// Boxes edit: colours the code of a block with the highlighter of the review.
SyntaxHighlighter: CodeHighlight,
});
11 changes: 7 additions & 4 deletions dashboard/src/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,17 @@
);

/*
* The review's code pane. Shiki puts the light and the dark colour of each
* token on its span as custom properties, and these rules pick one.
* The review's code pane and the code blocks in chat output. Shiki puts the
* light and the dark colour of each token on its span as custom properties,
* and these rules pick one.
*/
[data-line] code span {
[data-line] code span,
.aui-md-pre code span {
color: var(--shiki-light);
}

.dark [data-line] code span {
.dark [data-line] code span,
.dark .aui-md-pre code span {
color: var(--shiki-dark);
}

Expand Down
16 changes: 16 additions & 0 deletions dashboard/src/lib/highlight.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { tokenizeLines } from './highlight.ts';

test('an alias from a code fence selects the grammar of its language', async () => {
const lines = await tokenizeLines('const a = 1;\nlet b = 2;', 'TS');
assert.ok(lines);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.map((token) => token.content).join(''), 'const a = 1;');
assert.ok(lines[0]?.some((token) => token.style['--shiki-light'] && token.style['--shiki-dark']));
});

test('a language without a grammar stays plain', async () => {
assert.equal(await tokenizeLines('anything', 'klingon'), null);
assert.equal(await tokenizeLines('anything', ''), null);
});
62 changes: 47 additions & 15 deletions dashboard/src/lib/highlight.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/**
* Client-side syntax highlighting for the review's code pane.
* Client-side syntax highlighting for the review's code pane and for the code
* blocks in chat output.
*
* The API sends plain text, so each line can be its own row. The engine, the
* themes and the grammars are imported lazily, so only the review route loads
* them.
* The text is tokenized into one token list per line, so each line can be its
* own row. The engine, the themes and the grammars are imported lazily, so only
* a view that shows code loads them.
*/

import type { HighlighterCore, LanguageInput, ThemedToken } from 'shiki/core';
Expand All @@ -23,10 +24,12 @@ export interface Token {
style: Record<string, string>;
}

/** The grammars that the code pane can load, by the language name that the API reports. */
/** The grammars that can be loaded, by language name. */
const GRAMMARS: Record<string, LanguageInput> = {
typescript: () => import('@shikijs/langs/typescript'),
tsx: () => import('@shikijs/langs/tsx'),
javascript: () => import('@shikijs/langs/javascript'),
jsx: () => import('@shikijs/langs/jsx'),
json: () => import('@shikijs/langs/json'),
css: () => import('@shikijs/langs/css'),
scss: () => import('@shikijs/langs/scss'),
Expand Down Expand Up @@ -61,14 +64,42 @@ const GRAMMARS: Record<string, LanguageInput> = {
diff: () => import('@shikijs/langs/diff'),
};

/** Other names of the languages in {@link GRAMMARS}, as the info string of a markdown code fence often gives them. */
const ALIASES: Record<string, string> = {
ts: 'typescript',
mts: 'typescript',
cts: 'typescript',
js: 'javascript',
mjs: 'javascript',
cjs: 'javascript',
sh: 'bash',
shell: 'bash',
zsh: 'bash',
py: 'python',
yml: 'yaml',
md: 'markdown',
dockerfile: 'docker',
make: 'makefile',
golang: 'go',
rb: 'ruby',
rs: 'rust',
'c++': 'cpp',
cs: 'csharp',
kt: 'kotlin',
htm: 'html',
patch: 'diff',
};

/**
* Checks if a language has a grammar to load.
* Gives the name of the grammar for a language name or an alias.
*
* @param language The language name that the API reports.
* @returns True when a grammar exists.
* @param language A language name that the API reports, or an alias of one.
* @returns The key in {@link GRAMMARS}, or null when no grammar exists.
*/
function canHighlight(language: string): boolean {
return language in GRAMMARS;
function grammarName(language: string): string | null {
const name = language.toLowerCase();
const resolved = ALIASES[name] ?? name;
return resolved in GRAMMARS ? resolved : null;
}

/** The shared highlighter, once {@link highlighter} has started creating it. */
Expand Down Expand Up @@ -109,7 +140,7 @@ const loaded = new Map<string, Promise<void>>();
/**
* Loads one grammar into the shared highlighter, at most once.
*
* @param language The language name that the API reports.
* @param language A key in {@link GRAMMARS}.
*/
async function loadGrammar(language: string): Promise<void> {
const grammar = GRAMMARS[language];
Expand Down Expand Up @@ -163,19 +194,20 @@ export function withinLineLimit(content: string): boolean {
* failure in the grammar.
*
* @param content The text of the file.
* @param language The language name that the API reports.
* @param language The language name that the API reports, or an alias of one.
* @returns One token list per line, or null for a plain file.
*/
export async function tokenizeLines(content: string, language: string): Promise<Token[][] | null> {
if (!canHighlight(language)) return null;
const grammar = grammarName(language);
if (!grammar) return null;
if (!withinLineLimit(content)) return null;
if (content.split('\n').some((line) => line.length > MAX_LINE)) return null;

try {
await loadGrammar(language);
await loadGrammar(grammar);
const core = await highlighter();
const { tokens } = core.codeToTokens(content, {
lang: language,
lang: grammar,
themes: THEMES,
// No default colour, so the page's .dark class picks the theme.
defaultColor: false,
Expand Down