🎥 Make videos programmatically with React
`@remotion/studio`: Add Element drag and drop (#8633)
Igor Samokhovets09d4d527337a
diff --git a/packages/docs/elements-template/element.tsx b/packages/docs/elements-template/element.tsxindex fe6956bae0..f2851c0647 100644--- a/packages/docs/elements-template/element.tsx+++ b/packages/docs/elements-template/element.tsx@@ -1,23 +1,21 @@import React from 'react';-import {AbsoluteFill, Sequence} from 'remotion';+import {AbsoluteFill} from 'remotion';export const ElementComponent: React.FC = () => {return (- <Sequence width={1080} height={1080}>- <AbsoluteFill- style={{- alignItems: 'center',- backgroundColor: '#111827',- color: 'white',- display: 'flex',- fontFamily: 'Inter, system-ui, sans-serif',- fontSize: 96,- fontWeight: 700,- justifyContent: 'center',- }}- >- Element- </AbsoluteFill>- </Sequence>+ <AbsoluteFill+ style={{+ alignItems: 'center',+ backgroundColor: '#111827',+ color: 'white',+ display: 'flex',+ fontFamily: 'Inter, system-ui, sans-serif',+ fontSize: 96,+ fontWeight: 700,+ justifyContent: 'center',+ }}+ >+ Element+ </AbsoluteFill>);};diff --git a/packages/docs/elements-template/index.mdx b/packages/docs/elements-template/index.mdxindex 2ee0336836..bfbdcf5266 100644--- a/packages/docs/elements-template/index.mdx+++ b/packages/docs/elements-template/index.mdx@@ -14,26 +14,24 @@ One short paragraph explaining what this element demonstrates and when to use it```tsx twoslash title="element.tsx"import React from 'react';-import {AbsoluteFill, Sequence} from 'remotion';+import {AbsoluteFill} from 'remotion';export const ElementComponent: React.FC = () => {return (- <Sequence width={1080} height={1080}>- <AbsoluteFill- style={{- alignItems: 'center',- backgroundColor: '#111827',- color: 'white',- display: 'flex',- fontFamily: 'Inter, system-ui, sans-serif',- fontSize: 96,- fontWeight: 700,- justifyContent: 'center',- }}- >- Element- </AbsoluteFill>- </Sequence>+ <AbsoluteFill+ style={{+ alignItems: 'center',+ backgroundColor: '#111827',+ color: 'white',+ display: 'flex',+ fontFamily: 'Inter, system-ui, sans-serif',+ fontSize: 96,+ fontWeight: 700,+ justifyContent: 'center',+ }}+ >+ Element+ </AbsoluteFill>);};```diff --git a/packages/docs/elements/overlays/lower-third/index.mdx b/packages/docs/elements/overlays/lower-third/index.mdxindex af4282de4b..19f5ef45ba 100644--- a/packages/docs/elements/overlays/lower-third/index.mdx+++ b/packages/docs/elements/overlays/lower-third/index.mdx@@ -6,17 +6,28 @@ description: A clean animated lower third for names and titles.import {ElementPage} from '@site/src/components/Elements/ElementPage';import {LowerThird} from './lower-third';+{/* TODO: Unify the runnable Element source, visible code block, and drag payload source instead of duplicating it in three places. This is a separate task. */}+export const lowerThirdSource = "import React from 'react';\nimport {\n\tAbsoluteFill,\n\tinterpolate,\n\tspring,\n\tuseCurrentFrame,\n\tuseVideoConfig,\n} from 'remotion';\n\nexport const LowerThird: React.FC = () => {\n\tconst frame = useCurrentFrame();\n\tconst {durationInFrames, fps: videoFps} = useVideoConfig();\n\n\tconst entrance = spring({\n\t\tframe,\n\t\tfps: videoFps,\n\t\tconfig: {\n\t\t\tdamping: 18,\n\t\t\tstiffness: 120,\n\t\t},\n\t});\n\n\tconst exitStart = Math.max(0, durationInFrames - 25);\n\tconst exitEnd = Math.max(exitStart + 1, durationInFrames - 5);\n\n\tconst exit = interpolate(frame, [exitStart, exitEnd], [1, 0], {\n\t\textrapolateLeft: 'clamp',\n\t\textrapolateRight: 'clamp',\n\t});\n\n\tconst progress = entrance * exit;\n\n\treturn (\n\t\t<AbsoluteFill\n\t\t\tstyle={{\n\t\t\t\tfontFamily: 'Inter, system-ui, sans-serif',\n\t\t\t\tpointerEvents: 'none',\n\t\t\t}}\n\t\t>\n\t\t\t<div\n\t\t\t\tstyle={{\n\t\t\t\t\tposition: 'absolute',\n\t\t\t\t\tleft: 0,\n\t\t\t\t\tbottom: 0,\n\t\t\t\t\ttransform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,\n\t\t\t\t\topacity: progress,\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t<div\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\twidth: 660,\n\t\t\t\t\t\tpadding: '34px 42px',\n\t\t\t\t\t\tborderRadius: 28,\n\t\t\t\t\t\tbackground: 'rgba(255, 255, 255, 0.92)',\n\t\t\t\t\t\tboxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',\n\t\t\t\t\t}}\n\t\t\t\t>\n\t\t\t\t\t<div\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontSize: 54,\n\t\t\t\t\t\t\tfontWeight: 800,\n\t\t\t\t\t\t\tcolor: '#111827',\n\t\t\t\t\t\t\tletterSpacing: -1.5,\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\tAlex Morgan\n\t\t\t\t\t</div>\n\t\t\t\t\t<div\n\t\t\t\t\t\tstyle={{\n\t\t\t\t\t\t\tfontSize: 30,\n\t\t\t\t\t\t\tfontWeight: 600,\n\t\t\t\t\t\t\tcolor: '#2563eb',\n\t\t\t\t\t\t\tmarginTop: 10,\n\t\t\t\t\t\t}}\n\t\t\t\t\t>\n\t\t\t\t\t\tCreative Developer\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div\n\t\t\t\t\tstyle={{\n\t\t\t\t\t\twidth: interpolate(progress, [0, 1], [0, 520]),\n\t\t\t\t\t\theight: 10,\n\t\t\t\t\t\tborderRadius: 999,\n\t\t\t\t\t\tbackground: '#60a5fa',\n\t\t\t\t\t\tmarginTop: 18,\n\t\t\t\t\t}}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</AbsoluteFill>\n\t);\n};\n";+# Lower ThirdA clean animated lower third for introducing a speaker, guest, or section.-<ElementPage component={LowerThird}>+<ElementPage+ category="overlays"+ component={LowerThird}+ componentName="LowerThird"+ displayName="Lower Third"+ elementHeight={1080}+ elementWidth={1920}+ slug="overlays/lower-third"+ sourceCode={lowerThirdSource}+>```tsx twoslash title="lower-third.tsx"import React from 'react';import {AbsoluteFill,- Sequence,interpolate,spring,useCurrentFrame,@@ -47,64 +58,62 @@ export const LowerThird: React.FC = () => {const progress = entrance * exit;return (- <Sequence width={900} height={260}>- <AbsoluteFill+ <AbsoluteFill+ style={{+ fontFamily: 'Inter, system-ui, sans-serif',+ pointerEvents: 'none',+ }}+ >+ <divstyle={{- fontFamily: 'Inter, system-ui, sans-serif',- pointerEvents: 'none',+ position: 'absolute',+ left: 0,+ bottom: 0,+ transform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,+ opacity: progress,}}><divstyle={{- position: 'absolute',- left: 0,- bottom: 0,- transform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,- opacity: progress,+ width: 660,+ padding: '34px 42px',+ borderRadius: 28,+ background: 'rgba(255, 255, 255, 0.92)',+ boxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',}}><divstyle={{- width: 660,- padding: '34px 42px',- borderRadius: 28,- background: 'rgba(255, 255, 255, 0.92)',- boxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',+ fontSize: 54,+ fontWeight: 800,+ color: '#111827',+ letterSpacing: -1.5,}}>- <div- style={{- fontSize: 54,- fontWeight: 800,- color: '#111827',- letterSpacing: -1.5,- }}- >- Alex Morgan- </div>- <div- style={{- fontSize: 30,- fontWeight: 600,- color: '#2563eb',- marginTop: 10,- }}- >- Creative Developer- </div>+ Alex Morgan</div><divstyle={{- width: interpolate(progress, [0, 1], [0, 520]),- height: 10,- borderRadius: 999,- background: '#60a5fa',- marginTop: 18,+ fontSize: 30,+ fontWeight: 600,+ color: '#2563eb',+ marginTop: 10,}}- />+ >+ Creative Developer+ </div></div>- </AbsoluteFill>- </Sequence>+ <div+ style={{+ width: interpolate(progress, [0, 1], [0, 520]),+ height: 10,+ borderRadius: 999,+ background: '#60a5fa',+ marginTop: 18,+ }}+ />+ </div>+ </AbsoluteFill>);};```diff --git a/packages/docs/elements/overlays/lower-third/lower-third.tsx b/packages/docs/elements/overlays/lower-third/lower-third.tsxindex 255a26db15..791b1ccdc4 100644--- a/packages/docs/elements/overlays/lower-third/lower-third.tsx+++ b/packages/docs/elements/overlays/lower-third/lower-third.tsx@@ -1,7 +1,6 @@import React from 'react';import {AbsoluteFill,- Sequence,interpolate,spring,useCurrentFrame,@@ -32,63 +31,61 @@ export const LowerThird: React.FC = () => {const progress = entrance * exit;return (- <Sequence width={900} height={260}>- <AbsoluteFill+ <AbsoluteFill+ style={{+ fontFamily: 'Inter, system-ui, sans-serif',+ pointerEvents: 'none',+ }}+ >+ <divstyle={{- fontFamily: 'Inter, system-ui, sans-serif',- pointerEvents: 'none',+ position: 'absolute',+ left: 0,+ bottom: 0,+ transform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,+ opacity: progress,}}><divstyle={{- position: 'absolute',- left: 0,- bottom: 0,- transform: `translateX(${interpolate(progress, [0, 1], [-90, 0])}px)`,- opacity: progress,+ width: 660,+ padding: '34px 42px',+ borderRadius: 28,+ background: 'rgba(255, 255, 255, 0.92)',+ boxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',}}><divstyle={{- width: 660,- padding: '34px 42px',- borderRadius: 28,- background: 'rgba(255, 255, 255, 0.92)',- boxShadow: '0 24px 80px rgba(0, 0, 0, 0.3)',+ fontSize: 54,+ fontWeight: 800,+ color: '#111827',+ letterSpacing: -1.5,}}>- <div- style={{- fontSize: 54,- fontWeight: 800,- color: '#111827',- letterSpacing: -1.5,- }}- >- Alex Morgan- </div>- <div- style={{- fontSize: 30,- fontWeight: 600,- color: '#2563eb',- marginTop: 10,- }}- >- Creative Developer- </div>+ Alex Morgan</div><divstyle={{- width: interpolate(progress, [0, 1], [0, 520]),- height: 10,- borderRadius: 999,- background: '#60a5fa',- marginTop: 18,+ fontSize: 30,+ fontWeight: 600,+ color: '#2563eb',+ marginTop: 10,}}- />+ >+ Creative Developer+ </div></div>- </AbsoluteFill>- </Sequence>+ <div+ style={{+ width: interpolate(progress, [0, 1], [0, 520]),+ height: 10,+ borderRadius: 999,+ background: '#60a5fa',+ marginTop: 18,+ }}+ />+ </div>+ </AbsoluteFill>);};diff --git a/packages/docs/elements/submit-an-element.mdx b/packages/docs/elements/submit-an-element.mdxindex c74f306615..90c47fdd1a 100644--- a/packages/docs/elements/submit-an-element.mdx+++ b/packages/docs/elements/submit-an-element.mdx@@ -23,57 +23,65 @@ The preferred format is:- Focused on one visual idea, technique, or workflow- Easy to remix- Works as-is when dragged or copied into a project-- **Building block, not a composition:** The hosted docs page provides the preview size, frame rate, and duration. A user's active composition may have a different width, height, FPS, or duration than the preview.+- **Building block, not a composition:** The hosted docs page provides the preview size, frame rate, and duration.- [Interactivity-friendly](/docs/studio/interactivity): inline editable values so they can show up in the Studio inspector. See also [Make a component interactive](/docs/studio/make-component-interactive).- If two variants are worth showing, make two separate Element pages instead of adding a variant prop.For example:```tsx twoslash title="Element.tsx"-import {Sequence} from 'remotion';-export const MyElement = () => {- return (- <Sequence width={1080} height={1080}>- <div>...</div>- </Sequence>- );+ return <div style={{width: '100%', height: '100%'}}>...</div>;};```For animation, keep the timing inside the component but let the surrounding project decide how long the Element appears:```tsx twoslash title="AnimatedElement.tsx"-import {Interactive, Sequence, interpolate, useCurrentFrame} from 'remotion';+import {Interactive, interpolate, useCurrentFrame} from 'remotion';export const AnimatedElement = () => {const frame = useCurrentFrame();return (- <Sequence width={1080} height={1080}>- <Interactive.Div- style={{- opacity: interpolate(frame, [0, 20], [0, 1]),- translate: interpolate(frame, [0, 20], ['0px 40px', '0px 0px']),- }}- >- Hello- </Interactive.Div>- </Sequence>+ <Interactive.Div+ style={{+ width: '100%',+ height: '100%',+ opacity: interpolate(frame, [0, 20], [0, 1]),+ translate: interpolate(frame, [0, 20], ['0px 40px', '0px 0px']),+ }}+ >+ Hello+ </Interactive.Div>);};```## Sizing Elements-For object-like Elements, use a [`<Sequence>`](/docs/sequence) with `width` and `height`.-This is useful for overlays, lower thirds, callouts, motion graphics, cards, badges, and data animations.+To give an Element a fixed size, set `elementWidth` and `elementHeight` on the `ElementPage` in `index.mdx`:++```tsx title="index.mdx"+<ElementPage+ component={MyElement}+ elementWidth={900}+ elementHeight={260}+>+```++Then make the Element fill that area in its source file:++```tsx title="my-element.tsx"+import {AbsoluteFill} from 'remotion';-The Sequence acts as the Element's isolated container.-It is absolutely positioned by default, gives Remotion Studio a selectable outline and transform target, and makes [`useVideoConfig()`](/docs/use-video-config) return the Element's own `width` and `height` to children.+export const MyElement = () => {+ return <AbsoluteFill>...</AbsoluteFill>;+};+```-For full-frame backgrounds, usually do not set `width` or `height`.-Let the Element inherit the host composition size instead.+Use this for overlays, lower thirds, callouts, motion graphics, cards, badges, and data animations.+Do not put the wrapper [`<Sequence>`](/docs/sequence) into the Element source file.## Assets and dependenciesdiff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsxindex 50d89b2899..60a3cec180 100644--- a/packages/docs/src/components/Elements/ElementPage.tsx+++ b/packages/docs/src/components/Elements/ElementPage.tsx@@ -1,28 +1,113 @@-import React, {type ComponentType, type ReactNode} from 'react';+import {+ makeElementDragData,+ type ComponentDimensions,+} from '@remotion/studio-shared';+import React, {useMemo, type ComponentType, type ReactNode} from 'react';+import {Sequence} from 'remotion';+import {setElementDragData, setElementDragImage} from './element-drag-data';import {ElementPreview} from './ElementPreview';type ElementPageProps = {+ readonly category?: string;+ readonly children: ReactNode;readonly component: ComponentType<Record<string, never>>;+ readonly componentName?: string;+ readonly displayName?: string;readonly durationInFrames?: number;+ readonly elementHeight?: number;+ readonly elementWidth?: number;readonly fps?: number;readonly height?: number;+ readonly slug?: string;+ readonly sourceCode?: string;readonly width?: number;- readonly children: ReactNode;+};++const dragButtonStyle: React.CSSProperties = {+ display: 'inline-flex',+ alignItems: 'center',+ gap: 10,+ padding: '12px 16px',+ borderRadius: 10,+ border: '1px solid var(--ifm-color-emphasis-300)',+ background: 'var(--ifm-background-surface-color)',+ boxShadow: '0 6px 20px rgba(0, 0, 0, 0.08)',+ cursor: 'grab',+ fontWeight: 700,+ userSelect: 'none',};export const ElementPage: React.FC<ElementPageProps> = ({+ category,children,component,+ componentName,+ displayName,durationInFrames = 120,+ elementHeight,+ elementWidth,fps = 30,height = 1080,+ slug,+ sourceCode,width = 1920,}) => {+ const dragData = useMemo(() => {+ if (+ !slug ||+ !displayName ||+ !componentName ||+ !sourceCode ||+ elementWidth === undefined ||+ elementHeight === undefined+ ) {+ return null;+ }++ const dimensions: ComponentDimensions = {+ width: elementWidth,+ height: elementHeight,+ };++ return makeElementDragData({+ category,+ componentName,+ dimensions,+ displayName,+ slug,+ sourceCode,+ });+ }, [+ category,+ componentName,+ displayName,+ elementHeight,+ elementWidth,+ slug,+ sourceCode,+ ]);++ const PreviewComponent = useMemo(() => {+ if (elementWidth === undefined || elementHeight === undefined) {+ return component;+ }++ const Component = component;++ return () => {+ return (+ <Sequence height={elementHeight} width={elementWidth}>+ <Component />+ </Sequence>+ );+ };+ }, [component, elementHeight, elementWidth]);+return (<><h2>Preview</h2><ElementPreview- component={component}+ component={PreviewComponent}durationInFrames={durationInFrames}fps={fps}height={height}@@ -35,6 +120,26 @@ export const ElementPage: React.FC<ElementPageProps> = ({Element component. Preview dimensions, frame rate, and duration aresupplied by the gallery.</p>+ {dragData === null ? null : (+ <p>+ <button+ draggable+ onDragStart={(event) => {+ setElementDragData({+ dataTransfer: event.dataTransfer,+ dragData,+ });+ setElementDragImage(event.dataTransfer);+ }}+ style={dragButtonStyle}+ title="Drag into Remotion Studio"+ type="button"+ >+ <span aria-hidden="true">↘</span>+ Drag into Remotion Studio+ </button>+ </p>+ )}<h2>Source</h2>{children}diff --git a/packages/docs/src/components/Elements/element-drag-data.ts b/packages/docs/src/components/Elements/element-drag-data.tsnew file mode 100644index 0000000000..b3d4d10a2b--- /dev/null+++ b/packages/docs/src/components/Elements/element-drag-data.ts@@ -0,0 +1,59 @@+import {+ ELEMENT_DRAG_MIME_TYPE,+ type ElementDragData,+} from '@remotion/studio-shared';++const ELEMENT_ICON_PATH =+ 'M3 3.5C3 2.67157 3.67157 2 4.5 2H11.5C12.3284 2 13 2.67157 13 3.5V12.5C13 13.3284 12.3284 14 11.5 14H4.5C3.67157 14 3 13.3284 3 12.5V3.5ZM4.5 3.5V6H11.5V3.5H4.5ZM11.5 7.5H4.5V12.5H11.5V7.5Z';++const makeElementDragImage = () => {+ const wrapper = document.createElement('div');+ wrapper.style.position = 'fixed';+ wrapper.style.top = '-1000px';+ wrapper.style.left = '-1000px';+ wrapper.style.width = '44px';+ wrapper.style.height = '44px';+ wrapper.style.display = 'flex';+ wrapper.style.alignItems = 'center';+ wrapper.style.justifyContent = 'center';+ wrapper.style.borderRadius = '8px';+ wrapper.style.background = '#0b0b0f';+ wrapper.style.boxShadow = '0 8px 24px rgba(0, 0, 0, 0.28)';++ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', '0 0 16 16');+ svg.setAttribute('width', '26');+ svg.setAttribute('height', '26');++ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');+ path.setAttribute('d', ELEMENT_ICON_PATH);+ path.setAttribute('fill', 'white');++ svg.appendChild(path);+ wrapper.appendChild(svg);++ return wrapper;+};++export const setElementDragData = ({+ dataTransfer,+ dragData,+}: {+ readonly dataTransfer: DataTransfer;+ readonly dragData: ElementDragData;+}) => {+ const serialized = JSON.stringify(dragData);+ dataTransfer.effectAllowed = 'copy';+ dataTransfer.setData(ELEMENT_DRAG_MIME_TYPE, serialized);+ dataTransfer.setData('application/json', serialized);+ dataTransfer.setData('text/plain', serialized);+};++export const setElementDragImage = (dataTransfer: DataTransfer) => {+ const dragImage = makeElementDragImage();+ document.body.appendChild(dragImage);+ dataTransfer.setDragImage(dragImage, 22, 22);+ requestAnimationFrame(() => {+ document.body.removeChild(dragImage);+ });+};diff --git a/packages/docs/src/test/elements.test.ts b/packages/docs/src/test/elements.test.tsindex becbcae13a..de7cd2b275 100644--- a/packages/docs/src/test/elements.test.ts+++ b/packages/docs/src/test/elements.test.ts@@ -48,6 +48,11 @@ const extractTsxBlock = (mdx: string): string | null => {return match ? match[1] : null;};+const extractLowerThirdSource = (mdx: string): string | null => {+ const match = mdx.match(/export const lowerThirdSource = ("[\s\S]*?");\n/);+ return match ? (JSON.parse(match[1]) as string) : null;+};+const allElements = [...findElements(elementsRoot),...findElements(templateRoot),@@ -63,13 +68,14 @@ describe('Elements must follow the colocated single-file format', () => {const tsx = readFileSync(element.tsxPath, 'utf8');const mdx = readFileSync(element.mdxPath, 'utf8');- test('source file is an Element, not a composition', () => {+ test('source file is an Element, not a composition or wrapper Sequence', () => {expect(tsx).not.toContain('export const durationInFrames');expect(tsx).not.toContain('export const fps');expect(tsx).not.toContain('export const width');expect(tsx).not.toContain('export const height');expect(tsx).not.toContain('export const RemotionRoot');expect(tsx).not.toContain('<Composition');+ expect(tsx).not.toContain('<Sequence');});test('MDX uses the ElementPage template', () => {@@ -86,6 +92,30 @@ describe('Elements must follow the colocated single-file format', () => {// The fenced code block must be identical to the runnable .tsx file.expect(block?.trim()).toBe(tsx.trim());});++ test('drag payload source matches the source file if present', () => {+ const source = extractLowerThirdSource(mdx);+ if (source === null) {+ return;+ }++ expect(source.trim()).toBe(tsx.trim());+ expect(mdx).toContain('sourceCode={lowerThirdSource}');+ });++ test('Element drag file name is derived from the slug', () => {+ expect(mdx).not.toContain('fileName=');++ const match = mdx.match(/slug="([^"]+)"/);+ if (!match) {+ return;+ }++ const lastSlugSegment = match[1].split('/').at(-1);+ expect(lastSlugSegment).toBeTruthy();+ expect(lastSlugSegment).toBe(lastSlugSegment?.toLowerCase());+ expect(lastSlugSegment).not.toContain('..');+ });});}});diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsindex b11a48452e..1f39c84052 100644--- a/packages/studio-server/src/helpers/resolve-composition-component.ts+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -50,10 +50,11 @@ export type ResolvedCompositionComponent = {canAddSequence: boolean;};-type ResolvedCompositionComponentWithFile = ResolvedCompositionComponent & {- fileName: string;- exportName: string | 'default';-};+export type ResolvedCompositionComponentWithFile =+ ResolvedCompositionComponent & {+ fileName: string;+ exportName: string | 'default';+ };type ImportTarget = {importPath: string;@@ -901,10 +902,12 @@ const createSolidElement = ({};const createComponentElement = ({+ addPositionStyle,localName,props,position,}: {+ addPositionStyle: boolean;localName: string;props: ComponentProp[];position: InsertableCompositionElementPosition | null;@@ -914,7 +917,9 @@ const createComponentElement = ({recast.types.builders.jsxIdentifier(localName),[...props.map(createComponentProp),- createPositionAbsoluteStyleAttribute(position),+ ...(addPositionStyle+ ? [createPositionAbsoluteStyleAttribute(position)]+ : []),],true,),@@ -923,6 +928,34 @@ const createComponentElement = ({);};+const createSequenceWrappedElement = ({+ child,+ dimensions,+ position,+ sequenceLocalName,+}: {+ child: namedTypes.JSXElement;+ dimensions: {width: number; height: number};+ position: InsertableCompositionElementPosition | null;+ sequenceLocalName: string;+}): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ [+ createNumberAttribute('width', dimensions.width),+ createNumberAttribute('height', dimensions.height),+ createPositionAbsoluteStyleAttribute(position),+ ],+ false,+ ),+ recast.types.builders.jsxClosingElement(+ recast.types.builders.jsxIdentifier(sequenceLocalName),+ ),+ [child],+ );+};+const createAssetElement = ({addPositionStyle,localName,@@ -1109,6 +1142,30 @@ const ensureSolidImport = (ast: File) => {});};+const getAvailableSequenceLocalName = (ast: File) => {+ const candidates = ['Sequence', 'RemotionSequence'];+ const available = candidates.find((candidate) => {+ return !hasTopLevelBinding({ast, name: candidate});+ });++ if (!available) {+ throw new Error(+ 'Cannot add <Sequence> because Sequence is already defined',+ );+ }++ return available;+};++const ensureSequenceImport = (ast: File) => {+ return ensureNamedImport({+ ast,+ importedName: 'Sequence',+ sourcePath: 'remotion',+ localName: getAvailableSequenceLocalName(ast),+ });+};+const getImportDeclarations = ({ast,sourcePath,@@ -1543,7 +1600,7 @@ const getComponentLocationRecursively = async ({}};-const resolveCompositionComponentWithFile = async ({+export const resolveCompositionComponentWithFile = async ({remotionRoot,compositionFile,compositionId,@@ -1631,9 +1688,11 @@ export const resolveCompositionComponent = async ({};const createInsertableJsxElement = ({+ addPositionStyleToComponent,ast,element,}: {+ addPositionStyleToComponent: boolean;ast: File;element: InsertableCompositionElement;}) => {@@ -1657,6 +1716,7 @@ const createInsertableJsxElement = ({});return createComponentElement({+ addPositionStyle: addPositionStyleToComponent,localName: componentLocalName,props: element.props,position: element.position,@@ -1704,12 +1764,17 @@ export const insertJsxElementIntoComposition = async ({compositionId,element,prettierConfigOverride,+ wrapInSequence = null,}: {remotionRoot: string;compositionFile: string;compositionId: string;element: InsertableCompositionElement;prettierConfigOverride: Record<string, unknown> | null;+ wrapInSequence?: {+ dimensions: {width: number; height: number};+ position: InsertableCompositionElementPosition | null;+ } | null;}): Promise<{fileName: string;source: string;@@ -1734,11 +1799,23 @@ export const insertJsxElementIntoComposition = async ({fileName: location.fileName,});const ast = parseAst(input);- const elementToInsert = createInsertableJsxElement({ast, element});+ const elementToInsert = createInsertableJsxElement({+ addPositionStyleToComponent: wrapInSequence === null,+ ast,+ element,+ });+ const finalElementToInsert = wrapInSequence+ ? createSequenceWrappedElement({+ child: elementToInsert,+ dimensions: wrapInSequence.dimensions,+ position: wrapInSequence.position,+ sequenceLocalName: ensureSequenceImport(ast),+ })+ : elementToInsert;const logLine = addElementToComponentRoot({ast,exportName: location.exportName,- element: elementToInsert,+ element: finalElementToInsert,});const finalFile = serializeAst(ast);diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex 8c391ceac7..e604d8e020 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -16,6 +16,7 @@ import {deleteStaticFileHandler} from './routes/delete-static-file';import {downloadRemoteAssetHandler} from './routes/download-remote-asset';import {duplicateEffectHandler} from './routes/duplicate-effect';import {duplicateJsxNodeHandler} from './routes/duplicate-jsx-node';+import {insertElementHandler} from './routes/insert-element';import {insertJsxElementHandler} from './routes/insert-jsx-element';import {handleInstallPackage} from './routes/install-dependency';import {logStudioErrorHandler} from './routes/log-studio-error';@@ -94,6 +95,7 @@ export const allApiRoutes: {'/api/restart-studio': handleRestartStudio,'/api/install-package': handleInstallPackage,'/api/insert-jsx-element': insertJsxElementHandler,+ '/api/insert-element': insertElementHandler,'/api/download-remote-asset': downloadRemoteAssetHandler,'/api/undo': undoHandler,'/api/redo': redoHandler,diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsnew file mode 100644index 0000000000..550341218e--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -0,0 +1,296 @@+import {existsSync, readFileSync} from 'node:fs';+import path from 'node:path';+import {RenderInternals} from '@remotion/renderer';+import {+ isComponentIdentifier,+ makeElementFileNameFromSlug,+ type InsertElementRequest,+ type InsertElementResponse,+ type InsertableCompositionElementPosition,+} from '@remotion/studio-shared';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {+ insertJsxElementIntoComposition,+ resolveCompositionComponentWithFile,+} from '../../helpers/resolve-composition-component';+import type {ApiHandler} from '../api-types';+import {formatLogFileLocation} from '../format-log-file-location';+import {+ printUndoHint,+ pushTransactionToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {warnAboutPrettierOnce} from './log-updates/log-update';+import {withSavePropsLock} from './save-props-mutex';++const validatePosition = (+ position: InsertableCompositionElementPosition | null,+) => {+ if (position === null) {+ return;+ }++ if (!Number.isFinite(position.x) || !Number.isFinite(position.y)) {+ throw new Error('Position must be finite');+ }+};++const isInside = ({child, parent}: {child: string; parent: string}) => {+ const relative = path.relative(parent, child);+ return (+ relative === '' ||+ (!relative.startsWith('..') && !path.isAbsolute(relative))+ );+};++const withoutTsxExtension = (fileName: string) => {+ return fileName.replace(/\.tsx$/, '');+};++const normalizeSourceForComparison = (source: string) => {+ return source.replace(/\r\n/g, '\n').trim();+};++const makeRelativeImportPath = ({+ fromFile,+ toFile,+}: {+ fromFile: string;+ toFile: string;+}) => {+ const withoutExtension = withoutTsxExtension(toFile);+ let relative = path+ .relative(path.dirname(fromFile), withoutExtension)+ .split(path.sep)+ .join('/');++ if (!relative.startsWith('.')) {+ relative = `./${relative}`;+ }++ return relative;+};++const validateSourceExportsComponent = ({+ componentName,+ sourceCode,+}: {+ componentName: string;+ sourceCode: string;+}) => {+ const escaped = componentName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const patterns = [+ new RegExp(`export\\s+const\\s+${escaped}\\b`),+ new RegExp(`export\\s+function\\s+${escaped}\\b`),+ ];++ if (!patterns.some((pattern) => pattern.test(sourceCode))) {+ throw new Error(+ `Element source must export a named component called ${componentName}`,+ );+ }+};++const validateDimensions = (+ dimensions: InsertElementRequest['element']['dimensions'],+) => {+ if (+ !Number.isFinite(dimensions.width) ||+ !Number.isFinite(dimensions.height) ||+ dimensions.width <= 0 ||+ dimensions.height <= 0+ ) {+ throw new Error('Element dimensions must be positive finite numbers');+ }+};++const validateElement = (element: InsertElementRequest['element']) => {+ if (!isComponentIdentifier(element.componentName)) {+ throw new Error('Unsupported Element component name');+ }++ if (makeElementFileNameFromSlug(element.slug) === null) {+ throw new Error(+ 'Element slug must produce a safe lowercase .tsx file name',+ );+ }++ if (+ typeof element.sourceCode !== 'string' ||+ element.sourceCode.trim().length === 0 ||+ element.sourceCode.length > 200000+ ) {+ throw new Error('Unsupported Element source code');+ }++ validateSourceExportsComponent({+ componentName: element.componentName,+ sourceCode: element.sourceCode,+ });+ validateDimensions(element.dimensions);+};++export const insertElementHandler: ApiHandler<+ InsertElementRequest,+ InsertElementResponse+> = ({+ input: {compositionFile, compositionId, element, position},+ remotionRoot,+ logLevel,+}) =>+ withSavePropsLock(async () => {+ try {+ validateElement(element);+ validatePosition(position);++ RenderInternals.Log.trace(+ {indent: false, logLevel},+ `[insert-element] Received request for compositionFile="${compositionFile}" compositionId="${compositionId}" element="${element.slug}"`,+ );++ const location = await resolveCompositionComponentWithFile({+ remotionRoot,+ compositionFile,+ compositionId,+ });+ if (!location.canAddSequence) {+ throw new Error(+ 'Cannot insert Element into this composition component',+ );+ }++ const derivedElementFileName = makeElementFileNameFromSlug(element.slug);+ if (derivedElementFileName === null) {+ throw new Error(+ 'Element slug must produce a safe lowercase .tsx file name',+ );+ }++ const elementFileName = path.resolve(+ path.dirname(location.fileName),+ derivedElementFileName,+ );+ if (!isInside({child: elementFileName, parent: remotionRoot})) {+ throw new Error('Element file must stay inside the Remotion project');+ }++ const elementFileExists = existsSync(elementFileName);+ if (elementFileExists) {+ const existingSource = readFileSync(elementFileName, 'utf-8');+ if (+ normalizeSourceForComparison(existingSource) !==+ normalizeSourceForComparison(element.sourceCode)+ ) {+ throw new Error(+ `Element file already exists with different contents: ${derivedElementFileName}`,+ );+ }+ }++ const importPath = makeRelativeImportPath({+ fromFile: location.fileName,+ toFile: elementFileName,+ });++ const inserted = await insertJsxElementIntoComposition({+ remotionRoot,+ compositionFile,+ compositionId,+ element: {+ type: 'component',+ componentName: element.componentName,+ importName: element.componentName,+ importPath,+ props: [],+ position: null,+ },+ prettierConfigOverride: null,+ wrapInSequence: {+ dimensions: element.dimensions,+ position,+ },+ });++ pushTransactionToUndoStack({+ snapshots: [+ ...(elementFileExists+ ? []+ : [+ {+ filePath: elementFileName,+ oldContents: null,+ newContents: element.sourceCode,+ logLine: 1,+ },+ ]),+ {+ filePath: inserted.fileName,+ oldContents: inserted.oldContents,+ newContents: inserted.output,+ logLine: inserted.logLine,+ },+ ],+ logLevel,+ remotionRoot,+ description: {+ undoMessage: `↩️ Added ${element.displayName}`,+ redoMessage: `↪️ Added ${element.displayName}`,+ },+ entryType: 'insert-jsx-element',+ suppressHmrOnFileRestore: false,+ });+ if (!elementFileExists) {+ suppressUndoStackInvalidation(elementFileName);+ }++ suppressUndoStackInvalidation(inserted.fileName);++ if (!elementFileExists) {+ writeFileAndNotifyFileWatchers(+ elementFileName,+ element.sourceCode,+ undefined,+ );+ }++ writeFileAndNotifyFileWatchers(+ inserted.fileName,+ inserted.output,+ undefined,+ );++ const compositionLocationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: inserted.fileName,+ line: inserted.logLine,+ });+ const elementLocationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath: elementFileName,+ line: 1,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(elementLocationLabel)} ${elementFileExists ? 'Reused existing Element source' : 'Created Element source'}`,+ );+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${RenderInternals.chalk.blueBright(compositionLocationLabel)} Added <${element.componentName}>`,+ );+ if (!inserted.formatted) {+ warnAboutPrettierOnce(logLevel);+ }++ printUndoHint(logLevel);++ return {+ success: true,+ };+ } catch (err) {+ return {+ success: false,+ reason: (err as Error).message,+ stack: (err as Error).stack as string,+ };+ }+ });diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 3c0f2b0f29..775f60f021 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -30,6 +30,7 @@ import type {EffectClipboardPasteType,EffectClipboardSnapshot,} from './effect-clipboard-data';+import type {ElementDragData} from './element-drag-data';import type {PackageManager} from './package-manager';import type {ProjectInfo} from './project-info';import type {@@ -688,6 +689,23 @@ export type InsertJsxElementResponse =stack: string;};+export type InsertElementRequest = {+ compositionFile: string;+ compositionId: string;+ element: ElementDragData['element'];+ position: InsertableCompositionElementPosition | null;+};++export type InsertElementResponse =+ | {+ success: true;+ }+ | {+ success: false;+ reason: string;+ stack: string;+ };+export type DownloadRemoteAssetRequest = {url: string;};@@ -847,6 +865,7 @@ export type ApiRoutes = {InsertJsxElementRequest,InsertJsxElementResponse>;+ '/api/insert-element': ReqAndRes<InsertElementRequest, InsertElementResponse>;'/api/download-remote-asset': ReqAndRes<DownloadRemoteAssetRequest,DownloadRemoteAssetResponsediff --git a/packages/studio-shared/src/element-drag-data.ts b/packages/studio-shared/src/element-drag-data.tsnew file mode 100644index 0000000000..92cf32531b--- /dev/null+++ b/packages/studio-shared/src/element-drag-data.ts@@ -0,0 +1,159 @@+import {+ isComponentIdentifier,+ type ComponentDimensions,+} from './component-drag-data';++export const ELEMENT_DRAG_MIME_TYPE = 'application/vnd.remotion.element+json';++export type ElementDragData = {+ type: 'remotion-element';+ version: 1;+ element: {+ slug: string;+ displayName: string;+ componentName: string;+ sourceCode: string;+ dimensions: ComponentDimensions;+ category?: string;+ };+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+};++export const isLowercaseElementFileName = (value: unknown): value is string => {+ return (+ typeof value === 'string' &&+ value.length > 0 &&+ value.length < 120 &&+ value === value.toLowerCase() &&+ value.endsWith('.tsx') &&+ !value.includes('/') &&+ !value.includes('\\') &&+ !value.includes('\0') &&+ !value.includes('..') &&+ /^[a-z0-9][a-z0-9.-]*\.tsx$/.test(value)+ );+};++const isSlug = (value: unknown): value is string => {+ return (+ typeof value === 'string' &&+ value.length > 0 &&+ value.length < 120 &&+ /^[a-z0-9][a-z0-9/-]*$/.test(value) &&+ !value.includes('..') &&+ !value.includes('//')+ );+};++export const makeElementFileNameFromSlug = (slug: string) => {+ if (!isSlug(slug)) {+ return null;+ }++ const lastSegment = slug.split('/').at(-1);+ if (!lastSegment) {+ return null;+ }++ const fileName = `${lastSegment}.element.tsx`;+ return isLowercaseElementFileName(fileName) ? fileName : null;+};++const isDisplayName = (value: unknown): value is string => {+ return typeof value === 'string' && value.length > 0 && value.length < 120;+};++const isSourceCode = (value: unknown): value is string => {+ return (+ typeof value === 'string' &&+ value.trim().length > 0 &&+ value.length < 200000+ );+};++const isCategory = (value: unknown): value is string => {+ return typeof value === 'string' && /^[a-z0-9][a-z0-9/-]*$/.test(value);+};++const isDimensions = (value: unknown): value is ComponentDimensions => {+ if (!isRecord(value)) {+ return false;+ }++ return (+ typeof value.width === 'number' &&+ Number.isFinite(value.width) &&+ value.width > 0 &&+ typeof value.height === 'number' &&+ Number.isFinite(value.height) &&+ value.height > 0+ );+};++export const makeElementDragData = ({+ category,+ componentName,+ dimensions,+ displayName,+ slug,+ sourceCode,+}: ElementDragData['element']): ElementDragData => {+ return {+ type: 'remotion-element',+ version: 1,+ element: {+ slug,+ displayName,+ componentName,+ sourceCode,+ dimensions,+ ...(category ? {category} : {}),+ },+ };+};++export const parseElementDragData = (value: string): ElementDragData | null => {+ try {+ const parsed: unknown = JSON.parse(value);+ if (!isRecord(parsed)) {+ return null;+ }++ if (parsed.type !== 'remotion-element' || parsed.version !== 1) {+ return null;+ }++ if (!isRecord(parsed.element)) {+ return null;+ }++ const {category, componentName, dimensions, displayName, slug, sourceCode} =+ parsed.element;++ if (+ !isSlug(slug) ||+ !isDisplayName(displayName) ||+ !isComponentIdentifier(componentName) ||+ makeElementFileNameFromSlug(slug) === null ||+ !isSourceCode(sourceCode) ||+ !isDimensions(dimensions) ||+ (typeof category !== 'undefined' && !isCategory(category))+ ) {+ return null;+ }++ return makeElementDragData({+ slug,+ displayName,+ componentName,+ sourceCode,+ dimensions,+ ...(category ? {category} : {}),+ });+ } catch {+ return null;+ }+};diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 97074093b8..bcea3f69f6 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -40,6 +40,8 @@ export {DuplicateEffectResponse,DuplicateJsxNodeRequest,DuplicateJsxNodeResponse,+ InsertElementRequest,+ InsertElementResponse,InsertJsxElementRequest,InsertJsxElementResponse,InsertableCompositionElement,@@ -164,6 +166,14 @@ export {parseEffectDragData,type EffectDragData,} from './effect-drag-data';+export {+ ELEMENT_DRAG_MIME_TYPE,+ isLowercaseElementFileName,+ makeElementDragData,+ makeElementFileNameFromSlug,+ parseElementDragData,+ type ElementDragData,+} from './element-drag-data';export {EFFECT_CATALOG,getEffectCatalogCategories,diff --git a/packages/studio-shared/src/test/element-drag-data.test.ts b/packages/studio-shared/src/test/element-drag-data.test.tsnew file mode 100644index 0000000000..e069055fe0--- /dev/null+++ b/packages/studio-shared/src/test/element-drag-data.test.ts@@ -0,0 +1,136 @@+import {expect, test} from 'bun:test';+import {+ makeElementDragData,+ makeElementFileNameFromSlug,+ parseElementDragData,+} from '../element-drag-data';++const validElement = {+ slug: 'overlays/lower-third',+ displayName: 'Lower Third',+ componentName: 'LowerThird',+ sourceCode: 'export const LowerThird = () => null;',+ dimensions: {width: 900, height: 260},+ category: 'overlays',+};++test('parses element drag data', () => {+ expect(+ parseElementDragData(JSON.stringify(makeElementDragData(validElement))),+ ).toEqual({+ type: 'remotion-element',+ version: 1,+ element: validElement,+ });+});++test('parses element drag data without optional category', () => {+ expect(+ parseElementDragData(+ JSON.stringify(+ makeElementDragData({+ slug: 'lower-third',+ displayName: 'Lower Third',+ componentName: 'LowerThird',+ sourceCode: 'export const LowerThird = () => null;',+ dimensions: {width: 900, height: 260},+ }),+ ),+ ),+ ).toEqual({+ type: 'remotion-element',+ version: 1,+ element: {+ slug: 'lower-third',+ displayName: 'Lower Third',+ componentName: 'LowerThird',+ sourceCode: 'export const LowerThird = () => null;',+ dimensions: {width: 900, height: 260},+ },+ });+});++test('derives element file name from slug', () => {+ expect(makeElementFileNameFromSlug('overlays/lower-third')).toBe(+ 'lower-third.element.tsx',+ );+ expect(makeElementFileNameFromSlug('LowerThird')).toBe(null);+ expect(makeElementFileNameFromSlug('overlays/../lower-third')).toBe(null);+});++test('rejects invalid element drag data', () => {+ expect(parseElementDragData('')).toBe(null);+ expect(parseElementDragData('{')).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 2,+ element: validElement,+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-component',+ version: 1,+ element: validElement,+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, componentName: 'lowerThird'},+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, slug: 'LowerThird'},+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, slug: '../lower-third'},+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, sourceCode: ''},+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, dimensions: undefined},+ }),+ ),+ ).toBe(null);+ expect(+ parseElementDragData(+ JSON.stringify({+ type: 'remotion-element',+ version: 1,+ element: {...validElement, dimensions: {width: 0, height: 260}},+ }),+ ),+ ).toBe(null);+});diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 5dcd837b81..6646b29707 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -2,6 +2,7 @@ import type {Size} from '@remotion/player';import {ASSET_DRAG_MIME_TYPE,COMPONENT_DRAG_MIME_TYPE,+ ELEMENT_DRAG_MIME_TYPE,parseAssetDragData,parseComponentDragData,parseSfxDragData,@@ -46,10 +47,12 @@ import EditorGuides from './EditorGuides';import {EditorRulers} from './EditorRuler';import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';import {getEffectDragData} from './effect-drag-and-drop';+import {getElementDragData} from './element-drag-and-drop';import {importAssets,importRemoteAsset,insertComponent,+ insertElement,insertExistingAssets,insertRemoteAudio,type InsertElementDropPosition,@@ -100,6 +103,12 @@ const isComponentDragEvent = (event: DragEvent): boolean => {);};+const isElementDragEvent = (event: DragEvent): boolean => {+ return Array.from(event.dataTransfer?.types ?? []).includes(+ ELEMENT_DRAG_MIME_TYPE,+ );+};+const isSfxDragEvent = (event: DragEvent): boolean => {return Array.from(event.dataTransfer?.types ?? []).includes(SFX_DRAG_MIME_TYPE,@@ -111,6 +120,7 @@ const isRemoteAssetDragEvent = (event: DragEvent): boolean => {!isFileDragEvent(event) &&!isAssetDragEvent(event) &&!isComponentDragEvent(event) &&+ !isElementDragEvent(event) &&!isSfxDragEvent(event) &&hasRemoteAssetDragData(event.dataTransfer));@@ -737,6 +747,7 @@ export const Canvas: React.FC<{(!isFileDragEvent(event) &&!isAssetDragEvent(event) &&!isComponentDragEvent(event) &&+ !isElementDragEvent(event) &&!isSfxDragEvent(event) &&!isRemoteAssetDragEvent(event)) ||!isDragEventInsideCanvas(event)@@ -761,6 +772,7 @@ export const Canvas: React.FC<{(!isFileDragEvent(event) &&!isAssetDragEvent(event) &&!isComponentDragEvent(event) &&+ !isElementDragEvent(event) &&!isSfxDragEvent(event) &&!isRemoteAssetDragEvent(event)) ||!isDragEventInsideCanvas(event)@@ -825,6 +837,17 @@ export const Canvas: React.FC<{compositionId: currentCompositionId,});} else {+ const elementDragData = getElementDragData(event.dataTransfer);+ if (elementDragData !== null) {+ await insertElement({+ element: elementDragData.element,+ compositionFile,+ compositionId: currentCompositionId,+ dropPosition,+ });+ return;+ }+const componentDragData = getComponentDragData(event);if (componentDragData !== null) {await insertComponent({diff --git a/packages/studio/src/components/element-drag-and-drop.ts b/packages/studio/src/components/element-drag-and-drop.tsnew file mode 100644index 0000000000..c98550ebd5--- /dev/null+++ b/packages/studio/src/components/element-drag-and-drop.ts@@ -0,0 +1,35 @@+import {+ ELEMENT_DRAG_MIME_TYPE,+ parseElementDragData,+ type ElementDragData,+} from '@remotion/studio-shared';++export const hasElementDragType = (dataTransfer: DataTransfer | null) => {+ return Array.from(dataTransfer?.types ?? []).includes(ELEMENT_DRAG_MIME_TYPE);+};++export const getElementDragData = (+ dataTransfer: DataTransfer | null,+): ElementDragData | null => {+ if (!dataTransfer) {+ return null;+ }++ for (const type of [+ ELEMENT_DRAG_MIME_TYPE,+ 'application/json',+ 'text/plain',+ ]) {+ const raw = dataTransfer.getData(type);+ if (!raw) {+ continue;+ }++ const parsed = parseElementDragData(raw);+ if (parsed) {+ return parsed;+ }+ }++ return null;+};diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex f006782aab..ea06847cb1 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -6,6 +6,7 @@ import {type ComponentDragData,type ComponentProp,type DownloadRemoteAssetResponse,+ type ElementDragData,type FileType,type InsertableCompositionElement,type InsertableCompositionElementPosition,@@ -823,3 +824,41 @@ export const insertComponent = async ({);}};++export const insertElement = async ({+ compositionFile,+ compositionId,+ dropPosition,+ element,+}: {+ compositionFile: string;+ compositionId: string;+ dropPosition: InsertElementDropPosition | null;+ element: ElementDragData['element'];+}) => {+ try {+ const response = await callApi('/api/insert-element', {+ compositionFile,+ compositionId,+ element,+ position: getCenteredPosition({+ dimensions: element.dimensions,+ dropPosition,+ }),+ });++ if (!response.success) {+ showNotification(`Could not add Element: ${response.reason}`, 4000);+ return;+ }++ showNotification(`Added ${element.displayName} to source file`, 2000);+ } catch (error) {+ showNotification(+ `Could not add Element: ${+ error instanceof Error ? error.message : String(error)+ }`,+ 4000,+ );+ }+};