🎥 Make videos programmatically with React
`@remotion/studio`: Center dropped shapes (#8455)
Jonny Burger9b71c7d24571
diff --git a/packages/docs/components/shapes/shape-component-drag-data.ts b/packages/docs/components/shapes/shape-component-drag-data.tsindex 4d342a60dd..fda28fa78f 100644--- a/packages/docs/components/shapes/shape-component-drag-data.ts+++ b/packages/docs/components/shapes/shape-component-drag-data.ts@@ -4,6 +4,7 @@ import {type ComponentDragData,type ComponentProp,} from '@remotion/studio-shared';+import {getShapeDragInfo} from './shape-drag-info';import type {ShapeName} from './shapes-info';const shapeDefaultProps: Record<ShapeName, readonly ComponentProp[]> = {@@ -146,11 +147,19 @@ const makeShapeComponentDragData = ({readonly shape: ShapeName;readonly props: ComponentProp[];}): ComponentDragData => {- return makeComponentDragData({+ const component = {componentName: shape,importName: shape,importPath: '@remotion/shapes',props,+ } satisfies ComponentDragData['component'];+ const shapeInfo = getShapeDragInfo(component);++ return makeComponentDragData({+ ...component,+ dimensions: shapeInfo+ ? {width: shapeInfo.width, height: shapeInfo.height}+ : null,});};diff --git a/packages/docs/components/shapes/shape-drag-info.ts b/packages/docs/components/shapes/shape-drag-info.tsnew file mode 100644index 0000000000..db67a95aa8--- /dev/null+++ b/packages/docs/components/shapes/shape-drag-info.ts@@ -0,0 +1,220 @@+import {+ makeArrow,+ makeCallout,+ makeCircle,+ makeEllipse,+ makeHeart,+ makePie,+ makePolygon,+ makeRect,+ makeStar,+ makeTriangle,+} from '@remotion/shapes';+import type {ComponentDragData} from '@remotion/studio-shared';+import type {ShapeName} from './shapes-info';++export type ShapeDragInfo = {+ readonly fill: string;+ readonly height: number;+ readonly path: string;+ readonly width: number;+};++const shapeNames: readonly ShapeName[] = [+ 'Arrow',+ 'Callout',+ 'Circle',+ 'Ellipse',+ 'Heart',+ 'Pie',+ 'Polygon',+ 'Rect',+ 'Star',+ 'Triangle',+];++const isShapeName = (value: string): value is ShapeName => {+ return shapeNames.includes(value as ShapeName);+};++const getProp = (+ props: Record<string, string | number | boolean>,+ name: string,+) => props[name];++const getNumber = (+ props: Record<string, string | number | boolean>,+ name: string,+) => {+ const value = getProp(props, name);+ if (typeof value !== 'number') {+ throw new Error(`Expected ${name} to be a number`);+ }++ return value;+};++const getBoolean = (+ props: Record<string, string | number | boolean>,+ name: string,+) => {+ const value = getProp(props, name);+ if (typeof value !== 'boolean') {+ throw new Error(`Expected ${name} to be a boolean`);+ }++ return value;+};++const getDirection = (+ props: Record<string, string | number | boolean>,+ name: string,+) => {+ const value = getProp(props, name);+ if (+ value !== 'left' &&+ value !== 'right' &&+ value !== 'up' &&+ value !== 'down'+ ) {+ throw new Error(`Expected ${name} to be a direction`);+ }++ return value;+};++const withFill = (+ shapeInfo: Omit<ShapeDragInfo, 'fill'>,+ props: Record<string, string | number | boolean>,+): ShapeDragInfo => {+ const fill = getProp(props, 'fill');++ return {+ ...shapeInfo,+ fill: typeof fill === 'string' ? fill : '#0b84ff',+ };+};++export const getShapeDragInfo = (+ component: ComponentDragData['component'],+): ShapeDragInfo | null => {+ const shape =+ component.importPath === '@remotion/shapes' &&+ isShapeName(component.importName)+ ? component.importName+ : null;++ if (shape === null) {+ return null;+ }++ const props = Object.fromEntries(+ component.props.map((prop) => [prop.name, prop.value]),+ );++ switch (shape) {+ case 'Arrow':+ return withFill(+ makeArrow({+ length: getNumber(props, 'length'),+ headWidth: getNumber(props, 'headWidth'),+ headLength: getNumber(props, 'headLength'),+ shaftWidth: getNumber(props, 'shaftWidth'),+ direction: getDirection(props, 'direction'),+ cornerRadius:+ typeof props.cornerRadius === 'number' ? props.cornerRadius : 0,+ }),+ props,+ );+ case 'Callout':+ return withFill(+ makeCallout({+ width: getNumber(props, 'width'),+ height: getNumber(props, 'height'),+ pointerLength: getNumber(props, 'pointerLength'),+ pointerBaseWidth: getNumber(props, 'pointerBaseWidth'),+ pointerPosition: getNumber(props, 'pointerPosition'),+ pointerDirection: getDirection(props, 'pointerDirection'),+ cornerRadius: getNumber(props, 'cornerRadius'),+ edgeRoundness:+ typeof props.edgeRoundness === 'number'+ ? props.edgeRoundness+ : null,+ }),+ props,+ );+ case 'Circle':+ return withFill(makeCircle({radius: getNumber(props, 'radius')}), props);+ case 'Ellipse':+ return withFill(+ makeEllipse({+ rx: getNumber(props, 'rx'),+ ry: getNumber(props, 'ry'),+ }),+ props,+ );+ case 'Heart':+ return withFill(+ makeHeart({+ height: getNumber(props, 'height'),+ aspectRatio: getNumber(props, 'aspectRatio'),+ bottomRoundnessAdjustment: getNumber(+ props,+ 'bottomRoundnessAdjustment',+ ),+ depthAdjustment: getNumber(props, 'depthAdjustment'),+ }),+ props,+ );+ case 'Pie':+ return withFill(+ makePie({+ radius: getNumber(props, 'radius'),+ progress: getNumber(props, 'progress'),+ closePath: getBoolean(props, 'closePath'),+ counterClockwise: getBoolean(props, 'counterClockwise'),+ rotation: getNumber(props, 'rotation'),+ }),+ props,+ );+ case 'Polygon':+ return withFill(+ makePolygon({+ points: getNumber(props, 'points'),+ radius: getNumber(props, 'radius'),+ cornerRadius: getNumber(props, 'cornerRadius'),+ }),+ props,+ );+ case 'Rect':+ return withFill(+ makeRect({+ width: getNumber(props, 'width'),+ height: getNumber(props, 'height'),+ cornerRadius: getNumber(props, 'cornerRadius'),+ }),+ props,+ );+ case 'Star':+ return withFill(+ makeStar({+ points: getNumber(props, 'points'),+ innerRadius: getNumber(props, 'innerRadius'),+ outerRadius: getNumber(props, 'outerRadius'),+ cornerRadius: getNumber(props, 'cornerRadius'),+ }),+ props,+ );+ case 'Triangle':+ return withFill(+ makeTriangle({+ length: getNumber(props, 'length'),+ direction: getDirection(props, 'direction'),+ cornerRadius: getNumber(props, 'cornerRadius'),+ }),+ props,+ );+ default:+ return null;+ }+};diff --git a/packages/docs/components/shapes/shape-drag-preview.tsx b/packages/docs/components/shapes/shape-drag-preview.tsxindex a41d6efec1..fe1b3ae9ad 100644--- a/packages/docs/components/shapes/shape-drag-preview.tsx+++ b/packages/docs/components/shapes/shape-drag-preview.tsx@@ -1,217 +1,6 @@-import {- makeArrow,- makeCallout,- makeCircle,- makeEllipse,- makeHeart,- makePie,- makePolygon,- makeRect,- makeStar,- makeTriangle,-} from '@remotion/shapes';import type {ComponentDragData} from '@remotion/studio-shared';import React from 'react';-import type {ShapeName} from './shapes-info';--type ShapeInfo = {- readonly path: string;- readonly width: number;- readonly height: number;- readonly fill: string;-};--const shapeNames: readonly ShapeName[] = [- 'Arrow',- 'Callout',- 'Circle',- 'Ellipse',- 'Heart',- 'Pie',- 'Polygon',- 'Rect',- 'Star',- 'Triangle',-];--const isShapeName = (value: string): value is ShapeName => {- return shapeNames.includes(value as ShapeName);-};--const getProp = (- props: Record<string, string | number | boolean>,- name: string,-) => props[name];--const getNumber = (- props: Record<string, string | number | boolean>,- name: string,-) => {- const value = getProp(props, name);- if (typeof value !== 'number') {- throw new Error(`Expected ${name} to be a number`);- }-- return value;-};--const getBoolean = (- props: Record<string, string | number | boolean>,- name: string,-) => {- const value = getProp(props, name);- if (typeof value !== 'boolean') {- throw new Error(`Expected ${name} to be a boolean`);- }-- return value;-};--const getDirection = (- props: Record<string, string | number | boolean>,- name: string,-) => {- const value = getProp(props, name);- if (- value !== 'left' &&- value !== 'right' &&- value !== 'up' &&- value !== 'down'- ) {- throw new Error(`Expected ${name} to be a direction`);- }-- return value;-};--const withFill = (- shapeInfo: Omit<ShapeInfo, 'fill'>,- props: Record<string, string | number | boolean>,-): ShapeInfo => {- const fill = getProp(props, 'fill');-- return {- ...shapeInfo,- fill: typeof fill === 'string' ? fill : '#0b84ff',- };-};--const makeShapeInfo = (dragData: ComponentDragData): ShapeInfo | null => {- const shape = dragData.component.componentName;- if (!isShapeName(shape)) {- return null;- }-- const props = Object.fromEntries(- dragData.component.props.map((prop) => [prop.name, prop.value]),- );-- switch (shape) {- case 'Arrow':- return withFill(- makeArrow({- length: getNumber(props, 'length'),- headWidth: getNumber(props, 'headWidth'),- headLength: getNumber(props, 'headLength'),- shaftWidth: getNumber(props, 'shaftWidth'),- direction: getDirection(props, 'direction'),- cornerRadius:- typeof props.cornerRadius === 'number' ? props.cornerRadius : 0,- }),- props,- );- case 'Callout':- return withFill(- makeCallout({- width: getNumber(props, 'width'),- height: getNumber(props, 'height'),- pointerLength: getNumber(props, 'pointerLength'),- pointerBaseWidth: getNumber(props, 'pointerBaseWidth'),- pointerPosition: getNumber(props, 'pointerPosition'),- pointerDirection: getDirection(props, 'pointerDirection'),- cornerRadius: getNumber(props, 'cornerRadius'),- edgeRoundness:- typeof props.edgeRoundness === 'number'- ? props.edgeRoundness- : null,- }),- props,- );- case 'Circle':- return withFill(makeCircle({radius: getNumber(props, 'radius')}), props);- case 'Ellipse':- return withFill(- makeEllipse({- rx: getNumber(props, 'rx'),- ry: getNumber(props, 'ry'),- }),- props,- );- case 'Heart':- return withFill(- makeHeart({- height: getNumber(props, 'height'),- aspectRatio: getNumber(props, 'aspectRatio'),- bottomRoundnessAdjustment: getNumber(- props,- 'bottomRoundnessAdjustment',- ),- depthAdjustment: getNumber(props, 'depthAdjustment'),- }),- props,- );- case 'Pie':- return withFill(- makePie({- radius: getNumber(props, 'radius'),- progress: getNumber(props, 'progress'),- closePath: getBoolean(props, 'closePath'),- counterClockwise: getBoolean(props, 'counterClockwise'),- rotation: getNumber(props, 'rotation'),- }),- props,- );- case 'Polygon':- return withFill(- makePolygon({- points: getNumber(props, 'points'),- radius: getNumber(props, 'radius'),- cornerRadius: getNumber(props, 'cornerRadius'),- }),- props,- );- case 'Rect':- return withFill(- makeRect({- width: getNumber(props, 'width'),- height: getNumber(props, 'height'),- cornerRadius: getNumber(props, 'cornerRadius'),- }),- props,- );- case 'Star':- return withFill(- makeStar({- points: getNumber(props, 'points'),- innerRadius: getNumber(props, 'innerRadius'),- outerRadius: getNumber(props, 'outerRadius'),- cornerRadius: getNumber(props, 'cornerRadius'),- }),- props,- );- case 'Triangle':- return withFill(- makeTriangle({- length: getNumber(props, 'length'),- direction: getDirection(props, 'direction'),- cornerRadius: getNumber(props, 'cornerRadius'),- }),- props,- );- default:- return null;- }-};+import {getShapeDragInfo} from './shape-drag-info';export const ShapeDragPreview = React.forwardRef<SVGSVGElement,@@ -220,7 +9,7 @@ export const ShapeDragPreview = React.forwardRef<readonly size: number;}>(({dragData, size}, ref) => {- const shapeInfo = makeShapeInfo(dragData);+ const shapeInfo = getShapeDragInfo(dragData.component);if (shapeInfo === null) {return null;}diff --git a/packages/docs/src/test/shape-component-drag-data.test.ts b/packages/docs/src/test/shape-component-drag-data.test.tsnew file mode 100644index 0000000000..606d3ee5de--- /dev/null+++ b/packages/docs/src/test/shape-component-drag-data.test.ts@@ -0,0 +1,39 @@+import {expect, test} from 'bun:test';+import {+ makeDefaultShapeComponentDragData,+ makeShapeComponentDragDataFromDemoState,+} from '../../components/shapes/shape-component-drag-data';+import type {ShapeName} from '../../components/shapes/shapes-info';++const shapes: ShapeName[] = [+ 'Arrow',+ 'Callout',+ 'Circle',+ 'Ellipse',+ 'Heart',+ 'Pie',+ 'Polygon',+ 'Rect',+ 'Star',+ 'Triangle',+];++test('embeds dimensions into default shape drag data', () => {+ for (const shape of shapes) {+ const dragData = makeDefaultShapeComponentDragData(shape);++ expect(dragData.component.dimensions).toBeDefined();+ expect(dragData.component.dimensions?.width).toBeGreaterThan(0);+ expect(dragData.component.dimensions?.height).toBeGreaterThan(0);+ }+});++test('embeds dimensions from shape demo state', () => {+ const dragData = makeShapeComponentDragDataFromDemoState({+ demoId: 'heart',+ state: {height: 200, aspectRatio: 1.2},+ });++ expect(dragData?.component.dimensions?.width).toBeCloseTo(240);+ expect(dragData?.component.dimensions?.height).toBe(200);+});diff --git a/packages/studio-shared/src/component-drag-data.ts b/packages/studio-shared/src/component-drag-data.tsindex d64af4d7da..1ee1b6dfa0 100644--- a/packages/studio-shared/src/component-drag-data.ts+++ b/packages/studio-shared/src/component-drag-data.ts@@ -6,11 +6,17 @@ export type ComponentProp = {value: string | number | boolean;};+export type ComponentDimensions = {+ height: number;+ width: number;+};+export type ComponentDragData = {type: 'remotion-component';version: 1;component: {componentName: string;+ dimensions?: ComponentDimensions;importName: string;importPath: string;props: ComponentProp[];@@ -78,13 +84,32 @@ export const areComponentProps = (value: unknown): value is ComponentProp[] => {return true;};+const isComponentDimensions = (+ 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 makeComponentDragData = ({componentName,+ dimensions,importName,importPath,props,}: {componentName: string;+ dimensions?: ComponentDimensions | null;importName: string;importPath: string;props: ComponentProp[];@@ -94,6 +119,7 @@ export const makeComponentDragData = ({version: 1,component: {componentName,+ ...(dimensions ? {dimensions} : {}),importName,importPath,props,@@ -118,12 +144,14 @@ export const parseComponentDragData = (return null;}- const {componentName, importName, importPath, props} = parsed.component;+ const {componentName, dimensions, importName, importPath, props} =+ parsed.component;if (!isComponentIdentifier(componentName) ||!isComponentIdentifier(importName) ||!isComponentImportPath(importPath) ||- !areComponentProps(props)+ !areComponentProps(props) ||+ (typeof dimensions !== 'undefined' && !isComponentDimensions(dimensions))) {return null;}@@ -133,6 +161,7 @@ export const parseComponentDragData = (version: 1,component: {componentName,+ ...(dimensions ? {dimensions} : {}),importName,importPath,props,diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex f12906ea38..f50b999629 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -115,6 +115,7 @@ export {isComponentImportPath,makeComponentDragData,parseComponentDragData,+ type ComponentDimensions,type ComponentDragData,type ComponentProp,} from './component-drag-data';diff --git a/packages/studio-shared/src/test/component-drag-data.test.ts b/packages/studio-shared/src/test/component-drag-data.test.tsindex 8358047ca0..5caa1d6c1d 100644--- a/packages/studio-shared/src/test/component-drag-data.test.ts+++ b/packages/studio-shared/src/test/component-drag-data.test.ts@@ -10,6 +10,7 @@ test('parses component drag data', () => {JSON.stringify(makeComponentDragData({componentName: 'Circle',+ dimensions: {width: 200, height: 200},importName: 'Circle',importPath: '@remotion/shapes',props: [@@ -24,6 +25,7 @@ test('parses component drag data', () => {version: 1,component: {componentName: 'Circle',+ dimensions: {width: 200, height: 200},importName: 'Circle',importPath: '@remotion/shapes',props: [@@ -34,6 +36,30 @@ test('parses component drag data', () => {});});+test('parses component drag data without dimensions', () => {+ expect(+ parseComponentDragData(+ JSON.stringify(+ makeComponentDragData({+ componentName: 'Circle',+ importName: 'Circle',+ importPath: '@remotion/shapes',+ props: [{name: 'radius', value: 100}],+ }),+ ),+ ),+ ).toEqual({+ type: 'remotion-component',+ version: 1,+ component: {+ componentName: 'Circle',+ importName: 'Circle',+ importPath: '@remotion/shapes',+ props: [{name: 'radius', value: 100}],+ },+ });+});+test('rejects invalid component drag data', () => {expect(parseComponentDragData('')).toBe(null);expect(parseComponentDragData('{')).toBe(null);@@ -110,4 +136,19 @@ test('rejects invalid component drag data', () => {}),),).toBe(null);+ expect(+ parseComponentDragData(+ JSON.stringify({+ type: 'remotion-component',+ version: 1,+ component: {+ componentName: 'Circle',+ dimensions: {width: -100, height: 200},+ importName: 'Circle',+ importPath: '@remotion/shapes',+ props: [],+ },+ }),+ ),+ ).toBe(null);});diff --git a/packages/studio/src/components/CanvasIfSizeIsAvailable.tsx b/packages/studio/src/components/CanvasIfSizeIsAvailable.tsxindex da38102872..f78e933884 100644--- a/packages/studio/src/components/CanvasIfSizeIsAvailable.tsx+++ b/packages/studio/src/components/CanvasIfSizeIsAvailable.tsx@@ -1,6 +1,6 @@import {useContext, useMemo} from 'react';import {Internals} from 'remotion';-import {RULER_WIDTH} from '../state/editor-rulers';+import {applyRulerInsetsToCanvasSize} from '../helpers/ruler-canvas-size';import {CanvasOrLoading} from './CanvasOrLoading';import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';@@ -20,11 +20,7 @@ export const CanvasIfSizeIsAvailable: React.FC = () => {return null;}- return {- ...size,- width: size.width - RULER_WIDTH,- height: size.height - RULER_WIDTH,- };+ return applyRulerInsetsToCanvasSize({rulersAreVisible, size});}, [context, rulersAreVisible]);if (!sizeWithRulersApplied) {diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.tsindex 2af5a4ee14..f006782aab 100644--- a/packages/studio/src/components/import-assets.ts+++ b/packages/studio/src/components/import-assets.ts@@ -239,9 +239,13 @@ const getComponentPropNumber = (props: ComponentProp[], name: string) => {return typeof prop?.value === 'number' ? prop.value : null;};-const getComponentDimensions = (+export const getComponentDimensions = (component: ComponentDragData['component'],): Dimensions | null => {+ if (component.dimensions) {+ return component.dimensions;+ }+const width = getComponentPropNumber(component.props, 'width');const height = getComponentPropNumber(component.props, 'height');if (width !== null && height !== null) {diff --git a/packages/studio/src/helpers/ruler-canvas-size.ts b/packages/studio/src/helpers/ruler-canvas-size.tsnew file mode 100644index 0000000000..7b753a92ea--- /dev/null+++ b/packages/studio/src/helpers/ruler-canvas-size.ts@@ -0,0 +1,22 @@+import type {Size} from '@remotion/player';+import {RULER_WIDTH} from '../state/editor-rulers';++export const applyRulerInsetsToCanvasSize = ({+ rulersAreVisible,+ size,+}: {+ readonly rulersAreVisible: boolean;+ readonly size: Size;+}) => {+ if (!rulersAreVisible) {+ return size;+ }++ return {+ ...size,+ left: size.left + RULER_WIDTH,+ top: size.top + RULER_WIDTH,+ width: size.width - RULER_WIDTH,+ height: size.height - RULER_WIDTH,+ };+};diff --git a/packages/studio/src/test/canvas-rulers.test.ts b/packages/studio/src/test/canvas-rulers.test.tsnew file mode 100644index 0000000000..575e17a0f2--- /dev/null+++ b/packages/studio/src/test/canvas-rulers.test.ts@@ -0,0 +1,50 @@+import {expect, test} from 'bun:test';++Object.defineProperty(globalThis, 'localStorage', {+ configurable: true,+ value: {+ getItem: () => null,+ setItem: () => undefined,+ },+});++const getRulerModules = async () => {+ const [{applyRulerInsetsToCanvasSize}, {RULER_WIDTH}] = await Promise.all([+ import('../helpers/ruler-canvas-size'),+ import('../state/editor-rulers'),+ ]);++ return {applyRulerInsetsToCanvasSize, RULER_WIDTH};+};++const size = {+ height: 768,+ left: 100,+ refresh: () => undefined,+ top: 50,+ width: 1024,+ windowSize: {+ height: 900,+ width: 1440,+ },+};++test('ruler insets move the canvas origin with the padded preview area', async () => {+ const {applyRulerInsetsToCanvasSize, RULER_WIDTH} = await getRulerModules();++ expect(applyRulerInsetsToCanvasSize({rulersAreVisible: true, size})).toEqual({+ ...size,+ height: size.height - RULER_WIDTH,+ left: size.left + RULER_WIDTH,+ top: size.top + RULER_WIDTH,+ width: size.width - RULER_WIDTH,+ });+});++test('canvas size is unchanged if rulers are hidden', async () => {+ const {applyRulerInsetsToCanvasSize} = await getRulerModules();++ expect(applyRulerInsetsToCanvasSize({rulersAreVisible: false, size})).toBe(+ size,+ );+});diff --git a/packages/studio/src/test/import-assets.test.ts b/packages/studio/src/test/import-assets.test.tsindex 446378f6a4..46c47d7c89 100644--- a/packages/studio/src/test/import-assets.test.ts+++ b/packages/studio/src/test/import-assets.test.ts@@ -2,6 +2,7 @@ import {expect, test} from 'bun:test';import {getAssetElement,getAssetElementFromPath,+ getComponentDimensions,} from '../components/import-assets';test('maps audio file types to Audio assets', () => {@@ -98,3 +99,32 @@ test('does not map unsupported existing static file paths', () => {expect(getAssetElementFromPath('asset-without-extension')).toBe(null);expect(getAssetElementFromPath('nested\\photo.png')).toBe(null);});++test('uses explicit component dimensions from drag data', () => {+ expect(+ getComponentDimensions({+ componentName: 'Heart',+ dimensions: {width: 110, height: 100},+ importName: 'Heart',+ importPath: '@remotion/shapes',+ props: [+ {name: 'height', value: 100},+ {name: 'aspectRatio', value: 1.1},+ ],+ }),+ ).toEqual({width: 110, height: 100});+});++test('falls back to generic component dimensions', () => {+ expect(+ getComponentDimensions({+ componentName: 'CustomBox',+ importName: 'CustomBox',+ importPath: './CustomBox',+ props: [+ {name: 'width', value: 320},+ {name: 'height', value: 180},+ ],+ }),+ ).toEqual({width: 320, height: 180});+});