feat(webui): render Mermaid diagrams with Pele (#6302)

* feat(webui): render Mermaid diagrams with Pele

* fix(webui): reserve diagram replacement capacity

* fix(webui): prebundle lazy diagram worker dependencies

* fix(webui): account diagram capacity by encoded size

* fix(webui): use shared hover hints for diagram actions

* docs(webui): focus diagram guide on usage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-19 17:16:20 +08:00
1 parent 0f3b47bc3a
commit f57018aa7f
40 files changed
+2335 -1458

No files matched your search

+7 -33
View File
@@ -20,7 +20,8 @@ import { parseMathAwareMarkdownBlocks } from "@/lib/markdown-streaming-blocks";
import { DisplayMath } from "@/components/DisplayMath";
import { AttachmentTile } from "@/components/AttachmentTile";
import { CodeBlock } from "@/components/CodeBlock";
import { MarkdownCodeBlock } from "@/components/markdown-diagrams/MarkdownCodeBlock";
import { MarkdownCodeContext } from "@/components/markdown-diagrams/context";
import { WebLink } from "@/components/WebLink";
import {
INLINE_TOKEN_HIGHLIGHT_COLOR,
@@ -559,12 +560,6 @@ function useFaviconFallback(host: string) {
};
}
function isRenderedCodeBlock(value: ReactNode): boolean {
if (!isValidElement(value)) return false;
const props = value.props as { code?: unknown };
return value.type === CodeBlock || typeof props.code === "string";
}
function codeFenceFromPreChild(value: ReactNode): { code: string; language?: string } | null {
if (!isValidElement(value)) return null;
const props = value.props as { className?: unknown; children?: ReactNode };
@@ -609,19 +604,6 @@ export default function MarkdownTextRenderer({
() => ({
code({ className: cls, children: kids, node: _node, ...props }) {
void _node;
const match = /language-(\w+)/.exec(cls || "");
if (match) {
const code = String(kids).replace(/\n$/, "");
return (
<CodeBlock
language={match[1]}
code={code}
className="my-3"
highlight={highlightCode}
showLineNumbers={code.includes("\n")}
/>
);
}
const raw = String(kids).replace(/\n$/, "");
if (!documentPath && isLikelyFilePath(raw)) {
return (
@@ -662,20 +644,10 @@ export default function MarkdownTextRenderer({
pre({ children: markdownChildren }) {
const kids = Children.toArray(markdownChildren);
const lone = kids.length === 1 ? kids[0] : null;
/** Highlighted fences render ``CodeBlock`` (block shell); skip invalid ``<pre><div>``. */
if (isRenderedCodeBlock(lone)) {
return <>{markdownChildren}</>;
}
const fence = codeFenceFromPreChild(lone);
if (fence) {
return (
<CodeBlock
language={fence.language || "text"}
code={fence.code}
className="my-3"
highlight={highlightCode}
showLineNumbers={fence.code.includes("\n")}
/>
<MarkdownCodeBlock language={fence.language} code={fence.code} />
);
}
return (
@@ -896,10 +868,11 @@ export default function MarkdownTextRenderer({
);
},
}),
[highlightCode, onOpenFilePreview, documentPath, t],
[onOpenFilePreview, documentPath, t],
);
return (
<MarkdownCodeContext.Provider value={{ streaming, highlight: highlightCode }}>
<Streamdown
key={needsMath && mathPlugin ? "math" : "text"}
mode={streaming || preserveStreamingLayout ? "streaming" : "static"}
@@ -927,8 +900,9 @@ export default function MarkdownTextRenderer({
className,
)}
>
{/* Streamdown 2.5 ignores repair-option changes in its memo comparator. */}
{/* Repair follows generation, independently of the preserved layout mode. */}
{streaming ? remend(children, REMEND_OPTIONS) : children}
</Streamdown>
</MarkdownCodeContext.Provider>
);
}
+11 -116
View File
@@ -1,119 +1,14 @@
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
import { Minus, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ImageViewport } from "@/components/ui/image-viewport";
import { cn } from "@/lib/utils";
type Point = { x: number; y: number };
type View = Point & { scale: number };
const FIT: View = { x: 0, y: 0, scale: 1 };
const MAX_SCALE = 8;
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);
/** Image-local gestures; the surrounding page retains normal browser zoom. Remount per image. */
/** Photo lightbox layout; the gallery retains ownership of the arrow keys. */
export function ZoomableImage({ src, alt }: { src: string; alt: string }) {
const { t } = useTranslation();
const viewport = useRef<HTMLDivElement>(null);
const image = useRef<HTMLImageElement>(null);
const pointers = useRef(new Map<number, Point>());
const viewRef = useRef(FIT);
const [view, setView] = useState(FIT);
const [dragging, setDragging] = useState(false);
const apply = useCallback((next: View) => {
const scale = clamp(next.scale, 1, MAX_SCALE);
const maxX = Math.max(0, ((image.current?.offsetWidth ?? 0) * scale - (viewport.current?.clientWidth ?? 0)) / 2);
const maxY = Math.max(0, ((image.current?.offsetHeight ?? 0) * scale - (viewport.current?.clientHeight ?? 0)) / 2);
const bounded = { scale, x: clamp(next.x, -maxX, maxX), y: clamp(next.y, -maxY, maxY) };
viewRef.current = bounded;
setView(bounded);
}, []);
const zoom = useCallback((scale: number, from?: Point, to = from) => {
const rect = viewport.current?.getBoundingClientRect();
const current = viewRef.current;
const next = clamp(scale, 1, MAX_SCALE);
const center = rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : { x: 0, y: 0 };
const origin = from ?? center;
const target = to ?? origin;
apply({
scale: next,
x: target.x - center.x - (origin.x - center.x - current.x) * next / current.scale,
y: target.y - center.y - (origin.y - center.y - current.y) * next / current.scale,
});
}, [apply]);
useEffect(() => {
const element = viewport.current;
if (!element) return;
// React's wheel listener is passive; cancel browser zoom only over this image viewport.
const onWheel = (event: WheelEvent) => {
if (event.ctrlKey) {
event.preventDefault();
zoom(viewRef.current.scale * Math.exp(-clamp(event.deltaY, -50, 50) * 0.01), { x: event.clientX, y: event.clientY });
} else if (viewRef.current.scale > 1) {
event.preventDefault();
const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? element.clientHeight : 1;
apply({ ...viewRef.current, x: viewRef.current.x - event.deltaX * unit, y: viewRef.current.y - event.deltaY * unit });
}
};
element.addEventListener("wheel", onWheel, { passive: false });
const resize = new ResizeObserver(() => apply(viewRef.current));
resize.observe(element);
return () => { element.removeEventListener("wheel", onWheel); resize.disconnect(); };
}, [apply, zoom]);
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (event.button !== 0 || pointers.current.size >= 2) return;
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
event.currentTarget.setPointerCapture(event.pointerId);
setDragging(true);
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
if (!pointers.current.has(event.pointerId)) return;
const before = [...pointers.current.values()];
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
const after = [...pointers.current.values()];
if (before.length === 2) {
const previousDistance = distance(before[0], before[1]);
if (previousDistance > 0) zoom(viewRef.current.scale * distance(after[0], after[1]) / previousDistance,
midpoint(before[0], before[1]), midpoint(after[0], after[1]));
} else if (viewRef.current.scale > 1) {
apply({ ...viewRef.current, x: viewRef.current.x + after[0].x - before[0].x, y: viewRef.current.y + after[0].y - before[0].y });
}
};
const endPointer = (event: PointerEvent<HTMLDivElement>) => {
pointers.current.delete(event.pointerId);
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(pointers.current.size > 0);
};
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full text-white/90 transition-colors hover:text-white disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70";
return <>
<div ref={viewport} data-testid="image-zoom-viewport" tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("absolute inset-x-3 bottom-[calc(4rem+env(safe-area-inset-bottom))] top-14 flex touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-white/40 sm:inset-x-8", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in")}
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
onDoubleClick={(event) => zoom(view.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
onKeyDown={(event) => {
if (event.key === "+" || event.key === "=") zoom(view.scale * 1.5);
else if (event.key === "-") zoom(view.scale / 1.5);
else if (event.key === "0") apply(FIT);
else return;
event.preventDefault();
}}>
<img ref={image} src={src} alt={alt} decoding="async" draggable={false} onLoad={() => apply(viewRef.current)}
className="max-h-full max-w-full select-none rounded-compact object-contain shadow-2xl will-change-transform"
style={{ transform: `translate3d(${view.x}px, ${view.y}px, 0) scale(${view.scale})` }} />
</div>
<div className="absolute bottom-[calc(1rem+env(safe-area-inset-bottom))] left-1/2 flex -translate-x-1/2 items-center gap-1 rounded-full bg-black/55 p-1 backdrop-blur-sm">
<button type="button" aria-label={t("lightbox.zoomOut")} title={t("lightbox.zoomOut")} disabled={view.scale <= 1} className={buttonClass} onClick={() => zoom(view.scale / 1.5)}><Minus className="size-4" aria-hidden /></button>
<button type="button" aria-label={t("lightbox.resetZoom")} title={t("lightbox.resetZoom")}
className="h-9 min-w-14 rounded-full px-2 text-xs font-medium tabular-nums text-white/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70" onClick={() => apply(FIT)}>
{Math.round(view.scale * 100)}%
</button>
<button type="button" aria-label={t("lightbox.zoomIn")} title={t("lightbox.zoomIn")} disabled={view.scale >= MAX_SCALE} className={buttonClass} onClick={() => zoom(view.scale * 1.5)}><Plus className="size-4" aria-hidden /></button>
</div>
</>;
return <ImageViewport
src={src}
alt={alt}
testId="image-zoom-viewport"
panWithArrows={false}
className="absolute inset-x-3 bottom-[calc(4rem+env(safe-area-inset-bottom))] top-14 focus-visible:ring-white/40 sm:inset-x-8"
imageClassName="rounded-compact shadow-2xl"
controlsClassName="absolute bottom-[calc(1rem+env(safe-area-inset-bottom))] left-1/2 -translate-x-1/2 bg-black/55 text-white/90 backdrop-blur-sm [&_button:first-child:hover]:text-white [&_button:last-child:hover]:text-white [&_button:focus-visible]:ring-white/70"
/>;
}
@@ -0,0 +1,27 @@
import { Component, lazy, Suspense, useContext, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { MarkdownCodeContext } from "./context";
const MermaidBlock = lazy(() => import("./MermaidBlock"));
class DiagramBoundary extends Component<{ children: ReactNode; fallback: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() { return this.state.failed ? this.props.fallback : this.props.children; }
}
export function MarkdownCodeBlock({ code, language }: { code: string; language?: string }) {
const { t } = useTranslation();
const { streaming, highlight } = useContext(MarkdownCodeContext);
const source = <CodeBlock language={language || "text"} code={code} className="my-3" highlight={highlight} showLineNumbers={code.includes("\n")} />;
if (language?.toLowerCase() !== "mermaid") return source;
const preparing = <div aria-busy={streaming}>
<p className="my-1 text-xs text-muted-foreground" role="status">{t("diagram.preparing")}</p>{source}
</div>;
if (streaming) return preparing;
return <DiagramBoundary key={code} fallback={<><p className="text-xs text-muted-foreground" role="status">{t("diagram.errors.load")}</p>{source}</>}>
<Suspense fallback={preparing}><MermaidBlock source={code} /></Suspense>
</DiagramBoundary>;
}
@@ -0,0 +1,148 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { Check, Copy, Maximize2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { HoverHint } from "@/components/ui/hover-hint";
import { ImageViewport } from "@/components/ui/image-viewport";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { useDiagramScope } from "./context";
import { requestDiagram, type DiagramPalette, type DiagramRequest, type DiagramState } from "./runtime";
import type { DiagramInput } from "./types";
function readPalette(element: HTMLElement): DiagramPalette {
const style = getComputedStyle(element);
const color = (token: string) => `hsl(${style.getPropertyValue(token).trim()})`;
return {
"--pele-bg": color("--background"), "--pele-fg": color("--foreground"),
"--pele-muted": color("--muted-foreground"), "--pele-line": color("--foreground"),
"--pele-surface": color("--muted"), "--pele-surface-alt": color("--secondary"),
"--pele-border": color("--border"), "--pele-accent": color("--primary"),
"--pele-critical": color("--destructive"),
};
}
export default function MermaidBlock({ source }: { source: string }) {
const { t } = useTranslation();
const scope = useDiagramScope();
const container = useRef<HTMLDivElement>(null);
const mono = useRef<HTMLSpanElement>(null);
const request = useRef<DiagramRequest | null>(null);
const palette = useRef<DiagramPalette>({});
const visible = useRef(false);
const height = useRef(0);
const [input, setInput] = useState<Omit<DiagramInput, "source"> | null>(null);
const [state, setState] = useState<DiagramState>({ kind: "waiting" });
const [view, setView] = useState<"diagram" | "source">("diagram");
const [open, setOpen] = useState(false);
const [copied, setCopied] = useState(false);
const copyTimer = useRef<ReturnType<typeof setTimeout>>();
const demand = useRef({ view, open });
demand.current = { view, open };
const updateDemand = useCallback(() => request.current?.setDemand(document.hidden || demand.current.view === "source"
? "none" : demand.current.open ? "dialog" : visible.current ? "visible" : "none"), []);
useEffect(() => {
const element = container.current;
if (!element) return;
let active = true;
let frame = 0;
const measure = () => {
if (!active) return;
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const width = Math.floor(element.clientWidth);
if (width <= 0) return;
const style = getComputedStyle(element);
const next = { width, fonts: { sans: style.fontFamily, mono: getComputedStyle(mono.current!).fontFamily, size: 16 } };
// The open viewer fits its existing image; defer layout changes until it closes.
if (!demand.current.open) setInput((previous) => JSON.stringify(previous) === JSON.stringify(next) ? previous : next);
palette.current = readPalette(element);
request.current?.setPalette(palette.current);
});
};
const resize = new ResizeObserver(measure);
resize.observe(element);
const intersection = new IntersectionObserver(([entry]) => {
visible.current = entry.isIntersecting;
updateDemand();
});
intersection.observe(element);
const appearance = new MutationObserver(measure);
appearance.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style"] });
document.addEventListener("visibilitychange", updateDemand);
void document.fonts.ready.then(measure);
measure();
return () => {
active = false;
resize.disconnect(); intersection.disconnect(); appearance.disconnect();
document.removeEventListener("visibilitychange", updateDemand);
cancelAnimationFrame(frame);
};
}, [updateDemand, open]);
useLayoutEffect(() => { setOpen(false); }, [source, scope]);
useLayoutEffect(() => {
setState({ kind: "waiting" });
if (!input) return;
const controller = new AbortController();
const handle = requestDiagram({ ...input, source }, controller.signal, (next) => {
if (controller.signal.aborted) return;
if (next.kind === "ready") height.current = Math.min(448, next.image.height * Math.min(1, input.width / next.image.width));
setState(next);
});
request.current = handle;
handle.setPalette(palette.current);
updateDemand();
return () => { controller.abort(); request.current = null; };
}, [source, scope, input, updateDemand]);
useEffect(() => { updateDemand(); }, [view, open, updateDemand]);
useEffect(() => () => clearTimeout(copyTimer.current), []);
const copy = async () => {
if (!await copyTextToClipboard(source)) return;
setCopied(true);
clearTimeout(copyTimer.current);
copyTimer.current = setTimeout(() => setCopied(false), 2000);
};
const buttonClass = "rounded px-2 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
const showSource = view === "source" || state.kind === "failed";
const image = state.kind === "ready" ? state.image : null;
return <div ref={container} className="not-prose my-3 min-w-0 overflow-hidden rounded-lg border border-border/60" data-testid="mermaid-block">
<span ref={mono} className="hidden font-mono" aria-hidden />
<div className="flex flex-wrap items-center gap-1 border-b border-border/60 px-2 py-1">
<span className="mr-auto px-1 text-xs text-muted-foreground">Mermaid</span>
<button type="button" aria-pressed={view === "diagram"} className={cn(buttonClass, view === "diagram" && "bg-muted text-foreground")} onClick={() => setView("diagram")}>{t("diagram.graph")}</button>
<button type="button" aria-pressed={view === "source"} className={cn(buttonClass, view === "source" && "bg-muted text-foreground")} onClick={() => setView("source")}>{t("diagram.source")}</button>
<HoverHint content={t("diagram.copy")}>
<button type="button" className={buttonClass} aria-label={t("diagram.copy")} onClick={() => void copy()}>
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
</button>
</HoverHint>
<Dialog open={open && !!image} onOpenChange={setOpen}>
<HoverHint content={t("diagram.enlarge")}>
<DialogTrigger asChild><button type="button" className={buttonClass} aria-label={t("diagram.enlarge")} disabled={!image}><Maximize2 className="h-3.5 w-3.5" /></button></DialogTrigger>
</HoverHint>
<DialogContent className="h-[85dvh] max-w-[min(96vw,90rem)] gap-0 overflow-hidden p-3 sm:p-4" aria-describedby={undefined}>
<DialogTitle className="sr-only">{t("diagram.title")}</DialogTitle>
{image && <div className="flex h-full min-h-0 flex-col gap-2 pt-6"><ImageViewport src={image.url} alt={image.label || t("diagram.title")} className="flex-1" /></div>}
</DialogContent>
</Dialog>
</div>
{state.kind === "failed" && <div className="flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground" role="status">
<span>{t(`diagram.errors.${state.reason}`)}</span>
{["load", "worker", "deadline", "image"].includes(state.reason) && <button type="button" className={buttonClass} onClick={() => request.current?.retry()}>{t("common.retry")}</button>}
</div>}
{showSource ? <CodeBlock language="mermaid" code={source} chrome="none" highlight={false} showLineNumbers={source.includes("\n")} />
: image ? <div className="flex justify-center p-3"><img src={image.url} alt={image.label || t("diagram.title")} width={image.width} height={image.height} className="max-h-[28rem] max-w-full object-contain" /></div>
: <div className="px-3 py-2" style={{ minHeight: height.current || undefined }}>
<p className="m-0 py-1 text-xs text-muted-foreground" role="status">{t("diagram.preparing")}</p>
{!height.current && <CodeBlock language="mermaid" code={source} chrome="none" highlight={false} />}
</div>}
</div>;
}
@@ -0,0 +1,14 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
export const MarkdownCodeContext = createContext({ streaming: false, highlight: true });
const ScopeContext = createContext<object | null>(null);
// Context invalidates resource effects even through memoized Markdown fences.
export function DiagramScope({ identity, children }: { identity: string | null; children: ReactNode }) {
const scope = useMemo(() => ({ identity }), [identity]);
return <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider>;
}
export function useDiagramScope() {
return useContext(ScopeContext);
}
@@ -0,0 +1,42 @@
import { detectType, load, render, PeleError } from "pele/lazy";
import { canvasTextMeasurer } from "./render";
import { diagramImageTemplate, DiagramImageError } from "./svg-image";
import {
MAX_DIMENSION, OUTPUT_LIMIT, SOURCE_LIMIT,
type DiagramInput, type DiagramReply,
} from "./types";
self.onmessage = async (event: MessageEvent<DiagramInput>) => {
// One attempt per Worker. The parent owns watchdogs, termination, URLs and revisions.
self.onmessage = null;
const reply = (message: DiagramReply) => self.postMessage(message);
let started = false;
try {
const input = event.data;
if (input.source.length > SOURCE_LIMIT || !Number.isFinite(input.width)
|| input.width <= 0 || input.width > MAX_DIMENSION) throw new DiagramImageError("limit");
// detectType preprocesses source config synchronously. The parent's loading
// watchdog is already active here; it also covers all lazy module loading.
const type = detectType(input.source);
if (!await load(type)) throw new DiagramImageError("unsupported");
const measurer = canvasTextMeasurer(input.fonts);
reply({ kind: "started" });
started = true;
const result = render(input.source, {
measurer, fontFamily: input.fonts.sans, fontFamilyMono: input.fonts.mono,
fontSize: input.fonts.size, maxWidth: input.width, responsive: false,
links: false, images: false, limit: SOURCE_LIMIT, outputLimit: OUTPUT_LIMIT,
maxEdges: 500,
});
const template = diagramImageTemplate(result.svg, input.fonts);
if (template.width !== result.width || template.height !== result.height) throw new DiagramImageError("policy");
reply({ kind: "image", template });
} catch (error) {
if (error instanceof DiagramImageError) reply({ kind: "failed", reason: error.reason });
else if (error instanceof PeleError) reply({
kind: "failed", reason: error.code === "limit" ? "limit"
: error.code === "unsupported-diagram" ? "unsupported" : "syntax",
});
else reply({ kind: "failed", reason: started ? "worker" : "load" });
}
};
@@ -0,0 +1,29 @@
import { DiagramImageError } from "./svg-image";
import type { DiagramInput } from "./types";
// Pele's public TextMeasurer contract; the engine import stays in the Worker entry.
export function canvasTextMeasurer(fonts: DiagramInput["fonts"]): {
width(text: string, size: number, style: number): number;
} {
let context: OffscreenCanvasRenderingContext2D | null = null;
try {
if (typeof OffscreenCanvas !== "undefined") context = new OffscreenCanvas(1, 1).getContext("2d");
} catch { /* Capability failure, never Pele's approximate metrics fallback. */ }
if (!context) throw new DiagramImageError("capability");
const canvas = context;
return {
width(text, size, style) {
if (!Number.isFinite(size) || size <= 0 || size > 200 || (style & ~7) !== 0) {
throw new DiagramImageError("unsupported");
}
const font = `${style & 2 ? "italic " : ""}${style & 1 ? "bold " : ""}${size}px ${style & 4 ? fonts.mono : fonts.sans}`;
// Reset first so an invalid canvas font cannot reuse the preceding measurement.
canvas.font = "1px serif";
canvas.font = font;
if (canvas.font === "1px serif") throw new DiagramImageError("capability");
const width = canvas.measureText(text).width;
if (!Number.isFinite(width) || width < 0) throw new DiagramImageError("capability");
return width;
},
};
}
@@ -0,0 +1,311 @@
import { MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT, SOURCE_LIMIT } from "./types";
import type { DiagramFailure, DiagramInput, DiagramTemplate } from "./types";
export interface DiagramImage {
url: string;
width: number;
height: number;
label: string;
}
export type DiagramState = { kind: "waiting" | "rendering" }
| { kind: "ready"; image: DiagramImage }
| { kind: "failed"; reason: DiagramFailure };
export type DiagramPalette = Readonly<Record<string, string>>;
export interface DiagramRequest {
setDemand(demand: "none" | "visible" | "dialog"): void;
setPalette(palette: DiagramPalette): void;
retry(): void;
dispose(): void;
}
const RUNNING_LIMIT = 2;
const QUEUE_LIMIT = 4;
const BYTE_LIMIT = 8 * OUTPUT_LIMIT;
const PIXEL_LIMIT = 32_000_000;
const PALETTE_LIMIT = 4096;
// Reserve one largest replacement inside the totals so retained images can always be recolored.
const ADMISSION_BYTE_LIMIT = BYTE_LIMIT - OUTPUT_LIMIT;
const ADMISSION_PIXEL_LIMIT = PIXEL_LIMIT - MAX_PIXELS;
const tasks = new Set<Task>();
const queue: Task[] = [];
let capacityWakePending = false;
let running = 0;
let retainedBytes = 0;
let retainedPixels = 0;
function pump() {
queue.length = 0;
// Prioritize before bounding admission, including a viewer opened behind a full queue.
for (const demand of ["dialog", "visible"] as const) {
for (const task of tasks) {
if (queue.length >= QUEUE_LIMIT) break;
if (task.eligible && task.demand === demand) queue.push(task);
}
}
while (running < RUNNING_LIMIT && queue.length) {
const task = queue.shift()!;
if (task.eligible) task.run();
}
}
function capacityChanged() {
if (capacityWakePending) return;
capacityWakePending = true;
queueMicrotask(() => {
capacityWakePending = false;
for (const task of tasks) task.resumeCapacity();
pump();
});
}
function imageTemplate(value: unknown): value is DiagramTemplate {
if (!value || typeof value !== "object") return false;
const template = value as Partial<DiagramTemplate>;
return typeof template.content === "string" && template.content.length <= OUTPUT_LIMIT
&& typeof template.style === "string" && template.style.length <= 4096
&& typeof template.label === "string" && template.label.length <= 4096
&& typeof template.width === "number" && Number.isFinite(template.width)
&& typeof template.height === "number" && Number.isFinite(template.height)
&& template.width > 0 && template.width <= MAX_DIMENSION
&& template.height > 0 && template.height <= MAX_DIMENSION
&& template.width * template.height <= MAX_PIXELS;
}
const failures = new Set<DiagramFailure>(["syntax", "unsupported", "policy", "limit", "load", "deadline", "worker", "image", "capability"]);
const escapeAttribute = (value: string) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
function paletteStyle(palette: DiagramPalette): string {
return Object.entries(palette).map(([key, value]) => {
if (!/^--pele-(?:bg|fg|muted|line|surface|surface-alt|border|accent|critical|series-[1-8])$/.test(key)
|| !/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\([\d\s%,./+-]+\))$/i.test(value)) {
throw new Error("Invalid diagram palette");
}
return `${key}:${value}`;
}).join(";");
}
class Task implements DiagramRequest {
demand: "none" | "visible" | "dialog" = "none";
private worker: Worker | null = null;
private timer: ReturnType<typeof setTimeout> | undefined;
private disposed = false;
private failed = false;
private capacityBlocked = false;
private template: DiagramTemplate | null = null;
private templateBytes = 0;
private asset: { image: DiagramImage; release: () => void } | null = null;
private decoding: (() => void) | null = null;
private attempt = 0;
private palette: DiagramPalette = {};
constructor(private input: DiagramInput, private signal: AbortSignal, private publish: (state: DiagramState) => void) {
tasks.add(this);
signal.addEventListener("abort", this.dispose, { once: true });
}
get eligible() {
return !this.disposed && this.demand !== "none" && !this.failed && !this.capacityBlocked
&& !this.worker && !this.template && !this.decoding;
}
setDemand(demand: "none" | "visible" | "dialog") {
if (this.disposed || demand === this.demand) return;
this.demand = demand;
if (demand === "none") {
this.capacityBlocked = false;
this.cancel();
this.clearTemplate();
this.asset?.release();
this.asset = null;
if (!this.failed) this.publish({ kind: "waiting" });
}
pump();
}
setPalette(palette: DiagramPalette) {
if (this.disposed || JSON.stringify(palette) === JSON.stringify(this.palette)) return;
this.palette = palette;
if (this.template && !this.failed) this.decode();
}
retry() {
if (this.disposed || !this.failed) return;
this.failed = false;
this.clearTemplate();
this.publish({ kind: "waiting" });
pump();
}
private stopWorker() {
clearTimeout(this.timer);
if (this.worker) {
this.worker.onmessage = null;
this.worker.onerror = null;
this.worker.onmessageerror = null;
this.worker.terminate();
this.worker = null;
running--;
}
}
private cancel() {
this.attempt++;
const index = queue.indexOf(this);
if (index !== -1) queue.splice(index, 1);
this.stopWorker();
this.decoding?.();
this.decoding = null;
}
private clearTemplate() {
if (this.templateBytes) {
retainedBytes -= this.templateBytes;
capacityChanged();
}
this.templateBytes = 0;
this.template = null;
}
private waitForCapacity() {
this.capacityBlocked = true;
if (!this.asset) this.publish({ kind: "waiting" });
}
resumeCapacity() {
if (!this.capacityBlocked || this.disposed) return;
this.capacityBlocked = false;
if (this.template && this.demand !== "none" && !this.failed) this.decode();
}
private fail(reason: DiagramFailure) {
this.cancel();
this.failed = true;
this.clearTemplate();
this.asset?.release();
this.asset = null;
this.publish({ kind: "failed", reason });
queueMicrotask(pump);
}
run() {
if (this.input.source.length > SOURCE_LIMIT) { this.fail("limit"); return; }
if (typeof Worker === "undefined") { this.fail("capability"); return; }
this.publish({ kind: "rendering" });
try {
const worker = new Worker(new URL("./pele.worker.ts", import.meta.url), { type: "module" });
this.worker = worker;
running++;
const attempt = ++this.attempt;
this.timer = setTimeout(() => this.fail("load"), 10_000);
worker.onmessage = ({ data }: MessageEvent<unknown>) => {
if (this.disposed || this.worker !== worker || attempt !== this.attempt) return;
if (!data || typeof data !== "object" || !("kind" in data)) { this.fail("worker"); return; }
if (data.kind === "started") {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.fail("deadline"), 2000);
} else if (data.kind === "image" && "template" in data && imageTemplate(data.template)) {
this.stopWorker();
const bytes = new Blob([data.template.content, data.template.style]).size;
if (bytes > OUTPUT_LIMIT) { this.fail("limit"); return; }
if (retainedBytes + bytes > ADMISSION_BYTE_LIMIT) { this.waitForCapacity(); pump(); return; }
this.template = data.template;
this.templateBytes = bytes;
retainedBytes += bytes;
this.decode();
pump();
} else if (data.kind === "failed" && "reason" in data && failures.has(data.reason as DiagramFailure)) {
this.fail(data.reason as DiagramFailure);
} else this.fail("worker");
};
worker.onerror = worker.onmessageerror = () => this.fail("worker");
worker.postMessage(this.input);
} catch { this.fail("worker"); }
}
private decode() {
const template = this.template;
if (!template || this.disposed || this.demand === "none") return;
this.decoding?.();
const attempt = ++this.attempt;
let blob: Blob;
let paletteBytes: number;
try {
const palette = paletteStyle(this.palette);
paletteBytes = new Blob([palette]).size;
if (paletteBytes > PALETTE_LIMIT) { this.fail("limit"); return; }
const style = escapeAttribute(`${template.style};${palette}`);
blob = new Blob([`<svg xmlns="http://www.w3.org/2000/svg" width="${template.width}" height="${template.height}" viewBox="0 0 ${template.width} ${template.height}" fill="var(--_fg)" style="${style}">${template.content}</svg>`], { type: "image/svg+xml" });
} catch { this.fail("image"); return; }
const pixels = template.width * template.height;
// Only the bounded palette can vary for this template. Its envelope stays constant
// across themes, preserving replacement headroom without charging small SVGs 1 MiB.
const reservedBytes = Math.min(blob.size - paletteBytes + PALETTE_LIMIT, OUTPUT_LIMIT);
const byteLimit = this.asset ? BYTE_LIMIT : ADMISSION_BYTE_LIMIT;
const pixelLimit = this.asset ? PIXEL_LIMIT : ADMISSION_PIXEL_LIMIT;
if (blob.size > OUTPUT_LIMIT) { this.fail("limit"); return; }
if (retainedBytes + reservedBytes > byteLimit || retainedPixels + pixels > pixelLimit) {
this.waitForCapacity(); return;
}
this.capacityBlocked = false;
retainedBytes += reservedBytes;
retainedPixels += pixels;
let url: string;
try { url = URL.createObjectURL(blob); }
catch {
retainedBytes -= reservedBytes;
retainedPixels -= pixels;
this.fail("image"); return;
}
let released = false;
const release = () => {
if (released) return;
released = true;
URL.revokeObjectURL(url);
retainedBytes -= reservedBytes;
retainedPixels -= pixels;
capacityChanged();
};
const image = new Image();
image.decoding = "async";
const cleanup = () => {
clearTimeout(timer);
image.onload = image.onerror = null;
};
const finish = () => {
if (this.disposed || attempt !== this.attempt || this.demand === "none") { cleanup(); release(); return; }
cleanup();
this.decoding = null;
const previous = this.asset;
this.asset = { image: { url, width: template.width, height: template.height, label: template.label }, release };
this.publish({ kind: "ready", image: this.asset.image });
previous?.release();
};
const timer = setTimeout(() => this.fail("image"), 5000);
this.decoding = () => { cleanup(); image.removeAttribute("src"); release(); };
image.onerror = () => this.fail("image");
image.onload = () => {
if (typeof image.decode === "function") void image.decode().then(finish, () => {
if (attempt === this.attempt && !this.disposed) this.fail("image");
});
else finish();
};
image.src = url;
}
dispose = () => {
if (this.disposed) return;
this.disposed = true;
this.signal.removeEventListener("abort", this.dispose);
tasks.delete(this);
this.cancel();
this.asset?.release();
this.asset = null;
this.clearTemplate();
pump();
};
}
export function requestDiagram(input: DiagramInput, signal: AbortSignal, publish: (state: DiagramState) => void): DiagramRequest {
const task = new Task(input, signal, publish);
if (signal.aborted) task.dispose();
return task;
}
@@ -0,0 +1,342 @@
// Worker-only policy for Pele 1.6 image documents. This is NOT an inline-SVG sanitizer.
import { SaxesParser } from "saxes";
import type * as CssTree from "css-tree";
// css-tree publishes these split entry points, but @types/css-tree declares only the barrel.
// @ts-expect-error No declaration for the public parser entry point.
import parse from "css-tree/parser";
// @ts-expect-error No declaration for the public walker entry point.
import walk from "css-tree/walker";
// @ts-expect-error No declaration for the public generator entry point.
import generate from "css-tree/generator";
import {
MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT,
type DiagramFailure, type DiagramInput, type DiagramTemplate,
} from "./types";
const parseCss: typeof CssTree.parse = parse;
const walkCss: typeof CssTree.walk = walk;
const generateCss: typeof CssTree.generate = generate;
const SVG_NS = "http://www.w3.org/2000/svg";
const XML_NS = "http://www.w3.org/XML/1998/namespace";
const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
const ELEMENT_LIMIT = 10_000;
const encoder = new TextEncoder();
export class DiagramImageError extends Error {
constructor(readonly reason: DiagramFailure) {
super(`Diagram ${reason}`);
}
}
function fail(reason: DiagramFailure = "policy"): never {
throw new DiagramImageError(reason);
}
// Reviewed against the published 1.6.0 string renderer, including nested icon geometry.
// Local marker/clip structures are accepted, but never <use>, links, images or paint servers.
const ELEMENTS = new Set([
"svg", "g", "path", "rect", "circle", "ellipse", "line", "polyline", "polygon",
"text", "tspan", "title", "desc", "defs", "marker", "clipPath",
]);
const ATTRIBUTES = new Set([
"id", "class", "data-id", "data-icon", "role", "aria-hidden", "aria-roledescription",
"aria-labelledby", "aria-describedby", "style", "viewBox", "preserveAspectRatio",
"x", "y", "x1", "x2", "y1", "y2", "cx", "cy", "r", "rx", "ry", "width", "height",
"dx", "dy", "d", "points", "transform", "pathLength", "markerWidth", "markerHeight",
"refX", "refY", "orient", "markerUnits", "clipPathUnits",
]);
const NUMERIC_ATTRIBUTES = new Set([
"x", "y", "x1", "x2", "y1", "y2", "cx", "cy", "r", "rx", "ry", "width", "height",
"dx", "dy", "pathLength", "markerWidth", "markerHeight", "refX", "refY",
]);
const DRAWING_PROPERTIES = new Set([
"fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity",
"stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
"stroke-miterlimit", "opacity", "color", "rx", "ry", "text-anchor", "text-decoration",
"dominant-baseline", "alignment-baseline", "visibility", "display", "vector-effect",
"marker-start", "marker-mid", "marker-end", "clip-path", "clip-rule",
]);
const TYPOGRAPHY_PROPERTIES = new Set([
"font", "font-family", "font-size", "font-weight", "font-style", "letter-spacing",
"word-spacing", "text-transform", "direction",
]);
const ROOT_ALIASES: Readonly<Record<string, string>> = {
"--_bg": "var(--pele-bg,#fff)", "--_fg": "var(--pele-fg,#1f1f1f)",
"--_m": "var(--pele-muted,#6e6e6e)", "--_l": "var(--pele-line,#1f1f1f)",
"--_s": "var(--pele-surface,#f3f3f3)", "--_a": "var(--pele-surface-alt,#e6e6e6)",
"--_b": "var(--pele-border,#8a8a8a)", "--_c": "var(--pele-accent,#5b7bd5)",
"--_r": "var(--pele-radius,4px)", "--_tw": "var(--pele-title-weight,bold)",
"--_hw": "var(--pele-heading-weight,bold)", "--_w": "var(--pele-bold-weight,bold)",
};
const VARIABLES = new Set([
...Object.keys(ROOT_ALIASES), "--_fm", "--pele-bg", "--pele-fg", "--pele-muted",
"--pele-line", "--pele-surface", "--pele-surface-alt", "--pele-border", "--pele-accent",
"--pele-critical", ...Array.from({ length: 8 }, (_, i) => `--pele-series-${i + 1}`),
]);
const FUNCTIONS = new Set([
"rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "oklab", "oklch", "color",
"color-mix", "calc", "min", "max", "clamp",
]);
interface Reference { id: string; target: "marker" | "clipPath" }
function css(source: string, context: "value" | "declarationList"): CssTree.CssNode {
try {
return parseCss(source, {
context, parseCustomProperty: true,
onParseError: () => fail(),
});
} catch (error) {
if (error instanceof DiagramImageError) throw error;
return fail();
}
}
function family(source: string): string {
const ast = css(source, "value");
if (ast.type !== "Value" || ast.children.isEmpty) fail("capability");
for (const node of ast.children) {
if (node.type === "Identifier" && !/^(?:inherit|initial|unset|revert)$/i.test(node.name)) continue;
if (node.type === "String" && node.value.length > 0) continue;
if (node.type === "Operator" && node.value === ",") continue;
fail("capability");
}
return generateCss(ast);
}
function fontSize(node: CssTree.CssNode, allowUnitless: boolean): number {
if (node.type !== "Value" || node.children.size !== 1) return fail("unsupported");
const size = node.children.first;
if (size?.type !== "Dimension" && !(allowUnitless && size?.type === "Number")) return fail("unsupported");
if (size.type === "Dimension" && size.unit !== "px") return fail("unsupported");
const value = Number(size.value);
if (!Number.isFinite(value) || value <= 0 || value > 200) return fail("unsupported");
return value;
}
function typography(
property: string, value: CssTree.CssNode, root: boolean,
fonts: DiagramInput["fonts"], attribute: boolean,
): string {
const text = generateCss(value);
switch (property) {
case "font":
if (!root || text !== `${fonts.size}px sans-serif`) fail("unsupported");
break;
case "font-family":
if (root) {
const expected = generateCss(css(`var(--pele-font,${fonts.sans})`, "value"));
if (text !== expected) fail("unsupported");
return family(fonts.sans);
}
// Pele measures its built-in monospace sections with Style.Mono. Author style
// font-family is NOT measured, even when it happens to name our mono font.
if (!attribute || text !== "var(--_fm)") fail("unsupported");
break;
case "font-size":
fontSize(value, attribute);
break;
case "font-weight":
if (!["normal", "400", "bold", "700", "var(--_w)", "var(--_hw)", "var(--_tw)"].includes(text)) fail("unsupported");
break;
case "font-style":
if (text !== "normal" && text !== "italic") fail("unsupported");
break;
case "letter-spacing":
case "word-spacing":
if (text !== "normal") fail("unsupported");
break;
case "text-transform":
if (text !== "none") fail("unsupported");
break;
case "direction":
if (text !== "ltr") fail("unsupported");
}
return text;
}
function drawingValue(property: string, value: CssTree.CssNode, refs: Reference[]): string {
walkCss(value, (node) => {
if (node.type === "Raw") fail();
if (node.type === "Url") {
const target = property === "clip-path" ? "clipPath"
: property.startsWith("marker-") ? "marker" : fail();
if (!/^#[A-Za-z0-9_.:-]+$/.test(node.value)) fail();
refs.push({ id: node.value.slice(1), target });
}
if (node.type === "Function") {
if (node.name === "var") {
const name = node.children.first;
if (name?.type !== "Identifier" || !VARIABLES.has(name.name)) fail();
} else if (!FUNCTIONS.has(node.name.toLowerCase())) fail();
}
if ((node.type === "Number" || node.type === "Dimension" || node.type === "Percentage")
&& !Number.isFinite(Number(node.value))) fail("limit");
});
return generateCss(value);
}
function style(
source: string, root: boolean, fonts: DiagramInput["fonts"], refs: Reference[],
): string {
const ast = css(source, "declarationList");
if (ast.type !== "DeclarationList") return fail();
const declarations: string[] = [];
const properties = new Set<string>();
for (const declaration of ast.children) {
if (declaration.type !== "Declaration" || declaration.important) fail();
const { property, value } = declaration;
if (root && properties.has(property)) fail();
properties.add(property);
let accepted: string;
if (property === "--_fm") {
if (!root || generateCss(value) !== generateCss(css(`var(--pele-font-mono,${fonts.mono})`, "value"))) fail("unsupported");
accepted = family(fonts.mono);
} else if (Object.hasOwn(ROOT_ALIASES, property)) {
if (!root || generateCss(value) !== ROOT_ALIASES[property]) fail();
// Font weights and radius are layout constants, never theme-controlled values.
accepted = property === "--_r" ? "4px"
: ["--_tw", "--_hw", "--_w"].includes(property) ? "bold" : generateCss(value);
} else if (TYPOGRAPHY_PROPERTIES.has(property)) {
accepted = typography(property, value, root, fonts, false);
} else if (DRAWING_PROPERTIES.has(property)) {
accepted = drawingValue(property, value, refs);
} else if (root && ((property === "max-width" && generateCss(value) === "100%")
|| (property === "height" && generateCss(value) === "auto"))) {
accepted = generateCss(value);
} else fail();
declarations.push(`${property}:${accepted}`);
}
if (root) {
for (const required of [
"--_bg", "--_fg", "--_m", "--_l", "--_s", "--_a", "--_b", "--_c", "--_fm",
"font", "font-family", "letter-spacing", "word-spacing", "text-transform", "direction",
]) if (!properties.has(required)) fail();
}
return declarations.join(";");
}
const NUMBER = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/g;
function numbers(value: string, letters = ""): number[] {
if (new RegExp(`[^\\s,\\d.eE+\\-${letters}]`).test(value)) fail();
const values = Array.from(value.matchAll(NUMBER), (match) => Number(match[0]));
if (values.length === 0 || values.some((value) => !Number.isFinite(value))) fail("limit");
return values;
}
function dimension(value: string | undefined): number {
if (!value || !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value)) return fail("limit");
const number = Number(value);
if (!Number.isFinite(number) || number <= 0 || number > MAX_DIMENSION) return fail("limit");
return number;
}
function geometry(name: string, value: string): void {
if (NUMERIC_ATTRIBUTES.has(name)) {
const values = numbers(value);
if (values.length !== 1) fail();
if (["r", "rx", "ry", "width", "height", "markerWidth", "markerHeight", "pathLength"].includes(name)
&& values[0] < 0) fail("limit");
} else if (name === "d") numbers(value, "MmLlHhVvCcSsQqTtAaZz");
else if (name === "points" || name === "viewBox") numbers(value);
else if (name === "transform") {
const rest = value.replace(/(?:matrix|translate|scale|rotate|skewX|skewY)\(([^()]*)\)/g, (_, args: string) => {
numbers(args);
return "";
});
if (rest.trim() !== "") fail();
} else if (name === "orient" && value !== "auto" && value !== "auto-start-reverse") numbers(value);
}
function escapeXml(value: string): string {
return value.replace(/[&<>"\r\n\t]/g, (character) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;",
"\r": "&#13;", "\n": "&#10;", "\t": "&#9;",
})[character]!);
}
export function diagramImageTemplate(svg: string, fonts: DiagramInput["fonts"]): DiagramTemplate {
if (svg.length > OUTPUT_LIMIT || encoder.encode(svg).byteLength > OUTPUT_LIMIT) fail("limit");
family(fonts.sans);
family(fonts.mono);
if (!Number.isFinite(fonts.size) || fonts.size <= 0 || fonts.size > 200) fail("capability");
const parser = new SaxesParser({ xmlns: true });
const content: string[] = [];
const stack: string[] = [];
const ids = new Map<string, string>();
const refs: Reference[] = [];
let elements = 0;
let width = 0;
let height = 0;
let rootStyle = "";
let title = "";
let description = "";
parser.on("error", () => fail());
parser.on("doctype", () => fail());
parser.on("processinginstruction", () => fail());
parser.on("xmldecl", () => fail());
parser.on("opentag", (tag) => {
if (++elements > ELEMENT_LIMIT) fail("limit");
if (tag.uri !== SVG_NS || tag.prefix !== "" || !ELEMENTS.has(tag.local)) fail();
const root = stack.length === 0;
if (root && (elements !== 1 || tag.local !== "svg")) fail();
if (stack.at(-1) === "title" || stack.at(-1) === "desc") fail();
const attributes: string[] = [];
const rootDrawing: string[] = [];
for (const attribute of Object.values(tag.attributes)) {
const { name, value, uri } = attribute;
if (uri === XMLNS_NS) {
if (name !== "xmlns" || value !== SVG_NS) fail();
continue;
}
if (uri !== "" && !(uri === XML_NS && name === "xml:space")) fail();
let accepted = value;
if (name === "xml:space") {
if (value !== "preserve" && value !== "default") fail();
} else if (name === "style") accepted = style(value, root, fonts, refs);
else if (DRAWING_PROPERTIES.has(name)) accepted = drawingValue(name, css(value, "value"), refs);
else if (TYPOGRAPHY_PROPERTIES.has(name)) accepted = typography(name, css(value, "value"), root, fonts, true);
else if (!ATTRIBUTES.has(name)) fail();
else geometry(name, value);
if (name === "id") {
if (!/^[A-Za-z0-9_.:-]+$/.test(value) || ids.has(value)) fail();
ids.set(value, tag.local);
}
if (!root) attributes.push(` ${name}="${escapeXml(accepted)}"`);
else if (name === "style") rootStyle = accepted;
else if (DRAWING_PROPERTIES.has(name)) rootDrawing.push(`${name}:${accepted}`);
}
if (root) {
if (!rootStyle) fail();
rootStyle += rootDrawing.length ? `;${rootDrawing.join(";")}` : "";
width = dimension(tag.attributes.width?.value);
height = dimension(tag.attributes.height?.value);
if (width * height > MAX_PIXELS) fail("limit");
const viewBox = numbers(tag.attributes.viewBox?.value ?? "");
if (viewBox.length !== 4 || viewBox[0] !== 0 || viewBox[1] !== 0
|| viewBox[2] !== width || viewBox[3] !== height) fail("limit");
if (!rootStyle) fail();
} else content.push(`<${tag.local}${attributes.join("")}>`);
stack.push(tag.local);
});
const text = (value: string) => {
const element = stack.at(-1);
if (element === "title") title += value.slice(0, Math.max(0, 1000 - title.length));
if (element === "desc") description += value.slice(0, Math.max(0, 1000 - description.length));
if (stack.length > 1) {
if (value.trim() && !["title", "desc", "text", "tspan"].includes(element ?? "")) fail();
content.push(escapeXml(value));
} else if (value.trim()) fail();
};
parser.on("text", text);
parser.on("cdata", text);
parser.on("closetag", (tag) => {
if (stack.length > 1) content.push(`</${tag.local}>`);
stack.pop();
});
parser.write(svg).close();
for (const ref of refs) if (ids.get(ref.id) !== ref.target) fail();
const body = content.join("");
if (encoder.encode(body + rootStyle).byteLength > OUTPUT_LIMIT) fail("limit");
return {
content: body, style: rootStyle, width, height,
label: [title, description].filter(Boolean).join(". ").replace(/\s+/g, " ").trim().slice(0, 1000),
};
}
@@ -0,0 +1,27 @@
// Private feature contracts. Only the Worker imports Pele and the XML/CSS parsers.
export interface DiagramInput {
source: string;
width: number;
fonts: { sans: string; mono: string; size: number };
}
export type DiagramFailure = "syntax" | "unsupported" | "policy" | "limit"
| "load" | "deadline" | "worker" | "image" | "capability";
// Image-context only; never insert this content into the page DOM.
export interface DiagramTemplate {
content: string;
style: string;
width: number;
height: number;
label: string;
}
export type DiagramReply = { kind: "started" }
| { kind: "image"; template: DiagramTemplate }
| { kind: "failed"; reason: DiagramFailure };
export const SOURCE_LIMIT = 50_000;
export const OUTPUT_LIMIT = 1_048_576;
export const MAX_DIMENSION = 8192;
export const MAX_PIXELS = 8_000_000;
@@ -14,6 +14,7 @@ import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
import { SubagentThreadMessages, useHasSubagentContent } from "@/components/thread/SubagentTasks";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
import { ThreadCameraController } from "@/components/thread/thread-camera";
@@ -1028,6 +1029,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
)}
>
<div ref={messageContentRef} className="w-full">
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
messages={visibleMessages}
temporary={temporary}
@@ -1047,6 +1049,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onQuoteSelection={onQuoteSelection}
onActivityToggle={yieldCameraToUser}
/>
</DiagramScope>
</div>
<div aria-hidden className="thread-message-end-gap shrink-0" />
<div ref={bottomRef} aria-hidden className="h-px shrink-0" />
+155
View File
@@ -0,0 +1,155 @@
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
import { Minus, Plus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
type Point = { x: number; y: number };
type View = Point & { scale: number };
const FIT: View = { x: 0, y: 0, scale: 1 };
const MAX_SCALE = 8;
const PAN_STEP = 40;
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const midpoint = (a: Point, b: Point): Point => ({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });
const distance = (a: Point, b: Point) => Math.hypot(a.x - b.x, a.y - b.y);
export interface ImageViewportProps {
src: string;
alt: string;
/** Styles for the bounded viewport; controls are a separate sibling. */
className?: string;
imageClassName?: string;
controlsClassName?: string;
testId?: string;
/** Disable when a surrounding gallery owns the arrow keys. */
panWithArrows?: boolean;
}
/** Image-local gestures and controls. Provide viewport dimensions and remount per image. */
export function ImageViewport({
src,
alt,
className,
imageClassName,
controlsClassName,
testId = "image-viewport",
panWithArrows = true,
}: ImageViewportProps) {
const { t } = useTranslation();
const viewport = useRef<HTMLDivElement>(null);
const image = useRef<HTMLImageElement>(null);
const pointers = useRef(new Map<number, Point>());
const viewRef = useRef(FIT);
const [view, setView] = useState(FIT);
const [dragging, setDragging] = useState(false);
const apply = useCallback((next: View) => {
const scale = clamp(next.scale, 1, MAX_SCALE);
const maxX = Math.max(0, ((image.current?.offsetWidth ?? 0) * scale - (viewport.current?.clientWidth ?? 0)) / 2);
const maxY = Math.max(0, ((image.current?.offsetHeight ?? 0) * scale - (viewport.current?.clientHeight ?? 0)) / 2);
const bounded = { scale, x: clamp(next.x, -maxX, maxX), y: clamp(next.y, -maxY, maxY) };
viewRef.current = bounded;
setView(bounded);
}, []);
const zoom = useCallback((scale: number, from?: Point, to = from) => {
const rect = viewport.current?.getBoundingClientRect();
const current = viewRef.current;
const next = clamp(scale, 1, MAX_SCALE);
const center = rect ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } : { x: 0, y: 0 };
const origin = from ?? center;
const target = to ?? origin;
apply({
scale: next,
x: target.x - center.x - (origin.x - center.x - current.x) * next / current.scale,
y: target.y - center.y - (origin.y - center.y - current.y) * next / current.scale,
});
}, [apply]);
useEffect(() => {
const element = viewport.current;
if (!element) return;
const activePointers = pointers.current;
// React's wheel listener is passive; cancel browser zoom only over this viewport.
const onWheel = (event: WheelEvent) => {
if (event.ctrlKey) {
event.preventDefault();
zoom(viewRef.current.scale * Math.exp(-clamp(event.deltaY, -50, 50) * 0.01), { x: event.clientX, y: event.clientY });
} else if (viewRef.current.scale > 1) {
event.preventDefault();
const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? element.clientHeight : 1;
apply({ ...viewRef.current, x: viewRef.current.x - event.deltaX * unit, y: viewRef.current.y - event.deltaY * unit });
}
};
element.addEventListener("wheel", onWheel, { passive: false });
const resize = new ResizeObserver(() => apply(viewRef.current));
resize.observe(element);
return () => {
element.removeEventListener("wheel", onWheel);
resize.disconnect();
for (const pointerId of activePointers.keys()) {
if (element.hasPointerCapture(pointerId)) element.releasePointerCapture(pointerId);
}
activePointers.clear();
};
}, [apply, zoom]);
const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
if (event.button !== 0 || pointers.current.size >= 2) return;
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
event.currentTarget.setPointerCapture(event.pointerId);
setDragging(true);
};
const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
if (!pointers.current.has(event.pointerId)) return;
const before = [...pointers.current.values()];
pointers.current.set(event.pointerId, { x: event.clientX, y: event.clientY });
const after = [...pointers.current.values()];
if (before.length === 2) {
const previousDistance = distance(before[0], before[1]);
if (previousDistance > 0) zoom(viewRef.current.scale * distance(after[0], after[1]) / previousDistance,
midpoint(before[0], before[1]), midpoint(after[0], after[1]));
} else if (viewRef.current.scale > 1) {
apply({ ...viewRef.current, x: viewRef.current.x + after[0].x - before[0].x, y: viewRef.current.y + after[0].y - before[0].y });
}
};
const endPointer = (event: PointerEvent<HTMLDivElement>) => {
pointers.current.delete(event.pointerId);
if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
setDragging(pointers.current.size > 0);
};
const buttonClass = "grid size-9 shrink-0 place-items-center rounded-full transition-colors hover:text-foreground disabled:opacity-30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <>
<div ref={viewport} data-testid={testId} tabIndex={0} role="group" aria-label={t("lightbox.gestures")}
className={cn("flex min-h-0 min-w-0 touch-none select-none items-center justify-center overflow-hidden focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring", view.scale > 1 ? dragging ? "cursor-grabbing" : "cursor-grab" : "cursor-zoom-in", className)}
onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={endPointer} onPointerCancel={endPointer} onLostPointerCapture={endPointer}
onDoubleClick={(event) => zoom(viewRef.current.scale > 1 ? 1 : 2, { x: event.clientX, y: event.clientY })}
onKeyDown={(event) => {
if (event.ctrlKey || event.metaKey || event.altKey) return;
const current = viewRef.current;
if (event.key === "+" || event.key === "=") zoom(current.scale * 1.5);
else if (event.key === "-") zoom(current.scale / 1.5);
else if (event.key === "0") apply(FIT);
else if (panWithArrows && event.key === "ArrowLeft") apply({ ...current, x: current.x + PAN_STEP });
else if (panWithArrows && event.key === "ArrowRight") apply({ ...current, x: current.x - PAN_STEP });
else if (panWithArrows && event.key === "ArrowUp") apply({ ...current, y: current.y + PAN_STEP });
else if (panWithArrows && event.key === "ArrowDown") apply({ ...current, y: current.y - PAN_STEP });
else return;
event.preventDefault();
event.stopPropagation();
}}>
<img ref={image} src={src} alt={alt} decoding="async" draggable={false} onLoad={() => apply(viewRef.current)}
className={cn("max-h-full max-w-full select-none object-contain will-change-transform", imageClassName)}
style={{ transform: `translate3d(${view.x}px, ${view.y}px, 0) scale(${view.scale})` }} />
</div>
<div className={cn("flex items-center justify-center gap-1 rounded-full p-1 text-muted-foreground", controlsClassName)}>
<button type="button" aria-label={t("lightbox.zoomOut")} title={t("lightbox.zoomOut")} disabled={view.scale <= 1} className={buttonClass} onClick={() => zoom(viewRef.current.scale / 1.5)}><Minus className="size-4" aria-hidden /></button>
<button type="button" aria-label={t("lightbox.resetZoom")} title={t("lightbox.resetZoom")}
className="h-9 min-w-14 rounded-full px-2 text-xs font-medium tabular-nums focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" onClick={() => apply(FIT)}>
{Math.round(view.scale * 100)}%
</button>
<button type="button" aria-label={t("lightbox.zoomIn")} title={t("lightbox.zoomIn")} disabled={view.scale >= MAX_SCALE} className={buttonClass} onClick={() => zoom(viewRef.current.scale * 1.5)}><Plus className="size-4" aria-hidden /></button>
</div>
</>;
}
+10
View File
@@ -18,6 +18,7 @@ import { HoverHint, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, Tr
import { Disclosure } from "@/components/ui/disclosure";
import { ExpandableText } from "@/components/ui/expandable-text";
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
import { ImageViewport } from "@/components/ui/image-viewport";
import { Sample, type ComponentExample } from "./example";
function Buttons() {
@@ -223,6 +224,12 @@ function StreamingLabels() {
</div>;
}
function ImageViewports() {
return <div className="flex h-80 max-w-xl flex-col rounded-lg border p-3">
<ImageViewport src="/brand/nanobot_icon_512.png" alt="Nanobot" className="flex-1" />
</div>;
}
const base = "webui/src/components/ui/";
export const foundationExamples: ComponentExample[] = [
{ title: "Button · 按钮", files: ["button"], Preview: Buttons,
@@ -274,6 +281,9 @@ export const foundationExamples: ComponentExample[] = [
{ title: "ExpandableText · 文本展开", files: ["expandable-text"], Preview: Expandable,
description: "A line-limited preview of the same mounted text.", options: "The caller owns expanded. lines sets the collapsed line count; provide an accessible toggle.",
code: '<ExpandableText expanded={expanded} lines={2} className="text-sm leading-6">{description}</ExpandableText>' },
{ title: "ImageViewport · 图像视口", files: ["image-viewport"], Preview: ImageViewports,
description: "Image-local fit, zoom, pan and pinch controls.", options: "Supply a bounded className and remount for a different image identity. Set panWithArrows=false when a gallery owns arrow navigation.",
code: '<div className="flex h-80 flex-col"><ImageViewport src={url} alt={label} className="flex-1" /></div>' },
{ title: "StreamingLabelSheen · 流光文字", files: ["streaming-label-sheen"], Preview: StreamingLabels,
description: "A shared text animation for active thinking and tool labels.", options: "active controls animation. String or number children supply the glyph overlay; reduced-motion settings are respected.",
code: '<StreamingLabelSheen active={running}>Working…</StreamingLabelSheen>' },
+19
View File
@@ -2410,6 +2410,25 @@
"dismiss": "Dismiss",
"continue": "Continue"
},
"diagram": {
"graph": "Diagram",
"source": "Source",
"copy": "Copy source",
"enlarge": "Enlarge diagram",
"title": "Mermaid diagram",
"preparing": "Preparing diagram…",
"errors": {
"syntax": "Check the diagram syntax in the source.",
"unsupported": "This diagram type is not supported. View the source.",
"policy": "This diagram uses unsupported styling or resources. View the source.",
"limit": "This diagram exceeds the rendering limit. View the source.",
"load": "Couldn't load the diagram renderer. Try again.",
"deadline": "The diagram took too long to render. Simplify the source or try again.",
"worker": "Couldn't render the diagram. Try again.",
"image": "Couldn't display the diagram. Try again.",
"capability": "Diagram rendering is unavailable in this browser. View the source."
}
},
"lightbox": {
"viewAll": "View all {{count}} images",
"zoomIn": "Zoom in",
+19
View File
@@ -2211,6 +2211,25 @@
"dismiss": "Descartar",
"continue": "Continuar"
},
"diagram": {
"graph": "Diagrama",
"source": "Código fuente",
"copy": "Copiar código fuente",
"enlarge": "Ampliar diagrama",
"title": "Diagrama Mermaid",
"preparing": "Preparando diagrama…",
"errors": {
"syntax": "Comprueba la sintaxis del diagrama en el código fuente.",
"unsupported": "Este tipo de diagrama no es compatible. Consulta el código fuente.",
"policy": "El diagrama usa estilos o recursos no compatibles. Consulta el código fuente.",
"limit": "El diagrama supera el límite de renderizado. Consulta el código fuente.",
"load": "No se pudo cargar el motor de diagramas. Inténtalo de nuevo.",
"deadline": "El renderizado tardó demasiado. Simplifica el código fuente o inténtalo de nuevo.",
"worker": "No se pudo generar el diagrama. Inténtalo de nuevo.",
"image": "No se pudo mostrar el diagrama. Inténtalo de nuevo.",
"capability": "Este navegador no puede generar diagramas. Consulta el código fuente."
}
},
"lightbox": {
"viewAll": "Ver las {{count}} imágenes",
"zoomIn": "Acercar",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "Ignorer",
"continue": "Continuer"
},
"diagram": {
"graph": "Diagramme",
"source": "Source",
"copy": "Copier la source",
"enlarge": "Agrandir le diagramme",
"title": "Diagramme Mermaid",
"preparing": "Préparation du diagramme…",
"errors": {
"syntax": "Vérifiez la syntaxe du diagramme dans la source.",
"unsupported": "Ce type de diagramme n'est pas pris en charge. Consultez la source.",
"policy": "Ce diagramme utilise des styles ou ressources non pris en charge. Consultez la source.",
"limit": "Ce diagramme dépasse la limite de rendu. Consultez la source.",
"load": "Impossible de charger le moteur de diagrammes. Réessayez.",
"deadline": "Le rendu a pris trop de temps. Simplifiez la source ou réessayez.",
"worker": "Impossible de générer le diagramme. Réessayez.",
"image": "Impossible d'afficher le diagramme. Réessayez.",
"capability": "Ce navigateur ne peut pas générer le diagramme. Consultez la source."
}
},
"lightbox": {
"viewAll": "Voir les {{count}} images",
"zoomIn": "Agrandir",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "Abaikan",
"continue": "Lanjutkan"
},
"diagram": {
"graph": "Diagram",
"source": "Sumber",
"copy": "Salin sumber",
"enlarge": "Perbesar diagram",
"title": "Diagram Mermaid",
"preparing": "Menyiapkan diagram…",
"errors": {
"syntax": "Periksa sintaks diagram pada sumber.",
"unsupported": "Jenis diagram ini belum didukung. Lihat sumber.",
"policy": "Diagram memakai gaya atau sumber daya yang tidak didukung. Lihat sumber.",
"limit": "Diagram melampaui batas perenderan. Lihat sumber.",
"load": "Tidak dapat memuat perender diagram. Coba lagi.",
"deadline": "Perenderan diagram terlalu lama. Sederhanakan sumber atau coba lagi.",
"worker": "Tidak dapat merender diagram. Coba lagi.",
"image": "Tidak dapat menampilkan diagram. Coba lagi.",
"capability": "Browser ini tidak dapat merender diagram. Lihat sumber."
}
},
"lightbox": {
"viewAll": "Lihat semua {{count}} gambar",
"zoomIn": "Perbesar",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "閉じる",
"continue": "続行"
},
"diagram": {
"graph": "図",
"source": "ソース",
"copy": "ソースをコピー",
"enlarge": "図を拡大",
"title": "Mermaid 図",
"preparing": "図を準備中…",
"errors": {
"syntax": "ソースの図の構文を確認してください。",
"unsupported": "この図の種類には対応していません。ソースを確認してください。",
"policy": "未対応のスタイルやリソースが含まれています。ソースを確認してください。",
"limit": "図が描画の上限を超えています。ソースを確認してください。",
"load": "図の描画機能を読み込めませんでした。再試行してください。",
"deadline": "図の描画がタイムアウトしました。ソースを簡略化するか再試行してください。",
"worker": "図を描画できませんでした。再試行してください。",
"image": "図を表示できませんでした。再試行してください。",
"capability": "このブラウザーでは図を描画できません。ソースを確認してください。"
}
},
"lightbox": {
"viewAll": "すべての画像({{count}} 枚)を表示",
"zoomIn": "拡大",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "닫기",
"continue": "계속"
},
"diagram": {
"graph": "다이어그램",
"source": "소스",
"copy": "소스 복사",
"enlarge": "다이어그램 확대",
"title": "Mermaid 다이어그램",
"preparing": "다이어그램 준비 중…",
"errors": {
"syntax": "소스의 다이어그램 문법을 확인하세요.",
"unsupported": "지원하지 않는 다이어그램 유형입니다. 소스를 확인하세요.",
"policy": "지원하지 않는 스타일이나 리소스가 있습니다. 소스를 확인하세요.",
"limit": "다이어그램이 렌더링 제한을 초과했습니다. 소스를 확인하세요.",
"load": "다이어그램 렌더러를 불러오지 못했습니다. 다시 시도하세요.",
"deadline": "다이어그램 렌더링 시간이 초과되었습니다. 소스를 단순화하거나 다시 시도하세요.",
"worker": "다이어그램을 렌더링하지 못했습니다. 다시 시도하세요.",
"image": "다이어그램을 표시하지 못했습니다. 다시 시도하세요.",
"capability": "이 브라우저에서는 다이어그램을 렌더링할 수 없습니다. 소스를 확인하세요."
}
},
"lightbox": {
"viewAll": "이미지 {{count}}개 모두 보기",
"zoomIn": "확대",
+19
View File
@@ -2224,6 +2224,25 @@
"dismiss": "Descartar",
"continue": "Continuar"
},
"diagram": {
"graph": "Diagrama",
"source": "Código-fonte",
"copy": "Copiar código-fonte",
"enlarge": "Ampliar diagrama",
"title": "Diagrama Mermaid",
"preparing": "Preparando diagrama…",
"errors": {
"syntax": "Confira a sintaxe do diagrama no código-fonte.",
"unsupported": "Este tipo de diagrama não é compatível. Consulte o código-fonte.",
"policy": "O diagrama usa estilos ou recursos incompatíveis. Consulte o código-fonte.",
"limit": "O diagrama excede o limite de renderização. Consulte o código-fonte.",
"load": "Não foi possível carregar o renderizador. Tente novamente.",
"deadline": "A renderização demorou demais. Simplifique o código-fonte ou tente novamente.",
"worker": "Não foi possível gerar o diagrama. Tente novamente.",
"image": "Não foi possível exibir o diagrama. Tente novamente.",
"capability": "Este navegador não pode gerar diagramas. Consulte o código-fonte."
}
},
"lightbox": {
"viewAll": "Ver todas as {{count}} imagens",
"zoomIn": "Ampliar",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "Bỏ qua",
"continue": "Tiếp tục"
},
"diagram": {
"graph": "Sơ đồ",
"source": "Mã nguồn",
"copy": "Sao chép mã nguồn",
"enlarge": "Phóng to sơ đồ",
"title": "Sơ đồ Mermaid",
"preparing": "Đang chuẩn bị sơ đồ…",
"errors": {
"syntax": "Hãy kiểm tra cú pháp sơ đồ trong mã nguồn.",
"unsupported": "Chưa hỗ trợ loại sơ đồ này. Hãy xem mã nguồn.",
"policy": "Sơ đồ dùng kiểu hoặc tài nguyên không được hỗ trợ. Hãy xem mã nguồn.",
"limit": "Sơ đồ vượt quá giới hạn kết xuất. Hãy xem mã nguồn.",
"load": "Không thể tải bộ kết xuất sơ đồ. Hãy thử lại.",
"deadline": "Kết xuất sơ đồ quá thời gian. Hãy đơn giản hóa mã nguồn hoặc thử lại.",
"worker": "Không thể kết xuất sơ đồ. Hãy thử lại.",
"image": "Không thể hiển thị sơ đồ. Hãy thử lại.",
"capability": "Trình duyệt này không thể kết xuất sơ đồ. Hãy xem mã nguồn."
}
},
"lightbox": {
"viewAll": "Xem tất cả {{count}} ảnh",
"zoomIn": "Phóng to",
+19
View File
@@ -2410,6 +2410,25 @@
"dismiss": "忽略",
"continue": "继续"
},
"diagram": {
"graph": "图形",
"source": "源码",
"copy": "复制源码",
"enlarge": "放大查看",
"title": "Mermaid 图表",
"preparing": "正在准备图表…",
"errors": {
"syntax": "图表语法有误,请检查源码。",
"unsupported": "暂不支持此类图表,可查看源码。",
"policy": "图表含不支持的样式或资源,可查看源码。",
"limit": "图表超出渲染限制,可查看源码。",
"load": "图表渲染器加载失败,请重试。",
"deadline": "图表渲染超时,请简化源码或重试。",
"worker": "图表渲染失败,请重试。",
"image": "图表显示失败,请重试。",
"capability": "此浏览器无法渲染图表,可查看源码。"
}
},
"lightbox": {
"viewAll": "查看全部 {{count}} 张图片",
"zoomIn": "放大",
+19
View File
@@ -2210,6 +2210,25 @@
"dismiss": "略過",
"continue": "繼續"
},
"diagram": {
"graph": "圖形",
"source": "原始碼",
"copy": "複製原始碼",
"enlarge": "放大檢視",
"title": "Mermaid 圖表",
"preparing": "正在準備圖表…",
"errors": {
"syntax": "圖表語法有誤,請檢查原始碼。",
"unsupported": "尚不支援此類圖表,可檢視原始碼。",
"policy": "圖表含不支援的樣式或資源,可檢視原始碼。",
"limit": "圖表超出繪製限制,可檢視原始碼。",
"load": "圖表繪製器載入失敗,請重試。",
"deadline": "圖表繪製逾時,請簡化原始碼或重試。",
"worker": "圖表繪製失敗,請重試。",
"image": "圖表顯示失敗,請重試。",
"capability": "此瀏覽器無法繪製圖表,可檢視原始碼。"
}
},
"lightbox": {
"viewAll": "查看全部 {{count}} 張圖片",
"zoomIn": "放大",
+183
View File
@@ -0,0 +1,183 @@
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { detectType, load, render } from "pele/lazy";
import { canvasTextMeasurer } from "../components/markdown-diagrams/render";
import { diagramImageTemplate, DiagramImageError } from "../components/markdown-diagrams/svg-image";
import { OUTPUT_LIMIT, SOURCE_LIMIT, type DiagramInput, type DiagramReply } from "../components/markdown-diagrams/types";
const fonts: DiagramInput["fonts"] = {
sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
mono: 'ui-monospace, "Cascadia Code", monospace', size: 14,
};
const source = 'flowchart LR\n A["`**粗体** _italic_ 中文 😀`"] --> B[Result]';
let base: string;
async function peleSvg(text: string): Promise<string> {
await load(detectType(text));
return render(text, {
fontFamily: fonts.sans, fontFamilyMono: fonts.mono, fontSize: fonts.size,
measurer: { width: (text) => text.length * 7 }, links: false, images: false,
responsive: false, maxWidth: 600, maxEdges: 500,
}).svg;
}
function documentSvg(body: string): string {
return base.slice(0, base.indexOf(">") + 1) + body + "</svg>";
}
function reject(svg: string, reason = "policy"): void {
expect(() => diagramImageTemplate(svg, fonts)).toThrowError(
expect.objectContaining({ reason }),
);
}
function canvasFixture() {
const context = {
font: "",
measureText: vi.fn((text: string) => ({ width: text.length * 7 })),
};
vi.stubGlobal("OffscreenCanvas", class {
getContext() { return context; }
});
return context;
}
beforeAll(async () => { base = await peleSvg(source); });
afterEach(() => { vi.unstubAllGlobals(); });
describe("Pele image-only output", () => {
it.each([
source,
"sequenceDiagram\n Alice->>Bob: 中文 and emoji 😀\n Note over Alice,Bob: two lines<br/>second",
"stateDiagram-v2\n [*] --> Active\n state Active {\n [*] --> Ready\n Ready --> [*]\n }",
])("accepts the published engine's measured geometries: %s", async (text) => {
const svg = await peleSvg(text);
const image = diagramImageTemplate(svg, fonts);
expect(image.content).toContain("<text");
expect(image.content).not.toMatch(/^<svg/);
expect(image.style).toContain("--_bg:var(--pele-bg,#fff)");
expect(image.style).toContain('font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif');
expect(image.style).toContain('--_fm:ui-monospace,"Cascadia Code",monospace');
expect(image.style).not.toContain("--pele-font,");
expect(image.width).toBeGreaterThan(0);
expect(image.height).toBeGreaterThan(0);
});
it("retains measured bold, italic and numeric size styling", async () => {
const image = diagramImageTemplate(await peleSvg(`${source}\n classDef measured font-size:18px,font-weight:bold,font-style:italic\n class B measured`), fonts);
expect(image.style).toContain("--_w:bold");
expect(image.content).toContain("font-size:18px");
expect(image.content).toContain("font-style:italic");
expect(image.content).toContain('font-weight="var(--_w)"');
});
it.each([
"font-family:fantasy", "letter-spacing:4px", "word-spacing:1em",
"font-size:2em", "font-size:201px", "font-weight:600", "font-style:oblique",
])("rejects unmeasured author typography: %s", async (authorStyle) => {
reject(await peleSvg(`flowchart LR\n A[Label] --> B\n style A ${authorStyle}`), "unsupported");
});
it("preserves and resolves local marker/clip references and monospace attributes", () => {
const image = diagramImageTemplate(documentSvg('<defs><marker id="arrow" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto"><path d="M0 0L8 4L0 8Z"/></marker><clipPath id="clip"><rect width="40" height="20"/></clipPath></defs><path d="M0 0L40 20" marker-end="url(#arrow)" style="clip-path:url(#clip)"/><text font-family="var(--_fm)" font-size="12">code</text>'), fonts);
expect(image.content).toContain('marker-end="url(#arrow)"');
expect(image.content).toContain('style="clip-path:url(#clip)"');
expect(image.content).toContain('font-family="var(--_fm)"');
reject(documentSvg('<path d="M0 0L2 2" marker-end="url(#missing)"/>'));
reject(documentSvg('<g id="wrong"/><path d="M0 0L2 2" marker-end="url(#wrong)"/>'));
});
it("serializes XML and extracts an inert plain accessible label", () => {
const image = diagramImageTemplate(documentSvg('<title id="title">A &amp; B &lt;img&gt;</title><desc>中文\n description</desc><text><![CDATA[<script> & "quoted"]]></text>'), fonts);
expect(image.label).toBe("A & B <img>. 中文 description");
expect(image.content).toContain("&lt;script&gt; &amp; &quot;quoted&quot;");
expect(image.content).not.toContain("<![CDATA[");
});
it.each([
'<script>alert(1)</script>', '<foreignObject/>', '<animate attributeName="x"/>',
'<image href="https://bad.test/image"/>', '<a href="https://bad.test/"><text>link</text></a>',
'<use href="#shape"/>', '<path d="M0 0L1 1" onclick="alert(1)"/>',
'<g xmlns="http://www.w3.org/1999/xhtml"/>', '<text>&unknown;</text>',
'<path style="fill:url(https://bad.test/a)"/>', '<path style="fill:u\\72l(https://bad.test/a)"/>',
'<path style="fill:var(--custom,red)"/>', '<path style="fill:var(--_fg,url(https://bad.test/a))"/>',
'<path style="--custom:red;fill:var(--custom)"/>', '<path style="filter:blur(4px)"/>',
'<path style="@import url(https://bad.test/a)"/>',
])("rejects active/resource/unsupported XML or CSS: %s", (body) => {
reject(documentSvg(body));
});
it("rejects DTD/entity declarations and processing instructions", () => {
reject('<!DOCTYPE svg [<!ENTITY value "expanded">]>' + documentSvg("<text>&value;</text>"));
reject('<?xml-stylesheet href="https://bad.test/style"?>' + base);
});
it("bounds dimensions, finite geometry, element count and final UTF-8 bytes", () => {
reject(base.replace(/width="\d+"/, 'width="8193"'), "limit");
reject(base.replace(/viewBox="[^"]+"/, 'viewBox="0 0 1 1"'), "limit");
reject(base.replace(/viewBox="[^"]+"/, 'viewBox="0 0 3000 3000"').replace(/width="\d+"/, 'width="3000"').replace(/height="\d+"/, 'height="3000"'), "limit");
reject(documentSvg('<path d="M0 0L1e999 2"/>'), "limit");
reject(documentSvg("<g/>".repeat(10_000)), "limit");
const multibyte = documentSvg(`<text>${"中".repeat(360_000)}</text>`);
expect(multibyte.length).toBeLessThan(OUTPUT_LIMIT);
reject(multibyte, "limit");
reject(documentSvg(`<text><![CDATA[${"<".repeat(270_000)}]]></text>`), "limit");
});
});
describe("canvas-only typography", () => {
it("uses the exact sans/mono size, bold and italic flags", () => {
const context = canvasFixture();
const measurer = canvasTextMeasurer(fonts);
for (const [flags, expected] of [
[0, `18px ${fonts.sans}`], [1, `bold 18px ${fonts.sans}`],
[2, `italic 18px ${fonts.sans}`], [4, `18px ${fonts.mono}`],
[7, `italic bold 18px ${fonts.mono}`],
] as const) {
expect(measurer.width("中文 emoji 😀", 18, flags)).toBe(77);
expect(context.font).toBe(expected);
}
});
it("fails explicitly without OffscreenCanvas rather than using approximate metrics", () => {
vi.stubGlobal("OffscreenCanvas", undefined);
expect(() => canvasTextMeasurer(fonts)).toThrowError(new DiagramImageError("capability"));
});
});
describe("single-input Worker protocol", () => {
async function run(text: string): Promise<DiagramReply[]> {
vi.resetModules();
const replies: DiagramReply[] = [];
const worker: {
onmessage: ((event: MessageEvent<DiagramInput>) => Promise<void>) | null;
postMessage(reply: DiagramReply): void;
} = { onmessage: null, postMessage: (reply) => { replies.push(reply); } };
vi.stubGlobal("self", worker);
const canvas = canvasFixture();
canvas.measureText.mockImplementation((text) => {
expect(replies.at(-1)?.kind).toBe("started");
return { width: text.length * 7 };
});
await import("../components/markdown-diagrams/pele.worker");
if (!worker.onmessage) throw new Error("Worker handler missing");
await worker.onmessage(new MessageEvent<DiagramInput>("message", {
data: { source: text, width: 600, fonts },
}));
expect(worker.onmessage).toBeNull();
return replies;
}
it("loads the actual engine, announces sync work, and returns only an image template", async () => {
const replies = await run('---\ntitle: Supported frontmatter\nconfig:\n links: true\n images: true\n---\n%%{init: {"flowchart":{"wrappingWidth":120}}}%%\nflowchart LR\n A["<b>中文</b>"] --> B\n click A "https://bad.test/"\n');
expect(replies.map((reply) => reply.kind)).toEqual(["started", "image"]);
const image = replies[1];
if (image.kind !== "image") throw new Error("Image missing");
expect(image.template.content).toContain("Supported frontmatter");
expect(image.template.content).not.toMatch(/<a\b|href=|<image\b/);
});
it("enforces host source/edge limits and reports unsupported or invalid syntax", async () => {
expect(await run("x".repeat(SOURCE_LIMIT + 1))).toEqual([{ kind: "failed", reason: "limit" }]);
expect(await run("unknownDiagram A")).toEqual([{ kind: "failed", reason: "unsupported" }]);
expect((await run("flowchart LR\n A[unclosed")).at(-1)).toEqual({ kind: "failed", reason: "syntax" });
const edges = Array.from({ length: 501 }, (_, i) => `A${i} --> A${i + 1}`).join("\n");
expect((await run(`flowchart LR\n${edges}`)).at(-1)).toEqual({ kind: "failed", reason: "limit" });
});
});
+213
View File
@@ -0,0 +1,213 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { requestDiagram, type DiagramPalette, type DiagramRequest, type DiagramState } from "@/components/markdown-diagrams/runtime";
import type { DiagramInput, DiagramReply } from "@/components/markdown-diagrams/types";
class RenderWorker {
static instances: RenderWorker[] = [];
onmessage: ((event: MessageEvent) => void) | null = null;
onerror: (() => void) | null = null;
onmessageerror: (() => void) | null = null;
terminate = vi.fn();
postMessage = vi.fn();
constructor() { RenderWorker.instances.push(this); }
reply(data: DiagramReply) { this.onmessage?.({ data } as MessageEvent); }
}
class DecodedImage {
static instances: DecodedImage[] = [];
src = "";
decoding = "";
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
removeAttribute = vi.fn();
decode = vi.fn(() => Promise.resolve());
constructor() { DecodedImage.instances.push(this); }
}
const input: DiagramInput = { source: "flowchart LR\nA --> B", width: 500, fonts: { sans: "sans-serif", mono: "monospace", size: 16 } };
const result: DiagramReply = { kind: "image", template: { content: '<path d="M0 0L20 20"/>', style: "fill:black", width: 100, height: 50, label: "Example" } };
let requests: DiagramRequest[];
function start(source = input.source) {
const controller = new AbortController();
const states: DiagramState[] = [];
const request = requestDiagram({ ...input, source }, controller.signal, (state) => states.push(state));
requests.push(request);
request.setDemand("visible");
return { request, states, controller };
}
beforeEach(() => {
requests = [];
RenderWorker.instances = [];
DecodedImage.instances = [];
vi.useFakeTimers();
vi.stubGlobal("Worker", RenderWorker);
vi.stubGlobal("Image", DecodedImage);
vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:diagram-${DecodedImage.instances.length}`);
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
});
afterEach(() => {
requests.forEach((request) => request.dispose());
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("diagram runtime", () => {
it("bounds concurrent rendering, prioritizes an opened diagram and cancels only its task", () => {
const jobs = Array.from({ length: 8 }, () => start());
expect(RenderWorker.instances).toHaveLength(2);
jobs[7].request.setDemand("dialog");
jobs[0].controller.abort();
expect(RenderWorker.instances[0].terminate).toHaveBeenCalledOnce();
expect(RenderWorker.instances[1].terminate).not.toHaveBeenCalled();
expect(RenderWorker.instances).toHaveLength(3);
jobs[7].controller.abort();
expect(RenderWorker.instances[2].terminate).toHaveBeenCalledOnce();
});
it("terminates timed-out synchronous work and ignores its late result", () => {
const job = start();
const worker = RenderWorker.instances[0];
const lateReply = worker.onmessage!;
worker.reply({ kind: "started" });
vi.advanceTimersByTime(2000);
expect(worker.terminate).toHaveBeenCalledOnce();
expect(job.states.at(-1)).toEqual({ kind: "failed", reason: "deadline" });
lateReply({ data: result } as MessageEvent);
expect(URL.createObjectURL).not.toHaveBeenCalled();
});
it("releases the worker when module loading fails and permits an explicit retry", () => {
const job = start();
vi.advanceTimersByTime(10_000);
expect(job.states.at(-1)).toEqual({ kind: "failed", reason: "load" });
expect(RenderWorker.instances[0].terminate).toHaveBeenCalledOnce();
// Source view / scrolling offscreen must preserve the error and its retry action.
job.request.setDemand("none");
job.request.setDemand("visible");
expect(job.states.at(-1)).toEqual({ kind: "failed", reason: "load" });
expect(RenderWorker.instances).toHaveLength(1);
job.request.retry();
expect(RenderWorker.instances).toHaveLength(2);
});
it("decodes before publishing and rebinds the theme without executing Pele again", async () => {
const job = start();
RenderWorker.instances[0].reply(result);
expect(job.states.at(-1)?.kind).toBe("rendering");
expect(RenderWorker.instances[0].terminate).toHaveBeenCalledOnce();
DecodedImage.instances[0].onload?.();
await Promise.resolve();
expect(job.states.at(-1)).toMatchObject({ kind: "ready", image: { width: 100, label: "Example" } });
job.request.setPalette({ "--pele-fg": "#eeeeee" });
expect(RenderWorker.instances).toHaveLength(1);
DecodedImage.instances[1].onload?.();
await Promise.resolve();
expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:diagram-0");
job.controller.abort();
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2);
});
it("keeps twelve small visible diagrams ready through growing and shrinking palettes", async () => {
const jobs = Array.from({ length: 12 }, () => start());
for (let index = 0; index < jobs.length; index++) {
RenderWorker.instances[index].reply(result);
expect(DecodedImage.instances).toHaveLength(index + 1);
DecodedImage.instances[index].onload?.();
await Promise.resolve();
expect(jobs[index].states.at(-1)?.kind).toBe("ready");
}
const palettes: DiagramPalette[] = [
{ "--pele-bg": "hsl(210 40% 98%)", "--pele-fg": "hsl(222.2 84% 4.9%)", "--pele-accent": "rgb(12 34 56)" },
{ "--pele-fg": "#eee" },
];
for (const palette of palettes) {
const offset = DecodedImage.instances.length;
const before = jobs.map(({ states }) => states.at(-1));
jobs.forEach(({ request }) => request.setPalette(palette));
expect(DecodedImage.instances).toHaveLength(offset + jobs.length);
expect(jobs.map(({ states }) => states.at(-1))).toEqual(before);
for (let index = 0; index < jobs.length; index++) DecodedImage.instances[offset + index].onload?.();
await Promise.resolve();
expect(jobs.map(({ states }) => states.at(-1))).toEqual(jobs.map((_, index) => ({
kind: "ready", image: { url: `blob:diagram-${offset + index}`, width: 100, height: 50, label: "Example" },
})));
}
expect(RenderWorker.instances).toHaveLength(jobs.length);
jobs.forEach(({ controller }) => controller.abort());
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(36);
});
it("disposes a pending image on session change, suppressing its late decode", async () => {
const job = start();
RenderWorker.instances[0].reply(result);
const image = DecodedImage.instances[0];
let resolve!: () => void;
image.decode.mockImplementation(() => new Promise<void>((done) => { resolve = done; }));
image.onload?.();
job.controller.abort();
resolve();
await Promise.resolve();
expect(job.states.some((state) => state.kind === "ready")).toBe(false);
expect(URL.revokeObjectURL).toHaveBeenCalledOnce();
});
it("releases offscreen assets and re-renders only on renewed demand", async () => {
const job = start();
RenderWorker.instances[0].reply(result);
DecodedImage.instances[0].onload?.();
await Promise.resolve();
job.request.setDemand("none");
expect(URL.revokeObjectURL).toHaveBeenCalledOnce();
expect(job.states.at(-1)).toEqual({ kind: "waiting" });
expect(RenderWorker.instances).toHaveLength(1);
job.request.setDemand("visible");
expect(RenderWorker.instances).toHaveLength(2);
});
it.each([
{ budget: "pixels", content: "<path/>", width: 4000, height: 2000 },
{ budget: "bytes", content: `<path d="M0 0${" L1 1".repeat(190_000)}"/>`, width: 100, height: 50 },
])("reserves replacement $budget while a new fence waits for shared capacity", async ({ content, width, height }) => {
const jobs = Array.from({ length: 4 }, () => start());
const large: DiagramReply = { kind: "image", template: { content, style: "fill:black", width, height, label: "Large graph" } };
for (let index = 0; index < 3; index++) {
RenderWorker.instances[index].reply(large);
DecodedImage.instances[index].onload?.();
await Promise.resolve();
expect(jobs[index].states.at(-1)?.kind).toBe("ready");
}
RenderWorker.instances[3].reply(large);
expect(jobs[3].states.at(-1)).toEqual({ kind: "waiting" });
expect(DecodedImage.instances).toHaveLength(3);
// A theme change must progress at full admission capacity without losing the visible images.
jobs.slice(0, 3).forEach(({ request }) => request.setPalette({ "--pele-fg": "#eeeeee" }));
for (let index = 0; index < 3; index++) {
expect(DecodedImage.instances).toHaveLength(4 + index);
expect(URL.revokeObjectURL).not.toHaveBeenCalledWith(`blob:diagram-${index}`);
DecodedImage.instances[3 + index].onload?.();
await Promise.resolve();
await Promise.resolve();
expect(jobs[index].states.at(-1)).toMatchObject({ kind: "ready", image: { url: `blob:diagram-${3 + index}` } });
expect(URL.revokeObjectURL).toHaveBeenCalledWith(`blob:diagram-${index}`);
}
expect(jobs[3].states.at(-1)).toEqual({ kind: "waiting" });
jobs[0].controller.abort();
await Promise.resolve();
expect(DecodedImage.instances).toHaveLength(7);
DecodedImage.instances[6].onload?.();
await Promise.resolve();
expect(jobs[3].states.at(-1)?.kind).toBe("ready");
expect(RenderWorker.instances).toHaveLength(4);
});
it("retains source-only failure when Worker is unavailable or source exceeds the budget", () => {
const oversized = start("a".repeat(50_001));
expect(oversized.states.at(-1)).toEqual({ kind: "failed", reason: "limit" });
vi.stubGlobal("Worker", undefined);
const unavailable = start();
expect(unavailable.states.at(-1)).toEqual({ kind: "failed", reason: "capability" });
expect(RenderWorker.instances).toHaveLength(0);
});
});
+96 -7
View File
@@ -1,15 +1,17 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ImageLightbox } from "@/components/ImageLightbox";
import { ZoomableImage } from "@/components/ZoomableImage";
import { ImageViewport } from "@/components/ui/image-viewport";
afterEach(() => vi.unstubAllGlobals());
function renderImage() {
const result = render(<ZoomableImage src="data:image/png;base64,test" alt="Test chart" />);
const viewport = screen.getByTestId("image-zoom-viewport");
const result = render(<ImageViewport src="data:image/png;base64,test" alt="Test chart" />);
const viewport = screen.getByTestId("image-viewport");
const image = screen.getByRole("img", { name: "Test chart" });
Object.defineProperties(viewport, { clientWidth: { value: 800 }, clientHeight: { value: 600 } });
Object.defineProperties(image, { offsetWidth: { value: 800 }, offsetHeight: { value: 600 } });
Object.defineProperties(viewport, { clientWidth: { value: 800, configurable: true }, clientHeight: { value: 600, configurable: true } });
Object.defineProperties(image, { offsetWidth: { value: 800, configurable: true }, offsetHeight: { value: 600, configurable: true } });
viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);
return { ...result, viewport, image };
}
@@ -37,6 +39,13 @@ describe("image zoom", () => {
fireEvent.pointerMove(viewport, { pointerId: 1, clientX: 300, clientY: 300 });
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
expect(viewport.className).not.toContain("cursor-grabbing");
fireEvent.pointerDown(viewport, { pointerId: 3, button: 0, clientX: 400, clientY: 300 });
fireEvent.pointerMove(viewport, { pointerId: 3, clientX: 300, clientY: 300 });
expect(image.style.transform).toBe("translate3d(300px, 300px, 0) scale(2)");
fireEvent.lostPointerCapture(viewport, { pointerId: 3 });
fireEvent.pointerMove(viewport, { pointerId: 3, clientX: 200, clientY: 300 });
expect(image.style.transform).toBe("translate3d(300px, 300px, 0) scale(2)");
expect(viewport.className).not.toContain("cursor-grabbing");
fireEvent.click(screen.getByRole("button", { name: "Fit image" }));
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
});
@@ -47,6 +56,7 @@ describe("image zoom", () => {
expect(wheel(viewport, -50)).toBe(false);
expect(image.style.transform).toContain(`scale(${Math.exp(0.5)})`);
expect(wheel(document.body, -50)).toBe(true);
expect(wheel(document.body, 20, false)).toBe(true);
expect(wheel(viewport, 20, false)).toBe(false);
expect(image.style.transform).toContain("-20px");
for (let i = 0; i < 10; i++) wheel(viewport, -50);
@@ -63,6 +73,10 @@ describe("image zoom", () => {
expect(image.style.transform).toContain("scale(2)");
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
expect(image.style.transform).toContain("scale(1)");
fireEvent.keyDown(viewport, { key: "=" });
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
fireEvent.keyDown(viewport, { key: "-" });
expect(image.style.transform).toContain("scale(1)");
fireEvent.keyDown(viewport, { key: "+" });
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
fireEvent.keyDown(viewport, { key: "0" });
@@ -71,6 +85,81 @@ describe("image zoom", () => {
expect(image.style.transform).toContain("scale(1)");
});
it("pans with focused arrow keys within the image bounds", () => {
const { viewport, image } = renderImage();
viewport.focus();
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
expect(fireEvent.keyDown(viewport, { key: "ArrowRight" })).toBe(false);
expect(image.style.transform).toBe("translate3d(-40px, 0px, 0) scale(1.5)");
fireEvent.keyDown(viewport, { key: "ArrowDown" });
expect(image.style.transform).toBe("translate3d(-40px, -40px, 0) scale(1.5)");
fireEvent.keyDown(viewport, { key: "ArrowLeft" });
fireEvent.keyDown(viewport, { key: "ArrowUp" });
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1.5)");
for (let i = 0; i < 10; i++) {
fireEvent.keyDown(viewport, { key: "ArrowRight" });
fireEvent.keyDown(viewport, { key: "ArrowDown" });
}
expect(image.style.transform).toBe("translate3d(-200px, -150px, 0) scale(1.5)");
fireEvent.keyDown(viewport, { key: "0" });
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1)");
});
it("leaves outside keys and browser zoom shortcuts alone", () => {
const { viewport, image } = renderImage();
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
expect(fireEvent.keyDown(document.body, { key: "+" })).toBe(true);
expect(fireEvent.keyDown(document.body, { key: "ArrowRight" })).toBe(true);
expect(fireEvent.keyDown(viewport, { key: "+", ctrlKey: true })).toBe(true);
expect(fireEvent.keyDown(viewport, { key: "0", metaKey: true })).toBe(true);
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(1.5)");
});
it("reclamps on resize and image load, then releases observers, wheel and pointer capture", () => {
let onResize: (() => void) | undefined;
const observe = vi.fn();
const disconnect = vi.fn();
vi.stubGlobal("ResizeObserver", class {
constructor(callback: () => void) { onResize = callback; }
observe = observe;
disconnect = disconnect;
});
const { viewport, image, unmount } = renderImage();
const captured = new Set<number>();
viewport.setPointerCapture = (id) => { captured.add(id); };
viewport.hasPointerCapture = (id) => captured.has(id);
const release = vi.fn((id: number) => { captured.delete(id); });
viewport.releasePointerCapture = release;
expect(observe).toHaveBeenCalledWith(viewport);
fireEvent.doubleClick(viewport, { clientX: 400, clientY: 300 });
fireEvent.pointerDown(viewport, { pointerId: 1, button: 0, clientX: 400, clientY: 300 });
fireEvent.pointerMove(viewport, { pointerId: 1, clientX: 9000, clientY: 9000 });
expect(image.style.transform).toBe("translate3d(400px, 300px, 0) scale(2)");
Object.defineProperties(viewport, { clientWidth: { value: 1200 }, clientHeight: { value: 900 } });
act(() => onResize?.());
expect(image.style.transform).toBe("translate3d(200px, 150px, 0) scale(2)");
Object.defineProperties(image, { offsetWidth: { value: 500 }, offsetHeight: { value: 400 } });
fireEvent.load(image);
expect(image.style.transform).toBe("translate3d(0px, 0px, 0) scale(2)");
unmount();
expect(disconnect).toHaveBeenCalledOnce();
expect(release).toHaveBeenCalledWith(1);
expect(wheel(viewport, -50)).toBe(true);
});
it("preserves left/right gallery navigation from the focused, zoomed photo viewport", () => {
const images = [{ url: "data:image/png;base64,a", name: "A" }, { url: "data:image/png;base64,b", name: "B" }, { url: "data:image/png;base64,c", name: "C" }];
const onIndexChange = vi.fn();
render(<ImageLightbox images={images} index={1} onIndexChange={onIndexChange} onOpenChange={() => {}} />);
const viewport = screen.getByTestId("image-zoom-viewport");
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
viewport.focus();
fireEvent.keyDown(document.activeElement!, { key: "ArrowLeft" });
fireEvent.keyDown(document.activeElement!, { key: "ArrowRight" });
expect(onIndexChange.mock.calls).toEqual([[0], [2]]);
expect(screen.getByRole("button", { name: "Fit image" })).toHaveTextContent("150%");
});
it("resets zoom when switching images and reopening the lightbox", () => {
const images = [{ url: "data:image/png;base64,a", name: "A" }, { url: "data:image/png;base64,b", name: "B" }];
const view = (index: number | null) => <ImageLightbox images={images} index={index} onIndexChange={() => {}} onOpenChange={() => {}} />;
+78
View File
@@ -0,0 +1,78 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MessageBubble } from "@/components/MessageBubble";
import MarkdownTextRenderer from "@/components/MarkdownTextRenderer";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import type { DiagramInput } from "@/components/markdown-diagrams/types";
import type { DiagramState } from "@/components/markdown-diagrams/runtime";
const runtime = vi.hoisted(() => ({ request: vi.fn() }));
vi.mock("@/components/markdown-diagrams/runtime", () => ({ requestDiagram: runtime.request }));
const code = "flowchart LR\n开始 --> 完成";
const markdown = `Before the graph.\n\n\`\`\`mermaid\n${code}\n\`\`\`\n\nAfter the graph.`;
const jobs: { input: DiagramInput; signal: AbortSignal; publish: (state: DiagramState) => void; demand: ReturnType<typeof vi.fn> }[] = [];
class VisibleObserver {
constructor(private callback: (entries: { isIntersecting: boolean }[]) => void) {}
observe() { this.callback([{ isIntersecting: true }]); }
disconnect() {}
}
class SizeObserver {
constructor(private callback: () => void) {}
observe() { this.callback(); }
disconnect() {}
}
beforeEach(() => {
jobs.length = 0;
runtime.request.mockImplementation((input: DiagramInput, signal: AbortSignal, publish: (state: DiagramState) => void) => {
const demand = vi.fn();
jobs.push({ input, signal, publish, demand });
return { setDemand: demand, setPalette: vi.fn(), retry: vi.fn(), dispose: vi.fn() };
});
vi.stubGlobal("IntersectionObserver", VisibleObserver);
vi.stubGlobal("ResizeObserver", SizeObserver);
vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(640);
});
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe("Mermaid message fences", () => {
it("renders identical source at actual completion through preserved Streamdown layout", async () => {
const message = { id: "diagram", role: "assistant" as const, content: markdown, createdAt: 1, isStreaming: true };
const view = render(<MessageBubble message={message} />);
await waitFor(() => expect(view.container.querySelector(".markdown-content")).toBeInTheDocument());
const tree = view.container.querySelector(".markdown-content");
expect(runtime.request).not.toHaveBeenCalled();
expect(view.container).toHaveTextContent("开始 --> 完成");
view.rerender(<MessageBubble message={{ ...message, isStreaming: false }} />);
await waitFor(() => expect(jobs).toHaveLength(1));
expect(jobs[0].input.source).toBe(code);
expect(view.container.querySelector(".markdown-content")).toBe(tree);
act(() => jobs[0].publish({ kind: "ready", image: { url: "blob:completed-diagram", width: 200, height: 100, label: "A real diagram result" } }));
expect(screen.getByRole("img", { name: "A real diagram result" })).toHaveAttribute("src", "blob:completed-diagram");
expect(screen.getByRole("button", { name: "Enlarge diagram" })).not.toBeDisabled();
expect(view.container).toHaveTextContent("Before the graph.");
expect(view.container).toHaveTextContent("After the graph.");
});
it("keeps errors local and makes failed source available", async () => {
render(<MarkdownTextRenderer>{markdown}</MarkdownTextRenderer>);
await waitFor(() => expect(jobs).toHaveLength(1));
act(() => jobs[0].publish({ kind: "failed", reason: "syntax" }));
expect(screen.getByRole("status")).toHaveTextContent("Check the diagram syntax");
expect(screen.getByTestId("plain-code-fallback")).toHaveTextContent("开始 --> 完成");
expect(screen.getByText("After the graph.")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Copy source" })).toBeInTheDocument();
});
it("keeps a chosen source view and cancels resources when the conversation identity changes", async () => {
const view = render(<DiagramScope identity="first"><MarkdownTextRenderer>{markdown}</MarkdownTextRenderer></DiagramScope>);
await waitFor(() => expect(jobs).toHaveLength(1));
fireEvent.click(screen.getByRole("button", { name: "Source" }));
expect(jobs[0].demand).toHaveBeenLastCalledWith("none");
view.rerender(<DiagramScope identity="second"><MarkdownTextRenderer>{markdown}</MarkdownTextRenderer></DiagramScope>);
await waitFor(() => expect(jobs).toHaveLength(2));
expect(jobs[0].signal.aborted).toBe(true);
expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");
expect(jobs[1].demand).toHaveBeenLastCalledWith("none");
});
});
+12
View File
@@ -19,6 +19,15 @@ describe("development overlay dependencies", () => {
});
});
describe("development diagram Worker dependencies", () => {
it("pre-bundles Worker-only imports without a first-use page reload", () => {
const config = webuiConfig({ command: "serve", mode: "test" });
expect(config.optimizeDeps?.include).toEqual(expect.arrayContaining([
"pele/lazy", "saxes", "css-tree/parser", "css-tree/walker", "css-tree/generator",
]));
});
});
describe("gzipWebuiAssets", () => {
it("compresses finalized files after Rollup writes the bundle", async () => {
const plugin = gzipWebuiAssets();
@@ -63,10 +72,12 @@ describe("entryLazyFeatureImports", () => {
"assets/markdown-vendor-abc.js",
"assets/syntax-highlight-def.js",
"assets/katex-ghi.js",
"assets/MermaidBlock-jkl.js",
])).toEqual([
"assets/markdown-vendor-abc.js",
"assets/syntax-highlight-def.js",
"assets/katex-ghi.js",
"assets/MermaidBlock-jkl.js",
]);
});
});
@@ -102,6 +113,7 @@ describe("webuiManualChunk", () => {
});
it("keeps Streamdown and its repair helper in the markdown chunk", () => {
expect(webuiManualChunk("/repo/webui/src/components/markdown-diagrams/context.tsx")).toBeUndefined();
expect(webuiManualChunk("/repo/node_modules/streamdown/dist/index.js")).toBe(
"markdown-vendor",
);