Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Allow pasting and dropping SVGs (#9326)

Jonny Burger5fa42ab5d4dd
diff --git a/bun.lock b/bun.lock
index cabd828a31..15685a97cc 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1680,6 +1680,8 @@
"@remotion/bundler": "workspace:*",
"@remotion/renderer": "workspace:*",
"@remotion/studio-shared": "workspace:*",
+ "@svgr/core": "8.1.0",
+ "@svgr/plugin-jsx": "8.1.0",
"memfs": "3.4.3",
"open": "8.4.2",
"prettier": "catalog:",
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index c0950102ef..5f17094957 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -25,6 +25,8 @@
"dependencies": {
"@babel/types": "7.24.0",
"@babel/parser": "7.24.1",
+ "@svgr/core": "8.1.0",
+ "@svgr/plugin-jsx": "8.1.0",
"semver": "7.5.3",
"prettier": "catalog:",
"remotion": "workspace:*",
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index daa8d064b4..805ea9d3f9 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -33,6 +33,7 @@ import {
getImportedName,
insertImportDeclaration,
} from './imports';
+import {svgMarkupToJsx} from './svg-to-jsx';
type SourceLocation = {
line: number;
@@ -1026,6 +1027,54 @@ const createAssetElement = ({
);
};
+const createSvgElement = async ({
+ interactiveLocalName,
+ markup,
+ position,
+}: {
+ interactiveLocalName: string;
+ markup: string;
+ position: InsertableCompositionElementPosition | null;
+}): Promise<namedTypes.JSXElement> => {
+ const svgElement = await svgMarkupToJsx(markup);
+ const attributes = svgElement.openingElement.attributes ?? [];
+ svgElement.openingElement.attributes = attributes;
+ const styleAttribute = attributes.find(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'style',
+ );
+ const positionProperties = getPositionStyleProperties(position);
+
+ if (styleAttribute === undefined) {
+ attributes.push(createStyleAttribute(positionProperties));
+ } else if (
+ styleAttribute.type === 'JSXAttribute' &&
+ styleAttribute.value?.type === 'JSXExpressionContainer' &&
+ styleAttribute.value.expression.type === 'ObjectExpression'
+ ) {
+ styleAttribute.value.expression.properties.push(...positionProperties);
+ } else {
+ throw new Error('Could not convert the root SVG style to JSX');
+ }
+
+ const interactiveSvgName = () =>
+ recast.types.builders.jsxMemberExpression(
+ recast.types.builders.jsxIdentifier(interactiveLocalName),
+ recast.types.builders.jsxIdentifier('Svg'),
+ );
+ svgElement.openingElement.name = interactiveSvgName();
+ if (
+ svgElement.closingElement !== null &&
+ svgElement.closingElement !== undefined
+ ) {
+ svgElement.closingElement.name = interactiveSvgName();
+ }
+
+ return svgElement;
+};
+
const createFragmentWithElement = (element: namedTypes.JSXElement) => {
return recast.types.builders.jsxFragment(
recast.types.builders.jsxOpeningFragment(),
@@ -1203,6 +1252,44 @@ const ensureSequenceImport = (ast: File) => {
});
};
+const ensureInteractiveImport = (ast: File) => {
+ for (const statement of ast.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.type !== 'StringLiteral' ||
+ statement.source.value !== 'remotion'
+ ) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ getImportedName(specifier) === 'Interactive'
+ ) {
+ return specifier.local?.name ?? 'Interactive';
+ }
+ }
+ }
+
+ const candidates = ['Interactive', 'RemotionInteractive'];
+ const localName = candidates.find((candidate) => {
+ return !hasTopLevelBinding({ast, name: candidate});
+ });
+ if (localName === undefined) {
+ throw new Error(
+ 'Cannot add <Interactive.Svg> because Interactive is already defined',
+ );
+ }
+
+ return ensureNamedImport({
+ ast,
+ importedName: 'Interactive',
+ sourcePath: 'remotion',
+ localName,
+ });
+};
+
const getImportDeclarations = ({
ast,
sourcePath,
@@ -2077,6 +2164,14 @@ const createInsertableJsxElement = ({
});
}
+ if (element.type === 'svg') {
+ return createSvgElement({
+ interactiveLocalName: ensureInteractiveImport(ast),
+ markup: element.markup,
+ position: element.position,
+ });
+ }
+
if (element.type === 'composition') {
return Promise.resolve(
ensureCompositionComponentImport({
diff --git a/packages/studio-server/src/helpers/svg-to-jsx.ts b/packages/studio-server/src/helpers/svg-to-jsx.ts
new file mode 100644
index 0000000000..03c5fc2eaf
--- /dev/null
+++ b/packages/studio-server/src/helpers/svg-to-jsx.ts
@@ -0,0 +1,42 @@
+import {transform} from '@svgr/core';
+import jsxPlugin from '@svgr/plugin-jsx';
+import type {namedTypes} from 'ast-types';
+import * as recast from 'recast';
+import {parseAst} from '../codemods/parse-ast';
+
+export const svgMarkupToJsx = async (
+ markup: string,
+): Promise<namedTypes.JSXElement> => {
+ const componentCode = await transform(
+ markup,
+ {
+ expandProps: false,
+ jsxRuntime: 'automatic',
+ plugins: [jsxPlugin],
+ prettier: false,
+ typescript: true,
+ },
+ {componentName: 'PastedSvg'},
+ );
+ const ast = parseAst(componentCode);
+ let svgElement: namedTypes.JSXElement | null = null;
+
+ recast.types.visit(ast, {
+ visitJSXElement(path) {
+ const {name} = path.node.openingElement;
+ if (name.type === 'JSXIdentifier' && name.name === 'svg') {
+ svgElement = path.node;
+ return false;
+ }
+
+ this.traverse(path);
+ return undefined;
+ },
+ });
+
+ if (svgElement === null) {
+ throw new Error('The pasted markup does not contain an <svg> root element');
+ }
+
+ return svgElement;
+};
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index 894109ea50..3fddda2264 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -90,6 +90,14 @@ const validateElement = (
return;
}
+ if (element.type === 'svg') {
+ if (typeof element.markup !== 'string' || element.markup.trim() === '') {
+ throw new Error('SVG markup must be a non-empty string');
+ }
+
+ return;
+ }
+
if (element.type === 'asset') {
if (element.srcType === 'remote') {
if (!isUrl(element.src)) {
@@ -167,6 +175,10 @@ const getElementLabel = (element: InsertableCompositionElement) => {
return '<Solid>';
}
+ if (element.type === 'svg') {
+ return '<Interactive.Svg>';
+ }
+
if (element.type === 'asset') {
if (element.assetType === 'image') {
return '<Img>';
diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.ts
index aa4e1e7b89..10db267666 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -819,6 +819,63 @@ test('inserts a Solid into an empty component returning null', async () => {
}
});
+test('converts and inserts SVG markup as an Interactive.Svg', async () => {
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
+ try {
+ await fs.writeFile(
+ path.join(tempDir, 'Root.tsx'),
+ [
+ "import {Composition} from 'remotion';",
+ "import {MyComp} from './MyComp';",
+ 'export const RemotionRoot = () => {',
+ '\treturn <Composition id="test" component={MyComp} />;',
+ '};',
+ '',
+ ].join('\n'),
+ );
+ await fs.writeFile(
+ path.join(tempDir, 'MyComp.tsx'),
+ [
+ "import {AbsoluteFill} from 'remotion';",
+ '',
+ 'export const MyComp: React.FC = () => {',
+ '\treturn <AbsoluteFill>hello</AbsoluteFill>;',
+ '};',
+ '',
+ ].join('\n'),
+ );
+
+ const result = await insertJsxElementIntoComposition({
+ remotionRoot: tempDir,
+ compositionFile: 'Root.tsx',
+ compositionId: 'test',
+ element: {
+ type: 'svg',
+ markup:
+ '<svg width="100" height="50" viewBox="0 0 100 50" style="opacity: 0.8"><path fill-rule="evenodd" stroke-width="2" d="M0 0h10v10z" /></svg>',
+ position: {x: 120.25, y: 80},
+ },
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+
+ expect(result.output).toContain(
+ "import { AbsoluteFill, Interactive } from 'remotion';",
+ );
+ expect(result.output).toContain('<Interactive.Svg');
+ expect(result.output).toContain('</Interactive.Svg>');
+ expect(result.output).toContain('width={100}');
+ expect(result.output).toContain('height={50}');
+ expect(result.output).toContain('viewBox="0 0 100 50"');
+ expect(result.output).toContain('fillRule="evenodd"');
+ expect(result.output).toContain('strokeWidth={2}');
+ expect(result.output).toContain('opacity: 0.8');
+ expect(result.output).toContain("position: 'absolute'");
+ expect(result.output).toContain("translate: '120.3px 80px'");
+ } finally {
+ await fs.rm(tempDir, {recursive: true, force: true});
+ }
+});
+
test('inserts an Img asset into the resolved composition component', async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));
try {
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 3092534e81..24aa60288e 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -717,6 +717,11 @@ export type InsertableCompositionElement =
} | null;
position: InsertableCompositionElementPosition | null;
}
+ | {
+ type: 'svg';
+ markup: string;
+ position: InsertableCompositionElementPosition | null;
+ }
| {
type: 'composition';
compositionId: string;
diff --git a/packages/studio-shared/src/required-package.ts b/packages/studio-shared/src/required-package.ts
index d3862d91c0..05625fbe86 100644
--- a/packages/studio-shared/src/required-package.ts
+++ b/packages/studio-shared/src/required-package.ts
@@ -26,7 +26,7 @@ export const getRequiredPackageForImportPath = (
export const getRequiredPackageForInsertableElement = (
element: InsertableCompositionElement,
): string | null => {
- if (element.type === 'solid') {
+ if (element.type === 'solid' || element.type === 'svg') {
return null;
}
diff --git a/packages/studio-shared/src/test/required-package.test.ts b/packages/studio-shared/src/test/required-package.test.ts
index a0002a9dfc..4fe915b46a 100644
--- a/packages/studio-shared/src/test/required-package.test.ts
+++ b/packages/studio-shared/src/test/required-package.test.ts
@@ -14,6 +14,13 @@ test('gets required package for insertable elements', () => {
position: null,
}),
).toBe(null);
+ expect(
+ getRequiredPackageForInsertableElement({
+ type: 'svg',
+ markup: '<svg />',
+ position: null,
+ }),
+ ).toBe(null);
expect(
getRequiredPackageForInsertableElement({
type: 'asset',
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index aa3aee5642..4fbd994cf4 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -26,6 +26,7 @@ import {Internals, watchStaticFile, type PreviewSize} from 'remotion';
import {getStaticFiles} from '../api/get-static-files';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {getClipboardImageFiles} from '../helpers/clipboard-images';
+import {getClipboardSvgMarkup} from '../helpers/clipboard-svg';
import {BACKGROUND} from '../helpers/colors';
import type {AssetMetadata} from '../helpers/get-asset-metadata';
import {getAssetMetadata} from '../helpers/get-asset-metadata';
@@ -61,6 +62,7 @@ import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
import {getEffectDragData} from './effect-drag-and-drop';
import {getElementDragData} from './element-drag-and-drop';
import {
+ hasSvgFile,
importAssets,
importRemoteAsset,
insertComponent,
@@ -68,12 +70,14 @@ import {
insertElement,
insertExistingAssets,
insertRemoteAudio,
+ insertSvgMarkup,
type InsertElementDropPosition,
} from './import-assets';
import {SPACING_UNIT} from './layout';
import {showNotification} from './Notifications/NotificationCenter';
import {VideoPreview} from './Preview';
import {ResetZoomButton} from './ResetZoomButton';
+import {useSvgImportDialog} from './SvgImportDialog';
import {useResolvedStack} from './Timeline/use-resolved-stack';
const elementInstallCompositionIdStyle: React.CSSProperties = {
@@ -326,6 +330,7 @@ export const Canvas: React.FC<{
} | null>(null);
const keybindings = useKeybinding();
const confirm = useConfirmationDialog();
+ const chooseSvgImportMode = useSvgImportDialog();
const config = Internals.useUnsafeVideoConfig();
const areRulersVisible = useIsRulerVisible();
const {editorShowGuides} = useContext(EditorShowGuidesContext);
@@ -1099,6 +1104,13 @@ export const Canvas: React.FC<{
return;
}
+ const svgImportMode = hasSvgFile(files)
+ ? await chooseSvgImportMode()
+ : 'image';
+ if (svgImportMode === null) {
+ return;
+ }
+
await importAssets({
files,
compositionFile,
@@ -1106,6 +1118,7 @@ export const Canvas: React.FC<{
destinationDimensions:
contentDimensions === 'none' ? null : contentDimensions,
dropPosition,
+ svgImportMode,
});
} else if (isAssetDragEvent(event)) {
const assetPath = getAssetDragPath(event);
@@ -1190,6 +1203,7 @@ export const Canvas: React.FC<{
[
canDropAssets,
cannotAddSequence,
+ chooseSvgImportMode,
compositionFile,
contentDimensions,
currentCompositionId,
@@ -1214,6 +1228,33 @@ export const Canvas: React.FC<{
return;
}
+ const dropPosition =
+ contentDimensions === null || contentDimensions === 'none'
+ ? null
+ : {
+ centerX: contentDimensions.width / 2,
+ centerY: contentDimensions.height / 2,
+ };
+ const svgMarkup = getClipboardSvgMarkup(event.clipboardData);
+ if (svgMarkup !== null) {
+ event.preventDefault();
+ setIsAddingAsset(true);
+ try {
+ await insertSvgMarkup({
+ compositionFile,
+ compositionId: currentCompositionId,
+ destinationDimensions:
+ contentDimensions === 'none' ? null : contentDimensions,
+ dropPosition,
+ markup: svgMarkup,
+ });
+ } finally {
+ setIsAddingAsset(false);
+ }
+
+ return;
+ }
+
const files = getClipboardImageFiles({
clipboardData: event.clipboardData,
existingFileNames: getStaticFiles().map((file) => file.name),
@@ -1223,6 +1264,13 @@ export const Canvas: React.FC<{
}
event.preventDefault();
+ const svgImportMode = hasSvgFile(files)
+ ? await chooseSvgImportMode()
+ : 'image';
+ if (svgImportMode === null) {
+ return;
+ }
+
setIsAddingAsset(true);
try {
await importAssets({
@@ -1231,19 +1279,20 @@ export const Canvas: React.FC<{
compositionId: currentCompositionId,
destinationDimensions:
contentDimensions === 'none' ? null : contentDimensions,
- dropPosition:
- contentDimensions === null || contentDimensions === 'none'
- ? null
- : {
- centerX: contentDimensions.width / 2,
- centerY: contentDimensions.height / 2,
- },
+ dropPosition,
+ svgImportMode,
});
} finally {
setIsAddingAsset(false);
}
},
- [canDropAssets, compositionFile, contentDimensions, currentCompositionId],
+ [
+ canDropAssets,
+ chooseSvgImportMode,
+ compositionFile,
+ contentDimensions,
+ currentCompositionId,
+ ],
);
useEffect(() => {
diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsx
index b5ef922586..6129b35ffb 100644
--- a/packages/studio/src/components/Modals.tsx
+++ b/packages/studio/src/components/Modals.tsx
@@ -19,6 +19,7 @@ import QuickSwitcher from './QuickSwitcher/QuickSwitcher';
import {RenderStatusModal} from './RenderModal/RenderStatusModal';
import {RenderModalWithLoader} from './RenderModal/ServerRenderModal';
import {WebRenderModalWithLoader} from './RenderModal/WebRenderModal';
+import {SvgImportDialog} from './SvgImportDialog';
import {UpdateModal} from './UpdateModal/UpdateModal';
export const Modals: React.FC<{
@@ -181,6 +182,9 @@ export const Modals: React.FC<{
{modalContextType && modalContextType.type === 'confirmation-dialog' && (
<ConfirmationDialog state={modalContextType} />
)}
+ {modalContextType && modalContextType.type === 'svg-import-dialog' && (
+ <SvgImportDialog state={modalContextType} />
+ )}
{getStudioAskAIEnabled() && <AskAiModal />}
</>
);
diff --git a/packages/studio/src/components/SvgImportDialog.tsx b/packages/studio/src/components/SvgImportDialog.tsx
new file mode 100644
index 0000000000..d8ad1d67a1
--- /dev/null
+++ b/packages/studio/src/components/SvgImportDialog.tsx
@@ -0,0 +1,132 @@
+import React, {useCallback, useContext, useEffect, useRef} from 'react';
+import type {SvgImportDialogState} from '../state/modals';
+import {ModalsContext} from '../state/modals';
+import {Button} from './Button';
+import {Flex, Row, Spacing} from './layout';
+import {ModalButton} from './ModalButton';
+import {ModalContainer} from './ModalContainer';
+import {ModalFooterContainer} from './ModalFooter';
+import {ModalHeader} from './ModalHeader';
+
+export type SvgImportMode = 'image' | 'inline';
+
+const content: React.CSSProperties = {
+ padding: 16,
+ fontFamily: 'inherit',
+ fontSize: 14,
+ lineHeight: 1.4,
+ color: 'inherit',
+ minWidth: 560,
+};
+
+const inlineCode: React.CSSProperties = {
+ fontFamily: 'monospace',
+ fontSize: 'inherit',
+ lineHeight: 'inherit',
+ color: 'inherit',
+};
+
+export const useSvgImportDialog = () => {
+ const {setSelectedModal} = useContext(ModalsContext);
+
+ return useCallback(() => {
+ return new Promise<SvgImportMode | null>((resolve) => {
+ let settled = false;
+ const settle = (result: SvgImportMode | null) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ resolve(result);
+ };
+
+ setSelectedModal({
+ type: 'svg-import-dialog',
+ id: String(Math.random()),
+ onImage: () => settle('image'),
+ onInline: () => settle('inline'),
+ onDismiss: () => settle(null),
+ });
+ });
+ }, [setSelectedModal]);
+};
+
+export const SvgImportDialog: React.FC<{
+ readonly state: SvgImportDialogState;
+}> = ({state}) => {
+ const {setSelectedModal} = useContext(ModalsContext);
+ const settledRef = useRef(false);
+
+ const closeCurrentModal = useCallback(() => {
+ setSelectedModal((modal) =>
+ modal?.type === 'svg-import-dialog' && modal.id === state.id
+ ? null
+ : modal,
+ );
+ }, [setSelectedModal, state.id]);
+
+ const settle = useCallback(
+ (result: SvgImportMode | null) => {
+ if (settledRef.current) {
+ return;
+ }
+
+ settledRef.current = true;
+ closeCurrentModal();
+ if (result === 'image') {
+ state.onImage();
+ } else if (result === 'inline') {
+ state.onInline();
+ } else {
+ state.onDismiss();
+ }
+ },
+ [closeCurrentModal, state],
+ );
+
+ useEffect(() => {
+ return () => {
+ if (settledRef.current) {
+ return;
+ }
+
+ settledRef.current = true;
+ state.onDismiss();
+ };
+ }, [state]);
+
+ const onImage = useCallback(() => {
+ settle('image');
+ }, [settle]);
+
+ const onInline = useCallback(() => {
+ settle('inline');
+ }, [settle]);
+
+ const onDismiss = useCallback(() => {
+ settle(null);
+ }, [settle]);
+
+ return (
+ <ModalContainer onOutsideClick={onDismiss} onEscape={onDismiss}>
+ <ModalHeader title="Add .svg" onClose={onDismiss} />
+ <div style={content}>
+ Do you want to import this as an image or as inline SVG?
+ </div>
+ <ModalFooterContainer>
+ <Row align="center">
+ <Flex />
+ <Button onClick={onImage}>
+ Add to <code style={inlineCode}>public</code> and import as{' '}
+ <code style={inlineCode}>{'<Img>'}</code>
+ </Button>
+ <Spacing x={1} />
+ <ModalButton onClick={onInline} autoFocus>
+ Import as inline <code style={inlineCode}>{'<svg>'}</code>
+ </ModalButton>
+ </Row>
+ </ModalFooterContainer>
+ </ModalContainer>
+ );
+};
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index c64ef5615d..61c21db555 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -164,6 +164,7 @@ const TimelineContextMenuArea: React.FC<{
compositionId: currentCompositionId,
destinationDimensions: null,
dropPosition: null,
+ svgImportMode: 'image',
});
} finally {
setIsAddingAsset(false);
diff --git a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
index 69d5b160f4..c18489ca75 100644
--- a/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
+++ b/packages/studio/src/components/Timeline/TimelineClipboardKeybindings.tsx
@@ -26,6 +26,7 @@ import {
} from 'remotion';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {hasClipboardImage} from '../../helpers/clipboard-images';
+import {hasClipboardSvgMarkup} from '../../helpers/clipboard-svg';
import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
import {
areKeyboardShortcutsDisabled,
@@ -936,7 +937,8 @@ export const TimelineClipboardKeybindings: React.FC = () => {
if (
selectedItems.length === 0 ||
e.clipboardData === null ||
- hasClipboardImage(e.clipboardData)
+ hasClipboardImage(e.clipboardData) ||
+ hasClipboardSvgMarkup(e.clipboardData)
) {
return;
}
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 14e29e6ecc..68664429f8 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -211,6 +211,10 @@ export const getAssetElementForDroppedFile = ({
return getAssetElementFromPath(src);
};
+const isSvgFile = (file: File) => file.name.toLowerCase().endsWith('.svg');
+
+export const hasSvgFile = (files: File[]) => files.some(isSvgFile);
+
const getAssetLabel = (element: InsertableCompositionElement) => {
if (element.type !== 'asset') {
throw new Error('Expected asset element');
@@ -582,7 +586,7 @@ const notifyUnsupportedFiles = (unsupportedFiles: string[]) => {
}
};
-const insertAssetElement = async ({
+const insertCompositionElement = async ({
compositionFile,
compositionId,
element,
@@ -620,12 +624,14 @@ export const importAssets = async ({
destinationDimensions,
dropPosition,
files,
+ svgImportMode,
}: {
compositionFile: string;
compositionId: string;
destinationDimensions: Dimensions | null;
dropPosition: InsertElementDropPosition | null;
files: File[];
+ svgImportMode: 'image' | 'inline';
}) => {
if (files.length === 0) {
return;
@@ -633,6 +639,10 @@ export const importAssets = async ({
const staticFiles = getStaticFiles();
const differentExistingFile = files.find((file) => {
+ if (isSvgFile(file) && svgImportMode === 'inline') {
+ return false;
+ }
+
return staticFiles.some(
(existingStaticFile) =>
existingStaticFile.name === file.name &&
@@ -667,6 +677,32 @@ export const importAssets = async ({
for (const file of files) {
const contents = await file.arrayBuffer();
const fileType = detectFileType(new Uint8Array(contents));
+ const dimensions = await getFileDimensionsOrNull({file, fileType});
+
+ if (isSvgFile(file) && svgImportMode === 'inline') {
+ const svgInserted = await insertCompositionElement({
+ compositionFile,
+ compositionId,
+ element: {
+ type: 'svg',
+ markup: new TextDecoder().decode(contents),
+ position: getAssetPositionForDrop({
+ assetDimensions: dimensions,
+ destinationDimensions,
+ dropPosition,
+ }),
+ },
+ });
+
+ if (!svgInserted) {
+ notifyAddedStaticFiles();
+ return;
+ }
+
+ insertedLabels.push('<Interactive.Svg>');
+ continue;
+ }
+
const element = getAssetElementForDroppedFile({
fileType,
src: file.name,
@@ -691,10 +727,9 @@ export const importAssets = async ({
addedStaticFiles.push(file.name);
}
- const dimensions = await getFileDimensionsOrNull({file, fileType});
const resolvedDimensions = element.dimensions ?? dimensions;
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
@@ -729,6 +764,60 @@ export const importAssets = async ({
}
};
+export const insertSvgMarkup = async ({
+ compositionFile,
+ compositionId,
+ destinationDimensions,
+ dropPosition,
+ markup,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ destinationDimensions: Dimensions | null;
+ dropPosition: InsertElementDropPosition | null;
+ markup: string;
+}) => {
+ try {
+ const objectUrl = URL.createObjectURL(
+ new Blob([markup], {type: 'image/svg+xml'}),
+ );
+ let dimensions: Dimensions | null = null;
+ try {
+ dimensions = await getImageDimensions({
+ revokeObjectUrl: true,
+ src: objectUrl,
+ });
+ } catch {
+ dimensions = null;
+ }
+
+ const inserted = await insertCompositionElement({
+ compositionFile,
+ compositionId,
+ element: {
+ type: 'svg',
+ markup,
+ position: getAssetPositionForDrop({
+ assetDimensions: dimensions,
+ destinationDimensions,
+ dropPosition,
+ }),
+ },
+ });
+
+ if (inserted) {
+ notifyInsertedAssets(['<Interactive.Svg>']);
+ }
+ } catch (error) {
+ showNotification(
+ `Could not add SVG: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 4000,
+ );
+ }
+};
+
export const importRemoteAsset = async ({
compositionFile,
compositionId,
@@ -754,7 +843,7 @@ export const importRemoteAsset = async ({
return;
}
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
@@ -806,7 +895,7 @@ export const insertRemoteAudio = async ({
};
try {
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element,
@@ -858,7 +947,7 @@ export const insertExistingAssets = async ({
const dimensions =
element.dimensions ?? (await getStaticAssetDimensionsOrNull(assetPath));
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
@@ -903,7 +992,7 @@ export const insertComponent = async ({
dropPosition: InsertElementDropPosition | null;
}) => {
try {
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
@@ -983,7 +1072,7 @@ export const insertComposition = async ({
width: calculated.width,
height: calculated.height,
};
- const inserted = await insertAssetElement({
+ const inserted = await insertCompositionElement({
compositionFile,
compositionId,
element: {
diff --git a/packages/studio/src/helpers/clipboard-svg.ts b/packages/studio/src/helpers/clipboard-svg.ts
new file mode 100644
index 0000000000..1f555d62ae
--- /dev/null
+++ b/packages/studio/src/helpers/clipboard-svg.ts
@@ -0,0 +1,55 @@
+const svgOpeningTag = /^<svg(?:\s|>)/i;
+
+const removeSvgPreamble = (value: string) => {
+ let remaining = value.trim();
+
+ while (true) {
+ const withoutPreamble = remaining
+ .replace(/^<\?xml[\s\S]*?\?>\s*/i, '')
+ .replace(/^<!doctype[\s\S]*?>\s*/i, '')
+ .replace(/^<!--[\s\S]*?-->\s*/, '');
+ if (withoutPreamble === remaining) {
+ return remaining;
+ }
+
+ remaining = withoutPreamble;
+ }
+};
+
+export const extractSvgMarkup = (value: string): string | null => {
+ const withoutPreamble = removeSvgPreamble(value);
+ if (!svgOpeningTag.test(withoutPreamble)) {
+ return null;
+ }
+
+ const closingTagIndex = withoutPreamble.toLowerCase().lastIndexOf('</svg>');
+ if (closingTagIndex === -1) {
+ return null;
+ }
+
+ const afterClosingTag = withoutPreamble.slice(
+ closingTagIndex + '</svg>'.length,
+ );
+ if (afterClosingTag.trim() !== '') {
+ return null;
+ }
+
+ return withoutPreamble.slice(0, closingTagIndex + '</svg>'.length);
+};
+
+export const getClipboardSvgMarkup = (
+ clipboardData: DataTransfer,
+): string | null => {
+ for (const mimeType of ['text/plain', 'text/html']) {
+ const markup = extractSvgMarkup(clipboardData.getData(mimeType));
+ if (markup !== null) {
+ return markup;
+ }
+ }
+
+ return null;
+};
+
+export const hasClipboardSvgMarkup = (clipboardData: DataTransfer) => {
+ return getClipboardSvgMarkup(clipboardData) !== null;
+};
diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.ts
index 08bc0837bc..14910e90b8 100644
--- a/packages/studio/src/state/modals.ts
+++ b/packages/studio/src/state/modals.ts
@@ -120,6 +120,14 @@ export type ConfirmationDialogState = {
onCancel: () => void;
};
+export type SvgImportDialogState = {
+ type: 'svg-import-dialog';
+ id: string;
+ onImage: () => void;
+ onInline: () => void;
+ onDismiss: () => void;
+};
+
export type AddEffectModalState = {
type: 'add-effect';
fileName: string;
@@ -192,7 +200,8 @@ export type ModalState =
invocationTimestamp: number;
}
| AddEffectModalState
- | ConfirmationDialogState;
+ | ConfirmationDialogState
+ | SvgImportDialogState;
export type ModalContextType = {
selectedModal: ModalState | null;
diff --git a/packages/studio/src/test/clipboard-images.test.ts b/packages/studio/src/test/clipboard-images.test.ts
index 56fbcd3c42..780c7a51ae 100644
--- a/packages/studio/src/test/clipboard-images.test.ts
+++ b/packages/studio/src/test/clipboard-images.test.ts
@@ -67,3 +67,12 @@ test('uses an extension matching the clipboard MIME type', () => {
getClipboardImageFiles({clipboardData, existingFileNames: []})[0]?.name,
).toBe('pasted-image.jpg');
});
+
+test('keeps copied SVG files available for the SVG import dialog', () => {
+ const svg = new File(['<svg />'], 'icon.svg', {type: 'image/svg+xml'});
+ const clipboardData = makeClipboardData([svg]);
+
+ expect(
+ getClipboardImageFiles({clipboardData, existingFileNames: []}),
+ ).toEqual([svg]);
+});
diff --git a/packages/studio/src/test/clipboard-svg.test.ts b/packages/studio/src/test/clipboard-svg.test.ts
new file mode 100644
index 0000000000..e82689de6b
--- /dev/null
+++ b/packages/studio/src/test/clipboard-svg.test.ts
@@ -0,0 +1,66 @@
+import {expect, test} from 'bun:test';
+import {
+ extractSvgMarkup,
+ getClipboardSvgMarkup,
+ hasClipboardSvgMarkup,
+} from '../helpers/clipboard-svg';
+
+const makeClipboardData = ({
+ html = '',
+ text = '',
+}: {
+ html?: string;
+ text?: string;
+}): DataTransfer => {
+ return {
+ getData: (mimeType: string) => {
+ if (mimeType === 'text/plain') {
+ return text;
+ }
+
+ if (mimeType === 'text/html') {
+ return html;
+ }
+
+ return '';
+ },
+ } as unknown as DataTransfer;
+};
+
+test('extracts standalone SVG markup', () => {
+ const markup = '<svg viewBox="0 0 10 10"><path d="M0 0h10v10z" /></svg>';
+ expect(extractSvgMarkup(markup)).toBe(markup);
+});
+
+test('removes an SVG XML preamble', () => {
+ expect(
+ extractSvgMarkup(
+ '<?xml version="1.0"?><!DOCTYPE svg><!-- icon --><svg><circle /></svg>',
+ ),
+ ).toBe('<svg><circle /></svg>');
+});
+
+test('does not treat surrounding text as SVG markup', () => {
+ expect(extractSvgMarkup('Paste this: <svg><circle /></svg>')).toBe(null);
+ expect(extractSvgMarkup('<svg><circle /></svg> trailing')).toBe(null);
+ expect(extractSvgMarkup('<svg><circle />')).toBe(null);
+});
+
+test('prefers plain text SVG markup from the clipboard', () => {
+ const clipboardData = makeClipboardData({
+ text: '<svg><rect /></svg>',
+ html: '<svg><circle /></svg>',
+ });
+
+ expect(getClipboardSvgMarkup(clipboardData)).toBe('<svg><rect /></svg>');
+ expect(hasClipboardSvgMarkup(clipboardData)).toBe(true);
+});
+
+test('falls back to HTML clipboard data', () => {
+ const clipboardData = makeClipboardData({
+ html: '<svg><circle /></svg>',
+ text: 'not SVG',
+ });
+
+ expect(getClipboardSvgMarkup(clipboardData)).toBe('<svg><circle /></svg>');
+});
diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.ts
index d8f9e1b490..035047b5d5 100644
--- a/packages/studio/src/test/import-assets.test.ts
+++ b/packages/studio/src/test/import-assets.test.ts
@@ -7,6 +7,7 @@ import {
getComponentDimensions,
getCompositionPositionForDrop,
getElementPositionForDrop,
+ hasSvgFile,
} from '../components/import-assets';
test('maps audio file types to Audio assets', () => {
@@ -162,6 +163,16 @@ test('maps dropped SVG files to image assets', () => {
});
});
+test('detects whether dropped files include an SVG', () => {
+ expect(
+ hasSvgFile([
+ new File(['svg'], 'icon.SVG'),
+ new File(['image'], 'image.png'),
+ ]),
+ ).toBe(true);
+ expect(hasSvgFile([new File(['image'], 'image.png')])).toBe(false);
+});
+
test('does not map unsupported existing static file paths', () => {
expect(getAssetElementFromPath('data.json')).toBe(null);
expect(getAssetElementFromPath('asset-without-extension')).toBe(null);