refactor(webui): unify code and diff highlighting (#6412)
* refactor(webui): unify code and diff highlighting Replace Prism with shared Highlights tokens and Pierre read-only diffs, retaining rare grammars through lazy Shiki and preserving source, copy, preview and diff controls. Restore single-session Composer ownership inside the conversation column while retaining the shared multi-pane footer. Keep the measured large-diff scroll regression explicit during review. * fix(webui): contain highlighting errors and retain diff selections Refs NAN-343 * test(webui): align pane fixtures after main rebase * chore(webui): update highlighting dependencies Keep grammar fallback coverage on a language that still requires Shiki, and align reading-size assertions with main.
This commit is contained in:
1 parent
f5c359476b
commit
3a37269f3f
44 files changed
+2261
-1072
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { Suspense, lazy, memo, startTransition, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Component, Suspense, lazy, memo, startTransition, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useThemeValue } from "@/hooks/useTheme";
|
||||
import { hasAnsi, parseAnsiSegments, stripAnsi } from "@/lib/ansi";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { normalizeCodeLanguage } from "@/lib/code-language";
|
||||
import { discardCodeHighlight } from "@/lib/code-highlight-cache";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface CodeBlockProps {
|
||||
@@ -20,82 +21,41 @@ interface CodeBlockProps {
|
||||
viewportHighlight?: boolean;
|
||||
}
|
||||
|
||||
interface HighlightedCodeProps {
|
||||
language?: string;
|
||||
code: string;
|
||||
chrome: "default" | "none";
|
||||
showLineNumbers: boolean;
|
||||
wrapLongLines: boolean;
|
||||
viewportHighlight: boolean;
|
||||
}
|
||||
|
||||
const ANSI_LANGUAGES = new Set(["ansi", "ansi-output"]);
|
||||
|
||||
const LazyHighlightedCode = lazy(async () => {
|
||||
const [
|
||||
{ default: SyntaxHighlighter },
|
||||
{ ViewportCodeRows },
|
||||
{ WrappedCodeRows },
|
||||
] = await Promise.all([
|
||||
import("react-syntax-highlighter/dist/esm/prism-async-light"),
|
||||
import("@/components/ViewportCodeRows"),
|
||||
import("@/components/WrappedCodeRows"),
|
||||
]);
|
||||
|
||||
return {
|
||||
default({
|
||||
language,
|
||||
code,
|
||||
chrome,
|
||||
showLineNumbers,
|
||||
wrapLongLines,
|
||||
viewportHighlight,
|
||||
}: HighlightedCodeProps) {
|
||||
return (
|
||||
<SyntaxHighlighter
|
||||
language={language || "text"}
|
||||
useInlineStyles={false}
|
||||
style={{}}
|
||||
customStyle={{
|
||||
background: "transparent",
|
||||
margin: 0,
|
||||
padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
|
||||
fontFamily: "inherit",
|
||||
fontSize: "inherit",
|
||||
lineHeight: "inherit",
|
||||
tabSize: 2,
|
||||
// FilePreviewPanel owns both scroll axes. Replacing this <pre>
|
||||
// during progressive highlighting must not reset horizontal scroll.
|
||||
...(viewportHighlight ? { overflow: "visible" } : {}),
|
||||
}}
|
||||
codeTagProps={{
|
||||
style: {
|
||||
background: "transparent",
|
||||
fontFamily: "inherit",
|
||||
fontSize: "inherit",
|
||||
...(viewportHighlight ? { lineHeight: "inherit" } : {}),
|
||||
},
|
||||
}}
|
||||
lineNumberStyle={{
|
||||
minWidth: "2.6em",
|
||||
paddingRight: "1.15rem",
|
||||
color: "var(--code-comment)",
|
||||
fontFamily: "inherit",
|
||||
userSelect: "none",
|
||||
}}
|
||||
PreTag="pre"
|
||||
showLineNumbers={showLineNumbers && !viewportHighlight}
|
||||
wrapLongLines={wrapLongLines}
|
||||
renderer={viewportHighlight ? props => <ViewportCodeRows {...props} />
|
||||
: showLineNumbers && wrapLongLines ? props => <WrappedCodeRows {...props} /> : undefined}
|
||||
>
|
||||
{code}
|
||||
</SyntaxHighlighter>
|
||||
);
|
||||
},
|
||||
};
|
||||
const { HighlightedCode } = await import("./HighlightedCode");
|
||||
return { default: HighlightedCode };
|
||||
});
|
||||
|
||||
class CodeHighlightBoundary extends Component<{
|
||||
code: string;
|
||||
language: string;
|
||||
fallback: ReactNode;
|
||||
children: ReactNode;
|
||||
}, { failed: boolean }> {
|
||||
state = { failed: false };
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { failed: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error) {
|
||||
discardCodeHighlight(this.props.code, this.props.language);
|
||||
console.warn("Code highlighting failed.", error);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: Readonly<{ code: string; language: string }>) {
|
||||
if (this.state.failed && (previous.code !== this.props.code || previous.language !== this.props.language)) {
|
||||
this.setState({ failed: false });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.state.failed ? this.props.fallback : this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function renderPlainText(value: string): ReactNode {
|
||||
return value;
|
||||
}
|
||||
@@ -188,7 +148,7 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
const hasChrome = chrome === "default";
|
||||
const syntaxLanguage = normalizeCodeLanguage(language);
|
||||
const useViewportHighlight = viewportHighlight && showLineNumbers && !wrapLongLines;
|
||||
// Minified/very large previews must not monopolize the main thread in Prism.
|
||||
// Minified/very large previews must not monopolize the main thread during highlighting.
|
||||
// Plain text still contains the entire preview, with normal selection and find.
|
||||
const withinHighlightBudget = useMemo(() => {
|
||||
if (!useViewportHighlight) return true;
|
||||
@@ -226,6 +186,8 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
};
|
||||
}, [code, deferHighlight]);
|
||||
const copyLabel = copied ? t("code.copied") : t("code.copyAria");
|
||||
const plainBlock = <CodeTextBlock code={code} chrome={chrome} showLineNumbers={showLineNumbers}
|
||||
testId="plain-code-fallback" compact={useViewportHighlight} />;
|
||||
|
||||
const onCopy = useCallback(() => {
|
||||
void copyTextToClipboard(plainCode).then((ok) => {
|
||||
@@ -256,35 +218,19 @@ export const CodeBlock = memo(function CodeBlock({
|
||||
compact={useViewportHighlight}
|
||||
/>
|
||||
) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
|
||||
<Suspense
|
||||
fallback={
|
||||
<CodeTextBlock
|
||||
<CodeHighlightBoundary code={code} language={syntaxLanguage} fallback={plainBlock}>
|
||||
<Suspense fallback={plainBlock}>
|
||||
<LazyHighlightedCode
|
||||
language={syntaxLanguage}
|
||||
code={code}
|
||||
chrome={chrome}
|
||||
showLineNumbers={showLineNumbers}
|
||||
testId="plain-code-fallback"
|
||||
compact={useViewportHighlight}
|
||||
wrapLongLines={wrapLongLines}
|
||||
viewportHighlight={useViewportHighlight}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<LazyHighlightedCode
|
||||
language={syntaxLanguage}
|
||||
code={code}
|
||||
chrome={chrome}
|
||||
showLineNumbers={showLineNumbers}
|
||||
wrapLongLines={wrapLongLines}
|
||||
viewportHighlight={useViewportHighlight}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<CodeTextBlock
|
||||
code={code}
|
||||
chrome={chrome}
|
||||
showLineNumbers={showLineNumbers}
|
||||
testId="plain-code-fallback"
|
||||
compact={useViewportHighlight}
|
||||
/>
|
||||
)}
|
||||
</Suspense>
|
||||
</CodeHighlightBoundary>
|
||||
) : plainBlock}
|
||||
{hasChrome ? (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Fragment } from "react";
|
||||
|
||||
import type { CodeLine } from "@/lib/code-tokens";
|
||||
|
||||
export function CodeTokens({ lines }: { lines: CodeLine[] }) {
|
||||
return <>{lines.map((line, lineIndex) => <Fragment key={lineIndex}>
|
||||
{line.tokens.map((token, index) => token.color || token.fontStyle ? <span key={index} data-code-token="" style={{
|
||||
color: token.color,
|
||||
fontStyle: token.fontStyle && token.fontStyle & 1 ? "italic" : undefined,
|
||||
fontWeight: token.fontStyle && token.fontStyle & 2 ? 700 : undefined,
|
||||
textDecoration: token.fontStyle && token.fontStyle & 4 ? "underline" : undefined,
|
||||
}}>{token.content}</span> : token.content)}
|
||||
</Fragment>)}</>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { codeHighlight } from "@/lib/code-highlighter";
|
||||
import { CodeTokens } from "./CodeTokens";
|
||||
import { ViewportCodeRows } from "./ViewportCodeRows";
|
||||
|
||||
export interface HighlightedCodeProps {
|
||||
language?: string;
|
||||
code: string;
|
||||
chrome: "default" | "none";
|
||||
showLineNumbers: boolean;
|
||||
wrapLongLines: boolean;
|
||||
viewportHighlight: boolean;
|
||||
}
|
||||
|
||||
export function HighlightedCode({ language = "text", code, chrome, showLineNumbers, wrapLongLines, viewportHighlight }: HighlightedCodeProps) {
|
||||
const resource = useMemo(() => codeHighlight(code, language), [code, language]);
|
||||
const lines = resource.read();
|
||||
return <pre data-testid="highlighted-code" data-language={language} style={{
|
||||
background: "transparent", margin: 0,
|
||||
padding: viewportHighlight ? "0.75rem 1rem 0.75rem 0.5rem" : chrome === "none" ? "0.75rem 1rem" : "1rem 3.5rem 1rem 1.25rem",
|
||||
fontFamily: "inherit", fontSize: "inherit", lineHeight: "inherit", tabSize: 2,
|
||||
whiteSpace: wrapLongLines ? "pre-wrap" : "pre", overflow: viewportHighlight ? "visible" : "auto",
|
||||
overflowWrap: wrapLongLines ? "anywhere" : undefined,
|
||||
}}><code className="text-inherit">
|
||||
{viewportHighlight ? <ViewportCodeRows lines={lines} /> : showLineNumbers ? lines.map((line, index) => (
|
||||
<span key={index} className="flex">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground" style={{ minWidth: "2.6em" }}>{index + 1}</span>
|
||||
<span data-code-text="" className="min-w-0"><CodeTokens lines={[line]} /></span>
|
||||
</span>
|
||||
)) : <span data-code-text=""><CodeTokens lines={lines} /></span>}
|
||||
</code></pre>;
|
||||
}
|
||||
@@ -1,16 +1,10 @@
|
||||
import { memo, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
import createElement from "react-syntax-highlighter/dist/esm/create-element";
|
||||
|
||||
type RowsProps = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
|
||||
type Row = RowsProps["rows"][number];
|
||||
import type { CodeLine } from "@/lib/code-tokens";
|
||||
import { CodeTokens } from "./CodeTokens";
|
||||
const CHUNK_LINES = 40;
|
||||
|
||||
function textOf(node: Row): string {
|
||||
return node.type === "text" ? String(node.value ?? "") : (node.children ?? []).map(textOf).join("");
|
||||
}
|
||||
|
||||
const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useInlineStyles, highlighted, lineNumberWidth }: RowsProps & {
|
||||
const CodeChunk = memo(function CodeChunk({ lines, text, start, highlighted, lineNumberWidth }: {
|
||||
lines: CodeLine[];
|
||||
text: string;
|
||||
start: number;
|
||||
highlighted: boolean;
|
||||
@@ -20,33 +14,27 @@ const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useIn
|
||||
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
|
||||
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
|
||||
style={{ minWidth: lineNumberWidth }}>
|
||||
{rows.map((_, index) => start + index + 1).join("\n")}
|
||||
{lines.map((_, index) => start + index + 1).join("\n")}
|
||||
</span>
|
||||
<span data-highlighted={highlighted}>
|
||||
{highlighted ? rows.map((node, index) => createElement({
|
||||
node, stylesheet, useInlineStyles, key: start + index,
|
||||
})) : text}
|
||||
{highlighted ? <CodeTokens lines={lines} /> : text}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
/** Keep the complete source searchable/selectable; only offscreen token spans are omitted. */
|
||||
export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProps) {
|
||||
export function ViewportCodeRows({ lines }: { lines: CodeLine[] }) {
|
||||
const rootRef = useRef<HTMLSpanElement>(null);
|
||||
const [visible, setVisible] = useState(() => new Set([0]));
|
||||
// The inline renderer only matches token class combinations. Passing Prism's
|
||||
// unrelated toolbar/pseudo selectors makes it scan those again for every token.
|
||||
const tokenStyles = useMemo(() => Object.fromEntries(Object.entries(stylesheet)
|
||||
.filter(([selector]) => /^[\w-]+(?:\.[\w-]+)*$/.test(selector))), [stylesheet]);
|
||||
const chunks = useMemo(() => {
|
||||
const result = [];
|
||||
for (let start = 0; start < rows.length; start += CHUNK_LINES) {
|
||||
const chunk = rows.slice(start, start + CHUNK_LINES);
|
||||
result.push({ start, rows: chunk, text: chunk.map(textOf).join("") });
|
||||
for (let start = 0; start < lines.length; start += CHUNK_LINES) {
|
||||
const chunk = lines.slice(start, start + CHUNK_LINES);
|
||||
result.push({ start, lines: chunk, text: chunk.map(line => line.text).join("") });
|
||||
}
|
||||
return result;
|
||||
}, [rows]);
|
||||
}, [lines]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = rootRef.current;
|
||||
@@ -78,9 +66,8 @@ export function ViewportCodeRows({ rows, stylesheet, useInlineStyles }: RowsProp
|
||||
|
||||
return (
|
||||
<span ref={rootRef} className="block min-w-max" data-testid="viewport-code-rows">
|
||||
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk}
|
||||
stylesheet={tokenStyles} useInlineStyles={useInlineStyles} highlighted={visible.has(index)}
|
||||
lineNumberWidth={`calc(${String(rows.length).length}ch + 1.15rem)`} />)}
|
||||
{chunks.map((chunk, index) => <CodeChunk key={chunk.start} {...chunk} highlighted={visible.has(index)}
|
||||
lineNumberWidth={`calc(${String(lines.length).length}ch + 1.15rem)`} />)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
import createElement from "react-syntax-highlighter/dist/esm/create-element";
|
||||
|
||||
type RowsProps = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
|
||||
|
||||
export function WrappedCodeRows({ rows, ...props }: RowsProps) {
|
||||
return rows.map((row, index) => {
|
||||
const [lineNumber, ...content] = row.children!;
|
||||
return createElement({
|
||||
...props,
|
||||
key: index,
|
||||
node: {
|
||||
...row,
|
||||
children: [lineNumber, {
|
||||
type: "element",
|
||||
tagName: "span",
|
||||
properties: { className: ["min-w-0", "flex-1"] },
|
||||
children: content,
|
||||
}],
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { PromptRail } from "@/components/thread/PromptRail";
|
||||
import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
|
||||
import { DiagramScope } from "@/components/markdown-diagrams/context";
|
||||
import { DiffViewportContext } from "./activity/DiffViewportContext";
|
||||
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
|
||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||
@@ -306,6 +307,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const messageRegionRef = useRef<HTMLDivElement | null>(null);
|
||||
const messageContentRef = useRef<HTMLDivElement>(null);
|
||||
const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []);
|
||||
const emptyStateRef = useRef<HTMLDivElement>(null);
|
||||
const composerDockRef = useRef<HTMLDivElement>(null);
|
||||
const composerLayoutChangeRef = useRef(onComposerLayoutChange);
|
||||
@@ -1211,6 +1213,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
)}
|
||||
>
|
||||
<div ref={messageContentRef} className="w-full">
|
||||
<DiffViewportContext.Provider value={diffViewport}>
|
||||
<DiagramScope identity={conversationKey}>
|
||||
<SubagentThreadMessages
|
||||
key={messagesKey}
|
||||
@@ -1239,6 +1242,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
onActivityToggle={yieldCameraToUser}
|
||||
/>
|
||||
</DiagramScope>
|
||||
</DiffViewportContext.Provider>
|
||||
</div>
|
||||
<div aria-hidden className="thread-message-end-gap shrink-0" />
|
||||
<div ref={bottomRef} aria-hidden className="h-px shrink-0" />
|
||||
|
||||
@@ -1,187 +1,66 @@
|
||||
import { Suspense, lazy, type ReactNode } from "react";
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { RenderableFileDiffLine } from "@/lib/file-diff";
|
||||
import type { RenderableFileDiff, RenderableFileDiffLine } from "@/lib/file-diff";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface DiffSyntaxHighlightProps {
|
||||
export interface DiffSyntaxHighlightProps {
|
||||
language: string;
|
||||
lines: RenderableFileDiffLine[];
|
||||
text: string;
|
||||
diff: RenderableFileDiff;
|
||||
lineLimit: number;
|
||||
}
|
||||
|
||||
type RendererArgs = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
|
||||
type SyntaxNode = RendererArgs["rows"][number];
|
||||
|
||||
const LazyDiffSyntaxHighlight = lazy(async () => {
|
||||
const [
|
||||
{ default: SyntaxHighlighter },
|
||||
{ default: createSyntaxElement },
|
||||
] = await Promise.all([
|
||||
import("react-syntax-highlighter/dist/esm/prism-async-light"),
|
||||
import("react-syntax-highlighter/dist/esm/create-element"),
|
||||
]);
|
||||
return {
|
||||
default: function LoadedDiffSyntaxHighlight({
|
||||
language,
|
||||
lines,
|
||||
}: DiffSyntaxHighlightProps) {
|
||||
const code = lines.map((line) => line.content || " ").join("\n");
|
||||
return (
|
||||
<SyntaxHighlighter
|
||||
language={language}
|
||||
useInlineStyles={false}
|
||||
style={{}}
|
||||
PreTag="div"
|
||||
CodeTag="div"
|
||||
customStyle={{
|
||||
background: "transparent",
|
||||
margin: 0,
|
||||
padding: 0,
|
||||
overflow: "visible",
|
||||
fontFamily: "inherit",
|
||||
fontSize: "inherit",
|
||||
lineHeight: "inherit",
|
||||
}}
|
||||
codeTagProps={{
|
||||
style: {
|
||||
background: "transparent",
|
||||
fontFamily: "inherit",
|
||||
},
|
||||
}}
|
||||
data-language={language}
|
||||
className="code-content font-mono text-code-dense"
|
||||
data-testid="syntax-highlighted-diff-hunk"
|
||||
renderer={({ rows, stylesheet, useInlineStyles }) => (
|
||||
<DiffLineTable
|
||||
lines={lines}
|
||||
renderCode={(line, index) => {
|
||||
const node = rows[index];
|
||||
if (!node) return line.content || " ";
|
||||
return createSyntaxElement({
|
||||
node: stripConflictingTableClass(trimTrailingLineBreak(node)),
|
||||
stylesheet,
|
||||
useInlineStyles,
|
||||
key: `diff-code-${index}`,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
{code}
|
||||
</SyntaxHighlighter>
|
||||
);
|
||||
},
|
||||
};
|
||||
const renderer = await import("./PierreFileDiff");
|
||||
await renderer.prepareDiffRenderer();
|
||||
return { default: renderer.PierreFileDiff };
|
||||
});
|
||||
|
||||
export function DiffSyntaxHighlight({ language, lines }: DiffSyntaxHighlightProps) {
|
||||
export function DiffSyntaxHighlight(props: DiffSyntaxHighlightProps) {
|
||||
return (
|
||||
<Suspense fallback={<PlainDiffLines lines={lines} />}>
|
||||
<LazyDiffSyntaxHighlight language={language} lines={lines} />
|
||||
<Suspense fallback={<PlainDiffLines diff={props.diff} lineLimit={props.lineLimit} />}>
|
||||
<LazyDiffSyntaxHighlight {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function PlainDiffLines({ lines }: { lines: RenderableFileDiffLine[] }) {
|
||||
export function DiffHunkGap({ lineCount }: { lineCount: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div data-testid="plain-diff-hunk">
|
||||
<DiffLineTable lines={lines} renderCode={(line) => line.content || " "} />
|
||||
<div className="nanobot-diff-gap flex items-center gap-2 bg-muted/35 px-2 text-[11px] text-muted-foreground" data-testid="file-edit-diff-hunk-gap">
|
||||
<span className="select-none rounded border border-border/45 bg-background/70 px-1 font-mono text-muted-foreground/70" aria-hidden>...</span>
|
||||
<span>{t("message.fileEditUnchangedLinesHidden", { count: lineCount, defaultValue: "{{count}} unchanged lines hidden" })}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DiffLineTable({
|
||||
lines,
|
||||
renderCode,
|
||||
}: {
|
||||
lines: RenderableFileDiffLine[];
|
||||
renderCode: (line: RenderableFileDiffLine, index: number) => ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<table className="w-full border-collapse font-mono text-code-dense">
|
||||
<tbody>
|
||||
{lines.map((line, index) => (
|
||||
<DiffLineRow
|
||||
key={`${line.old_lineno ?? ""}:${line.new_lineno ?? ""}:${index}`}
|
||||
line={line}
|
||||
>
|
||||
{renderCode(line, index)}
|
||||
</DiffLineRow>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
export function PlainDiffLines({ diff, lineLimit }: { diff: RenderableFileDiff; lineLimit: number }) {
|
||||
let remaining = lineLimit;
|
||||
return <div data-testid="plain-diff-hunk">{diff.hunks.map((hunk, index) => {
|
||||
const lines = hunk.lines.slice(0, Math.max(0, remaining));
|
||||
remaining -= lines.length;
|
||||
if (lines.length === 0) return null;
|
||||
const previous = diff.hunks[index - 1];
|
||||
const skipped = previous ? Math.max(0, hunk.old_start - previous.old_start - previous.old_lines, hunk.new_start - previous.new_start - previous.new_lines) : 0;
|
||||
return <div key={index}>
|
||||
{skipped > 0 ? <DiffHunkGap lineCount={skipped} /> : null}
|
||||
<table className="w-full border-collapse font-mono text-code-dense"><tbody>
|
||||
{lines.map((line, lineIndex) => <DiffLineRow key={lineIndex} line={line}>{line.content || " "}</DiffLineRow>)}
|
||||
</tbody></table>
|
||||
</div>;
|
||||
})}</div>;
|
||||
}
|
||||
|
||||
function DiffLineRow({
|
||||
line,
|
||||
children,
|
||||
}: {
|
||||
line: RenderableFileDiffLine;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
function DiffLineRow({ line, children }: { line: RenderableFileDiffLine; children: ReactNode }) {
|
||||
const kind = line.kind === "add" || line.kind === "delete" ? line.kind : "context";
|
||||
const marker = kind === "add" ? "+" : kind === "delete" ? "-" : " ";
|
||||
return (
|
||||
<tr
|
||||
className={cn(
|
||||
"border-0",
|
||||
kind === "add" && "bg-diff-added",
|
||||
kind === "delete" && "bg-diff-deleted",
|
||||
)}
|
||||
>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
|
||||
{line.old_lineno ?? ""}
|
||||
</td>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
|
||||
{line.new_lineno ?? ""}
|
||||
</td>
|
||||
<td
|
||||
className={cn(
|
||||
"w-5 select-none px-1 text-center",
|
||||
kind === "add" && "text-diff-added-foreground",
|
||||
kind === "delete" && "text-diff-deleted-foreground",
|
||||
kind === "context" && "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{marker}
|
||||
</td>
|
||||
<td className="min-w-[16rem] px-1.5 text-foreground/86">
|
||||
<span className="whitespace-pre">{children}</span>
|
||||
</td>
|
||||
<tr className={cn("border-0", kind === "add" && "bg-diff-added", kind === "delete" && "bg-diff-deleted")}>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">{line.old_lineno ?? ""}</td>
|
||||
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">{line.new_lineno ?? ""}</td>
|
||||
<td className={cn("w-5 select-none px-1 text-center", kind === "add" && "text-diff-added-foreground", kind === "delete" && "text-diff-deleted-foreground", kind === "context" && "text-muted-foreground")}>{marker}</td>
|
||||
<td className="min-w-[16rem] px-1.5 text-foreground/86"><span className="whitespace-pre">{children}</span></td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
function trimTrailingLineBreak(node: SyntaxNode): SyntaxNode {
|
||||
if (node.type === "text" && typeof node.value === "string") {
|
||||
return { ...node, value: node.value.replace(/\n$/, "") };
|
||||
}
|
||||
if (!node.children?.length) return node;
|
||||
const children = [...node.children];
|
||||
children[children.length - 1] = trimTrailingLineBreak(children[children.length - 1]!);
|
||||
return { ...node, children };
|
||||
}
|
||||
|
||||
function stripConflictingTableClass(node: SyntaxNode): SyntaxNode {
|
||||
const className = node.properties?.className;
|
||||
const children = node.children?.map(stripConflictingTableClass);
|
||||
const hasTableClass = Array.isArray(className) && className.includes("table");
|
||||
|
||||
if (!hasTableClass && !children) return node;
|
||||
|
||||
return {
|
||||
...node,
|
||||
...(hasTableClass
|
||||
? {
|
||||
properties: {
|
||||
...node.properties,
|
||||
// Tailwind's global `.table` utility changes Prism's inline Markdown
|
||||
// table tokens into CSS tables, splitting a single diff line vertically.
|
||||
className: className.filter((name) => name !== "table"),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(children ? { children } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createContext, type RefObject } from "react";
|
||||
|
||||
export const DiffViewportContext = createContext<{
|
||||
scroller: RefObject<HTMLElement>;
|
||||
content: RefObject<HTMLElement>;
|
||||
} | null>(null);
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
hasRenderableFileDiff,
|
||||
parseRenderableFileDiff,
|
||||
type RenderableFileDiff,
|
||||
type RenderableFileDiffHunk,
|
||||
} from "@/lib/file-diff";
|
||||
import type { FileEditDisplayMode } from "@/lib/local-preferences";
|
||||
import type { UIFileDiff, UIFileEdit } from "@/lib/types";
|
||||
@@ -28,18 +27,6 @@ import { DiffSyntaxHighlight } from "./DiffSyntaxHighlight";
|
||||
const INITIAL_VISIBLE_DIFF_LINES = 160;
|
||||
const AUTO_COLLAPSE_DIFF_LINES = INITIAL_VISIBLE_DIFF_LINES;
|
||||
|
||||
interface VisibleDiffHunk {
|
||||
hunk: RenderableFileDiffHunk;
|
||||
skippedBefore: number;
|
||||
}
|
||||
|
||||
interface VisibleDiff {
|
||||
hunks: VisibleDiffHunk[];
|
||||
hiddenLineCount: number;
|
||||
}
|
||||
|
||||
const EMPTY_VISIBLE_DIFF: VisibleDiff = { hunks: [], hiddenLineCount: 0 };
|
||||
|
||||
export interface FileEditSummary {
|
||||
key: string;
|
||||
path: string;
|
||||
@@ -192,12 +179,7 @@ function FileUnifiedDiff({
|
||||
const lineLimit = expandedLines || !shouldLimitLines
|
||||
? totalLineCount
|
||||
: INITIAL_VISIBLE_DIFF_LINES;
|
||||
const visibleDiff = useMemo(
|
||||
() => shouldRenderBody
|
||||
? selectVisibleDiffLines(renderableDiff, lineLimit, totalLineCount)
|
||||
: EMPTY_VISIBLE_DIFF,
|
||||
[lineLimit, renderableDiff, shouldRenderBody, totalLineCount],
|
||||
);
|
||||
const hiddenLineCount = totalLineCount - lineLimit;
|
||||
const viewDiffLabel = shouldAutoCollapse
|
||||
? tx("message.fileEditViewLargeDiff", "View large diff")
|
||||
: tx("message.fileEditViewDiff", "View diff");
|
||||
@@ -227,18 +209,8 @@ function FileUnifiedDiff({
|
||||
className="mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
|
||||
data-testid="file-edit-diff"
|
||||
>
|
||||
{visibleDiff.hunks.map(({ hunk, skippedBefore }, index) => (
|
||||
<div
|
||||
key={`${hunk.old_start}-${hunk.new_start}-${index}`}
|
||||
className={cn("min-w-0", index > 0 && "border-t border-border/45")}
|
||||
>
|
||||
{skippedBefore > 0 ? <DiffHunkGap lineCount={skippedBefore} /> : null}
|
||||
<div className="overflow-x-auto">
|
||||
<DiffSyntaxHighlight language={language} lines={hunk.lines} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{visibleDiff.hiddenLineCount > 0 ? (
|
||||
<DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} />
|
||||
{hiddenLineCount > 0 ? (
|
||||
<div className="border-t border-border/45 bg-muted/30 px-2 py-1">
|
||||
<button
|
||||
type="button"
|
||||
@@ -251,7 +223,7 @@ function FileUnifiedDiff({
|
||||
>
|
||||
<ChevronDown className="h-3 w-3" aria-hidden />
|
||||
{t("message.fileEditShowMoreLines", {
|
||||
count: visibleDiff.hiddenLineCount,
|
||||
count: hiddenLineCount,
|
||||
defaultValue: "Show {{count}} more lines",
|
||||
})}
|
||||
</button>
|
||||
@@ -330,72 +302,3 @@ function FileUnifiedDiff({
|
||||
function countDiffLines(diff: RenderableFileDiff): number {
|
||||
return diff.hunks.reduce((total, hunk) => total + hunk.lines.length, 0);
|
||||
}
|
||||
|
||||
function selectVisibleDiffLines(
|
||||
diff: RenderableFileDiff,
|
||||
lineLimit: number,
|
||||
totalLineCount: number,
|
||||
): VisibleDiff {
|
||||
if (lineLimit >= totalLineCount) {
|
||||
return {
|
||||
hunks: diff.hunks.map((hunk, index) => ({
|
||||
hunk,
|
||||
skippedBefore: index > 0 ? countSkippedUnchangedLines(diff.hunks[index - 1], hunk) : 0,
|
||||
})),
|
||||
hiddenLineCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
let remaining = Math.max(0, lineLimit);
|
||||
const hunks: VisibleDiffHunk[] = [];
|
||||
let previousHunk: RenderableFileDiffHunk | null = null;
|
||||
for (const hunk of diff.hunks) {
|
||||
if (remaining <= 0) break;
|
||||
const skippedBefore = previousHunk ? countSkippedUnchangedLines(previousHunk, hunk) : 0;
|
||||
if (hunk.lines.length <= remaining) {
|
||||
hunks.push({ hunk, skippedBefore });
|
||||
remaining -= hunk.lines.length;
|
||||
previousHunk = hunk;
|
||||
continue;
|
||||
}
|
||||
hunks.push({ hunk: { ...hunk, lines: hunk.lines.slice(0, remaining) }, skippedBefore });
|
||||
remaining = 0;
|
||||
previousHunk = hunk;
|
||||
}
|
||||
return {
|
||||
hunks,
|
||||
hiddenLineCount: Math.max(0, totalLineCount - lineLimit),
|
||||
};
|
||||
}
|
||||
|
||||
function countSkippedUnchangedLines(
|
||||
previous: RenderableFileDiffHunk,
|
||||
current: RenderableFileDiffHunk,
|
||||
): number {
|
||||
const oldGap = current.old_start - (previous.old_start + previous.old_lines);
|
||||
const newGap = current.new_start - (previous.new_start + previous.new_lines);
|
||||
return Math.max(0, oldGap, newGap);
|
||||
}
|
||||
|
||||
function DiffHunkGap({ lineCount }: { lineCount: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className="flex items-center gap-2 bg-muted/35 px-2 py-1 text-[11px] text-muted-foreground"
|
||||
data-testid="file-edit-diff-hunk-gap"
|
||||
>
|
||||
<span
|
||||
className="select-none rounded border border-border/45 bg-background/70 px-1 font-mono text-muted-foreground/70"
|
||||
aria-hidden
|
||||
>
|
||||
...
|
||||
</span>
|
||||
<span>
|
||||
{t("message.fileEditUnchangedLinesHidden", {
|
||||
count: lineCount,
|
||||
defaultValue: "{{count}} unchanged lines hidden",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { FileDiff, getSharedHighlighter, getSingularPatch, registerCustomTheme, type FileDiffMetadata, type FileDiffOptions, type RenderRange } from "@pierre/diffs";
|
||||
import { WorkerPoolManager } from "@pierre/diffs/worker";
|
||||
import { isSupportedLanguage } from "@pierre/highlights";
|
||||
import { bundledLanguages } from "shiki/langs";
|
||||
import { useCallback, useContext, useLayoutEffect, useMemo, useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useThemeValue } from "@/hooks/useTheme";
|
||||
import { CODE_TEXTMATE_THEME, CODE_THEME, CODE_THEME_NAME, codeHighlighterLanguage } from "@/lib/code-theme";
|
||||
import { DiffViewportContext } from "./DiffViewportContext";
|
||||
import type { DiffSyntaxHighlightProps } from "./DiffSyntaxHighlight";
|
||||
import { DIFF_GAP_HEIGHT, diffRenderWindow, diffRowOffsets } from "./diff-render-window";
|
||||
import { selectedDiffRows } from "./diff-selection";
|
||||
|
||||
const THEME = CODE_THEME_NAME;
|
||||
const CACHE_ENTRIES = 16;
|
||||
const CACHE_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
const metadataCache = new Map<string, FileDiffMetadata>();
|
||||
let sourceBytes = 0;
|
||||
let revision = 0;
|
||||
let pool: WorkerPoolManager | undefined;
|
||||
let grammarPool: WorkerPoolManager | undefined;
|
||||
let preparation: Promise<void> | undefined;
|
||||
|
||||
registerCustomTheme(THEME, async () => CODE_THEME, "zed");
|
||||
registerCustomTheme(THEME, async () => CODE_TEXTMATE_THEME, "textmate");
|
||||
|
||||
export function prepareDiffRenderer(): Promise<void> {
|
||||
return preparation ??= (async () => {
|
||||
await getSharedHighlighter({ themes: [THEME], langs: ["text"], preferredHighlighter: "highlights" });
|
||||
pool = new WorkerPoolManager({
|
||||
// The zero-worker pool owns the bounded AST cache; Highlights shares its main-thread engine with code blocks.
|
||||
workerFactory: () => { throw new Error("The Highlights cache does not create workers"); },
|
||||
poolSize: 0,
|
||||
totalASTLRUCacheSize: CACHE_ENTRIES,
|
||||
mainThreadMaxCharacters: Number.MAX_SAFE_INTEGER,
|
||||
}, { theme: THEME, preferredHighlighter: "highlights", lineDiffType: "word" });
|
||||
})();
|
||||
}
|
||||
|
||||
function getGrammarPool(): WorkerPoolManager {
|
||||
return grammarPool ??= new WorkerPoolManager({
|
||||
workerFactory: () => new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), { type: "module" }),
|
||||
poolSize: 1, totalASTLRUCacheSize: CACHE_ENTRIES,
|
||||
}, { theme: THEME, preferredHighlighter: "shiki-js", lineDiffType: "word" });
|
||||
}
|
||||
|
||||
export function getDiffMetadata(text: string, language: string): FileDiffMetadata {
|
||||
const alias = codeHighlighterLanguage(language);
|
||||
const lang = isSupportedLanguage(alias) || Object.hasOwn(bundledLanguages, alias)
|
||||
? alias as NonNullable<FileDiffMetadata["lang"]> : "text";
|
||||
const key = `${lang}\0${text}`;
|
||||
const cached = metadataCache.get(key);
|
||||
if (cached) {
|
||||
metadataCache.delete(key);
|
||||
metadataCache.set(key, cached);
|
||||
return cached;
|
||||
}
|
||||
const metadata = getSingularPatch(text);
|
||||
metadata.lang = lang;
|
||||
const bytes = key.length * 2;
|
||||
if (bytes <= CACHE_SOURCE_BYTES) {
|
||||
while (metadataCache.size >= CACHE_ENTRIES || sourceBytes + bytes > CACHE_SOURCE_BYTES) {
|
||||
const [oldKey, oldMetadata] = metadataCache.entries().next().value!;
|
||||
metadataCache.delete(oldKey);
|
||||
sourceBytes -= oldKey.length * 2;
|
||||
pool?.evictDiffFromCache(oldMetadata.cacheKey!);
|
||||
grammarPool?.evictDiffFromCache(oldMetadata.cacheKey!);
|
||||
}
|
||||
metadata.cacheKey = `nanobot-diff-${++revision}`;
|
||||
metadataCache.set(key, metadata);
|
||||
sourceBytes += bytes;
|
||||
}
|
||||
return metadata;
|
||||
}
|
||||
|
||||
export function PierreFileDiff({ text, language, diff, lineLimit }: DiffSyntaxHighlightProps) {
|
||||
const theme = useThemeValue();
|
||||
const { t } = useTranslation();
|
||||
const viewport = useContext(DiffViewportContext);
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const instanceRef = useRef<FileDiff>();
|
||||
const metadata = useMemo(() => getDiffMetadata(text, language), [text, language]);
|
||||
const needsGrammar = !isSupportedLanguage(metadata.lang!);
|
||||
const gapLabel = useCallback((count: number) => `… ${t("message.fileEditUnchangedLinesHidden", { count, defaultValue: "{{count}} unchanged lines hidden" })}`, [t]);
|
||||
const options = useMemo<FileDiffOptions<undefined, undefined>>(() => ({
|
||||
theme: THEME, themeType: theme, preferredHighlighter: "highlights", diffStyle: "unified", diffIndicators: "classic",
|
||||
disableFileHeader: true, lineDiffType: "word",
|
||||
// Function separators disable Pierre's incremental row updates and destroy native selections.
|
||||
hunkSeparators: "line-info",
|
||||
onPostRender: (node, _instance, phase) => {
|
||||
if (phase === "unmount") return;
|
||||
for (const gap of node.shadowRoot!.querySelectorAll<HTMLElement>("[data-separator]")) {
|
||||
const nextIndex = Number(gap.nextElementSibling?.getAttribute("data-line-index")?.split(",")[0]);
|
||||
const hunk = metadata.hunks.find(item => item.unifiedLineStart === nextIndex);
|
||||
const label = gap.querySelector<HTMLElement>("[data-unmodified-lines]");
|
||||
if (!hunk || !label) continue;
|
||||
const text = gapLabel(hunk.collapsedBefore);
|
||||
if (label.textContent !== text) label.textContent = text;
|
||||
if (gap.closest("[data-gutter]")) label.dataset.testid = "file-edit-diff-hunk-gap";
|
||||
}
|
||||
},
|
||||
unsafeCSS: `:host, pre, code { font: inherit; } pre { padding-block: 0; } [data-line], [data-column-number] { padding-block: 1px; } [data-separator] { height: ${DIFF_GAP_HEIGHT}px; margin: 0; padding: 0; } [data-separator-wrapper], [data-separator-content] { background: transparent; color: hsl(var(--muted-foreground)); } [data-separator-wrapper] { padding-inline: 8px; background: hsl(var(--muted) / .35); font-size: 11px; } [data-separator-first], [data-separator-last] { display: none; }`,
|
||||
}), [theme, gapLabel, metadata]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const wrapper = wrapperRef.current!;
|
||||
const instance = new FileDiff({ theme: THEME, preferredHighlighter: "highlights" }, needsGrammar ? getGrammarPool() : pool);
|
||||
instanceRef.current = instance;
|
||||
return () => { instance.cleanUp(); instanceRef.current = undefined; wrapper.replaceChildren(); };
|
||||
}, [needsGrammar]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const wrapper = wrapperRef.current!;
|
||||
const instance = instanceRef.current!;
|
||||
instance.setOptions(options);
|
||||
const scroller = viewport?.scroller.current;
|
||||
const eventTarget = scroller ?? window;
|
||||
let frame = 0;
|
||||
let previous: RenderRange | undefined;
|
||||
let forceRender = true;
|
||||
const render = () => {
|
||||
frame = 0;
|
||||
const lineHeight = Math.floor((parseFloat(getComputedStyle(wrapper).lineHeight) + 2) * 64) / 64;
|
||||
const offsets = diffRowOffsets(diff, lineLimit, lineHeight);
|
||||
const rootRect = scroller?.getBoundingClientRect();
|
||||
const wrapperTop = wrapper.getBoundingClientRect().top;
|
||||
const top = (rootRect?.top ?? 0) - wrapperTop;
|
||||
const height = rootRect?.height ?? window.innerHeight;
|
||||
const range = diffRenderWindow(diff, offsets, top - height, top + height * 2, lineHeight, selectedDiffRows(wrapper, metadata));
|
||||
if (!forceRender && previous && Object.keys(range).every(key => range[key as keyof RenderRange] === previous![key as keyof RenderRange])) return;
|
||||
previous = range;
|
||||
instance.render({ fileDiff: metadata, containerWrapper: wrapper, renderRange: range, forceRender });
|
||||
forceRender = false;
|
||||
};
|
||||
const schedule = () => { if (!frame) frame = requestAnimationFrame(render); };
|
||||
// This observer projects a read-only window; ThreadCameraController remains the sole scroll writer.
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(wrapper);
|
||||
if (scroller) resize.observe(scroller);
|
||||
if (viewport?.content.current) resize.observe(viewport.content.current);
|
||||
const typography = new MutationObserver(schedule);
|
||||
typography.observe(document.documentElement, { attributes: true, attributeFilter: ["data-reading-text-size"] });
|
||||
eventTarget.addEventListener("scroll", schedule, { passive: true });
|
||||
document.addEventListener("selectionchange", schedule);
|
||||
window.addEventListener("resize", schedule);
|
||||
render();
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
typography.disconnect();
|
||||
eventTarget.removeEventListener("scroll", schedule);
|
||||
document.removeEventListener("selectionchange", schedule);
|
||||
window.removeEventListener("resize", schedule);
|
||||
};
|
||||
}, [diff, lineLimit, metadata, options, viewport]);
|
||||
|
||||
return <div ref={wrapperRef} className="nanobot-file-diff font-mono text-code-dense" data-testid="syntax-highlighted-diff-hunk" data-language={language} />;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { RenderableFileDiff } from "@/lib/file-diff";
|
||||
|
||||
export const DIFF_GAP_HEIGHT = 26;
|
||||
const ROW_BATCH = 40;
|
||||
|
||||
export function diffRowOffsets(diff: RenderableFileDiff, lineLimit: number, lineHeight: number): number[] {
|
||||
const offsets: number[] = [];
|
||||
let top = 0;
|
||||
for (const [index, hunk] of diff.hunks.entries()) {
|
||||
if (offsets.length >= lineLimit) break;
|
||||
const previous = diff.hunks[index - 1];
|
||||
if (previous && (hunk.old_start > previous.old_start + previous.old_lines || hunk.new_start > previous.new_start + previous.new_lines)) top += DIFF_GAP_HEIGHT;
|
||||
for (let line = 0; line < hunk.lines.length; line++) {
|
||||
if (offsets.length >= lineLimit) break;
|
||||
offsets.push(top);
|
||||
top += lineHeight;
|
||||
}
|
||||
}
|
||||
offsets.push(top);
|
||||
return offsets;
|
||||
}
|
||||
|
||||
export function diffRenderWindow(diff: RenderableFileDiff, offsets: number[], top: number, bottom: number, lineHeight: number, selected?: readonly [number, number]) {
|
||||
const count = offsets.length - 1;
|
||||
if (count <= 160) return { startingLine: 0, totalLines: count, bufferBefore: 0, bufferAfter: 0 };
|
||||
let start = offsets.findIndex((offset) => offset >= top);
|
||||
if (start < 0) start = count - 1;
|
||||
// Keep both edges together, with one extra batch for the rounded-down start.
|
||||
const capacity = Math.min(count, (Math.ceil((bottom - top) / lineHeight / ROW_BATCH) + 1) * ROW_BATCH);
|
||||
start = Math.min(count - capacity, Math.max(0, Math.floor((start - 1) / ROW_BATCH) * ROW_BATCH));
|
||||
let end = start + capacity;
|
||||
// Retain only the active selection's rows as the viewport keeps moving. Clearing it
|
||||
// returns to the ordinary bounded window; do not freeze rendering or accumulate old windows.
|
||||
if (selected) {
|
||||
start = Math.min(start, selected[0]);
|
||||
end = Math.min(count, Math.max(end, selected[1]));
|
||||
}
|
||||
let before = offsets[start];
|
||||
let after = offsets[count] - offsets[end];
|
||||
// A separator is rendered with its first row, not with the preceding window.
|
||||
let row = 0;
|
||||
for (const [index, hunk] of diff.hunks.entries()) {
|
||||
const previous = diff.hunks[index - 1];
|
||||
const gap = previous && (hunk.old_start > previous.old_start + previous.old_lines || hunk.new_start > previous.new_start + previous.new_lines);
|
||||
if (gap && row === start) before -= DIFF_GAP_HEIGHT;
|
||||
if (gap && row === end) after += DIFF_GAP_HEIGHT;
|
||||
row += hunk.lines.length;
|
||||
}
|
||||
return { startingLine: start, totalLines: end - start, bufferBefore: before, bufferAfter: after };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { FileDiffMetadata } from "@pierre/diffs";
|
||||
|
||||
// Native ranges must be read inside Pierre's shadow tree, not from retargeted host endpoints.
|
||||
export function selectedDiffRows(wrapper: HTMLElement, metadata: FileDiffMetadata): readonly [number, number] | undefined {
|
||||
const host = wrapper.querySelector("diffs-container");
|
||||
const root = host?.shadowRoot;
|
||||
const selection = document.getSelection();
|
||||
if (!root || !selection) return;
|
||||
const shadowSelection = (root as ShadowRoot & { getSelection?(): Selection | null }).getSelection?.();
|
||||
const ranges = typeof selection.getComposedRanges === "function"
|
||||
? selection.getComposedRanges({ shadowRoots: [root] })
|
||||
: shadowSelection?.rangeCount ? [shadowSelection.getRangeAt(0)] : selection.rangeCount ? [selection.getRangeAt(0)] : [];
|
||||
const selected = ranges[0];
|
||||
// Chromium can report document Selection.isCollapsed=true for a nonempty shadow selection.
|
||||
if (!selected || (selected.startContainer === selected.endContainer && selected.startOffset === selected.endOffset)) return;
|
||||
const startsInside = selected.startContainer.getRootNode() === root;
|
||||
const endsInside = selected.endContainer.getRootNode() === root;
|
||||
if (!startsInside && !endsInside && (!selection.rangeCount || !selection.getRangeAt(0).intersectsNode(host))) return;
|
||||
const localRange = document.createRange();
|
||||
localRange.selectNodeContents(root);
|
||||
if (startsInside) localRange.setStart(selected.startContainer, selected.startOffset);
|
||||
if (endsInside) localRange.setEnd(selected.endContainer, selected.endOffset);
|
||||
let first: number | undefined;
|
||||
let last: number | undefined;
|
||||
for (const row of root.querySelectorAll<HTMLElement>("[data-code] [data-line][data-line-index]")) {
|
||||
if (!localRange.intersectsNode(row)) continue;
|
||||
const index = Number(row.dataset.lineIndex!.split(",")[0]);
|
||||
let renderedStart = 0;
|
||||
for (const hunk of metadata.hunks) {
|
||||
if (index >= hunk.unifiedLineStart && index < hunk.unifiedLineStart + hunk.unifiedLineCount) {
|
||||
const renderedIndex = renderedStart + index - hunk.unifiedLineStart;
|
||||
first = first === undefined ? renderedIndex : Math.min(first, renderedIndex);
|
||||
last = last === undefined ? renderedIndex + 1 : Math.max(last, renderedIndex + 1);
|
||||
break;
|
||||
}
|
||||
renderedStart += hunk.unifiedLineCount;
|
||||
}
|
||||
}
|
||||
return first === undefined || last === undefined ? undefined : [first, last];
|
||||
}
|
||||
@@ -205,6 +205,7 @@ export function PaneWorkbench({
|
||||
}: PaneWorkbenchProps) {
|
||||
const { t } = useTranslation();
|
||||
const compact = useMediaQuery("(max-width: 767px)");
|
||||
const sharedComposer = chrome && panes.length > 1;
|
||||
const effectiveLayout = layout;
|
||||
const [headerPortalTarget, setHeaderPortalTarget] = useState<HTMLElement | null>(null);
|
||||
const [composerPortalTarget, setComposerPortalTarget] = useState<HTMLElement | null>(null);
|
||||
@@ -728,7 +729,7 @@ export function PaneWorkbench({
|
||||
active,
|
||||
multiplePanes: displayedPanes.length > 1,
|
||||
headerPortalTarget: chrome && displayedPanes.length > 1 ? headerPortalTarget : undefined,
|
||||
composerPortalTarget: chrome ? composerPortalTarget : undefined,
|
||||
composerPortalTarget: sharedComposer ? composerPortalTarget : undefined,
|
||||
navigationFrame: displayedPanes.length === 1 ? navigationFrame : undefined,
|
||||
headerActions,
|
||||
})}
|
||||
@@ -827,7 +828,7 @@ export function PaneWorkbench({
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{chrome ? (
|
||||
{sharedComposer ? (
|
||||
<footer className="workbench-composer-footer shrink-0 px-3 pb-[calc(0.5rem+env(safe-area-inset-bottom))] sm:px-4 sm:pb-[calc(0.75rem+env(safe-area-inset-bottom))]">
|
||||
<div
|
||||
ref={setComposerPortalTarget}
|
||||
|
||||
+27
-32
@@ -987,11 +987,6 @@
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* Prism's Markdown table tokens must not pick up Tailwind's table layout. */
|
||||
.not-prose pre .token.table {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
/* Markdown table cells retain whole-word minimum widths. The renderer's
|
||||
overflow-x:auto wrapper contains tables wider than the preview or chat. */
|
||||
|
||||
@@ -1877,35 +1872,35 @@
|
||||
to { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
/* Prism classes are generated at runtime, outside Tailwind's source inventory. */
|
||||
.code-content {
|
||||
--code-foreground: hsl(var(--foreground));
|
||||
--code-background: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
/* Flattened JSX tokens retain the ancestor tag class; let inner token types win. */
|
||||
.code-content .token.tag {
|
||||
color: var(--code-property);
|
||||
|
||||
.nanobot-file-diff {
|
||||
--code-foreground: hsl(var(--foreground));
|
||||
--code-background: hsl(var(--background));
|
||||
display: block;
|
||||
min-width: 0;
|
||||
--diffs-font-size: var(--text-code-dense-size);
|
||||
--diffs-line-height: calc(var(--text-code-dense-size) * 1.6);
|
||||
--diffs-gap-block: 0px;
|
||||
--diffs-bg-context-override: transparent;
|
||||
--diffs-bg-context-gutter-override: transparent;
|
||||
--diffs-bg-addition-override: var(--diff-added);
|
||||
--diffs-bg-addition-number-override: var(--diff-added);
|
||||
--diffs-bg-deletion-override: var(--diff-deleted);
|
||||
--diffs-bg-deletion-number-override: var(--diff-deleted);
|
||||
--diffs-addition-color-override: var(--diff-added-foreground);
|
||||
--diffs-deletion-color-override: var(--diff-deleted-foreground);
|
||||
--diffs-fg-number-override: hsl(var(--muted-foreground));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--diff-added-foreground) 15%, transparent);
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(in srgb, var(--diff-deleted-foreground) 15%, transparent);
|
||||
}
|
||||
.code-content :is(.token.comment, .token.prolog, .token.doctype, .token.cdata, .linenumber) {
|
||||
color: var(--code-comment);
|
||||
}
|
||||
.code-content .token.comment {
|
||||
font-style: italic;
|
||||
}
|
||||
.code-content :is(.token.string, .token.char, .token.attr-value, .token.regex, .token.inserted) {
|
||||
color: var(--code-string);
|
||||
}
|
||||
.code-content :is(.token.keyword, .token.selector, .token.important, .token.atrule) {
|
||||
color: var(--code-keyword);
|
||||
}
|
||||
.code-content :is(.token.function, .token.operator, .token.entity, .token.url) {
|
||||
color: var(--code-function);
|
||||
}
|
||||
.code-content :is(.token.number, .token.boolean, .token.constant, .token.symbol, .token.attr-name, .token.class-name, .token.builtin, .token.property, .token.deleted) {
|
||||
color: var(--code-property);
|
||||
}
|
||||
.code-content :is(.token.bold, .token.important) {
|
||||
font-weight: 600;
|
||||
}
|
||||
.code-content .token.italic {
|
||||
font-style: italic;
|
||||
|
||||
.nanobot-diff-gap {
|
||||
height: 26px;
|
||||
box-sizing: border-box;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { normalizeCodeLanguage } from "./code-language";
|
||||
import type { CodeLine } from "./code-tokens";
|
||||
|
||||
export interface CodeHighlight {
|
||||
read(): CodeLine[];
|
||||
}
|
||||
|
||||
const MAX_CACHED_SOURCE_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_CACHE_ENTRIES = 16;
|
||||
const cache = new Map<string, CodeHighlight>();
|
||||
let sourceBytes = 0;
|
||||
|
||||
function cacheKey(source: string, language: string): string {
|
||||
return `${normalizeCodeLanguage(language)}\0${source}`;
|
||||
}
|
||||
|
||||
export function cachedCodeHighlight(source: string, language: string): CodeHighlight | undefined {
|
||||
const key = cacheKey(source, language);
|
||||
const resource = cache.get(key);
|
||||
if (resource) {
|
||||
cache.delete(key);
|
||||
cache.set(key, resource);
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
export function discardCodeHighlight(source: string, language: string): void {
|
||||
const key = cacheKey(source, language);
|
||||
if (cache.delete(key)) sourceBytes -= key.length * 2;
|
||||
}
|
||||
|
||||
export function cacheCodeHighlight(source: string, language: string, resource: CodeHighlight): void {
|
||||
const key = cacheKey(source, language);
|
||||
const bytes = key.length * 2;
|
||||
if (bytes > MAX_CACHED_SOURCE_BYTES) return;
|
||||
discardCodeHighlight(source, language);
|
||||
while (cache.size >= MAX_CACHE_ENTRIES || sourceBytes + bytes > MAX_CACHED_SOURCE_BYTES) {
|
||||
const oldest = cache.keys().next().value!;
|
||||
cache.delete(oldest);
|
||||
sourceBytes -= oldest.length * 2;
|
||||
}
|
||||
cache.set(key, resource);
|
||||
sourceBytes += bytes;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createHighlighterCore } from "shiki/core";
|
||||
import { createJavaScriptRegexEngine } from "shiki/engine/javascript";
|
||||
import { bundledLanguages } from "shiki/langs";
|
||||
|
||||
import { CODE_TEXTMATE_THEME, CODE_THEME_NAME } from "./code-theme";
|
||||
import type { CodeToken } from "./code-tokens";
|
||||
|
||||
let loaded: Awaited<ReturnType<typeof createHighlighterCore>> | undefined;
|
||||
const highlighter = createHighlighterCore({
|
||||
engine: createJavaScriptRegexEngine(), langs: [],
|
||||
themes: [CODE_TEXTMATE_THEME],
|
||||
}).then(engine => { loaded = engine; return engine; });
|
||||
|
||||
export function highlightGrammar(source: string, language: string): CodeToken[][] | Promise<CodeToken[][]> {
|
||||
const loader = Object.hasOwn(bundledLanguages, language) ? bundledLanguages[language as keyof typeof bundledLanguages] : undefined;
|
||||
if (!loader) return source.split("\n").map(content => [{ content }]);
|
||||
if (loaded?.getLoadedLanguages().includes(language)) return loaded.codeToTokens(source, { lang: language, theme: CODE_THEME_NAME }).tokens;
|
||||
return highlighter.then(async engine => {
|
||||
await engine.loadLanguage(loader);
|
||||
return engine.codeToTokens(source, { lang: language, theme: CODE_THEME_NAME }).tokens;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { codeToTokens, isSupportedLanguage } from "@pierre/highlights";
|
||||
|
||||
import { cacheCodeHighlight, cachedCodeHighlight, type CodeHighlight } from "./code-highlight-cache";
|
||||
import { CODE_THEME, codeHighlighterLanguage } from "./code-theme";
|
||||
import { codeTokenLines, type CodeLine } from "./code-tokens";
|
||||
|
||||
type HighlightResult =
|
||||
| { state: "ready"; lines: CodeLine[] }
|
||||
| { state: "pending"; promise: Promise<void> }
|
||||
| { state: "failed"; error: unknown };
|
||||
let grammars: typeof import("./code-highlighter-grammars") | undefined;
|
||||
|
||||
function highlight(source: string, language: string): CodeHighlight {
|
||||
const code = source.replace(/\r\n/g, "\n").replace(/\r$/, "");
|
||||
let result: HighlightResult;
|
||||
if (isSupportedLanguage(language)) {
|
||||
result = { state: "ready", lines: codeTokenLines(source, codeToTokens(code, { lang: language, theme: CODE_THEME }).tokens) };
|
||||
} else {
|
||||
const tokens = grammars ? grammars.highlightGrammar(code, language) : import("./code-highlighter-grammars").then(module => {
|
||||
grammars = module;
|
||||
return module.highlightGrammar(code, language);
|
||||
});
|
||||
if (tokens instanceof Promise) {
|
||||
const promise = tokens.then(tokens => {
|
||||
result = { state: "ready", lines: codeTokenLines(source, tokens) };
|
||||
}, error => { result = { state: "failed", error }; });
|
||||
result = { state: "pending", promise };
|
||||
} else {
|
||||
result = { state: "ready", lines: codeTokenLines(source, tokens) };
|
||||
}
|
||||
}
|
||||
return { read() {
|
||||
if (result.state === "pending") throw result.promise;
|
||||
if (result.state === "failed") throw result.error;
|
||||
return result.lines;
|
||||
} };
|
||||
}
|
||||
|
||||
export function codeHighlight(source: string, language: string): CodeHighlight {
|
||||
const cached = cachedCodeHighlight(source, language);
|
||||
if (cached) return cached;
|
||||
const resource = highlight(source, codeHighlighterLanguage(language));
|
||||
cacheCodeHighlight(source, language, resource);
|
||||
return resource;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { Theme } from "@pierre/highlights";
|
||||
import type { ThemeRegistration } from "shiki";
|
||||
|
||||
export const CODE_THEME_NAME = "nanobot-code";
|
||||
export const CODE_THEME: Theme = {
|
||||
name: CODE_THEME_NAME, appearance: "dark", cssVariables: { prefix: "--code-" },
|
||||
style: {
|
||||
"editor.foreground": "foreground", "editor.background": "background",
|
||||
syntax: {
|
||||
comment: { color: "comment", font_style: "italic" },
|
||||
string: "string", "text.literal": "string",
|
||||
keyword: "keyword", preproc: "keyword",
|
||||
operator: "function", function: "function", constructor: "function",
|
||||
type: "property", attribute: "property", tag: "property",
|
||||
property: "property", number: "property", boolean: "property", constant: "property",
|
||||
title: { color: "keyword", font_weight: 700 }, emphasis: { font_style: "italic" }, "emphasis.strong": { font_weight: 700 },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const CODE_TEXTMATE_THEME: ThemeRegistration = {
|
||||
name: CODE_THEME_NAME, type: "dark", fg: "var(--code-foreground)", bg: "var(--code-background)",
|
||||
tokenColors: [
|
||||
{ scope: "comment", settings: { foreground: "var(--code-comment)", fontStyle: "italic" } },
|
||||
{ scope: ["string", "markup.raw"], settings: { foreground: "var(--code-string)" } },
|
||||
{ scope: ["keyword", "storage"], settings: { foreground: "var(--code-keyword)" } },
|
||||
{ scope: ["entity.name.function", "support.function", "variable.function", "keyword.operator"], settings: { foreground: "var(--code-function)" } },
|
||||
{ scope: ["constant", "support.type", "entity.name.type", "entity.name.tag", "entity.other.attribute-name", "entity.name.section"], settings: { foreground: "var(--code-property)" } },
|
||||
{ scope: ["keyword.operator.new", "keyword.operator.expression"], settings: { foreground: "var(--code-keyword)" } },
|
||||
{ scope: "markup.heading", settings: { foreground: "var(--code-keyword)", fontStyle: "bold" } },
|
||||
{ scope: "markup.italic", settings: { fontStyle: "italic" } },
|
||||
{ scope: "markup.bold", settings: { fontStyle: "bold" } },
|
||||
],
|
||||
};
|
||||
|
||||
export function codeHighlighterLanguage(language: string): string {
|
||||
return language === "markup" ? "html" : language === "docker" ? "dockerfile" : language;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export interface CodeToken {
|
||||
content: string;
|
||||
color?: string;
|
||||
fontStyle?: number;
|
||||
}
|
||||
|
||||
export interface CodeLine {
|
||||
text: string;
|
||||
tokens: CodeToken[];
|
||||
}
|
||||
|
||||
export function codeTokenLines(source: string, tokens: CodeToken[][]): CodeLine[] {
|
||||
const lines = source.split("\n");
|
||||
return lines.map((text, index) => {
|
||||
const ending = index < lines.length - 1 ? "\n" : "";
|
||||
const cr = text.endsWith("\r") ? "\r" : "";
|
||||
return { text: text + ending, tokens: [...tokens[index] ?? [], ...(cr || ending ? [{ content: cr + ending }] : [])] };
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,12 @@ import { setAppLanguage } from "@/i18n";
|
||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
import type { CliAppInfo, McpPresetInfo, UIMessage } from "@/lib/types";
|
||||
|
||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
||||
vi.mock("@/components/thread/activity/DiffSyntaxHighlight", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/components/thread/activity/DiffSyntaxHighlight")>();
|
||||
return { ...actual, DiffSyntaxHighlight: actual.PlainDiffLines };
|
||||
});
|
||||
|
||||
const BLENDER_CLI_APP: CliAppInfo = {
|
||||
name: "blender",
|
||||
display_name: "Blender",
|
||||
|
||||
@@ -4088,6 +4088,13 @@ describe("App layout", () => {
|
||||
.toEqual(["Alpha"]);
|
||||
expect(screen.queryByRole("button", { name: "Layout" }))
|
||||
.not.toBeInTheDocument();
|
||||
const alphaInput = screen.getByRole("textbox", { name: "Message Alpha" });
|
||||
expect(screen.getByTestId("workbench-pane-websocket:chat-alpha")).toContainElement(alphaInput);
|
||||
fireEvent.change(alphaInput, { target: { value: "keep this Alpha draft" } });
|
||||
fireEvent.change(alphaInput.closest(".thread-composer-surface")!.querySelector('input[type="file"]')!, {
|
||||
target: { files: [new File(["notes"], "alpha-notes.txt", { type: "text/plain" })] },
|
||||
});
|
||||
expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "alpha-notes.txt" })).toBeVisible();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add pane" }));
|
||||
expect(screen.queryByRole("dialog", { name: "Search" })).not.toBeInTheDocument();
|
||||
@@ -4163,6 +4170,11 @@ describe("App layout", () => {
|
||||
name: "Remove",
|
||||
}));
|
||||
await waitFor(() => expect(screen.getByTestId("pane-grid").children).toHaveLength(1));
|
||||
fireEvent.click(within(sidebar).getByRole("button", { name: "Alpha" }));
|
||||
const restoredInput = await screen.findByRole("textbox", { name: "Message Alpha" });
|
||||
expect(screen.getByTestId("workbench-pane-websocket:chat-alpha")).toContainElement(restoredInput);
|
||||
expect(restoredInput).toHaveValue("keep this Alpha draft");
|
||||
expect(within(await screen.findByTestId("composer-chip")).getByRole("button", { name: "alpha-notes.txt" })).toBeVisible();
|
||||
const researchGroup = within(sidebar).getByRole("button", {
|
||||
name: "Group: Research",
|
||||
}).closest("[data-sidebar-tab-group]") as HTMLElement;
|
||||
|
||||
@@ -1,31 +1,49 @@
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { HighlightedCodeProps } from "@/components/HighlightedCode";
|
||||
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
|
||||
default: ({
|
||||
children,
|
||||
language,
|
||||
customStyle,
|
||||
}: {
|
||||
children: string;
|
||||
language?: string;
|
||||
customStyle?: React.CSSProperties;
|
||||
}) => (
|
||||
<pre
|
||||
data-testid="highlighted-code"
|
||||
data-language={language}
|
||||
style={customStyle}
|
||||
>
|
||||
<code>{children}</code>
|
||||
</pre>
|
||||
),
|
||||
const failures = vi.hoisted(() => new Set<string>());
|
||||
|
||||
// Test CodeBlock's controls and enhancement boundary here; token/DOM rendering has dedicated real-engine and browser coverage.
|
||||
vi.mock("@/components/HighlightedCode", () => ({
|
||||
HighlightedCode: ({ code, language, viewportHighlight }: HighlightedCodeProps) => {
|
||||
if (failures.has(code)) throw new Error("Grammar download failed");
|
||||
return <pre data-testid="highlighted-code" data-language={language || "text"}
|
||||
style={{ overflow: viewportHighlight ? "visible" : "auto" }}><code data-code-text="">{code}</code></pre>;
|
||||
},
|
||||
}));
|
||||
|
||||
describe("CodeBlock", () => {
|
||||
it("contains a failed grammar, preserves source and copy, and enhances changed source", async () => {
|
||||
const source = "; 中文 😀\r\n[server]\r\nhost=localhost\r\n";
|
||||
failures.add(source);
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
|
||||
const errors = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const warnings = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
try {
|
||||
const { rerender } = render(<><textarea defaultValue="keep draft" /><CodeBlock code={source} language="ini" /></>);
|
||||
await waitFor(() => expect(warnings).toHaveBeenCalledWith("Code highlighting failed.", expect.any(Error)));
|
||||
expect(screen.getByTestId("plain-code-fallback").textContent).toBe(source);
|
||||
expect(screen.getByRole("textbox")).toHaveValue("keep draft");
|
||||
await user.click(screen.getByRole("button", { name: "Copy code" }));
|
||||
expect(writeText).toHaveBeenCalledWith(source);
|
||||
rerender(<><textarea defaultValue="keep draft" /><CodeBlock code={source + "; updated"} language="ini" /></>);
|
||||
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source + "; updated");
|
||||
expect(screen.getByRole("textbox")).toHaveValue("keep draft");
|
||||
} finally {
|
||||
failures.clear();
|
||||
errors.mockRestore();
|
||||
warnings.mockRestore();
|
||||
Reflect.deleteProperty(navigator, "clipboard");
|
||||
}
|
||||
});
|
||||
|
||||
it("renders and copies a large code block in full without pagination", async () => {
|
||||
const user = userEvent.setup();
|
||||
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||
@@ -37,7 +55,8 @@ describe("CodeBlock", () => {
|
||||
|
||||
try {
|
||||
render(<CodeBlock code={source} language="typescript" showLineNumbers />);
|
||||
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source);
|
||||
const code = await screen.findByTestId("highlighted-code");
|
||||
expect([...code.querySelectorAll("[data-code-text]")].map(node => node.textContent).join("")).toBe(source);
|
||||
expect(screen.getAllByRole("button")).toHaveLength(1);
|
||||
await user.click(screen.getByRole("button", { name: "Copy code" }));
|
||||
expect(writeText).toHaveBeenCalledWith(source);
|
||||
@@ -179,7 +198,7 @@ describe("CodeBlock", () => {
|
||||
expect(screen.getByText("const value = 1;")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("normalizes file language aliases before loading Prism", async () => {
|
||||
it("normalizes file language aliases before highlighting", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<CodeBlock language="html" code="<main />" />
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CodeTokens } from "@/components/CodeTokens";
|
||||
import { codeHighlight } from "@/lib/code-highlighter";
|
||||
|
||||
async function lines(source: string, language: string) {
|
||||
const resource = codeHighlight(source, language);
|
||||
try { return resource.read(); } catch (pending) {
|
||||
if (!(pending instanceof Promise)) throw pending;
|
||||
await pending;
|
||||
return resource.read();
|
||||
}
|
||||
}
|
||||
|
||||
describe("shared code highlighting", () => {
|
||||
it.each(["", "中文 😀\tconst x = 1;\n", "const a = 1;\r\n\tconst b = '中文';\r\n", "unterminated\r"])("preserves the complete source %j", async (source) => {
|
||||
const value = await lines(source, "typescript");
|
||||
expect(value.map(line => line.text).join("")).toBe(source);
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
});
|
||||
|
||||
it("tokenizes the complete large code block without pagination or dropping rows", async () => {
|
||||
const source = Array.from({ length: 1200 }, (_, index) => `const value${index} = ${index};`).join("\n");
|
||||
const value = await lines(source, "typescript");
|
||||
expect(value).toHaveLength(1200);
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
});
|
||||
|
||||
it("keeps multiline lexical context and produces the existing keyword/string palette", async () => {
|
||||
const value = await lines("/* start\ncomment\n*/\nexport const value = 'yes';", "typescript");
|
||||
expect(value[1].tokens.some(token => token.color === "var(--code-comment)" && token.fontStyle === 1)).toBe(true);
|
||||
expect(value[3].tokens.some(token => token.color === "var(--code-keyword)" && token.content.trim() === "export")).toBe(true);
|
||||
expect(value[3].tokens.some(token => token.color === "var(--code-string)" && token.content === "'yes'")).toBe(true);
|
||||
});
|
||||
|
||||
it("retains INI configuration-file colors", async () => {
|
||||
const source = "; comment\n[server]\nhost=localhost\n";
|
||||
const value = await lines(source, "ini");
|
||||
expect(value.flatMap(line => line.tokens).map(token => token.content).join("")).toBe(source);
|
||||
expect(value[0].tokens.some(token => token.color === "var(--code-comment)")).toBe(true);
|
||||
expect(value[1].tokens.some(token => token.color === "var(--code-property)")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps an unknown language readable and never turns source into active HTML", async () => {
|
||||
const source = "<script>alert('x')</script><img onerror='bad()'>";
|
||||
render(<pre data-testid="source"><CodeTokens lines={await lines(source, "unknown-file-format")} /></pre>);
|
||||
expect(screen.getByTestId("source").textContent).toBe(source);
|
||||
expect(document.querySelector("script, img")).toBeNull();
|
||||
});
|
||||
|
||||
it("reuses source revisions but does not return stale text after an edit", async () => {
|
||||
const source = "export const value = 1;";
|
||||
expect(codeHighlight(source, "typescript")).toBe(codeHighlight(source, "typescript"));
|
||||
const changed = await lines(source.replace("1", "2"), "typescript");
|
||||
expect(changed.flatMap(line => line.tokens).map(token => token.content).join("")).toBe("export const value = 2;");
|
||||
});
|
||||
});
|
||||
@@ -1,161 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { parse } from "postcss";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
|
||||
const globalStyles = parse(readFileSync(resolve(process.cwd(), "src/globals.css"), "utf8"));
|
||||
// happy-dom does not apply cascade layers; retain the real rules and their order.
|
||||
globalStyles.walkAtRules("layer", (layer) => {
|
||||
layer.replaceWith(...(layer.nodes ?? []));
|
||||
});
|
||||
|
||||
describe("DiffSyntaxHighlight with Prism", () => {
|
||||
it("loads the TSX grammar and renders styled syntax tokens", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="tsx"
|
||||
lines={[
|
||||
{
|
||||
kind: "context",
|
||||
old_lineno: 1,
|
||||
new_lineno: 1,
|
||||
content: 'import { useMemo } from "react";',
|
||||
},
|
||||
{
|
||||
kind: "delete",
|
||||
old_lineno: 2,
|
||||
new_lineno: null,
|
||||
content: "export function StatusBadge() {",
|
||||
},
|
||||
{
|
||||
kind: "add",
|
||||
old_lineno: null,
|
||||
new_lineno: 2,
|
||||
content: "export function StatusBadge(): JSX.Element {",
|
||||
},
|
||||
{
|
||||
kind: "context",
|
||||
old_lineno: 3,
|
||||
new_lineno: 3,
|
||||
content: ' return <span className="badge">ready</span>;',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
// Full-suite workers can keep the first Prism grammar import busy for more
|
||||
// than Testing Library's one-second default, especially on Windows.
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await waitFor(
|
||||
() => {
|
||||
const tokens = highlighted.querySelectorAll<HTMLElement>(
|
||||
"td:last-child .token",
|
||||
);
|
||||
expect(tokens).not.toHaveLength(0);
|
||||
expect(highlighted.querySelector(".token.keyword")).not.toBeNull();
|
||||
expect(highlighted.querySelector(".token.string")).not.toBeNull();
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
|
||||
expect(highlighted).toHaveAttribute("data-language", "tsx");
|
||||
expect(highlighted.querySelectorAll("tbody tr")).toHaveLength(4);
|
||||
});
|
||||
|
||||
it.each(["light", "dark"] as const)(
|
||||
"preserves nested JSX token colors in the %s appearance",
|
||||
async (appearance) => {
|
||||
const { container } = render(
|
||||
<div className={appearance === "dark" ? "dark" : ""}>
|
||||
<style>{globalStyles.toString()}</style>
|
||||
<DiffSyntaxHighlight
|
||||
language="tsx"
|
||||
lines={[{
|
||||
kind: "add",
|
||||
old_lineno: null,
|
||||
new_lineno: 1,
|
||||
content: '<span className={enabled ? "yes" : "no"} onClick={() => save(new Event("ok"))}>ready</span>',
|
||||
}]}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(highlighted.querySelector(".token.function")).not.toBeNull();
|
||||
}, { timeout: 10_000 });
|
||||
|
||||
const colors = getComputedStyle(
|
||||
appearance === "dark" ? container.firstElementChild! : document.documentElement,
|
||||
);
|
||||
const tokens = [...highlighted.querySelectorAll<HTMLElement>(".token")];
|
||||
for (const [text, category, variable] of [
|
||||
['"yes"', "string", "--code-string"],
|
||||
["new", "keyword", "--code-keyword"],
|
||||
["save", "function", "--code-function"],
|
||||
["=>", "operator", "--code-function"],
|
||||
["className", "attr-name", "--code-property"],
|
||||
["span", "tag", "--code-property"],
|
||||
]) {
|
||||
const token = tokens.find(
|
||||
(node) => node.textContent === text && node.classList.contains(category),
|
||||
);
|
||||
const expectedColor = colors.getPropertyValue(variable).trim();
|
||||
expect(token, `${category}: ${text}`).toBeDefined();
|
||||
expect(expectedColor).not.toBe("");
|
||||
expect.soft(getComputedStyle(token!).color, `${category}: ${text}`).toBe(expectedColor);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves markdown table line boundaries", async () => {
|
||||
const lines = [
|
||||
"## 发布安排",
|
||||
"",
|
||||
"| 日期 | 角色 | 方向 | 是否进实验 |",
|
||||
"| --- | --- | --- | --- |",
|
||||
"| 7/22 | trust / core | data-driven | yes |",
|
||||
];
|
||||
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="markdown"
|
||||
lines={lines.map((content, index) => ({
|
||||
kind: "add" as const,
|
||||
old_lineno: null,
|
||||
new_lineno: 20 + index,
|
||||
content,
|
||||
}))}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
|
||||
const highlighted = await screen.findByTestId(
|
||||
"syntax-highlighted-diff-hunk",
|
||||
{},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
const rows = [...highlighted.querySelectorAll("tbody tr")];
|
||||
|
||||
expect(rows).toHaveLength(lines.length);
|
||||
expect(rows.map((row) => row.querySelector("td:last-child")?.textContent)).toEqual(
|
||||
lines.map((line) => line || " "),
|
||||
);
|
||||
expect(highlighted.querySelector(".token.table")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,84 +1,85 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
|
||||
import { ThemeProvider } from "@/hooks/useTheme";
|
||||
import { getDiffMetadata } from "@/components/thread/activity/PierreFileDiff";
|
||||
import { DIFF_GAP_HEIGHT, diffRenderWindow, diffRowOffsets } from "@/components/thread/activity/diff-render-window";
|
||||
import { parseRenderableFileDiff } from "@/lib/file-diff";
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => {
|
||||
const MockSyntaxHighlighter = ({
|
||||
children,
|
||||
language,
|
||||
renderer,
|
||||
...props
|
||||
}: {
|
||||
children: string;
|
||||
language: string;
|
||||
renderer: (args: {
|
||||
rows: Array<{
|
||||
type: "element";
|
||||
tagName: "span";
|
||||
properties: { className: string[] };
|
||||
children: Array<{ type: "text"; value: string }>;
|
||||
}>;
|
||||
stylesheet: Record<string, React.CSSProperties>;
|
||||
useInlineStyles: boolean;
|
||||
}) => ReactNode;
|
||||
[key: string]: unknown;
|
||||
}) => (
|
||||
<div data-testid={String(props["data-testid"])} data-language={language}>
|
||||
{renderer({
|
||||
rows: children.split("\n").map((line) => ({
|
||||
type: "element" as const,
|
||||
tagName: "span" as const,
|
||||
properties: { className: ["token", "keyword"] },
|
||||
children: [{ type: "text" as const, value: `${line}\n` }],
|
||||
})),
|
||||
stylesheet: {},
|
||||
useInlineStyles: true,
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
return { default: MockSyntaxHighlighter };
|
||||
});
|
||||
const patch = (name: string, content: string, start = 20) => `--- a/${name}\n+++ b/${name}\n@@ -0,0 +${start},1 @@\n+${content}\n`;
|
||||
|
||||
vi.mock("react-syntax-highlighter/dist/esm/create-element", () => ({
|
||||
default: ({ node }: { node: { children?: Array<{ value?: string }> } }) => (
|
||||
<span data-testid="syntax-token">{node.children?.[0]?.value}</span>
|
||||
),
|
||||
}));
|
||||
describe("file diff render metadata", () => {
|
||||
it("preserves complete source and coordinates and reuses a revision across remounts", () => {
|
||||
const text = "--- a/fixture.ts\n+++ b/fixture.ts\n@@ -4,3 +4,3 @@\n export function run() {\n- return oldValue;\n+ return newValue;\n \n";
|
||||
const file = getDiffMetadata(text, "typescript");
|
||||
expect(file.hunks).toHaveLength(1);
|
||||
expect(file.hunks[0]).toMatchObject({ deletionStart: 4, additionStart: 4, deletionCount: 3, additionCount: 3, unifiedLineCount: 4 });
|
||||
expect(file.deletionLines).toEqual(["export function run() {\n", " return oldValue;\n", "\n"]);
|
||||
expect(file.additionLines).toEqual(["export function run() {\n", " return newValue;\n", "\n"]);
|
||||
expect(getDiffMetadata(text, "typescript")).toBe(file);
|
||||
expect(getDiffMetadata(text.replace("newValue", "changedValue"), "typescript").cacheKey).not.toBe(file.cacheKey);
|
||||
expect(getDiffMetadata(text, "javascript").cacheKey).not.toBe(file.cacheKey);
|
||||
});
|
||||
|
||||
describe("DiffSyntaxHighlight", () => {
|
||||
it("highlights a complete hunk while preserving diff rows and line numbers", async () => {
|
||||
render(
|
||||
<ThemeProvider theme="light">
|
||||
<DiffSyntaxHighlight
|
||||
language="typescript"
|
||||
lines={[
|
||||
{ kind: "context", old_lineno: 4, new_lineno: 4, content: "export function run() {" },
|
||||
{ kind: "delete", old_lineno: 5, new_lineno: null, content: " return oldValue;" },
|
||||
{ kind: "add", old_lineno: null, new_lineno: 5, content: " return newValue;" },
|
||||
]}
|
||||
/>
|
||||
</ThemeProvider>,
|
||||
);
|
||||
it.each([["markup", "html"], ["docker", "dockerfile"], ["ini", "ini"], ["lock", "text"]])("maps %s to %s without losing source", (language, expected) => {
|
||||
const file = getDiffMetadata(patch("fixture", "<span>中文 & text</span>"), language);
|
||||
expect(file.lang).toBe(expected);
|
||||
expect(file.additionLines).toEqual(["<span>中文 & text</span>\n"]);
|
||||
expect(file.hunks[0]).toMatchObject({ deletionCount: 0, additionStart: 20, additionCount: 1 });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
it("evicts older revisions under the entry budget without reusing their identity", () => {
|
||||
const text = patch("old.ts", "old revision");
|
||||
const old = getDiffMetadata(text, "typescript");
|
||||
for (let i = 0; i < 16; i++) getDiffMetadata(patch(`revision-${i}.ts`, `const item = ${i};`), "typescript");
|
||||
const reloaded = getDiffMetadata(text, "typescript");
|
||||
expect(reloaded.cacheKey).not.toBe(old.cacheKey);
|
||||
expect(reloaded.additionLines).toEqual(old.additionLines);
|
||||
});
|
||||
});
|
||||
|
||||
const highlighted = await screen.findByTestId("syntax-highlighted-diff-hunk");
|
||||
expect(highlighted).toHaveAttribute("data-language", "typescript");
|
||||
expect(screen.getAllByTestId("syntax-token")).toHaveLength(3);
|
||||
expect(screen.getByText("return oldValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-diff-deleted",
|
||||
);
|
||||
expect(screen.getByText("return newValue;", { exact: false }).closest("tr")).toHaveClass(
|
||||
"bg-diff-added",
|
||||
);
|
||||
expect(screen.getAllByText("5")).toHaveLength(2);
|
||||
expect(screen.getAllByTestId("syntax-token").some((node) => node.textContent?.endsWith("\n"))).toBe(false);
|
||||
describe("file diff render windows", () => {
|
||||
const lines = Array.from({ length: 200 }, (_, i) => `+export const item${i} = ${i};`);
|
||||
const text = `--- a/fixture.ts\n+++ b/fixture.ts\n@@ -0,0 +1,200 @@\n${lines.join("\n")}\n@@ -500,0 +501,200 @@\n${lines.join("\n")}\n`;
|
||||
const diff = parseRenderableFileDiff({ format: "unified", text });
|
||||
|
||||
it("keeps the initial 160-line disclosure bounded and reserves no space for hidden content", () => {
|
||||
const offsets = diffRowOffsets(diff, 160, 24);
|
||||
expect(offsets).toHaveLength(161);
|
||||
expect(offsets.at(-1)).toBe(160 * 24);
|
||||
expect(diffRenderWindow(diff, offsets, 0, 900, 24)).toEqual({ startingLine: 0, totalLines: 160, bufferBefore: 0, bufferAfter: 0 });
|
||||
});
|
||||
|
||||
it("retains a fixed row budget while an overlapping viewport remains in the same start chunk", () => {
|
||||
const offsets = diffRowOffsets(diff, 400, 24);
|
||||
expect(diffRenderWindow(diff, offsets, -900, 1800, 24)).toEqual(diffRenderWindow(diff, offsets, -300, 2400, 24));
|
||||
});
|
||||
|
||||
it("covers the requested overscan in short and tall reading viewports", () => {
|
||||
for (const lineHeight of [21.1875, 23.59375, 26]) {
|
||||
const offsets = diffRowOffsets(diff, 400, lineHeight);
|
||||
const height = offsets.at(-1)!;
|
||||
for (const viewportHeight of [240, 390, 844, 1050]) {
|
||||
for (let y = 0; y < height; y += lineHeight * 10) {
|
||||
const top = y - viewportHeight;
|
||||
const bottom = y + viewportHeight * 2;
|
||||
const window = diffRenderWindow(diff, offsets, top, bottom, lineHeight);
|
||||
expect(window.bufferBefore).toBeLessThanOrEqual(Math.max(0, top));
|
||||
expect(height - window.bufferAfter).toBeGreaterThanOrEqual(Math.min(height, bottom));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves total geometry and gap ownership across adjacent virtual windows", () => {
|
||||
const offsets = diffRowOffsets(diff, 400, 24);
|
||||
expect(offsets.at(-1)).toBe(400 * 24 + DIFF_GAP_HEIGHT);
|
||||
const first = diffRenderWindow(diff, offsets, 0, 3840, 24);
|
||||
expect(first).toEqual({ startingLine: 0, totalLines: 200, bufferBefore: 0, bufferAfter: 200 * 24 + DIFF_GAP_HEIGHT });
|
||||
const second = diffRenderWindow(diff, offsets, 4827, 6000, 24);
|
||||
expect(second.startingLine).toBe(200);
|
||||
expect(second.bufferBefore).toBe(200 * 24);
|
||||
expect(second.totalLines * 24 + DIFF_GAP_HEIGHT + second.bufferBefore + second.bufferAfter).toBe(offsets.at(-1));
|
||||
const tail = diffRenderWindow(diff, offsets, 30000, 32000, 24);
|
||||
expect(tail.startingLine + tail.totalLines).toBe(400);
|
||||
expect(tail.bufferAfter).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -108,17 +108,24 @@ function BspWorkbenchHarness() {
|
||||
}
|
||||
|
||||
describe("PaneWorkbench", () => {
|
||||
it("keeps a single conversation's header inside that pane instead of above its previews", () => {
|
||||
it("keeps a single conversation's header and composer inside its preview layout", () => {
|
||||
const composer = <textarea aria-label="Composer Alpha" />;
|
||||
render(<PaneWorkbench panes={[{ key: "alpha", title: "Alpha" }]} activePaneKey="alpha"
|
||||
layout="columns" chrome showLayoutControl={false} onActivatePane={vi.fn()} onAddPane={vi.fn()}
|
||||
onLayoutChange={vi.fn()} onPaneOrderChange={vi.fn()}
|
||||
renderPane={(_pane, context) => {
|
||||
expect(context.headerPortalTarget).toBeUndefined();
|
||||
expect(context.multiplePanes).toBe(false);
|
||||
return <div data-testid="local-toolbar">{context.headerActions}</div>;
|
||||
return <div data-testid="local-toolbar">
|
||||
{context.headerActions}
|
||||
{context.composerPortalTarget === undefined ? composer : context.composerPortalTarget
|
||||
? createPortal(composer, context.composerPortalTarget) : null}
|
||||
</div>;
|
||||
}} />);
|
||||
expect(screen.getByTestId("workbench-header-host")).toBeEmptyDOMElement();
|
||||
expect(within(screen.getByTestId("local-toolbar")).getByRole("button", { name: "Add pane" })).toBeVisible();
|
||||
const conversation = screen.getByTestId("local-toolbar");
|
||||
expect(within(conversation).getByRole("button", { name: "Add pane" })).toBeVisible();
|
||||
expect(within(conversation).getByRole("textbox", { name: "Composer Alpha" })).toBeVisible();
|
||||
});
|
||||
|
||||
const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
|
||||
@@ -168,7 +175,7 @@ describe("PaneWorkbench", () => {
|
||||
.toEqual(["Alpha", "Beta"]);
|
||||
expect(screen.getByRole("button", { name: "Focus Alpha" })).toHaveAttribute("data-multiple-panes", "true");
|
||||
expect(screen.getByRole("button", { name: "Focus Beta" })).toHaveAttribute("data-multiple-panes", "true");
|
||||
expect(screen.getByLabelText("Composer Beta")).toBeVisible();
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByLabelText("Composer Beta")).toBeVisible();
|
||||
expect(screen.getByLabelText("Composer Alpha")).not.toBeVisible();
|
||||
|
||||
fireEvent.pointerDown(
|
||||
@@ -400,7 +407,12 @@ describe("PaneWorkbench", () => {
|
||||
renderPane: (pane: { key: string; title: string }, context: {
|
||||
headerActions: ReactNode;
|
||||
multiplePanes: boolean;
|
||||
}) => <>{context.headerActions}<span data-multiple-panes={context.multiplePanes}>{pane.title}</span></>,
|
||||
composerPortalTarget: HTMLElement | null | undefined;
|
||||
}) => <>{context.headerActions}<span data-multiple-panes={context.multiplePanes}>{pane.title}</span>
|
||||
{context.composerPortalTarget ? createPortal(
|
||||
<textarea aria-label={`Composer ${pane.title}`} />, context.composerPortalTarget,
|
||||
) : null}
|
||||
</>,
|
||||
};
|
||||
|
||||
const { rerender } = render(<PaneWorkbench {...props} activePaneKey="gamma" />);
|
||||
@@ -408,6 +420,7 @@ describe("PaneWorkbench", () => {
|
||||
expect(screen.getByTestId("pane-grid").children).toHaveLength(1);
|
||||
expect(screen.getByTestId("workbench-pane-gamma")).toBeInTheDocument();
|
||||
expect(screen.getByText("gamma", { selector: "span" })).toHaveAttribute("data-multiple-panes", "false");
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByRole("textbox", { name: "Composer gamma" })).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Layout" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Add pane" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("separator")).not.toBeInTheDocument();
|
||||
@@ -415,6 +428,7 @@ describe("PaneWorkbench", () => {
|
||||
rerender(<PaneWorkbench {...props} activePaneKey="delta" />);
|
||||
expect(screen.getByTestId("pane-grid").children).toHaveLength(1);
|
||||
expect(screen.getByTestId("workbench-pane-delta")).toBeInTheDocument();
|
||||
expect(within(screen.getByTestId("workbench-composer-host")).getByRole("textbox", { name: "Composer delta" })).toBeVisible();
|
||||
expect(screen.queryByTestId("workbench-pane-gamma")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -11,6 +11,12 @@ import {
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
||||
vi.mock("@/components/thread/activity/DiffSyntaxHighlight", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/components/thread/activity/DiffSyntaxHighlight")>();
|
||||
return { ...actual, DiffSyntaxHighlight: actual.PlainDiffLines };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import SyntaxHighlighter from "react-syntax-highlighter/dist/esm/prism-light";
|
||||
import markup from "react-syntax-highlighter/dist/esm/languages/prism/markup";
|
||||
import oneLight from "react-syntax-highlighter/dist/esm/styles/prism/one-light";
|
||||
import { codeHighlight } from "@/lib/code-highlighter";
|
||||
|
||||
import { ViewportCodeRows } from "@/components/ViewportCodeRows";
|
||||
|
||||
SyntaxHighlighter.registerLanguage("markup", markup);
|
||||
|
||||
let notify: (entries: IntersectionObserverEntry[]) => void;
|
||||
const disconnect = vi.fn();
|
||||
const observe = vi.fn();
|
||||
@@ -25,8 +21,7 @@ function sourceText() {
|
||||
return [...document.querySelectorAll("[data-highlighted]")].map(node => node.textContent).join("");
|
||||
}
|
||||
function preview(code: string) {
|
||||
return <div data-file-preview-scroll><SyntaxHighlighter language="markup" style={oneLight}
|
||||
renderer={props => <ViewportCodeRows {...props} />}>{code}</SyntaxHighlighter></div>;
|
||||
return <div data-file-preview-scroll><ViewportCodeRows lines={codeHighlight(code, "markup").read()} /></div>;
|
||||
}
|
||||
|
||||
describe("viewport code highlighting", () => {
|
||||
|
||||
@@ -70,14 +70,18 @@ describe("entryLazyFeatureImports", () => {
|
||||
expect(entryLazyFeatureImports(["assets/react-vendor-abc.js"])).toEqual([]);
|
||||
expect(entryLazyFeatureImports([
|
||||
"assets/markdown-vendor-abc.js",
|
||||
"assets/syntax-highlight-def.js",
|
||||
"assets/katex-ghi.js",
|
||||
"assets/MermaidBlock-jkl.js",
|
||||
"assets/HighlightedCode-def.js",
|
||||
"assets/code-highlighter-ghi.js",
|
||||
"assets/PierreFileDiff-jkl.js",
|
||||
"assets/katex-mno.js",
|
||||
"assets/MermaidBlock-pqr.js",
|
||||
])).toEqual([
|
||||
"assets/markdown-vendor-abc.js",
|
||||
"assets/syntax-highlight-def.js",
|
||||
"assets/katex-ghi.js",
|
||||
"assets/MermaidBlock-jkl.js",
|
||||
"assets/HighlightedCode-def.js",
|
||||
"assets/code-highlighter-ghi.js",
|
||||
"assets/PierreFileDiff-jkl.js",
|
||||
"assets/katex-mno.js",
|
||||
"assets/MermaidBlock-pqr.js",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -100,12 +104,6 @@ describe("webuiManualChunk", () => {
|
||||
expect(webuiManualChunk("\0vite/preload-helper.js")).toBe("react-vendor");
|
||||
});
|
||||
|
||||
it("keeps Refractor's selector parser in the syntax highlighting chunk", () => {
|
||||
expect(
|
||||
webuiManualChunk("/repo/node_modules/hast-util-parse-selector/index.js"),
|
||||
).toBe("syntax-highlight");
|
||||
});
|
||||
|
||||
it("keeps markdown-only hast utilities in the markdown chunk", () => {
|
||||
expect(
|
||||
webuiManualChunk("/repo/node_modules/hast-util-to-jsx-runtime/lib/index.js"),
|
||||
@@ -132,6 +130,6 @@ describe("webuiManualChunk", () => {
|
||||
});
|
||||
|
||||
it("leaves language grammars as independently loaded chunks", () => {
|
||||
expect(webuiManualChunk("/repo/node_modules/refractor/lang/python.js")).toBeUndefined();
|
||||
expect(webuiManualChunk("/repo/node_modules/@shikijs/langs/dist/ini.mjs")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,22 +0,0 @@
|
||||
declare module "react-syntax-highlighter/dist/esm/prism-async-light" {
|
||||
import * as React from "react";
|
||||
import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
|
||||
|
||||
export default class SyntaxHighlighter extends React.Component<SyntaxHighlighterProps> {
|
||||
static registerLanguage(name: string, func: unknown): void;
|
||||
}
|
||||
}
|
||||
|
||||
declare module "react-syntax-highlighter/dist/esm/styles/prism/one-dark" {
|
||||
import type * as React from "react";
|
||||
|
||||
const style: { [key: string]: React.CSSProperties };
|
||||
export default style;
|
||||
}
|
||||
|
||||
declare module "react-syntax-highlighter/dist/esm/styles/prism/one-light" {
|
||||
import type * as React from "react";
|
||||
|
||||
const style: { [key: string]: React.CSSProperties };
|
||||
export default style;
|
||||
}
|
||||
Reference in new issue
Block a user