diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx new file mode 100644 index 0000000000..dd3ca02f4d --- /dev/null +++ b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx @@ -0,0 +1,130 @@ +import React from 'react'; +import * as Tabs from '@radix-ui/react-tabs'; +import { render } from '@testing-library/react'; +import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled'; +import type { Artifact } from '~/common'; +import SandboxArtifactTabs from './SandboxArtifactTabs'; + +interface PreviewProps { + files: Record; + fileKey: string; + currentCode?: string; +} + +const mockPreview = jest.fn((_props: PreviewProps) => null); +let mockCurrentCode: string | undefined; + +jest.mock('./ArtifactCodeEditor', () => ({ + ArtifactCodeEditor: () => null, +})); + +jest.mock('./ArtifactPreview', () => ({ + ArtifactPreview: (props: PreviewProps) => mockPreview(props), +})); + +jest.mock('~/Providers/EditorContext', () => ({ + useCodeState: () => ({ currentCode: mockCurrentCode, setCurrentCode: jest.fn() }), +})); + +jest.mock('~/Providers', () => ({ + useShareContext: () => ({ shareId: undefined }), +})); + +jest.mock('~/data-provider', () => ({ + useGetStartupConfig: () => ({ data: {} }), + useGetSharedStartupConfig: () => ({ data: {} }), +})); + +const previewRef = { + current: Object.create(null) as SandpackPreviewRef, +} as React.MutableRefObject; + +const original = + ''; +const edited = + ''; + +const svgArtifact: Artifact = { + id: 'svg-artifact-1', + type: 'image/svg+xml', + title: 'Chart', + content: original, + lastUpdateTime: 1, +}; + +function renderTabs(artifact: Artifact = svgArtifact) { + return render( + + + , + ); +} + +function lastFiles(): Record { + return mockPreview.mock.calls.at(-1)?.[0].files ?? {}; +} + +describe('SandboxArtifactTabs SVG preview', () => { + beforeEach(() => { + mockCurrentCode = undefined; + mockPreview.mockClear(); + }); + + /** An SVG preview renders a derived `index.html`, so an edit that only + * replaced `index.svg` left the preview showing the original drawing. */ + it('rebuilds the preview shell from the edited source', () => { + const { rerender } = renderTabs(); + expect(lastFiles()['index.html']).toContain(original); + + /* Editor text belongs to the preview only once it was typed against the + * artifact on screen, so it lands on a later render, not on mount. */ + mockCurrentCode = edited; + rerender( + + + , + ); + + const files = lastFiles(); + expect(files['index.svg']).toBe(edited); + expect(files['index.html']).toContain(edited); + expect(files['index.html']).not.toContain(' { + const { rerender } = renderTabs(); + + mockCurrentCode = ''; + rerender( + + + , + ); + + expect(lastFiles()['index.html']).toContain(original); + }); + + it('leaves artifacts whose preview entry is the edited file untouched', () => { + const htmlArtifact: Artifact = { + id: 'html-artifact-1', + type: 'text/html', + title: 'Page', + content: '

original

', + lastUpdateTime: 1, + }; + + const { rerender } = renderTabs(htmlArtifact); + + mockCurrentCode = '

edited

'; + rerender( + + + , + ); + + /* `ArtifactPreview` owns this swap; the tabs must not pre-empt it. */ + const call = mockPreview.mock.calls.at(-1)?.[0]; + expect(call?.files['index.html']).toBe('

original

'); + expect(call?.currentCode).toBe('

edited

'); + }); +}); diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.tsx index 2fcede516a..acde5944e2 100644 --- a/client/src/components/Artifacts/SandboxArtifactTabs.tsx +++ b/client/src/components/Artifacts/SandboxArtifactTabs.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef } from 'react'; +import { useEffect, useMemo, useRef } from 'react'; import * as Tabs from '@radix-ui/react-tabs'; import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled'; import type { editor } from 'monaco-editor'; @@ -42,7 +42,16 @@ export default function SandboxArtifactTabs({ lastIdRef.current = artifact.id; }, [artifact.id, setCurrentCode]); - const { files, fileKey, template, sharedProps } = useArtifactProps({ artifact }); + const { files, fileKey, template, sharedProps, deriveFiles } = useArtifactProps({ artifact }); + const editedCode = hasCurrentArtifactCode ? currentCode : undefined; + + /* An artifact whose preview entry is derived from its source needs the whole + * set rebuilt from the editor text; `ArtifactPreview` can only swap the file + * the editor owns. Empty text counts as no edit there, so it does here too. */ + const previewFiles = useMemo( + () => (deriveFiles != null && editedCode ? deriveFiles(editedCode) : files), + [deriveFiles, editedCode, files], + ); return (
@@ -65,12 +74,12 @@ export default function SandboxArtifactTabs({ tabIndex={-1} > diff --git a/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts b/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts index 1f71e4c2c0..76044d7a57 100644 --- a/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts +++ b/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts @@ -1,7 +1,7 @@ import { renderHook } from '@testing-library/react'; -import useArtifactProps from '../useArtifactProps'; -import { TOOL_ARTIFACT_TYPES, wrapAsFencedCodeBlock } from '~/utils/artifacts'; import type { Artifact } from '~/common'; +import { TOOL_ARTIFACT_TYPES, wrapAsFencedCodeBlock } from '~/utils/artifacts'; +import useArtifactProps from '../useArtifactProps'; describe('useArtifactProps', () => { const createArtifact = (partial: Partial): Artifact => ({ @@ -184,6 +184,51 @@ describe('useArtifactProps', () => { }); }); + describe('svg artifacts', () => { + const svg = + ''; + + it('uses index.svg as the editor fileKey on the static template', () => { + const artifact = createArtifact({ type: 'image/svg+xml', content: svg }); + const { result } = renderHook(() => useArtifactProps({ artifact })); + expect(result.current.fileKey).toBe('index.svg'); + expect(result.current.template).toBe('static'); + }); + + it('keeps the source on index.svg and wraps it in index.html for preview', () => { + const artifact = createArtifact({ type: 'image/svg+xml', content: svg }); + const { result } = renderHook(() => useArtifactProps({ artifact })); + expect(result.current.files['index.svg']).toBe(svg); + expect(result.current.files['index.html']).toMatch(//i); + expect(result.current.files['index.html']).toContain(svg); + }); + + it('accepts the image/svg alias', () => { + const artifact = createArtifact({ type: 'image/svg', content: '' }); + const { result } = renderHook(() => useArtifactProps({ artifact })); + expect(result.current.fileKey).toBe('index.svg'); + expect(result.current.files['index.html']).toContain(''); + }); + + it('exposes deriveFiles so edited source can rebuild the derived preview entry', () => { + const artifact = createArtifact({ type: 'image/svg+xml', content: svg }); + const { result } = renderHook(() => useArtifactProps({ artifact })); + + const edited = ''; + const rebuilt = result.current.deriveFiles?.(edited) ?? {}; + + expect(rebuilt['index.svg']).toBe(edited); + expect(rebuilt['index.html']).toContain(edited); + expect(rebuilt['index.html']).not.toContain(' { + const artifact = createArtifact({ type: 'text/html', content: '

hi

' }); + const { result } = renderHook(() => useArtifactProps({ artifact })); + expect(result.current.deriveFiles).toBeUndefined(); + }); + }); + describe('edge cases', () => { it('should handle artifact with language parameter', () => { const artifact = createArtifact({ diff --git a/client/src/hooks/Artifacts/useArtifactProps.ts b/client/src/hooks/Artifacts/useArtifactProps.ts index 017bdb195d..26271390a0 100644 --- a/client/src/hooks/Artifacts/useArtifactProps.ts +++ b/client/src/hooks/Artifacts/useArtifactProps.ts @@ -7,6 +7,8 @@ import { getProps, getTemplate, getArtifactFilename, + getSvgFiles, + isSvgArtifactType, languageForFilename, wrapAsFencedCodeBlock, TOOL_ARTIFACT_TYPES, @@ -67,6 +69,10 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) { ]; } + if (isSvgArtifactType(type)) { + return [getArtifactFilename(type), getSvgFiles(artifact.content ?? '')]; + } + const fileKey = getArtifactFilename(artifact.type ?? '', artifact.language); const files = removeNullishValues({ [fileKey]: artifact.content, @@ -88,10 +94,20 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) { const sharedProps = useMemo(() => getProps(artifact.type ?? ''), [artifact.type]); + /* SVG previews render a *derived* `index.html`, not the edited file itself, + * so swapping `fileKey` alone would leave the preview on the original + * source while the code tab shows the new one. Consumers that hold editor + * text rebuild the whole set through this instead. */ + const deriveFiles = useMemo( + () => (isSvgArtifactType(artifact.type ?? '') ? getSvgFiles : undefined), + [artifact.type], + ); + return { files, fileKey, template, sharedProps, + deriveFiles, }; } diff --git a/client/src/utils/__tests__/artifacts.test.ts b/client/src/utils/__tests__/artifacts.test.ts index 874d361bb0..11d2fedb6d 100644 --- a/client/src/utils/__tests__/artifacts.test.ts +++ b/client/src/utils/__tests__/artifacts.test.ts @@ -4,16 +4,100 @@ import { artifactRowKind, buildSandpackOptions, getArtifactDownloadFilename, + getArtifactFilename, + getDependencies, + getSvgFiles, + getTemplate, detectArtifactTypeFromFile, fileToArtifact, isCodeOnlyArtifact, isPreviewOnlyArtifact, + isSvgArtifactType, languageForFilename, TOOL_ARTIFACT_TYPES, } from '../artifacts'; const TAILWIND_CDN = 'https://cdn.tailwindcss.com/3.4.17#tailwind.js'; +describe('SVG artifact template mapping (#16087)', () => { + /* Bare `` handed to the static template as `index.html` renders + * blank. These types must map to a dedicated SVG file (and empty + * Sandpack deps) instead of riding `artifactFilename.default`. */ + it.each(['image/svg+xml', 'image/svg'])( + 'maps %s to index.svg on the static template, not default index.html', + (type) => { + expect(getArtifactFilename(type)).toBe('index.svg'); + expect(getTemplate(type)).toBe('static'); + expect(getDependencies(type)).toEqual({}); + }, + ); + + it('wraps a bare SVG in an HTML document for the static preview entry', () => { + const svg = + ''; + const files = getSvgFiles(svg); + expect(files['index.svg']).toBe(svg); + expect(files['index.html']).toMatch(//i); + expect(files['index.html']).toContain(' { + const svg = ''; + const files = getSvgFiles(`\n${svg}`); + expect(files['index.html']).not.toMatch(/<\?xml/i); + expect(files['index.html']).toContain(svg); + }); + + it('sizes only the root SVG so a nested viewport keeps its own geometry', () => { + const originalHead = document.head.innerHTML; + const originalBody = document.body.innerHTML; + try { + const html = getSvgFiles( + '' + + '' + + '', + )['index.html']; + /* Mount the shell's own generated style and body. CSS overrides SVG + * presentation attributes, so an unscoped `svg` rule would stretch the + * nested viewport to the panel and corrupt the drawing's layout. */ + const css = html.match(/([\s\S]*?)<\/body>/i)?.[1] ?? ''; + document.head.innerHTML = ``; + document.body.innerHTML = markup; + + const root = document.body.querySelector('svg'); + const nested = document.getElementById('sprite'); + if (root == null || nested == null) { + throw new Error('expected the mounted shell to hold both SVG viewports'); + } + expect(getComputedStyle(root).width).toBe('100%'); + expect(getComputedStyle(root).height).toBe('100%'); + expect(getComputedStyle(nested).width).not.toBe('100%'); + expect(getComputedStyle(nested).height).not.toBe('100%'); + } finally { + document.head.innerHTML = originalHead; + document.body.innerHTML = originalBody; + } + }); + + it('recognizes both SVG artifact types and nothing else', () => { + expect(isSvgArtifactType('image/svg+xml')).toBe(true); + expect(isSvgArtifactType('image/svg')).toBe(true); + expect(isSvgArtifactType('image/png')).toBe(false); + expect(isSvgArtifactType('text/html')).toBe(false); + expect(isSvgArtifactType('')).toBe(false); + }); + + it('rebuilds both entries so no original source survives an edit', () => { + const edited = ''; + const files = getSvgFiles(edited); + expect(files['index.svg']).toBe(edited); + expect(files['index.html']).toContain(edited); + expect(files['index.html']).not.toContain(' { it('includes externalResources with .js fragment hint for static template', () => { const options = buildSandpackOptions('static'); diff --git a/client/src/utils/artifacts.ts b/client/src/utils/artifacts.ts index cae3937eef..e192e93061 100644 --- a/client/src/utils/artifacts.ts +++ b/client/src/utils/artifacts.ts @@ -31,6 +31,11 @@ const artifactFilename = { 'application/vnd.librechat.docx-preview': 'index.html', 'application/vnd.librechat.spreadsheet-preview': 'index.html', 'application/vnd.librechat.presentation-preview': 'index.html', + /* SVG artifacts are a bare `` document. The Sandpack `static` + * template always loads `index.html`, so `getSvgFiles` ships a + * companion HTML shell; the editor/download file stays `index.svg`. */ + 'image/svg+xml': 'index.svg', + 'image/svg': 'index.svg', // mermaid and markdown types are handled separately in useArtifactProps.ts default: 'index.html', // 'css': 'css', @@ -68,6 +73,8 @@ const artifactTemplate: Record< 'application/vnd.librechat.docx-preview': 'static', 'application/vnd.librechat.spreadsheet-preview': 'static', 'application/vnd.librechat.presentation-preview': 'static', + 'image/svg+xml': 'static', + 'image/svg': 'static', default: 'static', // 'css': 'css', // 'javascript': 'js', @@ -189,6 +196,47 @@ export function getTemplate(type: string, language?: string): SandpackPredefined return artifactTemplate[key] ?? (artifactTemplate.default as SandpackPredefinedTemplate); } +/** `image/svg` is the alias some callers emit for `image/svg+xml`. */ +export function isSvgArtifactType(type: string): boolean { + return type === 'image/svg+xml' || type === 'image/svg'; +} + +/** + * Files for an `image/svg+xml` (or `image/svg`) artifact. The Sandpack + * `static` template always loads `index.html`; a bare SVG in that slot + * renders blank. Keep the source on `index.svg` for the code tab and wrap + * a copy in a full-viewport HTML shell for the preview. viewBox-only + * sources fill the panel via `body > svg { width/height: 100% }`, scoped to + * the root because CSS beats presentation attributes: an unscoped `svg` rule + * would stretch a nested `` viewport, such as a sprite or inset diagram, + * over its own `width`/`height` and corrupt the artifact's internal layout. + * + * The shell holds a *copy* of the source, so an edit cannot be applied by + * replacing `index.svg` alone — both entries have to be rebuilt from the + * new text. `useArtifactProps` exposes this builder as `deriveFiles` for + * exactly that. + */ +export function getSvgFiles(content: string): Record { + const svg = content.replace(/^\uFEFF?\s*<\?xml\b[^?]*\?>\s*/i, ''); + return { + 'index.svg': content, + 'index.html': ` + + + + + + + +${svg} + +`, + }; +} + const standardDependencies = { three: '^0.167.1', 'lucide-react': '^0.394.0', @@ -265,6 +313,9 @@ const dependenciesMap: Record< 'application/vnd.librechat.docx-preview': {}, 'application/vnd.librechat.spreadsheet-preview': {}, 'application/vnd.librechat.presentation-preview': {}, + /* SVG preview is a static HTML shell + the source file; no npm deps. */ + 'image/svg+xml': {}, + 'image/svg': {}, default: standardDependencies, };