🎥 Make videos programmatically with React
`@remotion/studio`: Add new composition codemod (#8579)
Jonny Burgerea4c379d7828
diff --git a/packages/studio-server/src/codemods/duplicate-composition.ts b/packages/studio-server/src/codemods/duplicate-composition.tsindex c2bc73270c..8773a026af 100644--- a/packages/studio-server/src/codemods/duplicate-composition.ts+++ b/packages/studio-server/src/codemods/duplicate-composition.ts@@ -68,6 +68,21 @@ export const parseAndApplyCodemod = ({});}+ if (codeMod.type === 'new-composition') {+ ensureNamedImport({+ ast: newAst,+ importedName: 'Composition',+ sourcePath: 'remotion',+ localName: 'Composition',+ });+ ensureNamedImport({+ ast: newAst,+ importedName: codeMod.componentName,+ sourcePath: codeMod.componentImportPath,+ localName: codeMod.componentName,+ });+ }+const output = serializeAst(newAst);return {changesMade, newContents: output};diff --git a/packages/studio-server/src/codemods/recast-mods.ts b/packages/studio-server/src/codemods/recast-mods.tsindex 03ae4cac28..f59387f243 100644--- a/packages/studio-server/src/codemods/recast-mods.ts+++ b/packages/studio-server/src/codemods/recast-mods.ts@@ -10,6 +10,7 @@ import type {JSXAttribute,JSXElement,JSXFragment,+ JSXIdentifier,NullLiteral,ReturnStatement,Statement,@@ -17,12 +18,15 @@ import type {VariableDeclarator,} from '@babel/types';import type {RecastCodemod} from '@remotion/studio-shared';+import * as recast from 'recast';import {applyVisualControl} from './apply-visual-control';export type Change = {description: string;};+const b = recast.types.builders;+export type ApplyCodeModReturnType = {newAst: File; changesMade: Change[]};export const applyCodemod = ({@@ -142,6 +146,21 @@ const mapReturnStatement = (return statement;}+ if (+ transformation.type === 'new-composition' &&+ (statement.argument.type === 'JSXElement' ||+ statement.argument.type === 'JSXFragment')+ ) {+ return {+ ...statement,+ argument: addNewCompositionToRootJsx(+ statement.argument,+ transformation,+ changesMade,+ ),+ };+ }+const replacement = transformLoneJsxElement(statement.argument,transformation,@@ -209,6 +228,87 @@ const isMeaningfulJsxChild = (child: JSXFragment['children'][number]) => {return child.type !== 'JSXText' || child.value.trim() !== '';};+const jsxId = (name: string): JSXIdentifier => ({type: 'JSXIdentifier', name});++const jsxAttributeWithString = (name: string, value: string): JSXAttribute => ({+ type: 'JSXAttribute',+ name: jsxId(name),+ value: {type: 'StringLiteral', value},+});++const jsxAttributeWithExpression = (+ name: string,+ expression: Expression,+): JSXAttribute => ({+ type: 'JSXAttribute',+ name: jsxId(name),+ value: {+ type: 'JSXExpressionContainer',+ expression,+ },+});++const newCompositionElement = (+ transformation: Extract<RecastCodemod, {type: 'new-composition'}>,+): JSXElement => {+ return {+ type: 'JSXElement',+ openingElement: {+ type: 'JSXOpeningElement',+ name: jsxId('Composition'),+ attributes: [+ jsxAttributeWithString('id', transformation.newId),+ jsxAttributeWithExpression(+ 'component',+ b.identifier(transformation.componentName) as Expression,+ ),+ jsxAttributeWithExpression(+ 'durationInFrames',+ b.numericLiteral(transformation.newDurationInFrames) as Expression,+ ),+ jsxAttributeWithExpression(+ 'fps',+ b.numericLiteral(transformation.newFps) as Expression,+ ),+ jsxAttributeWithExpression(+ 'width',+ b.numericLiteral(transformation.newWidth) as Expression,+ ),+ jsxAttributeWithExpression(+ 'height',+ b.numericLiteral(transformation.newHeight) as Expression,+ ),+ ],+ selfClosing: true,+ },+ closingElement: null,+ children: [],+ };+};++const addNewCompositionToRootJsx = <T extends JSXElement | JSXFragment>(+ root: T,+ transformation: Extract<RecastCodemod, {type: 'new-composition'}>,+ changesMade: Change[],+): JSXElement | JSXFragment => {+ if (changesMade.length > 0) {+ return root;+ }++ changesMade.push({+ description: 'Added new composition',+ });++ if (root.type === 'JSXFragment') {+ return {+ ...root,+ children: [...root.children, newCompositionElement(transformation)],+ };+ }++ return wrapInJsxFragment([root, newCompositionElement(transformation)]);+};+// When a <Composition> JSX element appears in a position where it cannot// simply be removed from a parent's children list (e.g. as the sole return// value of a wrapper component or as the concise body of an arrow function),@@ -419,6 +519,21 @@ const mapRecognizedType = <T extends RecognizedType>(expression.type === 'ArrowFunctionExpression' ||expression.type === 'FunctionExpression') {+ if (+ transformation.type === 'new-composition' &&+ (expression.body.type === 'JSXElement' ||+ expression.body.type === 'JSXFragment')+ ) {+ return {+ ...expression,+ body: addNewCompositionToRootJsx(+ expression.body,+ transformation,+ changesMade,+ ),+ };+ }+if (expression.type === 'ArrowFunctionExpression' &&expression.body.type === 'JSXElement'diff --git a/packages/studio-server/src/preview-server/routes/apply-codemod.ts b/packages/studio-server/src/preview-server/routes/apply-codemod.tsindex 51024af8c3..cf2f5720ab 100644--- a/packages/studio-server/src/preview-server/routes/apply-codemod.ts+++ b/packages/studio-server/src/preview-server/routes/apply-codemod.ts@@ -1,4 +1,4 @@-import {readFileSync} from 'node:fs';+import {existsSync, readFileSync} from 'node:fs';import path from 'node:path';import {RenderInternals} from '@remotion/renderer';import type {@@ -9,6 +9,7 @@ import {applyCodemodToFile,resolveFilePathFromSymbolicatedStack,} from '../../codemods/apply-codemod-to-file';+import {formatOutput} from '../../codemods/duplicate-composition';import {simpleDiff} from '../../codemods/simple-diff';import {writeFileAndNotifyFileWatchers} from '../../file-watcher';import type {ApiHandler} from '../api-types';@@ -16,10 +17,20 @@ import {getProjectInfo} from '../project-info';import {printUndoHint,pushToUndoStack,+ pushTransactionToUndoStack,suppressUndoStackInvalidation,} from '../undo-stack';import {checkIfTypeScriptFile} from './can-update-default-props';+const formatNewCompositionFile = (componentName: string) => {+ return formatOutput(`import React from 'react';++export const ${componentName}: React.FC = () => {+ return null;+};+`);+};+const getCodemodUndoDescription = (codemod: ApplyCodemodRequest['codemod']) => {if (codemod.type === 'delete-composition') {return {@@ -47,6 +58,14 @@ const getCodemodUndoDescription = (codemod: ApplyCodemodRequest['codemod']) => {};}+ if (codemod.type === 'new-composition') {+ return {+ undoMessage: `↩️ Creation of composition "${codemod.newId}"`,+ redoMessage: `↪️ Creation of composition "${codemod.newId}"`,+ entryType: codemod.type,+ };+ }+if (codemod.type === 'delete-folder') {const label = `folder "${codemod.parentName ? `${codemod.parentName}/` : ''}${codemod.folderName}"`;return {@@ -96,6 +115,24 @@ export const applyCodemodHandler: ApiHandler<checkIfTypeScriptFile(filePath);+ const newCompositionComponentFilePath =+ codemod.type === 'new-composition'+ ? path.join(path.dirname(filePath), `${codemod.componentName}.tsx`)+ : null;++ if (+ codemod.type === 'new-composition' &&+ newCompositionComponentFilePath &&+ existsSync(newCompositionComponentFilePath)+ ) {+ throw new Error(+ `Cannot create ${path.relative(+ remotionRoot,+ newCompositionComponentFilePath,+ )} because it already exists`,+ );+ }+const input = readFileSync(filePath, 'utf-8');const formatted = await applyCodemodToFile({filePath,@@ -110,22 +147,76 @@ export const applyCodemodHandler: ApiHandler<if (!dryRun) {const {entryType, undoMessage, redoMessage} =getCodemodUndoDescription(codemod);- pushToUndoStack({- filePath,- oldContents: input,- newContents: null,- logLevel,- remotionRoot,- logLine: symbolicatedStack?.originalLineNumber ?? 1,- description: {- undoMessage,- redoMessage,+ const snapshots: Parameters<+ typeof pushTransactionToUndoStack+ >[0]['snapshots'] = [+ {+ filePath,+ oldContents: input,+ newContents: null,+ logLine: symbolicatedStack?.originalLineNumber ?? 1,},- entryType,- suppressHmrOnFileRestore: false,- });+ ];+ let componentFilePath: string | null = null;+ let componentFileContents: string | null = null;++ if (codemod.type === 'new-composition') {+ componentFilePath = newCompositionComponentFilePath;+ if (componentFilePath === null) {+ throw new Error('Could not determine the new component file path');+ }++ componentFileContents = await formatNewCompositionFile(+ codemod.componentName,+ );+ snapshots.push({+ filePath: componentFilePath,+ oldContents: null,+ newContents: componentFileContents,+ logLine: 1,+ });+ pushTransactionToUndoStack({+ snapshots,+ logLevel,+ remotionRoot,+ description: {+ undoMessage,+ redoMessage,+ },+ entryType,+ suppressHmrOnFileRestore: false,+ });+ } else {+ pushToUndoStack({+ filePath,+ oldContents: input,+ newContents: null,+ logLevel,+ remotionRoot,+ logLine: symbolicatedStack?.originalLineNumber ?? 1,+ description: {+ undoMessage,+ redoMessage,+ },+ entryType,+ suppressHmrOnFileRestore: false,+ });+ }+suppressUndoStackInvalidation(filePath);+ if (componentFilePath) {+ suppressUndoStackInvalidation(componentFilePath);+ }+writeFileAndNotifyFileWatchers(filePath, formatted, undefined);+ if (componentFilePath && componentFileContents !== null) {+ writeFileAndNotifyFileWatchers(+ componentFilePath,+ componentFileContents,+ undefined,+ );+ }+const end = Date.now() - time;const relativePath = path.relative(remotionRoot, filePath);RenderInternals.Log.info(diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsindex ed9a21e9b3..2197211f08 100644--- a/packages/studio-server/src/preview-server/undo-stack.ts+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -1,4 +1,4 @@-import {readFileSync} from 'node:fs';+import {existsSync, rmSync, readFileSync} from 'node:fs';import type {LogLevel} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';import {parseAst} from '../codemods/parse-ast';@@ -36,13 +36,14 @@ type UndoEntryType =| 'insert-jsx-element'| 'delete-composition'| 'rename-composition'+ | 'new-composition'| 'duplicate-composition'| 'delete-folder'| 'rename-folder';type UndoEntrySnapshot = {filePath: string;- oldContents: string;+ oldContents: string | null;newContents: string | null;/** 1-based source line for terminal/IDE file links (e.g. path:line). */logLine: number;@@ -74,6 +75,7 @@ type UndoEntry = {| {entryType: 'insert-jsx-element'}| {entryType: 'delete-composition'}| {entryType: 'rename-composition'}+ | {entryType: 'new-composition'}| {entryType: 'duplicate-composition'}| {entryType: 'delete-folder'}| {entryType: 'rename-folder'}@@ -184,7 +186,7 @@ export function pushTransactionToUndoStack({}: {snapshots: Array<{filePath: string;- oldContents: string;+ oldContents: string | null;newContents: string | null;logLine: number;}>;@@ -420,7 +422,10 @@ export function popUndo(): {success: true} | {success: false; reason: string} {return {...snapshot,newContents:- snapshot.newContents ?? readFileSync(snapshot.filePath, 'utf-8'),+ snapshot.newContents ??+ (existsSync(snapshot.filePath)+ ? readFileSync(snapshot.filePath, 'utf-8')+ : null),};});redoStack.push(@@ -441,11 +446,15 @@ export function popUndo(): {success: true} | {success: false; reason: string} {suppressBundlerUpdateForFile(snapshot.filePath);}- writeFileAndNotifyFileWatchers(- snapshot.filePath,- snapshot.oldContents,- undefined,- );+ if (snapshot.oldContents === null) {+ rmSync(snapshot.filePath, {force: true});+ } else {+ writeFileAndNotifyFileWatchers(+ snapshot.filePath,+ snapshot.oldContents,+ undefined,+ );+ }}RenderInternals.Log.verbose(@@ -458,7 +467,9 @@ export function popUndo(): {success: true} | {success: false; reason: string} {if (entry.entryType === 'visual-control') {for (const snapshot of entry.snapshots) {- emitVisualControlChanges(snapshot.oldContents);+ if (snapshot.oldContents !== null) {+ emitVisualControlChanges(snapshot.oldContents);+ }}}diff --git a/packages/studio-server/src/test/apply-codemod.test.ts b/packages/studio-server/src/test/apply-codemod.test.tsindex 3d9a8df324..5428a8081e 100644--- a/packages/studio-server/src/test/apply-codemod.test.ts+++ b/packages/studio-server/src/test/apply-codemod.test.ts@@ -1,5 +1,11 @@import {expect, test} from 'bun:test';-import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import {tmpdir} from 'node:os';import path from 'node:path';import type {RecastCodemod} from '@remotion/studio-shared';@@ -231,6 +237,84 @@ test('applyCodemodHandler pushes composition duplications to undo and redo stack});});+test('applyCodemodHandler creates new composition files with undo and redo', async () => {+ const remotionRoot = mkdtempSync(path.join(tmpdir(), 'remotion-codemod-'));+ const cleanupFileWatcher = setFileWatcherRegistry(+ createFileWatcherRegistry(),+ );+ const cleanupLiveEvents = setLiveEventsListener({+ sendEventToClient: () => undefined,+ sendEventToClientId: () => undefined,+ router: () => Promise.resolve(),+ closeConnections: () => Promise.resolve(),+ addNewClientListener: () => () => undefined,+ });++ try {+ clearUndoRedoStacks();+ const entryPoint = path.join(remotionRoot, 'Root.tsx');+ const componentFile = path.join(remotionRoot, 'FreshVideo.tsx');+ writeFileSync(entryPoint, rootContents);++ const applyResponse = await applyCodemodHandler(+ getHandlerOptions({+ input: {+ codemod: {+ type: 'new-composition',+ newId: 'FreshVideo',+ componentName: 'FreshVideo',+ componentImportPath: './FreshVideo',+ newDurationInFrames: 150,+ newFps: 30,+ newHeight: 1080,+ newWidth: 1920,+ } satisfies RecastCodemod,+ dryRun: false,+ symbolicatedStack: {+ originalFunctionName: null,+ originalFileName: 'Root.tsx',+ originalLineNumber: 9,+ originalColumnNumber: 4,+ originalScriptCode: null,+ },+ },+ entryPoint,+ remotionRoot,+ }),+ );++ expect(applyResponse.success).toBe(true);+ expect(readFileSync(entryPoint, 'utf-8')).toContain('id="FreshVideo"');+ expect(readFileSync(entryPoint, 'utf-8')).toContain(+ "import {FreshVideo} from './FreshVideo'",+ );+ expect(readFileSync(componentFile, 'utf-8')).toContain(+ 'export const FreshVideo',+ );++ const undoResponse = await undoHandler(+ getHandlerOptions({input: {}, entryPoint, remotionRoot}),+ );+ expect(undoResponse.success).toBe(true);+ expect(readFileSync(entryPoint, 'utf-8')).toBe(rootContents);+ expect(existsSync(componentFile)).toBe(false);++ const redoResponse = await redoHandler(+ getHandlerOptions({input: {}, entryPoint, remotionRoot}),+ );+ expect(redoResponse.success).toBe(true);+ expect(readFileSync(entryPoint, 'utf-8')).toContain('id="FreshVideo"');+ expect(readFileSync(componentFile, 'utf-8')).toContain(+ 'export const FreshVideo',+ );+ } finally {+ clearUndoRedoStacks();+ cleanupLiveEvents();+ cleanupFileWatcher();+ rmSync(remotionRoot, {recursive: true, force: true});+ }+});+test('renames a nested folder by parent path', () => {const {changesMade, newContents} = parseAndApplyCodemod({input: folderRootContents,diff --git a/packages/studio-server/src/test/recast-mods.test.ts b/packages/studio-server/src/test/recast-mods.test.tsindex c5f49ad1be..73e2155f81 100644--- a/packages/studio-server/src/test/recast-mods.test.ts+++ b/packages/studio-server/src/test/recast-mods.test.ts@@ -231,3 +231,31 @@ export const NewVideoComp = () => {.filter((l: string) => l.includes('import') && l.includes('remotion'));expect(importLines.length).toBe(1);});++test('New composition appends to root and adds imports', () => {+ const {newContents, changesMade} = parseAndApplyCodemod({+ input: compositionInRoot,+ codeMod: {+ type: 'new-composition',+ newId: 'FreshVideo',+ componentName: 'FreshVideo',+ componentImportPath: './FreshVideo',+ newDurationInFrames: 150,+ newFps: 30,+ newHeight: 1080,+ newWidth: 1920,+ },+ });++ expect(changesMade.length).toBeGreaterThan(0);+ expect(newContents).toMatch(+ /import\s*\{[^}]*FreshVideo[^}]*\}\s*from\s*['"].\/FreshVideo['"]/,+ );+ expect(newContents).toMatch(+ /import\s*\{[^}]*Composition[^}]*\}\s*from\s*['"]remotion['"]/,+ );+ expect(newContents).toContain('id="FreshVideo"');+ expect(newContents).toContain('component={FreshVideo}');+ expect(newContents).toContain('durationInFrames={150}');+ expect(newContents).toContain('width={1920}');+});diff --git a/packages/studio-shared/src/codemods.ts b/packages/studio-shared/src/codemods.tsindex 92f8bd6645..539612b462 100644--- a/packages/studio-shared/src/codemods.ts+++ b/packages/studio-shared/src/codemods.ts@@ -13,6 +13,16 @@ export type ApplyVisualControlCodemod = {};export type RecastCodemod =+ | {+ type: 'new-composition';+ newId: string;+ componentName: string;+ componentImportPath: string;+ newHeight: number;+ newWidth: number;+ newFps: number;+ newDurationInFrames: number;+ }| {type: 'duplicate-composition';idToDuplicate: string;diff --git a/packages/studio/src/components/Modals.tsx b/packages/studio/src/components/Modals.tsxindex 057cf91f54..a892921d1c 100644--- a/packages/studio/src/components/Modals.tsx+++ b/packages/studio/src/components/Modals.tsx@@ -8,6 +8,7 @@ import {InstallPackageModal} from './InstallPackage';import {DeleteComposition} from './NewComposition/DeleteComposition';import {DeleteFolder} from './NewComposition/DeleteFolder';import {DuplicateComposition} from './NewComposition/DuplicateComposition';+import {NewComposition} from './NewComposition/NewComposition';import {RenameComposition} from './NewComposition/RenameComposition';import {RenameFolder} from './NewComposition/RenameFolder';import {RenameStaticFileModal} from './NewComposition/RenameStaticFile';@@ -29,6 +30,9 @@ export const Modals: React.FC<{return (<>+ {modalContextType && modalContextType.type === 'new-comp' && (+ <NewComposition />+ )}{modalContextType && modalContextType.type === 'duplicate-comp' && (<DuplicateCompositioncompositionType={modalContextType.compositionType}diff --git a/packages/studio/src/components/NewComposition/CodemodFooter.tsx b/packages/studio/src/components/NewComposition/CodemodFooter.tsxindex 480fe1e412..10766e044a 100644--- a/packages/studio/src/components/NewComposition/CodemodFooter.tsx+++ b/packages/studio/src/components/NewComposition/CodemodFooter.tsx@@ -31,6 +31,7 @@ export const CodemodFooter: React.FC<{readonly genericSubmitLabel: string;readonly submitLabel: (options: {relativeRootPath: string}) => string;readonly onSuccess: (() => void) | null;+ readonly fallbackToRootFile?: boolean;}> = ({codemod,stack,@@ -41,6 +42,7 @@ export const CodemodFooter: React.FC<{genericSubmitLabel,submitLabel,onSuccess,+ fallbackToRootFile = false,}) => {const [submitting, setSubmitting] = useState(false);const {setSelectedModal} = useContext(ModalsContext);@@ -110,6 +112,25 @@ export const CodemodFooter: React.FC<{useEffect(() => {if (!stack) {+ if (fallbackToRootFile) {+ const rootFileAbortController = new AbortController();+ let rootFileAborted = false;+ getCanApplyCodemod(rootFileAbortController.signal)+ .then(() => undefined)+ .catch((err) => {+ if (rootFileAborted) {+ return;+ }++ showNotification(`${errorNotification}: ${err.message}`, 3000);+ });++ return () => {+ rootFileAborted = true;+ rootFileAbortController.abort();+ };+ }+setCanApplyCodemod({type: 'fail',error: 'Could not determine where this item is defined',@@ -145,12 +166,18 @@ export const CodemodFooter: React.FC<{aborted = true;abortController.abort();};- }, [errorNotification, getCanApplyCodemod, stack, symbolicatedStack]);+ }, [+ errorNotification,+ fallbackToRootFile,+ getCanApplyCodemod,+ stack,+ symbolicatedStack,+ ]);const disabled =!valid ||submitting ||- symbolicatedStack === null ||+ (symbolicatedStack === null && !fallbackToRootFile) ||codemodStatus.type !== 'success';const {registerKeybinding} = useKeybinding();diff --git a/packages/studio/src/components/NewComposition/NewComposition.tsx b/packages/studio/src/components/NewComposition/NewComposition.tsxnew file mode 100644index 0000000000..bab9e87350--- /dev/null+++ b/packages/studio/src/components/NewComposition/NewComposition.tsx@@ -0,0 +1,324 @@+import type {RecastCodemod} from '@remotion/studio-shared';+import type {ChangeEventHandler} from 'react';+import React, {useCallback, useContext, useMemo, useState} from 'react';+import {Internals, type _InternalTypes} from 'remotion';+import {pushUrl} from '../../helpers/url-state';+import {+ validateCompositionDimension,+ validateCompositionName,+} from '../../helpers/validate-new-comp-data';+import {Spacing} from '../layout';+import {ModalFooterContainer} from '../ModalFooter';+import {ModalHeader} from '../ModalHeader';+import {label, optionRow, rightRow} from '../RenderModal/layout';+import {CodemodFooter} from './CodemodFooter';+import {DismissableModal} from './DismissableModal';+import {InputDragger} from './InputDragger';+import {NewCompDuration} from './NewCompDuration';+import {RemotionInput} from './RemInput';+import {ValidationMessage} from './ValidationMessage';++const content: React.CSSProperties = {+ padding: 12,+ paddingRight: 12,+ flex: 1,+ fontSize: 13,+ minWidth: 500,+};++const toPascalCase = (value: string) => {+ const words = value.match(/[a-zA-Z0-9]+/g) ?? [];+ const candidate = words+ .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)+ .join('');++ if (!candidate) {+ return 'NewComposition';+ }++ if (/^[0-9]/.test(candidate)) {+ return `Composition${candidate}`;+ }++ return candidate;+};++const waitForComposition = (compositionId: string) => {+ return new Promise<void>((resolve) => {+ const started = Date.now();+ const interval = window.setInterval(() => {+ const compositionNames = window.remotion_getCompositionNames?.() ?? [];+ if (+ compositionNames.includes(compositionId) ||+ Date.now() - started > 10000+ ) {+ window.clearInterval(interval);+ resolve();+ }+ }, 100);+ });+};++const getUniqueCompositionName = (+ compositions: _InternalTypes['AnyComposition'][],+) => {+ let counter = 1;++ while (true) {+ const name = counter === 1 ? 'NewComposition' : `NewComposition${counter}`;+ const err = validateCompositionName(name, compositions);+ if (!err) {+ return name;+ }++ counter++;+ }+};++const NewCompositionLoaded: React.FC = () => {+ const {compositions} = useContext(Internals.CompositionManager);+ const [newId, setName] = useState(() =>+ getUniqueCompositionName(compositions),+ );+ const [selectedFrameRate, setFrameRate] = useState(30);+ const [size, setSize] = useState(() => ({+ width: 1920,+ height: 1080,+ }));+ const [durationInFrames, setDurationInFrames] = useState(150);++ const onWidthChanged = useCallback((newValue: string) => {+ setSize((s) => {+ return {+ height: s.height,+ width: Number(newValue),+ };+ });+ }, []);++ const onWidthDirectlyChanged = useCallback((newWidth: number) => {+ setSize((s) => {+ return {+ height: s.height,+ width: newWidth,+ };+ });+ }, []);++ const onHeightDirectlyChanged = useCallback((newHeight: number) => {+ setSize((s) => {+ return {+ width: s.width,+ height: newHeight,+ };+ });+ }, []);++ const onHeightChanged = useCallback((newValue: string) => {+ setSize((s) => {+ return {+ width: s.width,+ height: Number(newValue),+ };+ });+ }, []);++ const onNameChange: ChangeEventHandler<HTMLInputElement> = useCallback(+ (e) => {+ setName(e.target.value);+ },+ [],+ );++ const onTextFpsChange = useCallback((newFps: string) => {+ setFrameRate(Number(newFps));+ }, []);++ const onFpsChange = useCallback((newFps: number) => {+ setFrameRate(newFps);+ }, []);++ const compNameErrMessage = validateCompositionName(newId, compositions);+ const compWidthErrMessage = validateCompositionDimension('Width', size.width);+ const compHeightErrMessage = validateCompositionDimension(+ 'Height',+ size.height,+ );+ const componentName = toPascalCase(newId);++ const valid =+ compNameErrMessage === null &&+ compWidthErrMessage === null &&+ compHeightErrMessage === null;++ const codemod: RecastCodemod = useMemo(() => {+ return {+ type: 'new-composition',+ newDurationInFrames: Number(durationInFrames),+ newFps: Number(selectedFrameRate),+ newHeight: Number(size.height),+ newWidth: Number(size.width),+ newId,+ componentName,+ componentImportPath: `./${componentName}`,+ };+ }, [+ componentName,+ durationInFrames,+ newId,+ selectedFrameRate,+ size.height,+ size.width,+ ]);++ const onSuccess = useCallback(() => {+ waitForComposition(newId).then(() => {+ pushUrl(`/${newId}`);+ });+ }, [newId]);++ const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback((e) => {+ e.preventDefault();+ }, []);++ return (+ <>+ <ModalHeader title="New composition" />+ <form onSubmit={onSubmit}>+ <div style={content}>+ <div style={optionRow}>+ <div style={label}>ID</div>+ <div style={rightRow}>+ <div>+ <RemotionInput+ value={newId}+ onChange={onNameChange}+ type="text"+ autoFocus+ placeholder="Composition ID"+ status="ok"+ rightAlign+ />+ {compNameErrMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={compNameErrMessage}+ type="error"+ />+ </>+ ) : null}+ </div>+ </div>+ </div>+ <div style={optionRow}>+ <div style={label}>Width</div>+ <div style={rightRow}>+ <InputDragger+ type="number"+ value={size.width}+ placeholder="Width"+ onTextChange={onWidthChanged}+ name="width"+ step={2}+ min={2}+ required+ status="ok"+ formatter={(w) => `${w}px`}+ max={100000000}+ onValueChange={onWidthDirectlyChanged}+ rightAlign={false}+ />+ {compWidthErrMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={compWidthErrMessage}+ type="error"+ />+ </>+ ) : null}+ </div>+ </div>+ <div style={optionRow}>+ <div style={label}>Height</div>+ <div style={rightRow}>+ <InputDragger+ type="number"+ value={size.height}+ onTextChange={onHeightChanged}+ placeholder="Height"+ name="height"+ step={2}+ required+ formatter={(h) => `${h}px`}+ min={2}+ status="ok"+ max={100000000}+ onValueChange={onHeightDirectlyChanged}+ rightAlign={false}+ />+ {compHeightErrMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={compHeightErrMessage}+ type="error"+ />+ </>+ ) : null}+ </div>+ </div>+ <NewCompDuration+ durationInFrames={durationInFrames}+ setDurationInFrames={setDurationInFrames}+ />+ <div style={optionRow}>+ <div style={label}>FPS</div>+ <div style={rightRow}>+ <InputDragger+ type="number"+ value={selectedFrameRate}+ onTextChange={onTextFpsChange}+ placeholder="Frame rate (fps)"+ name="fps"+ min={1}+ required+ status="ok"+ max={240}+ step={0.01}+ onValueChange={onFpsChange}+ rightAlign={false}+ />+ </div>+ </div>+ </div>+ <ModalFooterContainer>+ <CodemodFooter+ loadingNotification="Creating composition..."+ errorNotification="Could not create composition"+ successNotification={`Created ${newId}`}+ genericSubmitLabel="Add to root file"+ submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}+ codemod={codemod}+ stack={null}+ valid={valid}+ onSuccess={onSuccess}+ fallbackToRootFile+ />+ </ModalFooterContainer>+ </form>+ </>+ );+};++export const NewComposition: React.FC = () => {+ return (+ <DismissableModal>+ <NewCompositionLoaded />+ </DismissableModal>+ );+};diff --git a/packages/studio/src/components/composition-menu-items.ts b/packages/studio/src/components/composition-menu-items.tsindex 41b485894a..fd827dbaaa 100644--- a/packages/studio/src/components/composition-menu-items.ts+++ b/packages/studio/src/components/composition-menu-items.ts@@ -126,6 +126,23 @@ export const getCompositionMenuItems = ({id: 'show-in-editor-divider',}: null,+ {+ id: 'new',+ keyHint: null,+ label: `New...`,+ leftItem: null,+ onClick: () => {+ closeMenu();+ setSelectedModal({+ type: 'new-comp',+ });+ },+ quickSwitcherLabel: 'New composition...',+ subMenu: null,+ type: 'item' as const,+ value: 'new',+ disabled: readOnlyStudio,+ },{id: 'rename',keyHint: null,diff --git a/packages/studio/src/state/modals.ts b/packages/studio/src/state/modals.tsindex 10d9b05142..a1fb6fe34a 100644--- a/packages/studio/src/state/modals.ts+++ b/packages/studio/src/state/modals.ts@@ -128,6 +128,9 @@ export type AddEffectModalState = {};export type ModalState =+ | {+ type: 'new-comp';+ }| {type: 'duplicate-comp';compositionId: string;