Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(visualize): inline + themed SVG rendering, html sendPrompt bridge

Bingxi Zhao (Frank)b499ba7aaf93
diff --git a/web/components/visualize/VisualizationViewer.tsx b/web/components/visualize/VisualizationViewer.tsx
index 122f32971..de5c84e3e 100644
--- a/web/components/visualize/VisualizationViewer.tsx
+++ b/web/components/visualize/VisualizationViewer.tsx
@@ -1,12 +1,13 @@
"use client";
import dynamic from "next/dynamic";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import { Code2, Copy, Check, ExternalLink, Maximize2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Mermaid } from "@/components/Mermaid";
import { prepareIframeHtml } from "@/lib/iframe-html";
import { isManimResult, type VisualizeResult } from "@/lib/visualize-types";
+import "./svg-theme.css";
const MathAnimatorViewer = dynamic(
() => import("@/components/math-animator/MathAnimatorViewer"),
@@ -108,6 +109,7 @@ function ChartJsRenderer({ config }: { config: string }) {
function HtmlRenderer({ html }: { html: string }) {
const { t } = useTranslation();
const iframeRef = useRef<HTMLIFrameElement>(null);
+ const [height, setHeight] = useState(560);
const prepared = useMemo(() => prepareIframeHtml(html || ""), [html]);
@@ -117,6 +119,29 @@ function HtmlRenderer({ html }: { html: string }) {
iframe.srcdoc = prepared;
}, [prepared]);
+ // Listen for the iframe bridge: a sendPrompt() call (mirror into the composer
+ // via the shared window event) or a height report (grow to fit, no clipping).
+ useEffect(() => {
+ const onMessage = (e: MessageEvent) => {
+ const iframe = iframeRef.current;
+ if (!iframe || e.source !== iframe.contentWindow) return;
+ const data = e.data as { type?: string; text?: string; height?: number };
+ if (!data || typeof data !== "object") return;
+ if (data.type === "dt:visualize-prompt" && data.text) {
+ window.dispatchEvent(
+ new CustomEvent("dt:visualize-prompt", { detail: data.text }),
+ );
+ } else if (
+ data.type === "dt:visualize-height" &&
+ typeof data.height === "number"
+ ) {
+ setHeight(Math.min(2400, Math.max(240, Math.ceil(data.height) + 8)));
+ }
+ };
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, []);
+
const handleOpenInNewTab = () => {
try {
const contentUrl = URL.createObjectURL(
@@ -152,43 +177,181 @@ function HtmlRenderer({ html }: { html: string }) {
title={t("HTML visualization")}
sandbox="allow-scripts"
className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)]"
- style={{ minHeight: 480, height: 560 }}
+ style={{ minHeight: 320, height }}
/>
</div>
);
}
-function SvgRenderer({ svg }: { svg: string }) {
+// Per-page sequence used to scope SVG ids (see the scoping block below).
+let svgScopeSeq = 0;
+
+// Sanitize an SVG string for safe inline rendering: parse as XML, strip
+// script/foreign-object/event-handler vectors, then reserialize. SVGs come from
+// our own LLM and already pass a backend well-formedness check, but we still
+// defend against prompt-injected <script>/on* handlers. Kept dependency-free
+// (same sanitize→string contract as DOMPurify, so it can be swapped later).
+function sanitizeSvg(raw: string): string {
+ const trimmed = raw.trim();
+ if (typeof DOMParser === "undefined") return "";
+ const doc = new DOMParser().parseFromString(trimmed, "image/svg+xml");
+ const root = doc.documentElement;
+ if (!root || root.nodeName.toLowerCase() !== "svg") return "";
+ if (root.getElementsByTagName("parsererror").length > 0) return "";
+
+ const STRIP = [
+ "script",
+ "foreignObject",
+ "iframe",
+ "object",
+ "embed",
+ "audio",
+ "video",
+ "handler",
+ ];
+ root.querySelectorAll(STRIP.join(",")).forEach((n) => n.remove());
+
+ const walk = (el: Element) => {
+ const tag = el.nodeName.toLowerCase();
+ for (const attr of Array.from(el.attributes)) {
+ const name = attr.name.toLowerCase();
+ const val = attr.value.replace(/\s+/g, "").toLowerCase();
+ if (name.startsWith("on")) {
+ el.removeAttribute(attr.name);
+ } else if (
+ (name === "href" || name === "xlink:href") &&
+ (val.startsWith("javascript:") ||
+ (val.startsWith("data:") && !val.startsWith("data:image/")))
+ ) {
+ el.removeAttribute(attr.name);
+ } else if (name === "style" && val.includes("javascript:")) {
+ el.removeAttribute(attr.name);
+ } else if (
+ (tag === "set" || tag === "animate") &&
+ name === "attributename" &&
+ val.startsWith("on")
+ ) {
+ // <set attributeName="onclick" .../> can inject a handler — drop it.
+ el.remove();
+ return;
+ }
+ }
+ Array.from(el.children).forEach((child) => walk(child));
+ };
+ walk(root);
+
+ // Scope ids so multiple inlined SVGs on one page don't collide: marker /
+ // clipPath / gradient defs are referenced via url(#id) or href="#id". A bare
+ // <img> kept each SVG in its own document; inline DOM shares one namespace,
+ // so without this the 2nd+ figure's arrows/gradients break.
+ const ids = new Set<string>();
+ root.querySelectorAll("[id]").forEach((el) => {
+ const id = el.getAttribute("id");
+ if (id) ids.add(id);
+ });
+ if (ids.size) {
+ const prefix = `dtsvg${svgScopeSeq++}-`;
+ const rescope = (el: Element) => {
+ const ownId = el.getAttribute("id");
+ if (ownId && ids.has(ownId)) el.setAttribute("id", prefix + ownId);
+ for (const attr of Array.from(el.attributes)) {
+ const lname = attr.name.toLowerCase();
+ let v = attr.value.replace(
+ /url\(\s*(['"]?)#([^)'"\s]+)\1\s*\)/g,
+ (m, q, id) => (ids.has(id) ? `url(${q}#${prefix}${id}${q})` : m),
+ );
+ if (
+ (lname === "href" || lname.endsWith(":href")) &&
+ v.charAt(0) === "#" &&
+ ids.has(v.slice(1))
+ ) {
+ v = `#${prefix}${v.slice(1)}`;
+ } else if (lname === "aria-labelledby" || lname === "aria-describedby") {
+ v = v
+ .split(/\s+/)
+ .map((token) => (ids.has(token) ? prefix + token : token))
+ .join(" ");
+ }
+ if (v !== attr.value) el.setAttribute(attr.name, v);
+ }
+ Array.from(el.children).forEach((child) => rescope(child));
+ };
+ rescope(root);
+ }
+
+ return root.outerHTML;
+}
+
+function SvgFigure({ svg }: { svg: string }) {
const { t } = useTranslation();
- const trimmedSvg = svg.trim();
- const error = trimmedSvg.startsWith("<svg")
- ? null
- : t("Invalid SVG: does not start with <svg");
- const svgUrl = useMemo(
- () =>
- error
- ? ""
- : `data:image/svg+xml;charset=utf-8,${encodeURIComponent(trimmedSvg)}`,
- [error, trimmedSvg],
+ const trimmed = svg.trim();
+ const looksSvg = trimmed.startsWith("<svg") || trimmed.startsWith("<?xml");
+
+ // Client-only component (mounted via dynamic ssr:false), so DOMParser is
+ // always available and there's no SSR/hydration concern — sanitize in useMemo.
+ const safe = useMemo(
+ () => (looksSvg ? sanitizeSvg(trimmed) : ""),
+ [looksSvg, trimmed],
);
- if (error) {
+ if (!looksSvg || !safe) {
return (
<div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900/60 dark:bg-red-950/30">
<p className="text-sm font-medium text-red-600 dark:text-red-400">
{t("SVG rendering error")}
</p>
<pre className="mt-2 whitespace-pre-wrap text-xs text-red-500">
- {error}
+ {looksSvg
+ ? t("SVG could not be safely rendered")
+ : t("Invalid SVG: does not start with <svg")}
</pre>
</div>
);
}
+ // Inline (not <img>) so host CSS and the SVG's own <style> apply. Clicking a
+ // node carrying data-prompt drops a follow-up question into the composer (via
+ // a window event the chat page listens for) — prefilled, not auto-sent.
+ const onSvgClick = (e: MouseEvent<HTMLDivElement>) => {
+ const node = (e.target as Element).closest?.("[data-prompt]");
+ const prompt = node?.getAttribute("data-prompt")?.trim();
+ if (prompt) {
+ window.dispatchEvent(
+ new CustomEvent("dt:visualize-prompt", { detail: prompt }),
+ );
+ }
+ };
+
+ return (
+ <div
+ className="dt-svg-root flex justify-center overflow-x-auto"
+ onClick={onSvgClick}
+ dangerouslySetInnerHTML={{ __html: safe }}
+ />
+ );
+}
+
+// A model occasionally emits several <svg> blocks in one response, and the
+// backend extractor concatenates everything from the first <svg to the last
+// </svg> — so one code.content can hold multiple svgs with colliding ids
+// (marker/gradient/clipPath). Split them and render each as its own figure,
+// independently sanitized and id-scoped, instead of one malformed multi-root
+// document where only the last svg's defs win.
+function splitSvgBlocks(raw: string): string[] {
+ const blocks = raw.match(/<svg[\s\S]*?<\/svg>/gi);
+ return blocks && blocks.length ? blocks : [raw.trim()];
+}
+
+function SvgRenderer({ svg }: { svg: string }) {
+ const blocks = useMemo(() => splitSvgBlocks(svg.trim()), [svg]);
+ if (blocks.length <= 1) {
+ return <SvgFigure svg={blocks[0] ?? svg} />;
+ }
return (
- <div className="flex justify-center overflow-x-auto">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img src={svgUrl} alt={t("SVG visualization")} className="max-w-full" />
+ <div className="flex w-full flex-col gap-4">
+ {blocks.map((block, i) => (
+ <SvgFigure key={i} svg={block} />
+ ))}
</div>
);
}
diff --git a/web/components/visualize/svg-theme.css b/web/components/visualize/svg-theme.css
new file mode 100644
index 000000000..d8a1108ff
--- /dev/null
+++ b/web/components/visualize/svg-theme.css
@@ -0,0 +1,193 @@
+/* Theme for inlined visualization SVGs (rendered under .dt-svg-root).
+ The codegen prompt (rules_svg) emits these pre-built classes instead of
+ hard-coded fills, so figures follow the app's light/dark theme and font:
+ text: .t (14px), .th (14px/500), .ts (12px muted)
+ neutral: .box (container), .arr (arrow), .leader (dashed leader)
+ interactive: .node (hover), [data-prompt] (clickable)
+ color ramps: .c-{gray,blue,teal,coral,pink,purple,green,amber,red}
+ Ramp values are Claude's 9-ramp palette. Light = 50 fill / 600 stroke /
+ 800 text; dark = 800 fill / 200 stroke / 100 text — switched via .dark. */
+
+.dt-svg-root svg {
+ display: block;
+ width: 100%;
+ height: auto;
+}
+
+/* Use the app sans font (Geist), overriding any font-family on the SVG itself
+ and the serif (Lora) inherited from a surrounding .prose container. */
+.dt-svg-root,
+.dt-svg-root text {
+ font-family: var(
+ --font-sans,
+ ui-sans-serif,
+ system-ui,
+ -apple-system,
+ "Segoe UI",
+ sans-serif
+ );
+}
+
+/* Text roles */
+.dt-svg-root text.t,
+.dt-svg-root text.th {
+ font-size: 14px;
+ fill: var(--foreground);
+}
+.dt-svg-root text.th {
+ font-weight: 500;
+}
+.dt-svg-root text.ts {
+ font-size: 12px;
+ fill: var(--muted-foreground);
+}
+
+/* Neutral container + connectors */
+.dt-svg-root .box {
+ fill: var(--secondary);
+ stroke: var(--border);
+ stroke-width: 0.5;
+}
+.dt-svg-root .arr {
+ stroke: var(--muted-foreground);
+ stroke-width: 1.5;
+ fill: none;
+}
+.dt-svg-root .leader {
+ stroke: var(--muted-foreground);
+ stroke-width: 0.5;
+ stroke-dasharray: 3 3;
+ fill: none;
+}
+
+/* Interactive affordances */
+.dt-svg-root .node,
+.dt-svg-root [data-prompt] {
+ cursor: pointer;
+}
+.dt-svg-root .node {
+ transition: opacity 0.15s ease;
+}
+.dt-svg-root .node:hover,
+.dt-svg-root [data-prompt]:hover {
+ opacity: 0.82;
+}
+
+/* Color ramps — each publishes --fill / --stroke / --text (light defaults). */
+.dt-svg-root .c-gray {
+ --fill: #f1efe8;
+ --stroke: #5f5e5a;
+ --text: #2c2c2a;
+}
+.dt-svg-root .c-blue {
+ --fill: #e6f1fb;
+ --stroke: #185fa5;
+ --text: #0c447c;
+}
+.dt-svg-root .c-teal {
+ --fill: #e1f5ee;
+ --stroke: #0f6e56;
+ --text: #085041;
+}
+.dt-svg-root .c-coral {
+ --fill: #faece7;
+ --stroke: #993c1d;
+ --text: #712b13;
+}
+.dt-svg-root .c-pink {
+ --fill: #fbeaf0;
+ --stroke: #993556;
+ --text: #72243e;
+}
+.dt-svg-root .c-purple {
+ --fill: #eeedfe;
+ --stroke: #534ab7;
+ --text: #3c3489;
+}
+.dt-svg-root .c-green {
+ --fill: #eaf3de;
+ --stroke: #3b6d11;
+ --text: #27500a;
+}
+.dt-svg-root .c-amber {
+ --fill: #faeeda;
+ --stroke: #854f0b;
+ --text: #633806;
+}
+.dt-svg-root .c-red {
+ --fill: #fcebeb;
+ --stroke: #a32d2d;
+ --text: #791f1f;
+}
+
+/* Dark mode: flip to 800 fill / 200 stroke / 100 text. */
+.dark .dt-svg-root .c-gray {
+ --fill: #444441;
+ --stroke: #b4b2a9;
+ --text: #d3d1c7;
+}
+.dark .dt-svg-root .c-blue {
+ --fill: #0c447c;
+ --stroke: #85b7eb;
+ --text: #b5d4f4;
+}
+.dark .dt-svg-root .c-teal {
+ --fill: #085041;
+ --stroke: #5dcaa5;
+ --text: #9fe1cb;
+}
+.dark .dt-svg-root .c-coral {
+ --fill: #712b13;
+ --stroke: #f0997b;
+ --text: #f5c4b3;
+}
+.dark .dt-svg-root .c-pink {
+ --fill: #72243e;
+ --stroke: #ed93b1;
+ --text: #f4c0d1;
+}
+.dark .dt-svg-root .c-purple {
+ --fill: #3c3489;
+ --stroke: #afa9ec;
+ --text: #cecbf6;
+}
+.dark .dt-svg-root .c-green {
+ --fill: #27500a;
+ --stroke: #97c459;
+ --text: #c0dd97;
+}
+.dark .dt-svg-root .c-amber {
+ --fill: #633806;
+ --stroke: #ef9f27;
+ --text: #fac775;
+}
+.dark .dt-svg-root .c-red {
+ --fill: #791f1f;
+ --stroke: #f09595;
+ --text: #f7c1c1;
+}
+
+/* Apply ramp vars: shapes take fill+stroke, descendant text takes ramp text. */
+.dt-svg-root
+ :is(.c-gray, .c-blue, .c-teal, .c-coral, .c-pink, .c-purple, .c-green, .c-amber, .c-red)
+ > :is(rect, circle, ellipse, polygon),
+.dt-svg-root
+ :is(rect, circle, ellipse, polygon):is(
+ .c-gray,
+ .c-blue,
+ .c-teal,
+ .c-coral,
+ .c-pink,
+ .c-purple,
+ .c-green,
+ .c-amber,
+ .c-red
+ ) {
+ fill: var(--fill);
+ stroke: var(--stroke);
+}
+.dt-svg-root
+ :is(.c-gray, .c-blue, .c-teal, .c-coral, .c-pink, .c-purple, .c-green, .c-amber, .c-red)
+ text {
+ fill: var(--text);
+}
diff --git a/web/lib/iframe-html.ts b/web/lib/iframe-html.ts
index 9492525ce..871eade5e 100644
--- a/web/lib/iframe-html.ts
+++ b/web/lib/iframe-html.ts
@@ -83,9 +83,39 @@ export function sanitizeIframeHtml(html: string): string {
}
/**
- * Convenience: inject KaTeX, then sanitize. Suitable for a one-shot iframe
- * `srcdoc` write.
+ * Bridge injected into every widget iframe. The iframe runs in a null origin
+ * (sandbox="allow-scripts", no allow-same-origin), so it talks to the host only
+ * via postMessage:
+ * - `window.sendPrompt(text)` → posts a follow-up question; the host prefills
+ * it into the composer (the widget analogue of an SVG node's data-prompt).
+ * - a ResizeObserver posts the content height so the host can grow the iframe
+ * to fit instead of clipping at a fixed height.
+ */
+const BRIDGE_SCRIPT =
+ "<script data-dt-bridge>" +
+ "(function(){" +
+ 'window.sendPrompt=function(t){try{parent.postMessage({type:"dt:visualize-prompt",text:String(t||"")},"*")}catch(e){}};' +
+ "function rh(){try{var b=document.body,h=Math.max(document.documentElement.scrollHeight,b?b.scrollHeight:0);parent.postMessage({type:\"dt:visualize-height\",height:h},\"*\")}catch(e){}}" +
+ 'if(typeof ResizeObserver!=="undefined"){var ro=new ResizeObserver(rh);document.addEventListener("DOMContentLoaded",function(){ro.observe(document.documentElement);rh()})}' +
+ 'document.addEventListener("DOMContentLoaded",rh);window.addEventListener("load",rh);' +
+ "})();" +
+ "<" +
+ "/script>";
+
+function injectBridge(html: string): string {
+ if (html.includes("</body>")) {
+ return html.replace("</body>", BRIDGE_SCRIPT + "\n</body>");
+ }
+ if (html.includes("</html>")) {
+ return html.replace("</html>", BRIDGE_SCRIPT + "\n</html>");
+ }
+ return html + "\n" + BRIDGE_SCRIPT;
+}
+
+/**
+ * Convenience: inject KaTeX, sanitize, then add the host bridge. Suitable for a
+ * one-shot iframe `srcdoc` write.
*/
export function prepareIframeHtml(html: string): string {
- return sanitizeIframeHtml(injectKaTeX(html));
+ return injectBridge(sanitizeIframeHtml(injectKaTeX(html)));
}