Skip to content

🎥 Make videos programmatically with React

`@remotion/shapes`: Add effects, schemas, outline, sequence support (#8205)

Jonny Burgera375fbc71e22
diff --git a/bun.lock b/bun.lock
index ac7af3dca6..d56945fbab 100644
--- a/bun.lock
+++ b/bun.lock
@@ -1443,6 +1443,7 @@
"version": "4.0.473",
"dependencies": {
"@remotion/paths": "workspace:*",
+ "remotion": "workspace:*",
},
"devDependencies": {
"@happy-dom/global-registrator": "14.5.1",
diff --git a/packages/core/src/CompositionManager.tsx b/packages/core/src/CompositionManager.tsx
index 4af41fa273..60ace68eb4 100644
--- a/packages/core/src/CompositionManager.tsx
+++ b/packages/core/src/CompositionManager.tsx
@@ -117,7 +117,7 @@ export type TSequence = {
premountDisplay: number | null;
postmountDisplay: number | null;
controls: SequenceControls | null;
- refForOutline: React.RefObject<HTMLElement | null> | null;
+ refForOutline: React.RefObject<Element | null> | null;
effects: readonly EffectDefinition<unknown>[];
isInsideSeries: boolean;
} & EnhancedTSequenceData;
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index 4dcbc05990..17d5e69e0e 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -103,7 +103,7 @@ export type SequencePropsWithoutDuration = {
/**
* @deprecated For internal use only.
*/
- readonly _remotionInternalRefForOutline?: React.RefObject<HTMLElement | null> | null;
+ readonly _remotionInternalRefForOutline?: React.RefObject<Element | null> | null;
} & LayoutAndStyle;
export type SequenceProps = {
diff --git a/packages/core/src/use-media-in-timeline.ts b/packages/core/src/use-media-in-timeline.ts
index a2e9a95ac4..d591de69a7 100644
--- a/packages/core/src/use-media-in-timeline.ts
+++ b/packages/core/src/use-media-in-timeline.ts
@@ -157,7 +157,7 @@ export const useMediaInTimeline = ({
postmountDisplay: number | null;
loopDisplay: LoopDisplay | undefined;
documentationLink: string | null;
- refForOutline: React.RefObject<HTMLElement | null> | null;
+ refForOutline: React.RefObject<Element | null> | null;
}) => {
const parentSequence = useContext(SequenceContext);
const startsAt = useMediaStartsAt();
diff --git a/packages/docs/components/shapes/shape-component-drag-data.ts b/packages/docs/components/shapes/shape-component-drag-data.ts
new file mode 100644
index 0000000000..750d55568d
--- /dev/null
+++ b/packages/docs/components/shapes/shape-component-drag-data.ts
@@ -0,0 +1,92 @@
+import {
+ COMPONENT_DRAG_MIME_TYPE,
+ makeComponentDragData,
+ type ComponentDragData,
+ type ComponentProp,
+} from '@remotion/studio-shared';
+import type {ShapeName} from './shapes-info';
+
+const shapeDefaultProps: Record<ShapeName, readonly ComponentProp[]> = {
+ Arrow: [
+ {name: 'length', value: 300},
+ {name: 'headWidth', value: 185},
+ {name: 'headLength', value: 120},
+ {name: 'shaftWidth', value: 80},
+ {name: 'direction', value: 'right'},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Circle: [
+ {name: 'radius', value: 100},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Ellipse: [
+ {name: 'rx', value: 100},
+ {name: 'ry', value: 50},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Heart: [
+ {name: 'height', value: 100},
+ {name: 'aspectRatio', value: 1.1},
+ {name: 'bottomRoundnessAdjustment', value: 0},
+ {name: 'depthAdjustment', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Pie: [
+ {name: 'radius', value: 100},
+ {name: 'progress', value: 0.75},
+ {name: 'closePath', value: true},
+ {name: 'counterClockwise', value: false},
+ {name: 'rotation', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Polygon: [
+ {name: 'points', value: 5},
+ {name: 'radius', value: 100},
+ {name: 'cornerRadius', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Rect: [
+ {name: 'width', value: 100},
+ {name: 'height', value: 100},
+ {name: 'cornerRadius', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Star: [
+ {name: 'points', value: 5},
+ {name: 'innerRadius', value: 50},
+ {name: 'outerRadius', value: 100},
+ {name: 'cornerRadius', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ Triangle: [
+ {name: 'length', value: 100},
+ {name: 'direction', value: 'right'},
+ {name: 'cornerRadius', value: 0},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+};
+
+export const makeDefaultShapeComponentDragData = (
+ shape: ShapeName,
+): ComponentDragData => {
+ return makeComponentDragData({
+ componentName: shape,
+ importName: shape,
+ importPath: '@remotion/shapes',
+ props: [...shapeDefaultProps[shape]],
+ });
+};
+
+export const setComponentDragData = ({
+ dataTransfer,
+ dragData,
+}: {
+ readonly dataTransfer: DataTransfer;
+ readonly dragData: ComponentDragData;
+}) => {
+ const serialized = JSON.stringify(dragData);
+ dataTransfer.effectAllowed = 'copy';
+ dataTransfer.setData(COMPONENT_DRAG_MIME_TYPE, serialized);
+ dataTransfer.setData('application/json', serialized);
+ dataTransfer.setData('text/plain', serialized);
+};
diff --git a/packages/docs/components/shapes/shapes-info.tsx b/packages/docs/components/shapes/shapes-info.tsx
index 428780476d..90d4a9cdd6 100644
--- a/packages/docs/components/shapes/shapes-info.tsx
+++ b/packages/docs/components/shapes/shapes-info.tsx
@@ -10,6 +10,8 @@ import {
makeTriangle,
} from '@remotion/shapes';
import React from 'react';
+// eslint-disable-next-line no-restricted-imports
+import {AvailableFrom} from '../../src/components/AvailableFrom';
import {
DebugOption,
RectEdgeRoundness,
@@ -22,8 +24,19 @@ type Param = {
description: React.ReactNode;
};
+export type ShapeName =
+ | 'Arrow'
+ | 'Circle'
+ | 'Ellipse'
+ | 'Heart'
+ | 'Pie'
+ | 'Polygon'
+ | 'Rect'
+ | 'Star'
+ | 'Triangle';
+
export type ShapeComponent = {
- shape: string;
+ shape: ShapeName;
fn: (options: unknown) => unknown;
params: Param[];
};
@@ -308,8 +321,9 @@ const globalParams: Param[] = [
type: 'string',
description: (
<>
- CSS properties that will be applied to the <code>{'<svg>'}</code> tag.
- Default style: <code>{"overflow: 'visible'"}</code>
+ CSS properties that will be applied to the <code>{'<svg>'}</code> tag,
+ or to the generated <code>{'<canvas>'}</code> if <code>effects</code>{' '}
+ are passed. Default style: <code>{"overflow: 'visible'"}</code>
</>
),
},
@@ -347,6 +361,31 @@ const globalParams: Param[] = [
</>
),
},
+ {
+ name: 'effects',
+ type: 'EffectsProp',
+ description: (
+ <>
+ Apply <a href="/docs/effects/api">effects</a> after the shape has been
+ painted to a canvas. Available from v4.0.474. If this is a non-empty
+ array, the shape is wrapped in{' '}
+ <a href="/docs/remotion/html-in-canvas">
+ <code>{'<HtmlInCanvas>'}</code>
+ </a>
+ .
+ </>
+ ),
+ },
+ {
+ name: 'pixelDensity',
+ type: 'number',
+ description: (
+ <>
+ Controls the backing bitmap density when <code>effects</code> are
+ passed. Default: <code>1</code>. Available from v4.0.474.
+ </>
+ ),
+ },
];
export const ShapeOptions: React.FC<{
@@ -407,6 +446,33 @@ export const ShapeOptions: React.FC<{
) : null}
{all ? (
<>
+ <h3>
+ Inherited props
+ <AvailableFrom v="4.0.474" />
+ </h3>
+ <p>
+ <code>{`<${shapeComponent.shape}>`}</code> inherits{' '}
+ <a href="/docs/sequence#from">
+ <code>from</code>
+ </a>
+ ,{' '}
+ <a href="/docs/sequence#durationinframes">
+ <code>durationInFrames</code>
+ </a>
+ ,{' '}
+ <a href="/docs/sequence#name">
+ <code>name</code>
+ </a>
+ ,{' '}
+ <a href="/docs/sequence#showintimeline">
+ <code>showInTimeline</code>
+ </a>{' '}
+ and{' '}
+ <a href="/docs/sequence#hidden">
+ <code>hidden</code>
+ </a>{' '}
+ from <a href="/docs/sequence">{'<Sequence>'}</a>.
+ </p>
<h3>Other props</h3>{' '}
<p>
All other props that can be passed to a <code>{'<path>'}</code> are
diff --git a/packages/docs/docs/effects.mdx b/packages/docs/docs/effects.mdx
index 586e22f64e..d1b33276ff 100644
--- a/packages/docs/docs/effects.mdx
+++ b/packages/docs/docs/effects.mdx
@@ -21,6 +21,7 @@ The following components support effects:
- [`<AnimatedImage>`](/docs/animatedimage)
- [`<Gif>`](/docs/gif/gif)
- [`<RemotionRiveCanvas>`](/docs/rive/remotionrivecanvas)
+- [`@remotion/shapes` components](/docs/shapes)<AvailableFrom v="4.0.474" inline />
## Usage
diff --git a/packages/docs/docs/shapes/table-of-contents.tsx b/packages/docs/docs/shapes/table-of-contents.tsx
index d05ce2dfd4..d24150c595 100644
--- a/packages/docs/docs/shapes/table-of-contents.tsx
+++ b/packages/docs/docs/shapes/table-of-contents.tsx
@@ -1,4 +1,8 @@
import React from 'react';
+import {
+ makeDefaultShapeComponentDragData,
+ setComponentDragData,
+} from '../../components/shapes/shape-component-drag-data';
import {shapeComponents} from '../../components/shapes/shapes-info';
import {Grid} from '../../components/TableOfContents/Grid';
import {TOCItem} from '../../components/TableOfContents/TOCItem';
@@ -14,7 +18,17 @@ export const TableOfContents: React.FC = () => {
<strong>make{c.shape}()</strong>
<div>Generate SVG Path for a {c.shape.toLowerCase()}</div>
</TOCItem>
- <TOCItem link={'/docs/shapes/' + c.shape.toLowerCase()}>
+ <TOCItem
+ link={'/docs/shapes/' + c.shape.toLowerCase()}
+ draggable
+ onDragStart={(e) => {
+ setComponentDragData({
+ dataTransfer: e.dataTransfer,
+ dragData: makeDefaultShapeComponentDragData(c.shape),
+ });
+ }}
+ title="Drag this shape into Remotion Studio"
+ >
<strong>{'<' + c.shape + '/>'}</strong>
<div>Render a {c.shape.toLowerCase()}</div>
</TOCItem>
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 442d78cc4e..63444824ef 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -116,6 +116,7 @@ import {WidthHeightSequences} from './Sequence/WidthHeightSequences';
import CircleTest from './Shapes/CircleTest';
import EllipseTest from './Shapes/EllipseTest';
import RectTest from './Shapes/RectTest';
+import ShapeEffectsTest from './Shapes/ShapeEffectsTest';
import StarTest from './Shapes/StarTest';
import TriangleTest from './Shapes/TriangleTest';
import {SimpleImg} from './SimpleImg';
@@ -1866,6 +1867,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={150}
/>
+ <Composition
+ id="shape-effects-test"
+ component={ShapeEffectsTest}
+ width={1200}
+ height={630}
+ fps={30}
+ durationInFrames={150}
+ />
</Folder>
<Folder name="Rive">
<Composition
diff --git a/packages/example/src/Shapes/ShapeEffectsTest.tsx b/packages/example/src/Shapes/ShapeEffectsTest.tsx
new file mode 100644
index 0000000000..417164895e
--- /dev/null
+++ b/packages/example/src/Shapes/ShapeEffectsTest.tsx
@@ -0,0 +1,27 @@
+import {tint} from '@remotion/effects/tint';
+import {Circle} from '@remotion/shapes';
+import React from 'react';
+import {AbsoluteFill, usePixelDensity} from 'remotion';
+
+const ShapeEffectsTest: React.FC = () => {
+ const pixelDensity = usePixelDensity();
+
+ return (
+ <AbsoluteFill
+ style={{
+ alignItems: 'center',
+ backgroundColor: 'white',
+ justifyContent: 'center',
+ }}
+ >
+ <Circle
+ radius={160}
+ fill="#13c26b"
+ effects={[tint({color: '#8b5cf6', amount: 0.8})]}
+ pixelDensity={pixelDensity}
+ />
+ </AbsoluteFill>
+ );
+};
+
+export default ShapeEffectsTest;
diff --git a/packages/shapes/package.json b/packages/shapes/package.json
index 7af0641d78..290d3c086b 100644
--- a/packages/shapes/package.json
+++ b/packages/shapes/package.json
@@ -51,7 +51,8 @@
"react-dom": ">=16.8.0"
},
"dependencies": {
- "@remotion/paths": "workspace:*"
+ "@remotion/paths": "workspace:*",
+ "remotion": "workspace:*"
},
"homepage": "https://www.remotion.dev/docs/shapes"
}
diff --git a/packages/shapes/src/components/arrow.tsx b/packages/shapes/src/components/arrow.tsx
index aeaf472663..3fdc38f583 100644
--- a/packages/shapes/src/components/arrow.tsx
+++ b/packages/shapes/src/components/arrow.tsx
@@ -1,11 +1,46 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeArrowProps} from '../utils/make-arrow';
import {makeArrow} from '../utils/make-arrow';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {enumField, makeShapeSchema, numberField} from './schema';
export type ArrowProps = MakeArrowProps & AllShapesProps;
+const arrowSchema = makeShapeSchema({
+ length: numberField({
+ defaultValue: 300,
+ description: 'Length',
+ min: 0,
+ }),
+ headWidth: numberField({
+ defaultValue: 185,
+ description: 'Head Width',
+ min: 0,
+ }),
+ headLength: numberField({
+ defaultValue: 120,
+ description: 'Head Length',
+ min: 0,
+ }),
+ shaftWidth: numberField({
+ defaultValue: 80,
+ description: 'Shaft Width',
+ min: 0,
+ }),
+ direction: enumField({
+ defaultValue: 'right',
+ description: 'Direction',
+ variants: ['right', 'left', 'up', 'down'],
+ }),
+ cornerRadius: numberField({
+ defaultValue: 0,
+ description: 'Corner Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element containing an arrow shape.
* @param {Number} length The total length of the arrow along its direction axis. Default 300.
@@ -16,7 +51,7 @@ export type ArrowProps = MakeArrowProps & AllShapesProps;
* @param {Number} cornerRadius Rounds the corner using an arc. Similar to CSS's border-radius.
* @see [Documentation](https://www.remotion.dev/docs/shapes/arrow)
*/
-export const Arrow: React.FC<ArrowProps> = ({
+const ArrowInner: React.FC<ArrowProps> = ({
length,
headWidth,
headLength,
@@ -27,6 +62,8 @@ export const Arrow: React.FC<ArrowProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Arrow>"
+ documentationLink="https://www.remotion.dev/docs/shapes/arrow"
{...makeArrow({
length,
headWidth,
@@ -39,3 +76,11 @@ export const Arrow: React.FC<ArrowProps> = ({
/>
);
};
+
+export const Arrow = Internals.wrapInSchema({
+ Component: ArrowInner,
+ schema: arrowSchema,
+ supportsEffects: true,
+}) as React.FC<ArrowProps>;
+
+Internals.addSequenceStackTraces(Arrow);
diff --git a/packages/shapes/src/components/circle.tsx b/packages/shapes/src/components/circle.tsx
index efdace7d59..5a1e372d91 100644
--- a/packages/shapes/src/components/circle.tsx
+++ b/packages/shapes/src/components/circle.tsx
@@ -1,16 +1,41 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeCircleProps} from '../utils/make-circle';
import {makeCircle} from '../utils/make-circle';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type CircleProps = MakeCircleProps & AllShapesProps;
+const circleSchema = makeShapeSchema({
+ radius: numberField({
+ defaultValue: 100,
+ description: 'Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element drawing a circle.
* @param {Number} radius The radius of the circle.
* @see [Documentation](https://www.remotion.dev/docs/shapes/circle)
*/
-export const Circle: React.FC<CircleProps> = ({radius, ...props}) => {
- return <RenderSvg {...makeCircle({radius})} {...props} />;
+const CircleInner: React.FC<CircleProps> = ({radius, ...props}) => {
+ return (
+ <RenderSvg
+ defaultName="<Circle>"
+ documentationLink="https://www.remotion.dev/docs/shapes/circle"
+ {...makeCircle({radius})}
+ {...props}
+ />
+ );
};
+
+export const Circle = Internals.wrapInSchema({
+ Component: CircleInner,
+ schema: circleSchema,
+ supportsEffects: true,
+}) as React.FC<CircleProps>;
+
+Internals.addSequenceStackTraces(Circle);
diff --git a/packages/shapes/src/components/ellipse.tsx b/packages/shapes/src/components/ellipse.tsx
index a70dd5d479..5325a17870 100644
--- a/packages/shapes/src/components/ellipse.tsx
+++ b/packages/shapes/src/components/ellipse.tsx
@@ -1,11 +1,26 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeEllipseOptions} from '../utils/make-ellipse';
import {makeEllipse} from '../utils/make-ellipse';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type EllipseProps = MakeEllipseOptions & AllShapesProps;
+const ellipseSchema = makeShapeSchema({
+ rx: numberField({
+ defaultValue: 100,
+ description: 'X Radius',
+ min: 0,
+ }),
+ ry: numberField({
+ defaultValue: 50,
+ description: 'Y Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element drawing an ellipse.
* @param {Number} rx The radius of the ellipse on the X axis.
@@ -13,6 +28,21 @@ export type EllipseProps = MakeEllipseOptions & AllShapesProps;
* @see [Documentation](https://www.remotion.dev/docs/shapes/ellipse)
*/
-export const Ellipse: React.FC<EllipseProps> = ({rx, ry, ...props}) => {
- return <RenderSvg {...makeEllipse({rx, ry})} {...props} />;
+const EllipseInner: React.FC<EllipseProps> = ({rx, ry, ...props}) => {
+ return (
+ <RenderSvg
+ defaultName="<Ellipse>"
+ documentationLink="https://www.remotion.dev/docs/shapes/ellipse"
+ {...makeEllipse({rx, ry})}
+ {...props}
+ />
+ );
};
+
+export const Ellipse = Internals.wrapInSchema({
+ Component: EllipseInner,
+ schema: ellipseSchema,
+ supportsEffects: true,
+}) as React.FC<EllipseProps>;
+
+Internals.addSequenceStackTraces(Ellipse);
diff --git a/packages/shapes/src/components/heart.tsx b/packages/shapes/src/components/heart.tsx
index 3b1331bd0b..380186901d 100644
--- a/packages/shapes/src/components/heart.tsx
+++ b/packages/shapes/src/components/heart.tsx
@@ -1,17 +1,43 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeHeartProps} from '../utils/make-heart';
import {makeHeart} from '../utils/make-heart';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type HeartProps = MakeHeartProps & AllShapesProps;
+const heartSchema = makeShapeSchema({
+ height: numberField({
+ defaultValue: 100,
+ description: 'Height',
+ min: 0,
+ }),
+ aspectRatio: numberField({
+ defaultValue: 1.1,
+ description: 'Aspect Ratio',
+ min: 0,
+ step: 0.01,
+ }),
+ bottomRoundnessAdjustment: numberField({
+ defaultValue: 0,
+ description: 'Bottom Roundness Adjustment',
+ step: 0.01,
+ }),
+ depthAdjustment: numberField({
+ defaultValue: 0,
+ description: 'Depth Adjustment',
+ step: 0.01,
+ }),
+});
+
/**
* @description Renders an SVG element containing a heart.
* @param {Number} size The size of the heart.
* @see [Documentation](https://www.remotion.dev/docs/shapes/heart)
*/
-export const Heart: React.FC<HeartProps> = ({
+const HeartInner: React.FC<HeartProps> = ({
aspectRatio,
height,
bottomRoundnessAdjustment = 0,
@@ -20,6 +46,8 @@ export const Heart: React.FC<HeartProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Heart>"
+ documentationLink="https://www.remotion.dev/docs/shapes/heart"
{...makeHeart({
aspectRatio,
height,
@@ -30,3 +58,11 @@ export const Heart: React.FC<HeartProps> = ({
/>
);
};
+
+export const Heart = Internals.wrapInSchema({
+ Component: HeartInner,
+ schema: heartSchema,
+ supportsEffects: true,
+}) as React.FC<HeartProps>;
+
+Internals.addSequenceStackTraces(Heart);
diff --git a/packages/shapes/src/components/pie.tsx b/packages/shapes/src/components/pie.tsx
index 1873b3cea6..638f13c577 100644
--- a/packages/shapes/src/components/pie.tsx
+++ b/packages/shapes/src/components/pie.tsx
@@ -1,11 +1,41 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakePieProps} from '../utils/make-pie';
import {makePie} from '../utils/make-pie';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {booleanField, makeShapeSchema, numberField} from './schema';
export type PieProps = MakePieProps & AllShapesProps;
+const pieSchema = makeShapeSchema({
+ radius: numberField({
+ defaultValue: 100,
+ description: 'Radius',
+ min: 0,
+ }),
+ progress: numberField({
+ defaultValue: 0.5,
+ description: 'Progress',
+ max: 1,
+ min: 0,
+ step: 0.01,
+ }),
+ closePath: booleanField({
+ defaultValue: true,
+ description: 'Close Path',
+ }),
+ counterClockwise: booleanField({
+ defaultValue: false,
+ description: 'Counter Clockwise',
+ }),
+ rotation: numberField({
+ defaultValue: 0,
+ description: 'Rotation',
+ step: 0.01,
+ }),
+});
+
/**
* @description Renders an SVG element drawing a pie piece.
* @param {Number} radius The radius of the circle..
@@ -16,7 +46,7 @@ export type PieProps = MakePieProps & AllShapesProps;
* @see [Documentation](https://www.remotion.dev/docs/shapes/pie)
*/
-export const Pie: React.FC<PieProps> = ({
+const PieInner: React.FC<PieProps> = ({
radius,
progress,
closePath,
@@ -26,8 +56,18 @@ export const Pie: React.FC<PieProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Pie>"
+ documentationLink="https://www.remotion.dev/docs/shapes/pie"
{...makePie({radius, progress, closePath, counterClockwise, rotation})}
{...props}
/>
);
};
+
+export const Pie = Internals.wrapInSchema({
+ Component: PieInner,
+ schema: pieSchema,
+ supportsEffects: true,
+}) as React.FC<PieProps>;
+
+Internals.addSequenceStackTraces(Pie);
diff --git a/packages/shapes/src/components/polygon.tsx b/packages/shapes/src/components/polygon.tsx
index 6fce783682..790c1789d4 100644
--- a/packages/shapes/src/components/polygon.tsx
+++ b/packages/shapes/src/components/polygon.tsx
@@ -1,12 +1,33 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakePolygonProps} from '../utils/make-polygon';
import {makePolygon} from '../utils/make-polygon';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type PolygonProps = MakePolygonProps & Omit<AllShapesProps, 'points'>;
-export const Polygon: React.FC<PolygonProps> = ({
+const polygonSchema = makeShapeSchema({
+ points: numberField({
+ defaultValue: 5,
+ description: 'Points',
+ min: 3,
+ step: 1,
+ }),
+ radius: numberField({
+ defaultValue: 100,
+ description: 'Radius',
+ min: 0,
+ }),
+ cornerRadius: numberField({
+ defaultValue: 0,
+ description: 'Corner Radius',
+ min: 0,
+ }),
+});
+
+const PolygonInner: React.FC<PolygonProps> = ({
points,
radius,
cornerRadius,
@@ -15,6 +36,8 @@ export const Polygon: React.FC<PolygonProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Polygon>"
+ documentationLink="https://www.remotion.dev/docs/shapes/polygon"
{...makePolygon({
points,
cornerRadius,
@@ -25,3 +48,11 @@ export const Polygon: React.FC<PolygonProps> = ({
/>
);
};
+
+export const Polygon = Internals.wrapInSchema({
+ Component: PolygonInner,
+ schema: polygonSchema,
+ supportsEffects: true,
+}) as React.FC<PolygonProps>;
+
+Internals.addSequenceStackTraces(Polygon);
diff --git a/packages/shapes/src/components/rect.tsx b/packages/shapes/src/components/rect.tsx
index 5ea0c1adc7..d804d43dd1 100644
--- a/packages/shapes/src/components/rect.tsx
+++ b/packages/shapes/src/components/rect.tsx
@@ -1,11 +1,31 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeRectOptions} from '../utils/make-rect';
import {makeRect} from '../utils/make-rect';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type RectProps = MakeRectOptions & AllShapesProps;
+const rectSchema = makeShapeSchema({
+ width: numberField({
+ defaultValue: 100,
+ description: 'Width',
+ min: 0,
+ }),
+ height: numberField({
+ defaultValue: 100,
+ description: 'Height',
+ min: 0,
+ }),
+ cornerRadius: numberField({
+ defaultValue: 0,
+ description: 'Corner Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element containing a rectangle.
* @param {Number} width The width of the Rectangle
@@ -14,7 +34,7 @@ export type RectProps = MakeRectOptions & AllShapesProps;
* @param {null|Number} edgeRoundness Allows to modify the shape by rounding the edges using bezier curves. Default null.
* @see [Documentation](https://www.remotion.dev/docs/shapes/rect)
*/
-export const Rect: React.FC<RectProps> = ({
+const RectInner: React.FC<RectProps> = ({
width,
edgeRoundness,
height,
@@ -23,8 +43,18 @@ export const Rect: React.FC<RectProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Rect>"
+ documentationLink="https://www.remotion.dev/docs/shapes/rect"
{...makeRect({height, width, edgeRoundness, cornerRadius})}
{...props}
/>
);
};
+
+export const Rect = Internals.wrapInSchema({
+ Component: RectInner,
+ schema: rectSchema,
+ supportsEffects: true,
+}) as React.FC<RectProps>;
+
+Internals.addSequenceStackTraces(Rect);
diff --git a/packages/shapes/src/components/render-svg.tsx b/packages/shapes/src/components/render-svg.tsx
index 3e514e5aa6..d9ec1f7f6e 100644
--- a/packages/shapes/src/components/render-svg.tsx
+++ b/packages/shapes/src/components/render-svg.tsx
@@ -1,17 +1,42 @@
import type {Instruction} from '@remotion/paths';
-import React, {useMemo} from 'react';
+import React, {useCallback, useMemo, useRef} from 'react';
import {version} from 'react-dom';
+import {
+ HtmlInCanvas,
+ Internals,
+ Sequence,
+ type EffectsProp,
+ type HtmlInCanvasPixelDensity,
+ type SequenceControls,
+ type SequenceProps,
+} from 'remotion';
import {doesReactSupportTransformOriginProperty} from '../utils/does-react-support-canary';
-export type AllShapesProps = Omit<
- React.SVGProps<SVGPathElement>,
- 'width' | 'height' | 'd'
+type ShapeSequenceProps = Pick<
+ SequenceProps,
+ 'durationInFrames' | 'from' | 'hidden' | 'name' | 'showInTimeline'
> & {
- readonly debug?: boolean;
- readonly pathStyle?: React.CSSProperties;
+ readonly _experimentalControls?: SequenceControls;
};
+export type AllShapesProps = Omit<
+ React.SVGProps<SVGPathElement>,
+ 'width' | 'height' | 'd' | 'hidden' | 'name'
+> &
+ ShapeSequenceProps & {
+ readonly debug?: boolean;
+ readonly effects?: EffectsProp;
+ readonly pathStyle?: React.CSSProperties;
+ readonly pixelDensity?: HtmlInCanvasPixelDensity;
+ /**
+ * @deprecated For internal use only
+ */
+ readonly stack?: string;
+ };
+
export const RenderSvg = ({
+ defaultName,
+ documentationLink,
width,
height,
path,
@@ -19,9 +44,20 @@ export const RenderSvg = ({
pathStyle,
transformOrigin,
debug,
+ effects = [],
instructions,
+ pixelDensity,
+ durationInFrames,
+ from,
+ hidden,
+ name,
+ showInTimeline,
+ _experimentalControls: controls,
+ stack,
...props
}: {
+ readonly defaultName: string;
+ readonly documentationLink: string;
readonly width: number;
readonly height: number;
readonly path: string;
@@ -42,16 +78,34 @@ export const RenderSvg = ({
};
}, [pathStyle]);
+ const outlineRef = useRef<Element | null>(null);
+ const setSvgRef = useCallback((node: SVGSVGElement | null) => {
+ outlineRef.current = node;
+ }, []);
+
+ const setCanvasRef = useCallback((canvas: HTMLCanvasElement | null) => {
+ outlineRef.current = canvas;
+ }, []);
+
+ const memoizedEffectDefinitions =
+ Internals.useMemoizedEffectDefinitions(effects);
+ const videoConfig = Internals.useUnsafeVideoConfig();
+
const reactSupportsTransformOrigin =
doesReactSupportTransformOriginProperty(version);
- return (
+ const svg = (
<svg
+ ref={effects.length === 0 || !videoConfig ? setSvgRef : undefined}
width={width}
height={height}
viewBox={`0 0 ${width} ${height}`}
xmlns="http://www.w3.org/2000/svg"
- style={actualStyle}
+ style={
+ effects.length === 0 || !videoConfig
+ ? actualStyle
+ : {overflow: 'visible'}
+ }
>
<path
{...(reactSupportsTransformOrigin
@@ -129,4 +183,48 @@ export const RenderSvg = ({
: null}
</svg>
);
+
+ const content =
+ effects.length === 0 ? (
+ svg
+ ) : (
+ <HtmlInCanvas
+ ref={setCanvasRef}
+ width={Math.ceil(width)}
+ height={Math.ceil(height)}
+ effects={effects}
+ pixelDensity={pixelDensity}
+ showInTimeline={false}
+ style={actualStyle}
+ _experimentalControls={controls}
+ >
+ {svg}
+ </HtmlInCanvas>
+ );
+
+ const stackProps = stack === undefined ? null : ({stack} as const);
+
+ if (!videoConfig) {
+ return svg;
+ }
+
+ return (
+ <Sequence
+ layout="none"
+ from={from}
+ hidden={hidden}
+ showInTimeline={showInTimeline}
+ _experimentalControls={controls}
+ _remotionInternalEffects={memoizedEffectDefinitions}
+ durationInFrames={durationInFrames}
+ name={name ?? defaultName}
+ _remotionInternalRefForOutline={outlineRef}
+ _remotionInternalDocumentationLink={
+ name === undefined ? documentationLink : undefined
+ }
+ {...stackProps}
+ >
+ {content}
+ </Sequence>
+ );
};
diff --git a/packages/shapes/src/components/schema.ts b/packages/shapes/src/components/schema.ts
new file mode 100644
index 0000000000..791d0b5a9a
--- /dev/null
+++ b/packages/shapes/src/components/schema.ts
@@ -0,0 +1,94 @@
+import {
+ Internals,
+ type SequenceFieldSchema,
+ type SequenceSchema,
+} from 'remotion';
+
+export const numberField = ({
+ defaultValue,
+ description,
+ hiddenFromList = false,
+ max,
+ min,
+ step = 1,
+}: {
+ readonly defaultValue: number | undefined;
+ readonly description: string;
+ readonly hiddenFromList?: boolean;
+ readonly max?: number;
+ readonly min?: number;
+ readonly step?: number;
+}): SequenceFieldSchema => {
+ return {
+ type: 'number',
+ default: defaultValue,
+ description,
+ hiddenFromList,
+ max,
+ min,
+ step,
+ };
+};
+
+export const booleanField = ({
+ defaultValue,
+ description,
+}: {
+ readonly defaultValue: boolean;
+ readonly description: string;
+}): SequenceFieldSchema => {
+ return {
+ type: 'boolean',
+ default: defaultValue,
+ description,
+ };
+};
+
+export const colorField = ({
+ defaultValue,
+ description,
+}: {
+ readonly defaultValue: string | undefined;
+ readonly description: string;
+}): SequenceFieldSchema => {
+ return {
+ type: 'color',
+ default: defaultValue,
+ description,
+ };
+};
+
+export const enumField = <T extends string>({
+ defaultValue,
+ description,
+ variants,
+}: {
+ readonly defaultValue: T;
+ readonly description: string;
+ readonly variants: readonly T[];
+}): SequenceFieldSchema => {
+ return {
+ type: 'enum',
+ default: defaultValue,
+ description,
+ variants: Object.fromEntries(
+ variants.map((variant) => [variant, {}]),
+ ) as Record<T, SequenceSchema>,
+ };
+};
+
+export const makeShapeSchema = (
+ shapeFields: SequenceSchema,
+): SequenceSchema => {
+ return {
+ from: Internals.sequenceSchema.from,
+ durationInFrames: Internals.sequenceSchema.durationInFrames,
+ ...shapeFields,
+ fill: colorField({
+ defaultValue: '#0b84ff',
+ description: 'Fill',
+ }),
+ ...Internals.sequenceVisualStyleSchema,
+ hidden: Internals.sequenceSchema.hidden,
+ };
+};
diff --git a/packages/shapes/src/components/star.tsx b/packages/shapes/src/components/star.tsx
index 83f10eefb7..be2b130669 100644
--- a/packages/shapes/src/components/star.tsx
+++ b/packages/shapes/src/components/star.tsx
@@ -1,11 +1,37 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeStarProps} from '../utils/make-star';
import {makeStar} from '../utils/make-star';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {makeShapeSchema, numberField} from './schema';
export type StarProps = MakeStarProps & Omit<AllShapesProps, 'points'>;
+const starSchema = makeShapeSchema({
+ points: numberField({
+ defaultValue: 5,
+ description: 'Points',
+ min: 3,
+ step: 1,
+ }),
+ innerRadius: numberField({
+ defaultValue: 50,
+ description: 'Inner Radius',
+ min: 0,
+ }),
+ outerRadius: numberField({
+ defaultValue: 100,
+ description: 'Outer Radius',
+ min: 0,
+ }),
+ cornerRadius: numberField({
+ defaultValue: 0,
+ description: 'Corner Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element containing a star.
* @param {Number} innerRadius The inner radius of the star.
@@ -16,7 +42,7 @@ export type StarProps = MakeStarProps & Omit<AllShapesProps, 'points'>;
* @see [Documentation](https://www.remotion.dev/docs/shapes/star)
*/
-export const Star: React.FC<StarProps> = ({
+const StarInner: React.FC<StarProps> = ({
innerRadius,
outerRadius,
points,
@@ -26,6 +52,8 @@ export const Star: React.FC<StarProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Star>"
+ documentationLink="https://www.remotion.dev/docs/shapes/star"
{...makeStar({
innerRadius,
outerRadius,
@@ -37,3 +65,11 @@ export const Star: React.FC<StarProps> = ({
/>
);
};
+
+export const Star = Internals.wrapInSchema({
+ Component: StarInner,
+ schema: starSchema,
+ supportsEffects: true,
+}) as React.FC<StarProps>;
+
+Internals.addSequenceStackTraces(Star);
diff --git a/packages/shapes/src/components/triangle.tsx b/packages/shapes/src/components/triangle.tsx
index eb50359dc1..f39e4aab5c 100644
--- a/packages/shapes/src/components/triangle.tsx
+++ b/packages/shapes/src/components/triangle.tsx
@@ -1,11 +1,31 @@
import React from 'react';
+import {Internals} from 'remotion';
import type {MakeTriangleProps} from '../utils/make-triangle';
import {makeTriangle} from '../utils/make-triangle';
import type {AllShapesProps} from './render-svg';
import {RenderSvg} from './render-svg';
+import {enumField, makeShapeSchema, numberField} from './schema';
export type TriangleProps = MakeTriangleProps & AllShapesProps;
+const triangleSchema = makeShapeSchema({
+ length: numberField({
+ defaultValue: 100,
+ description: 'Length',
+ min: 0,
+ }),
+ direction: enumField({
+ defaultValue: 'right',
+ description: 'Direction',
+ variants: ['right', 'left', 'up', 'down'],
+ }),
+ cornerRadius: numberField({
+ defaultValue: 0,
+ description: 'Corner Radius',
+ min: 0,
+ }),
+});
+
/**
* @description Renders an SVG element containing a triangle with same length on all sides.
* @param {Number} length The length of one triangle side.
@@ -14,7 +34,7 @@ export type TriangleProps = MakeTriangleProps & AllShapesProps;
* @param {Number} cornerRadius Rounds the corner using an arc. Similar to CSS's border-radius. Cannot be used together with edgeRoundness.
* @see [Documentation](https://www.remotion.dev/docs/shapes/triangle)
*/
-export const Triangle: React.FC<TriangleProps> = ({
+const TriangleInner: React.FC<TriangleProps> = ({
length,
direction,
edgeRoundness,
@@ -23,8 +43,18 @@ export const Triangle: React.FC<TriangleProps> = ({
}) => {
return (
<RenderSvg
+ defaultName="<Triangle>"
+ documentationLink="https://www.remotion.dev/docs/shapes/triangle"
{...makeTriangle({length, direction, edgeRoundness, cornerRadius})}
{...props}
/>
);
};
+
+export const Triangle = Internals.wrapInSchema({
+ Component: TriangleInner,
+ schema: triangleSchema,
+ supportsEffects: true,
+}) as React.FC<TriangleProps>;
+
+Internals.addSequenceStackTraces(Triangle);
diff --git a/packages/shapes/src/test/effects.test.tsx b/packages/shapes/src/test/effects.test.tsx
new file mode 100644
index 0000000000..a16dca4f30
--- /dev/null
+++ b/packages/shapes/src/test/effects.test.tsx
@@ -0,0 +1,277 @@
+import {expect, mock, test} from 'bun:test';
+import React from 'react';
+import type {EffectsProp, HtmlInCanvasPixelDensity} from 'remotion';
+import {render} from './test-utils';
+
+type HtmlInCanvasCall = {
+ readonly width: number;
+ readonly height: number;
+ readonly effects: EffectsProp;
+ readonly pixelDensity: HtmlInCanvasPixelDensity | undefined;
+ readonly showInTimeline: boolean | undefined;
+ readonly style: React.CSSProperties | undefined;
+ readonly _experimentalControls: unknown;
+};
+
+type SequenceCall = {
+ readonly layout: string | undefined;
+ readonly from: number | undefined;
+ readonly durationInFrames: number | undefined;
+ readonly hidden: boolean | undefined;
+ readonly name: string | undefined;
+ readonly showInTimeline: boolean | undefined;
+ readonly _experimentalControls: unknown;
+ readonly _remotionInternalDocumentationLink: string | undefined;
+ readonly _remotionInternalEffects: unknown;
+ readonly _remotionInternalRefForOutline:
+ | React.RefObject<Element | null>
+ | undefined;
+ readonly stack: string | undefined;
+};
+
+const htmlInCanvasCalls: HtmlInCanvasCall[] = [];
+const sequenceCalls: SequenceCall[] = [];
+const stackTraceComponents: unknown[] = [];
+const effectDefinitions = [{type: 'effect-definition'}];
+let hasVideoConfig = true;
+const addSequenceStackTraces = mock((component: unknown) => {
+ stackTraceComponents.push(component);
+});
+
+mock.module('remotion', () => {
+ return {
+ HtmlInCanvas: ({
+ children,
+ width,
+ height,
+ effects,
+ pixelDensity,
+ showInTimeline,
+ style,
+ _experimentalControls,
+ ref,
+ }: HtmlInCanvasCall & {
+ readonly children: React.ReactNode;
+ readonly ref?: React.Ref<HTMLCanvasElement>;
+ }) => {
+ htmlInCanvasCalls.push({
+ width,
+ height,
+ effects,
+ pixelDensity,
+ showInTimeline,
+ style,
+ _experimentalControls,
+ });
+
+ return (
+ <canvas
+ ref={ref}
+ data-height={height}
+ data-testid="html-in-canvas"
+ data-width={width}
+ >
+ {children}
+ </canvas>
+ );
+ },
+ Internals: {
+ addSequenceStackTraces,
+ CanUseRemotionHooks: React.createContext(true),
+ CompositionManagerProvider: ({
+ children,
+ }: {
+ readonly children: React.ReactNode;
+ }) => children,
+ RemotionRootContexts: ({
+ children,
+ }: {
+ readonly children: React.ReactNode;
+ }) => children,
+ ResolveCompositionContext: React.createContext({}),
+ sequenceSchema: {
+ durationInFrames: {},
+ from: {},
+ hidden: {},
+ },
+ sequenceVisualStyleSchema: {},
+ useUnsafeVideoConfig: mock(() =>
+ hasVideoConfig
+ ? {
+ id: 'shape-test',
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ durationInFrames: 100,
+ defaultProps: {},
+ props: {},
+ defaultCodec: null,
+ defaultOutName: null,
+ defaultVideoImageFormat: null,
+ defaultPixelFormat: null,
+ defaultProResProfile: null,
+ defaultSampleRate: null,
+ }
+ : null,
+ ),
+ useMemoizedEffectDefinitions: mock(() => effectDefinitions),
+ wrapInSchema: mock(({Component}) => Component),
+ },
+ Sequence: ({
+ children,
+ ...props
+ }: SequenceCall & {
+ readonly children: React.ReactNode;
+ }) => {
+ sequenceCalls.push(props);
+
+ return <div data-testid="sequence">{children}</div>;
+ },
+ };
+});
+
+const loadComponents = async () => {
+ const [{Circle}, {Rect}] = await Promise.all([
+ import('../components/circle'),
+ import('../components/rect'),
+ ]);
+
+ return {Circle, Rect};
+};
+
+const effect = {} as EffectsProp[number];
+
+test('Should render a shape with effects in HtmlInCanvas', async () => {
+ const {Circle} = await loadComponents();
+ hasVideoConfig = true;
+ htmlInCanvasCalls.length = 0;
+ sequenceCalls.length = 0;
+
+ const {container} = render(
+ <Circle
+ radius={100}
+ fill="green"
+ stroke="red"
+ strokeWidth={1}
+ effects={[effect]}
+ pixelDensity={2}
+ style={{opacity: 0.5}}
+ />,
+ );
+
+ expect(container.querySelector('[data-testid="html-in-canvas"]')).not.toBe(
+ null,
+ );
+ expect(container.querySelector('svg')).not.toBe(null);
+ expect(container.querySelector('path')?.getAttribute('fill')).toBe('green');
+ expect(htmlInCanvasCalls).toEqual([
+ expect.objectContaining({
+ width: 200,
+ height: 200,
+ effects: [effect],
+ pixelDensity: 2,
+ showInTimeline: false,
+ style: {
+ overflow: 'visible',
+ opacity: 0.5,
+ },
+ }),
+ ]);
+ expect(htmlInCanvasCalls[0]._experimentalControls ?? null).toBe(null);
+ expect(sequenceCalls[0]).toMatchObject({
+ layout: 'none',
+ name: '<Circle>',
+ _remotionInternalDocumentationLink:
+ 'https://www.remotion.dev/docs/shapes/circle',
+ _remotionInternalEffects: effectDefinitions,
+ });
+ expect(
+ sequenceCalls[0]._remotionInternalRefForOutline?.current?.tagName,
+ ).toBe('CANVAS');
+});
+
+test('Should keep rendering SVG directly with no effects', async () => {
+ const {Circle} = await loadComponents();
+ hasVideoConfig = true;
+ htmlInCanvasCalls.length = 0;
+ sequenceCalls.length = 0;
+
+ const {container} = render(
+ <Circle
+ radius={100}
+ fill="green"
+ stroke="red"
+ effects={[]}
+ from={12}
+ durationInFrames={23}
+ showInTimeline={false}
+ />,
+ );
+
+ expect(container.querySelector('[data-testid="html-in-canvas"]')).toBe(null);
+ expect(container.querySelector('svg')).not.toBe(null);
+ expect(htmlInCanvasCalls).toEqual([]);
+ expect(sequenceCalls[0]).toMatchObject({
+ durationInFrames: 23,
+ from: 12,
+ layout: 'none',
+ name: '<Circle>',
+ showInTimeline: false,
+ _remotionInternalDocumentationLink:
+ 'https://www.remotion.dev/docs/shapes/circle',
+ });
+ expect(
+ sequenceCalls[0]._remotionInternalRefForOutline?.current?.tagName,
+ ).toBe('svg');
+});
+
+test('Should pass integer dimensions to HtmlInCanvas', async () => {
+ const {Rect} = await loadComponents();
+ hasVideoConfig = true;
+ htmlInCanvasCalls.length = 0;
+
+ render(<Rect width={10.1} height={20.2} effects={[effect]} />);
+
+ expect(htmlInCanvasCalls[0].width).toBe(11);
+ expect(htmlInCanvasCalls[0].height).toBe(21);
+});
+
+test('Should forward stack to the shape Sequence', async () => {
+ const {Circle} = await loadComponents();
+ hasVideoConfig = true;
+ htmlInCanvasCalls.length = 0;
+ sequenceCalls.length = 0;
+
+ render(<Circle radius={100} effects={[effect]} stack="shape-stack" />);
+
+ expect(htmlInCanvasCalls[0]).not.toBe(undefined);
+ expect(sequenceCalls[0].stack).toBe('shape-stack');
+});
+
+test('Should not add a documentation link if a custom name is passed', async () => {
+ const {Circle} = await loadComponents();
+ hasVideoConfig = true;
+ sequenceCalls.length = 0;
+
+ render(<Circle radius={100} name="Custom circle" />);
+
+ expect(sequenceCalls[0].name).toBe('Custom circle');
+ expect(sequenceCalls[0]._remotionInternalDocumentationLink).toBe(undefined);
+});
+
+test('Should render SVG without Sequence outside a Remotion video config', async () => {
+ const {Rect} = await loadComponents();
+ hasVideoConfig = false;
+ htmlInCanvasCalls.length = 0;
+ sequenceCalls.length = 0;
+
+ const {container} = render(
+ <Rect width={100} height={50} fill="red" style={{opacity: 0.5}} />,
+ );
+
+ expect(container.querySelector('svg')).not.toBe(null);
+ expect(container.querySelector('svg')?.style.opacity).toBe('0.5');
+ expect(container.querySelector('path')?.getAttribute('fill')).toBe('red');
+ expect(htmlInCanvasCalls).toEqual([]);
+ expect(sequenceCalls).toEqual([]);
+});
diff --git a/packages/shapes/src/test/schema.test.ts b/packages/shapes/src/test/schema.test.ts
new file mode 100644
index 0000000000..b08516b917
--- /dev/null
+++ b/packages/shapes/src/test/schema.test.ts
@@ -0,0 +1,10 @@
+import {expect, test} from 'bun:test';
+import {makeShapeSchema} from '../components/schema';
+
+test('adds a fill control to shape schemas', () => {
+ expect(makeShapeSchema({}).fill).toEqual({
+ type: 'color',
+ default: '#0b84ff',
+ description: 'Fill',
+ });
+});
diff --git a/packages/shapes/src/test/test-utils.tsx b/packages/shapes/src/test/test-utils.tsx
index bae81ef8b6..3b45d295e1 100644
--- a/packages/shapes/src/test/test-utils.tsx
+++ b/packages/shapes/src/test/test-utils.tsx
@@ -1,6 +1,53 @@
import type {queries, RenderOptions} from '@testing-library/react';
import {render, screen} from '@testing-library/react';
import type {FC, ReactElement} from 'react';
+import {Internals} from 'remotion';
+
+const videoConfig = {
+ defaultCodec: null,
+ defaultOutName: null,
+ defaultPixelFormat: null,
+ defaultProps: {},
+ defaultProResProfile: null,
+ defaultSampleRate: null,
+ defaultVideoImageFormat: null,
+ durationInFrames: 100,
+ fps: 30,
+ height: 1080,
+ id: 'shape-test',
+ props: {},
+ width: 1920,
+};
+
+const initialCanvasContent = {
+ compositionId: 'shape-test',
+ type: 'composition' as const,
+};
+
+const initialCompositions = [
+ {
+ calculateMetadata: null,
+ component: () => null,
+ defaultProps: {},
+ durationInFrames: 100,
+ folderName: null,
+ fps: 30,
+ height: 1080,
+ id: 'shape-test',
+ nonce: [[0, 0] as [number, number]],
+ parentFolderName: null,
+ schema: null,
+ stack: null,
+ width: 1920,
+ },
+];
+
+const resolveCompositionContext = {
+ 'shape-test': {
+ result: videoConfig,
+ type: 'success' as const,
+ },
+};
const AllTheProviders: FC<{
readonly children: React.ReactNode;
@@ -8,7 +55,32 @@ const AllTheProviders: FC<{
// overwriting console.error console does not gets poluted with all the errors
window.console.error = () => {};
- return <div>{children}</div>;
+ return (
+ <Internals.CompositionManagerProvider
+ currentCompositionMetadata={videoConfig}
+ initialCanvasContent={initialCanvasContent}
+ initialCompositions={initialCompositions}
+ onlyRenderComposition="shape-test"
+ >
+ <Internals.RemotionRootContexts
+ audioEnabled
+ audioLatencyHint="interactive"
+ frameState={null}
+ logLevel="info"
+ numberOfAudioTags={0}
+ previewSampleRate={null}
+ videoEnabled
+ >
+ <Internals.CanUseRemotionHooks.Provider value>
+ <Internals.ResolveCompositionContext.Provider
+ value={resolveCompositionContext}
+ >
+ <div>{children}</div>
+ </Internals.ResolveCompositionContext.Provider>
+ </Internals.CanUseRemotionHooks.Provider>
+ </Internals.RemotionRootContexts>
+ </Internals.CompositionManagerProvider>
+ );
};
const customRender = (
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index db90469a01..74126e62d1 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -15,6 +15,7 @@ import type {
} from '@babel/types';
import {
isUrl,
+ type ComponentProp,
type InsertableCompositionElement,
} from '@remotion/studio-shared';
import type {namedTypes} from 'ast-types';
@@ -736,6 +737,28 @@ const createNumberAttribute = (
);
};
+const createStringAttribute = (
+ name: string,
+ value: string,
+): namedTypes.JSXAttribute => {
+ return recast.types.builders.jsxAttribute(
+ recast.types.builders.jsxIdentifier(name),
+ recast.types.builders.stringLiteral(value),
+ );
+};
+
+const createBooleanAttribute = (
+ name: string,
+ value: boolean,
+): namedTypes.JSXAttribute => {
+ return recast.types.builders.jsxAttribute(
+ recast.types.builders.jsxIdentifier(name),
+ recast.types.builders.jsxExpressionContainer(
+ recast.types.builders.booleanLiteral(value),
+ ),
+ );
+};
+
const createPositionAbsoluteStyleAttribute = (): namedTypes.JSXAttribute => {
return recast.types.builders.jsxAttribute(
recast.types.builders.jsxIdentifier('style'),
@@ -768,6 +791,21 @@ const createStaticFileSrcAttribute = ({
);
};
+const createComponentProp = ({
+ name,
+ value,
+}: ComponentProp): namedTypes.JSXAttribute => {
+ if (typeof value === 'number') {
+ return createNumberAttribute(name, value);
+ }
+
+ if (typeof value === 'boolean') {
+ return createBooleanAttribute(name, value);
+ }
+
+ return createStringAttribute(name, value);
+};
+
const createStringSrcAttribute = (src: string): namedTypes.JSXAttribute => {
return recast.types.builders.jsxAttribute(
recast.types.builders.jsxIdentifier('src'),
@@ -799,6 +837,27 @@ const createSolidElement = ({
);
};
+const createComponentElement = ({
+ localName,
+ props,
+}: {
+ localName: string;
+ props: ComponentProp[];
+}): namedTypes.JSXElement => {
+ return recast.types.builders.jsxElement(
+ recast.types.builders.jsxOpeningElement(
+ recast.types.builders.jsxIdentifier(localName),
+ [
+ ...props.map(createComponentProp),
+ createPositionAbsoluteStyleAttribute(),
+ ],
+ true,
+ ),
+ null,
+ [],
+ );
+};
+
const createAssetElement = ({
localName,
staticFileLocalName,
@@ -1129,6 +1188,67 @@ const ensureGifImport = (ast: File) => {
});
};
+const hasComponentLocalImport = ({
+ ast,
+ importName,
+ importPath,
+}: {
+ ast: File;
+ importName: string;
+ importPath: string;
+}) => {
+ for (const importDeclaration of getImportDeclarations({
+ ast,
+ sourcePath: importPath,
+ })) {
+ for (const specifier of importDeclaration.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ getImportedName(specifier) === importName
+ ) {
+ return specifier.local?.name ?? importName;
+ }
+ }
+ }
+
+ return null;
+};
+
+const ensureComponentImport = ({
+ ast,
+ componentName,
+ importName,
+ importPath,
+}: {
+ ast: File;
+ componentName: string;
+ importName: string;
+ importPath: string;
+}) => {
+ const existingLocalName = hasComponentLocalImport({
+ ast,
+ importName,
+ importPath,
+ });
+
+ if (existingLocalName) {
+ return existingLocalName;
+ }
+
+ if (hasTopLevelBinding({ast, name: componentName})) {
+ throw new Error(
+ `Cannot add <${componentName}> because ${componentName} is already defined`,
+ );
+ }
+
+ return ensureNamedImport({
+ ast,
+ importedName: importName,
+ sourcePath: importPath,
+ localName: componentName,
+ });
+};
+
const addElementToComponentRoot = ({
ast,
exportName,
@@ -1453,6 +1573,20 @@ const createInsertableJsxElement = ({
});
}
+ if (element.type === 'component') {
+ const componentLocalName = ensureComponentImport({
+ ast,
+ componentName: element.componentName,
+ importName: element.importName,
+ importPath: element.importPath,
+ });
+
+ return createComponentElement({
+ localName: componentLocalName,
+ props: element.props,
+ });
+ }
+
if (element.type === 'asset') {
if (element.srcType === 'remote' && !isUrl(element.src)) {
throw new Error('Remote asset source must be a URL');
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 9073cc45dd..a0e1399c1b 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
@@ -1,5 +1,8 @@
import {RenderInternals} from '@remotion/renderer';
import {
+ areComponentProps,
+ isComponentIdentifier,
+ isComponentImportPath,
isUrl,
type InsertJsxElementRequest,
type InsertJsxElementResponse,
@@ -47,6 +50,26 @@ const validateElement = (element: InsertableCompositionElement) => {
return;
}
+ if (element.type === 'component') {
+ if (!isComponentIdentifier(element.componentName)) {
+ throw new Error('Unsupported component name');
+ }
+
+ if (!isComponentIdentifier(element.importName)) {
+ throw new Error('Unsupported component import name');
+ }
+
+ if (!isComponentImportPath(element.importPath)) {
+ throw new Error('Unsupported component import path');
+ }
+
+ if (!areComponentProps(element.props)) {
+ throw new Error('Unsupported component props');
+ }
+
+ return;
+ }
+
throw new Error('Unsupported element type');
};
@@ -73,6 +96,10 @@ const getElementLabel = (element: InsertableCompositionElement) => {
}
}
+ if (element.type === 'component') {
+ return `<${element.componentName}>`;
+ }
+
throw new Error('Unsupported element type');
};
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 515e964e69..d0151a282c 100644
--- a/packages/studio-server/src/test/resolve-composition-component.test.ts
+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts
@@ -967,3 +967,60 @@ test('rejects inserting an Audio asset if Audio is already defined', async () =>
await fs.rm(tempDir, {recursive: true, force: true});
}
});
+
+test('inserts a component into the resolved composition component', 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: 'component',
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [
+ {name: 'fill', value: '#0b84ff'},
+ {name: 'dataShapeIndex', value: 1},
+ {name: 'debug', value: false},
+ ],
+ },
+ prettierConfigOverride: {singleQuote: true, useTabs: true},
+ });
+
+ expect(result.output).toContain(
+ "import { Circle } from '@remotion/shapes';",
+ );
+ expect(result.output).toContain('<Circle');
+ expect(result.output).toContain('fill="#0b84ff"');
+ expect(result.output).toContain('dataShapeIndex={1}');
+ expect(result.output).toContain('debug={false}');
+ expect(result.output).toContain("position: 'absolute'");
+ } finally {
+ await fs.rm(tempDir, {recursive: true, force: true});
+ }
+});
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 489b63d6b1..3a676c6339 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -23,6 +23,7 @@ import type {
SequenceSchema,
} from 'remotion';
import type {RecastCodemod, VisualControlChange} from './codemods';
+import type {ComponentProp} from './component-drag-data';
import type {
EffectClipboardParam,
EffectClipboardPasteType,
@@ -599,6 +600,13 @@ export type InsertableCompositionElement =
width: number;
height: number;
}
+ | {
+ type: 'component';
+ componentName: string;
+ importName: string;
+ importPath: string;
+ props: ComponentProp[];
+ }
| {
type: 'asset';
assetType: 'image' | 'video' | 'gif' | 'audio';
diff --git a/packages/studio-shared/src/component-drag-data.ts b/packages/studio-shared/src/component-drag-data.ts
new file mode 100644
index 0000000000..d64af4d7da
--- /dev/null
+++ b/packages/studio-shared/src/component-drag-data.ts
@@ -0,0 +1,144 @@
+export const COMPONENT_DRAG_MIME_TYPE =
+ 'application/vnd.remotion.component+json';
+
+export type ComponentProp = {
+ name: string;
+ value: string | number | boolean;
+};
+
+export type ComponentDragData = {
+ type: 'remotion-component';
+ version: 1;
+ component: {
+ componentName: string;
+ importName: string;
+ importPath: string;
+ props: ComponentProp[];
+ };
+};
+
+const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+};
+
+export const isComponentIdentifier = (value: unknown): value is string => {
+ return typeof value === 'string' && /^[A-Z_$][A-Za-z0-9_$]*$/.test(value);
+};
+
+export const isComponentImportPath = (value: unknown): value is string => {
+ return (
+ typeof value === 'string' &&
+ value.length > 0 &&
+ value.length < 200 &&
+ !value.includes('\\') &&
+ !value.includes('\0') &&
+ !value.startsWith('/') &&
+ /^[A-Za-z0-9@._/-]+$/.test(value)
+ );
+};
+
+export const isComponentPropName = (value: unknown): value is string => {
+ return (
+ typeof value === 'string' &&
+ value !== 'style' &&
+ /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value)
+ );
+};
+
+export const isComponentProp = (value: unknown): value is ComponentProp => {
+ if (!isRecord(value)) {
+ return false;
+ }
+
+ if (!isComponentPropName(value.name)) {
+ return false;
+ }
+
+ return (
+ typeof value.value === 'string' ||
+ typeof value.value === 'boolean' ||
+ (typeof value.value === 'number' && Number.isFinite(value.value))
+ );
+};
+
+export const areComponentProps = (value: unknown): value is ComponentProp[] => {
+ if (!Array.isArray(value)) {
+ return false;
+ }
+
+ const seen = new Set<string>();
+ for (const prop of value) {
+ if (!isComponentProp(prop) || seen.has(prop.name)) {
+ return false;
+ }
+
+ seen.add(prop.name);
+ }
+
+ return true;
+};
+
+export const makeComponentDragData = ({
+ componentName,
+ importName,
+ importPath,
+ props,
+}: {
+ componentName: string;
+ importName: string;
+ importPath: string;
+ props: ComponentProp[];
+}): ComponentDragData => {
+ return {
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName,
+ importName,
+ importPath,
+ props,
+ },
+ };
+};
+
+export const parseComponentDragData = (
+ value: string,
+): ComponentDragData | null => {
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (!isRecord(parsed)) {
+ return null;
+ }
+
+ if (parsed.type !== 'remotion-component' || parsed.version !== 1) {
+ return null;
+ }
+
+ if (!isRecord(parsed.component)) {
+ return null;
+ }
+
+ const {componentName, importName, importPath, props} = parsed.component;
+ if (
+ !isComponentIdentifier(componentName) ||
+ !isComponentIdentifier(importName) ||
+ !isComponentImportPath(importPath) ||
+ !areComponentProps(props)
+ ) {
+ return null;
+ }
+
+ return {
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName,
+ importName,
+ importPath,
+ props,
+ },
+ };
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 00e9e790d2..dbd8c3ce20 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -100,6 +100,16 @@ export {
type AssetDragData,
} from './asset-drag-data';
export type {ApplyVisualControlCodemod, RecastCodemod} from './codemods';
+export {
+ COMPONENT_DRAG_MIME_TYPE,
+ areComponentProps,
+ isComponentIdentifier,
+ isComponentImportPath,
+ makeComponentDragData,
+ parseComponentDragData,
+ type ComponentDragData,
+ type ComponentProp,
+} from './component-drag-data';
export {DEFAULT_BUFFER_STATE_DELAY_IN_MILLISECONDS} from './default-buffer-state-delay-in-milliseconds';
export {
detectFileType,
@@ -197,11 +207,6 @@ export {
getEffectFieldsToShow,
getFieldsToShow,
} from './schema-field-info';
-export {
- SFX_DRAG_MIME_TYPE,
- parseSfxDragData,
- type SfxDragData,
-} from './sfx-drag-data';
export type {
AnySchemaFieldInfo,
DragOverrides,
@@ -211,6 +216,11 @@ export type {
SequenceControls,
SequenceSchemaFieldInfo,
} from './schema-field-info';
+export {
+ SFX_DRAG_MIME_TYPE,
+ parseSfxDragData,
+ type SfxDragData,
+} from './sfx-drag-data';
export {
ScriptLine,
SomeStackFrame,
@@ -236,8 +246,8 @@ export {
optimisticMoveSequenceKeyframes,
type OptimisticKeyframeMove,
} from './optimistic-move-keyframe';
-export {optimisticUpdateForPropStatuses} from './optimistic-update-for-prop-statuses';
export {optimisticUpdateForEffectPropStatuses} from './optimistic-update-for-effect-prop-statuses';
+export {optimisticUpdateForPropStatuses} from './optimistic-update-for-prop-statuses';
export {
optimisticUpdateEffectKeyframeSettings,
optimisticUpdateSequenceKeyframeSettings,
diff --git a/packages/studio-shared/src/required-package.ts b/packages/studio-shared/src/required-package.ts
index 8a122959d4..af969e4343 100644
--- a/packages/studio-shared/src/required-package.ts
+++ b/packages/studio-shared/src/required-package.ts
@@ -1,5 +1,21 @@
import type {InsertableCompositionElement} from './api-requests';
+export const getRequiredPackageForImportPath = (
+ importPath: string,
+): string | null => {
+ if (importPath === 'remotion' || importPath.startsWith('.')) {
+ return null;
+ }
+
+ if (importPath.startsWith('@')) {
+ const [scope, scopedPackageName] = importPath.split('/');
+ return scope && scopedPackageName ? `${scope}/${scopedPackageName}` : null;
+ }
+
+ const [packageName] = importPath.split('/');
+ return packageName || null;
+};
+
export const getRequiredPackageForInsertableElement = (
element: InsertableCompositionElement,
): string | null => {
@@ -7,6 +23,10 @@ export const getRequiredPackageForInsertableElement = (
return null;
}
+ if (element.type === 'component') {
+ return getRequiredPackageForImportPath(element.importPath);
+ }
+
if (element.assetType === 'video' || element.assetType === 'audio') {
return '@remotion/media';
}
diff --git a/packages/studio-shared/src/test/component-drag-data.test.ts b/packages/studio-shared/src/test/component-drag-data.test.ts
new file mode 100644
index 0000000000..8358047ca0
--- /dev/null
+++ b/packages/studio-shared/src/test/component-drag-data.test.ts
@@ -0,0 +1,113 @@
+import {expect, test} from 'bun:test';
+import {
+ makeComponentDragData,
+ parseComponentDragData,
+} from '../component-drag-data';
+
+test('parses component drag data', () => {
+ expect(
+ parseComponentDragData(
+ JSON.stringify(
+ makeComponentDragData({
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [
+ {name: 'radius', value: 100},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ }),
+ ),
+ ),
+ ).toEqual({
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [
+ {name: 'radius', value: 100},
+ {name: 'fill', value: '#0b84ff'},
+ ],
+ },
+ });
+});
+
+test('rejects invalid component drag data', () => {
+ expect(parseComponentDragData('')).toBe(null);
+ expect(parseComponentDragData('{')).toBe(null);
+ expect(
+ parseComponentDragData(
+ JSON.stringify({
+ type: 'remotion-component',
+ version: 2,
+ component: {
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ },
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseComponentDragData(
+ JSON.stringify({
+ type: 'remotion-shape',
+ version: 1,
+ component: {
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ },
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseComponentDragData(
+ JSON.stringify({
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName: 'circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ },
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseComponentDragData(
+ JSON.stringify({
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [{name: 'style', value: 'position: absolute'}],
+ },
+ }),
+ ),
+ ).toBe(null);
+ expect(
+ parseComponentDragData(
+ JSON.stringify({
+ type: 'remotion-component',
+ version: 1,
+ component: {
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [
+ {name: 'radius', value: 100},
+ {name: 'radius', value: 200},
+ ],
+ },
+ }),
+ ),
+ ).toBe(null);
+});
diff --git a/packages/studio-shared/src/test/required-package.test.ts b/packages/studio-shared/src/test/required-package.test.ts
index 366ecd59d2..c3be2652e4 100644
--- a/packages/studio-shared/src/test/required-package.test.ts
+++ b/packages/studio-shared/src/test/required-package.test.ts
@@ -48,6 +48,24 @@ test('gets required package for insertable elements', () => {
dimensions: null,
}),
).toBe('@remotion/gif');
+ expect(
+ getRequiredPackageForInsertableElement({
+ type: 'component',
+ componentName: 'Circle',
+ importName: 'Circle',
+ importPath: '@remotion/shapes',
+ props: [],
+ }),
+ ).toBe('@remotion/shapes');
+ expect(
+ getRequiredPackageForInsertableElement({
+ type: 'component',
+ componentName: 'Sequence',
+ importName: 'Sequence',
+ importPath: 'remotion',
+ props: [],
+ }),
+ ).toBe(null);
});
test('gets required package for effect import paths', () => {
diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsx
index bb5e4b976b..5178938691 100644
--- a/packages/studio/src/components/Canvas.tsx
+++ b/packages/studio/src/components/Canvas.tsx
@@ -1,9 +1,12 @@
import type {Size} from '@remotion/player';
import {
ASSET_DRAG_MIME_TYPE,
- SFX_DRAG_MIME_TYPE,
+ COMPONENT_DRAG_MIME_TYPE,
parseAssetDragData,
+ parseComponentDragData,
parseSfxDragData,
+ SFX_DRAG_MIME_TYPE,
+ type ComponentDragData,
} from '@remotion/studio-shared';
import React, {
useCallback,
@@ -44,8 +47,9 @@ import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
import {
importAssets,
importRemoteAsset,
- insertRemoteAudio,
+ insertComponent,
insertExistingAssets,
+ insertRemoteAudio,
} from './import-assets';
import {SPACING_UNIT} from './layout';
import {VideoPreview} from './Preview';
@@ -87,6 +91,12 @@ const isAssetDragEvent = (event: DragEvent): boolean => {
);
};
+const isComponentDragEvent = (event: DragEvent): boolean => {
+ return Array.from(event.dataTransfer?.types ?? []).includes(
+ COMPONENT_DRAG_MIME_TYPE,
+ );
+};
+
const isSfxDragEvent = (event: DragEvent): boolean => {
return Array.from(event.dataTransfer?.types ?? []).includes(
SFX_DRAG_MIME_TYPE,
@@ -97,6 +107,7 @@ const isRemoteAssetDragEvent = (event: DragEvent): boolean => {
return (
!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isComponentDragEvent(event) &&
!isSfxDragEvent(event) &&
hasRemoteAssetDragData(event.dataTransfer)
);
@@ -111,6 +122,26 @@ const getAssetDragPath = (event: DragEvent): string | null => {
return parseAssetDragData(value)?.assetPath ?? null;
};
+const getComponentDragData = (event: DragEvent): ComponentDragData | null => {
+ for (const type of [
+ COMPONENT_DRAG_MIME_TYPE,
+ 'application/json',
+ 'text/plain',
+ ]) {
+ const value = event.dataTransfer?.getData(type);
+ if (!value) {
+ continue;
+ }
+
+ const parsed = parseComponentDragData(value);
+ if (parsed) {
+ return parsed;
+ }
+ }
+
+ return null;
+};
+
const getSfxDragUrl = (event: DragEvent): string | null => {
const {dataTransfer} = event;
if (!dataTransfer) {
@@ -666,6 +697,7 @@ export const Canvas: React.FC<{
!canDropAssets ||
(!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isComponentDragEvent(event) &&
!isSfxDragEvent(event) &&
!isRemoteAssetDragEvent(event)) ||
!isDragEventInsideCanvas(event)
@@ -689,6 +721,7 @@ export const Canvas: React.FC<{
currentCompositionId === null ||
(!isFileDragEvent(event) &&
!isAssetDragEvent(event) &&
+ !isComponentDragEvent(event) &&
!isSfxDragEvent(event) &&
!isRemoteAssetDragEvent(event)) ||
!isDragEventInsideCanvas(event)
@@ -735,6 +768,16 @@ export const Canvas: React.FC<{
compositionId: currentCompositionId,
});
} else {
+ const componentDragData = getComponentDragData(event);
+ if (componentDragData !== null) {
+ await insertComponent({
+ component: componentDragData.component,
+ compositionFile,
+ compositionId: currentCompositionId,
+ });
+ return;
+ }
+
const url = getRemoteAssetUrlFromDataTransfer(event.dataTransfer);
if (url === null) {
return;
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index 47ce3ad3e1..54f457254d 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -104,7 +104,7 @@ type SelectedOutlineContextMenuOpenHandler = () =>
type SelectedOutlineTarget = {
readonly key: string;
readonly nodePathInfo: SequenceNodePathInfo;
- readonly ref: React.RefObject<HTMLElement | null>;
+ readonly ref: React.RefObject<Element | null>;
readonly selected: boolean;
readonly selection: TimelineSelection;
readonly sequence: TSequence;
@@ -487,7 +487,7 @@ const quadToPoints = (
};
const getElementOutlinePoints = (
- element: HTMLElement,
+ element: Element,
containerRect: DOMRect,
): SelectedOutline['points'] | null => {
const elementRect = element.getBoundingClientRect();
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 42b8169cdc..e614ce4789 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -2,6 +2,7 @@ import {
detectFileType,
getRequiredPackageForInsertableElement,
isUrl,
+ type ComponentDragData,
type DownloadRemoteAssetResponse,
type FileType,
type InsertableCompositionElement,
@@ -156,6 +157,10 @@ const getAssetLabel = (element: InsertableCompositionElement) => {
throw new Error('Unsupported asset type');
};
+const getComponentLabel = (component: ComponentDragData['component']) => {
+ return `<${component.componentName}>`;
+};
+
export const pickFilesToImport = (): Promise<File[]> => {
return new Promise((resolve) => {
const input = document.createElement('input');
@@ -470,3 +475,43 @@ export const insertExistingAssets = async ({
);
}
};
+
+export const insertComponent = async ({
+ component,
+ compositionFile,
+ compositionId,
+}: {
+ component: ComponentDragData['component'];
+ compositionFile: string;
+ compositionId: string;
+}) => {
+ try {
+ const inserted = await insertAssetElement({
+ compositionFile,
+ compositionId,
+ element: {
+ type: 'component',
+ componentName: component.componentName,
+ importName: component.importName,
+ importPath: component.importPath,
+ props: component.props,
+ },
+ });
+
+ if (!inserted) {
+ return;
+ }
+
+ showNotification(
+ `Added ${getComponentLabel(component)} to source file`,
+ 2000,
+ );
+ } catch (error) {
+ showNotification(
+ `Could not add component: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ 4000,
+ );
+ }
+};