Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(markdown): static SVG artifact preview
Akarshan Biswas378dc2afa92f
diff --git a/web-app/src/components/HtmlArtifact.tsx b/web-app/src/components/HtmlArtifact.tsxindex 30906f1f0..39fc6a23b 100644--- a/web-app/src/components/HtmlArtifact.tsx+++ b/web-app/src/components/HtmlArtifact.tsx@@ -18,6 +18,12 @@ interface HtmlArtifactProps {* network access so it cannot phone home or pull remote payloads.*/allowNetwork?: boolean+ /**+ * Static mode for SVG: no scripts at all (CSP script-src 'none' and the+ * iframe drops allow-scripts). Code view highlights as the given language.+ */+ allowScripts?: boolean+ language?: string}type View = 'code' | 'preview'@@ -27,7 +33,16 @@ type View = 'code' | 'preview'* an opaque origin (sandbox without allow-same-origin), so this only governs* what the document itself may reach out to.*/-function buildCsp(allowNetwork: boolean): string {+function buildCsp(allowNetwork: boolean, allowScripts: boolean): string {+ if (!allowScripts) {+ return [+ "default-src 'none'",+ 'img-src data: blob:',+ "style-src 'unsafe-inline'",+ 'font-src data:',+ "connect-src 'none'",+ ].join('; ')+ }if (allowNetwork) {return ["default-src 'none'",@@ -48,8 +63,12 @@ function buildCsp(allowNetwork: boolean): string {].join('; ')}-function buildSrcDoc(code: string, allowNetwork: boolean): string {- const csp = buildCsp(allowNetwork)+function buildSrcDoc(+ code: string,+ allowNetwork: boolean,+ allowScripts: boolean+): string {+ const csp = buildCsp(allowNetwork, allowScripts)const meta = `<meta http-equiv="Content-Security-Policy" content="${csp}">`if (/<head[\s>]/i.test(code)) {return code.replace(/<head([^>]*)>/i, `<head$1>${meta}`)@@ -65,13 +84,16 @@ function HtmlArtifactComponent({className,isStreaming,allowNetwork = false,+ allowScripts = true,+ language = 'html',}: HtmlArtifactProps) {const { t } = useTranslation()const [view, setView] = useState<View>('preview')const srcDoc = useMemo(- () => (view === 'preview' ? buildSrcDoc(code, allowNetwork) : ''),- [view, code, allowNetwork]+ () =>+ view === 'preview' ? buildSrcDoc(code, allowNetwork, allowScripts) : '',+ [view, code, allowNetwork, allowScripts])const previewDisabled = isStreaming ?? false@@ -131,12 +153,12 @@ function HtmlArtifactComponent({title={t('htmlArtifact.preview')}data-testid="html-artifact-iframe"className="h-[600px] max-h-[80vh] min-h-64 w-full resize-y overflow-auto border-0 bg-white"- sandbox="allow-scripts"+ sandbox={allowScripts ? 'allow-scripts' : ''}referrerPolicy="no-referrer"srcDoc={srcDoc}/>) : (- <CodeBlock code={code} language="html" />+ <CodeBlock code={code} language={language} />)}</div>)diff --git a/web-app/src/components/__tests__/HtmlArtifact.test.tsx b/web-app/src/components/__tests__/HtmlArtifact.test.tsxindex df93b8310..221a3d50b 100644--- a/web-app/src/components/__tests__/HtmlArtifact.test.tsx+++ b/web-app/src/components/__tests__/HtmlArtifact.test.tsx@@ -55,6 +55,25 @@ describe('HtmlArtifact', () => {expect(doc).toContain(HTML)})+ it('drops allow-scripts and forbids scripts in static (svg) mode', async () => {+ const user = userEvent.setup()+ render(<HtmlArtifact code="<svg/>" allowScripts={false} language="xml" />)+ const iframe = screen.getByTestId(+ 'html-artifact-iframe'+ ) as HTMLIFrameElement+ expect(iframe.getAttribute('sandbox')).toBe('')++ await user.click(screen.getByRole('tab', { name: /preview/i }))+ const doc = iframe.getAttribute('srcdoc') ?? ''+ expect(doc).not.toContain('script-src')+ expect(doc).toContain("default-src 'none'")++ await user.click(screen.getByRole('tab', { name: /code/i }))+ expect(screen.getByTestId('code-block').getAttribute('data-language')).toBe(+ 'xml'+ )+ })+it('relaxes CSP for network when allowNetwork is set', async () => {const user = userEvent.setup()render(<HtmlArtifact code={HTML} allowNetwork />)diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsxindex ff1aa02ed..3ad23fa22 100644--- a/web-app/src/containers/RenderMarkdown.tsx+++ b/web-app/src/containers/RenderMarkdown.tsx@@ -186,7 +186,9 @@ function RenderMarkdownComponent({const segments = useMemo(() => {if (isStreaming || !renderHtmlArtifacts) return nullconst segs = splitHtmlArtifacts(normalizedContent)- return segs.some((s) => s.type === 'html') ? segs : null+ return segs.some((s) => s.type === 'html' || s.type === 'svg')+ ? segs+ : null}, [normalizedContent, isStreaming, renderHtmlArtifacts])return (@@ -202,6 +204,13 @@ function RenderMarkdownComponent({? segments.map((seg, i) =>seg.type === 'html' ? (<HtmlArtifact key={i} code={seg.content} />+ ) : seg.type === 'svg' ? (+ <HtmlArtifact+ key={i}+ code={seg.content}+ allowScripts={false}+ language="xml"+ />) : (<StreamdownViewkey={i}diff --git a/web-app/src/lib/__tests__/utils.test.ts b/web-app/src/lib/__tests__/utils.test.tsindex 2b4523e4c..72661de2a 100644--- a/web-app/src/lib/__tests__/utils.test.ts+++ b/web-app/src/lib/__tests__/utils.test.ts@@ -382,4 +382,30 @@ describe('splitHtmlArtifacts', () => {const segs = splitHtmlArtifacts('````html\n<p>z</p>\n````')expect(segs).toEqual([{ type: 'html', content: '<p>z</p>' }])})++ it('extracts a ```svg fenced block as an svg segment', () => {+ const segs = splitHtmlArtifacts('```svg\n<svg><rect/></svg>\n```')+ expect(segs).toEqual([{ type: 'svg', content: '<svg><rect/></svg>' }])+ })++ it('extracts a raw <svg> block from prose', () => {+ const content = 'before\n<svg width="10"><circle/></svg>\nafter'+ const segs = splitHtmlArtifacts(content)+ expect(segs.map((s) => s.type)).toEqual(['markdown', 'svg', 'markdown'])+ expect(segs[1].content).toBe('<svg width="10"><circle/></svg>')+ expect(segs[0].content).toContain('before')+ expect(segs[2].content).toContain('after')+ })++ it('keeps adjacent raw <svg> blocks separate (non-greedy)', () => {+ const segs = splitHtmlArtifacts('<svg>a</svg>\n<svg>b</svg>')+ const svgs = segs.filter((s) => s.type === 'svg')+ expect(svgs.map((s) => s.content)).toEqual(['<svg>a</svg>', '<svg>b</svg>'])+ })++ it('extracts html and svg artifacts side by side', () => {+ const content = '```html\n<p>x</p>\n```\nmid\n```svg\n<svg/>\n```'+ const segs = splitHtmlArtifacts(content)+ expect(segs.map((s) => s.type)).toEqual(['html', 'markdown', 'svg'])+ })})diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.tsindex 79224bc62..5eb657ab5 100644--- a/web-app/src/lib/utils.ts+++ b/web-app/src/lib/utils.ts@@ -58,31 +58,43 @@ export function disableIndentedCodeBlockPlugin() {}export interface MarkdownSegment {- type: 'markdown' | 'html'+ type: 'markdown' | 'html' | 'svg'content: string}-// Top-level fenced ```html block: opening fence (3+ backticks) + html lang,-// body, matching closing fence on its own line. The \b stops langs like-// "html5"/"htmlbar" from matching.-const HTML_FENCE_RE = /(^|\n)(`{3,})[ \t]*html\b[^\n]*\n([\s\S]*?)\n\2[ \t]*(?=\n|$)/gi+// Standalone artifact, any of:+// 1. ```html fenced block → groups 1 (lead \n) 2 (ticks) 3 (lang) 4 (body)+// 2. ```svg fenced block → same groups, lang === 'svg'+// 3. raw <svg>…</svg> in prose → group 5+// \b stops langs like "html5"/"htmlbar" from matching. Raw SVG is matched+// non-greedily so adjacent diagrams stay separate.+const ARTIFACT_RE =+ /(^|\n)(`{3,})[ \t]*(html|svg)\b[^\n]*\n([\s\S]*?)\n\2[ \t]*(?=\n|$)|(<svg\b[\s\S]*?<\/svg>)/gi/**- * Split markdown into alternating prose and standalone HTML-artifact segments.- * Used to render interactive HTML previews without replacing Streamdown's code- * component (which would lose inline-code, mermaid, and Shiki handling).+ * Split markdown into alternating prose and standalone artifact segments+ * (interactive HTML previews and static SVG). Splitting the string keeps+ * Streamdown's code/mermaid/inline handling intact for everything else —+ * overriding its `code` component would replace all of it.*/export function splitHtmlArtifacts(content: string): MarkdownSegment[] {const segments: MarkdownSegment[] = []let lastIndex = 0let match: RegExpExecArray | null- HTML_FENCE_RE.lastIndex = 0- while ((match = HTML_FENCE_RE.exec(content)) !== null) {- const blockStart = match.index + match[1].length+ ARTIFACT_RE.lastIndex = 0+ while ((match = ARTIFACT_RE.exec(content)) !== null) {+ const isFence = match[2] !== undefined+ // Fence keeps the leading newline as prose; raw SVG starts at match.index.+ const blockStart = isFence ? match.index + match[1].length : match.indexconst before = content.slice(lastIndex, blockStart)if (before.length) segments.push({ type: 'markdown', content: before })- segments.push({ type: 'html', content: match[3] })- lastIndex = HTML_FENCE_RE.lastIndex+ if (isFence) {+ const type = match[3].toLowerCase() === 'svg' ? 'svg' : 'html'+ segments.push({ type, content: match[4] })+ } else {+ segments.push({ type: 'svg', content: match[5] })+ }+ lastIndex = ARTIFACT_RE.lastIndex}const rest = content.slice(lastIndex)if (rest.length) segments.push({ type: 'markdown', content: rest })