š„ Make videos programmatically with React
Elements: Add new composition destination to Studio installs (#10890)
Igor Samokhovets12bd0d7e6cee
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex 918667846c..ae1944199c 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -296,8 +296,7 @@ export const ${componentName}: React.FC = () => {`;const getElementInstallPlanForProject = async ({- compositionFile,- compositionId,+ destination,element,project,}: Parameters<BrowserStudioOperations['prepareElementInstall']>[0] & {@@ -314,17 +313,47 @@ const getElementInstallPlanForProject = async ({throw new Error('Invalid Element source');}- const target = await resolveCompositionComponentWithFile({- compositionFile,- compositionId,- environment: makeInMemoryInsertJsxElementCodemodEnvironment({- formatFile: formatCodemodFile,- project,- svgMarkupToJsx,- }),+ const target =+ destination.type === 'current-composition'+ ? await resolveCompositionComponentWithFile({+ compositionFile: destination.compositionFile,+ compositionId: destination.compositionId,+ environment: makeInMemoryInsertJsxElementCodemodEnvironment({+ formatFile: formatCodemodFile,+ project,+ svgMarkupToJsx,+ }),+ })+ : null;+ if (target !== null && !target.canAddSequence) {+ throw new Error('Cannot insert Element into this composition component');+ }++ const rootFile =+ destination.type === 'new-composition' &&+ destination.compositionFile === null+ ? getRootFileForProject({+ entryPoint: project.entryPoint,+ project,+ })+ : null;+ const compositionFile =+ destination.type === 'new-composition' &&+ destination.compositionFile === null+ ? rootFile+ : destination.compositionFile;+ if (compositionFile === null) {+ throw new Error('Could not find the root file of the project');+ }++ const destinationCompositionFilePath = findProjectFile({+ filePath: compositionFile,+ project,});- const elementFilePath = `${dirname(target.fileName)}/${elementFileName}`;- if (elementFilePath === target.fileName) {+ const elementSiblingFilePath =+ target?.fileName ?? destinationCompositionFilePath;+ const elementFilePath = `${dirname(elementSiblingFilePath)}/${elementFileName}`;+ if (elementFilePath === elementSiblingFilePath) {throw new Error('Element source file conflicts with the composition file');}@@ -339,6 +368,7 @@ const getElementInstallPlanForProject = async ({return {componentName,+ destinationCompositionFilePath,elementFilePath,existingSource,expectedFileState,@@ -1939,8 +1969,11 @@ export const createBrowserStudioOperations = ({try {const project = getProject();const plan = await getElementInstallPlanForProject({- compositionFile: request.compositionFile,- compositionId: request.compositionId,+ destination: {+ type: 'current-composition',+ compositionFile: request.compositionFile,+ compositionId: request.compositionId,+ },element: request.element,project,});@@ -2082,6 +2115,7 @@ export const createBrowserStudioOperations = ({return {success: true,plan: {+ compositionFile: plan.destinationCompositionFilePath,expectedFileState: plan.expectedFileState,filePath: plan.filePath,},diff --git a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts b/packages/browser-studio/src/test/browser-studio-project-operations.test.tsindex 9ad4330a88..53f1ad9cb3 100644--- a/packages/browser-studio/src/test/browser-studio-project-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-project-operations.test.ts@@ -403,8 +403,11 @@ export const LowerThird = () => <Rect width={640} height={180} />;`,} satisfies ElementDragData['element'];const preflight = await operations.prepareElementInstall({- compositionFile: '/project/src/Composition.tsx',- compositionId: 'MyComp',+ destination: {+ type: 'current-composition',+ compositionFile: '/project/src/Composition.tsx',+ compositionId: 'MyComp',+ },element,});if (!preflight.success) {@@ -412,9 +415,26 @@ export const LowerThird = () => <Rect width={640} height={180} />;}expect(preflight.plan).toEqual({+ compositionFile: '/project/src/Composition.tsx',expectedFileState: {exists: false},filePath: 'src/lower-third.element.tsx',});+ const newCompositionPreflight = await operations.prepareElementInstall({+ destination: {+ type: 'new-composition',+ compositionFile: null,+ },+ element,+ });+ expect(newCompositionPreflight).toEqual({+ success: true,+ plan: {+ compositionFile: '/project/src/Root.tsx',+ expectedFileState: {exists: false},+ filePath: 'src/lower-third.element.tsx',+ },+ });+const inserted = await operations.insertElement({compositionFile: '/project/src/Composition.tsx',compositionId: 'MyComp',diff --git a/packages/docs/docs/studio-protocol/install-in-studio.mdx b/packages/docs/docs/studio-protocol/install-in-studio.mdxindex 8848caa569..b7b1d51f25 100644--- a/packages/docs/docs/studio-protocol/install-in-studio.mdx+++ b/packages/docs/docs/studio-protocol/install-in-studio.mdx@@ -57,15 +57,15 @@ Returns a promise with a discriminated union.### success-Indicates whether the request reached the exact selected Studio tab and composition.+Indicates whether the request reached the exact selected Studio tab. The returned composition is the context for the request; the final destination is chosen in Studio.### status-On success, the value is `"awaiting-confirmation"`. Studio is showing or queuing a confirmation dialog. No dependency or source-file installation is guaranteed yet.+On success, the value is `"awaiting-confirmation"`. Studio is showing or queuing a destination and installation confirmation dialog. No composition, dependency, or source-file installation is guaranteed yet.### target-On success, contains the project name, composition ID, Studio origin, and Studio version.+On success, contains the project name, contextual composition ID, Studio origin, and Studio version.### code@@ -88,7 +88,7 @@ A human-readable failure message. Use `code` for application logic.## Discovery-Ports 3000 through 3009 are probed in parallel. The most recently focused compatible target is selected. Discovery returns a short-lived, single-use token bound to that Studio tab and composition.+Ports 3000 through 3009 are probed in parallel. The most recently focused compatible target is selected. Discovery returns a short-lived, single-use token bound to that Studio tab and contextual composition.Studios older than 4.0.502 are detected and return `studio-upgrade-required`. The Element is not sent through the legacy endpoint.diff --git a/packages/docs/src/components/Elements/ElementPage.tsx b/packages/docs/src/components/Elements/ElementPage.tsxindex 61040d3261..144cec0eea 100644--- a/packages/docs/src/components/Elements/ElementPage.tsx+++ b/packages/docs/src/components/Elements/ElementPage.tsx@@ -122,7 +122,7 @@ export const ElementPage: React.FC<ElementPageProps> = ({const {target} = result;setInstallStatus({type: 'success',- message: `Sent to ${target.projectName ?? 'Remotion Studio'} / ${target.compositionId}. Confirm the installation in Studio.`,+ message: `Sent to ${target.projectName ?? 'Remotion Studio'} (currently ${target.compositionId}). Confirm the installation destination in Studio.`,});if (window.location.origin === 'https://www.remotion.dev') {diff --git a/packages/example/e2e/studio-protocol.test.mts b/packages/example/e2e/studio-protocol.test.mtsindex 188f90cfe3..11327f2d9c 100644--- a/packages/example/e2e/studio-protocol.test.mts+++ b/packages/example/e2e/studio-protocol.test.mts@@ -59,23 +59,57 @@ test('installs an Element from a website into a clean Studio project', async ({fs.writeFileSync(path.join(temporaryProject, 'src', 'Composition.tsx'),`import {AbsoluteFill, Composition} from 'remotion';+import {CloseupFolder} from './closeups/Closeup';export const MyComposition = () => {return (- <Composition- id="MyComp"- component={MyComponent}- durationInFrames={60}- fps={30}- width={1280}- height={720}- />+ <>+ <Composition+ id="MyComp"+ component={MyComponent}+ durationInFrames={60}+ fps={30}+ width={1280}+ height={720}+ />+ <CloseupFolder />+ </>);};export const MyComponent = () => {return <AbsoluteFill></AbsoluteFill>;};+`,+ );+ const closeupDirectory = path.join(+ temporaryProject,+ 'src',+ 'closeups',+ );+ fs.mkdirSync(closeupDirectory);+ fs.writeFileSync(+ path.join(closeupDirectory, 'Closeup.tsx'),+ `import {AbsoluteFill, Composition, Folder} from 'remotion';++export const CloseupFolder = () => {+ return (+ <Folder name="Closeup">+ <Composition+ id="CloseupPlaceholder"+ component={CloseupPlaceholder}+ durationInFrames={60}+ fps={30}+ width={1280}+ height={720}+ />+ </Folder>+ );+};++const CloseupPlaceholder = () => {+ return <AbsoluteFill />;+};`,);const externalLibraryUrl = 'https://external-elements.example.com/library';@@ -349,9 +383,130 @@ export const MyComponent = () => {await studioPage.mouse.click(500, 300);const senderPage = await context.newPage();await senderPage.goto(senderUrl);+ await senderPage.getByRole('button', {name: 'Install in Studio'}).click();+ await studioPage.bringToFront();+ const newCompositionDialog = studioPage.getByRole('dialog');+ await expect(+ newCompositionDialog.getByText('Install Element'),+ ).toBeVisible();+ await newCompositionDialog+ .getByRole('button', {name: 'New composition'})+ .click();+ await expect(+ newCompositionDialog.getByPlaceholder('Composition ID'),+ ).toHaveValue('ProtocolElementComposition');+ const widthControl = newCompositionDialog.getByRole('button', {+ name: 'Width',+ });+ const heightControl = newCompositionDialog.getByRole('button', {+ name: 'Height',+ });+ const durationControl = newCompositionDialog.getByRole('button', {+ name: 'Duration in frames',+ });+ await expect(widthControl).toHaveText('640px');+ await expect(heightControl).toHaveText('120px');+ await expect(durationControl).toHaveText('30');+ await newCompositionDialog+ .getByPlaceholder('Composition ID')+ .fill('ProtocolElementScene');+ await newCompositionDialog.getByTitle('Folder').click();+ await studioPage+ .getByRole('button', {name: 'Closeup', exact: true})+ .last()+ .click();+ await widthControl.click();+ const widthInput = newCompositionDialog.getByRole('textbox', {+ name: 'Width',+ });+ await widthInput.fill('800');+ await widthInput.press('Enter');+ await heightControl.click();+ const heightInput = newCompositionDialog.getByRole('textbox', {+ name: 'Height',+ });+ await heightInput.fill('450');+ await heightInput.press('Enter');+ await durationControl.click();+ const durationInput = newCompositionDialog.getByRole('textbox', {+ name: 'Duration in frames',+ });+ await durationInput.fill('90');+ await durationInput.press('Enter');+ const installIntoNewComposition = newCompositionDialog.getByRole('button', {+ name: /Install/,+ });+ await expect(installIntoNewComposition).toBeEnabled();+ await installIntoNewComposition.click();++ const newCompositionFile = path.join(+ closeupDirectory,+ 'ProtocolElementScene.tsx',+ );+ await waitForFile(newCompositionFile);+ await expect+ .poll(() => fs.readFileSync(newCompositionFile, 'utf8'))+ .toContain('ProtocolElement');+ expect(+ fs.readFileSync(+ path.join(closeupDirectory, 'protocol-element.element.tsx'),+ 'utf8',+ ),+ ).toContain('export const ProtocolElement');+ const sourceWithNewComposition = fs.readFileSync(+ path.join(closeupDirectory, 'Closeup.tsx'),+ 'utf8',+ );+ expect(sourceWithNewComposition).toContain('id="ProtocolElementScene"');+ expect(sourceWithNewComposition).toContain('durationInFrames={90}');+ expect(sourceWithNewComposition).toContain('width={800}');+ expect(sourceWithNewComposition).toContain('height={450}');+ const folderStart = sourceWithNewComposition.indexOf(+ '<Folder name="Closeup">',+ );+ const folderEnd = sourceWithNewComposition.indexOf(+ '</Folder>',+ folderStart,+ );+ const newCompositionPosition = sourceWithNewComposition.indexOf(+ 'id="ProtocolElementScene"',+ );+ expect(newCompositionPosition).toBeGreaterThan(folderStart);+ expect(newCompositionPosition).toBeLessThan(folderEnd);+ expect(+ fs.readFileSync(+ path.join(temporaryProject, 'src', 'Composition.tsx'),+ 'utf8',+ ),+ ).not.toContain('id="ProtocolElementScene"');+ await expect(studioPage).toHaveURL(/ProtocolElementScene/, {+ timeout: 30_000,+ });++ await studioPage.bringToFront();+ await studioPage.mouse.click(500, 300);+ await expect+ .poll(() =>+ fetch(`${studioUrl}/api/studio-protocol`, {+ headers: {Origin: 'http://localhost:4000'},+ })+ .then((response) => response.json())+ .then(+ (response) =>+ response.capabilities.find(+ (capability: {type: string}) =>+ capability.type === 'install-element',+ )?.target?.compositionId ?? null,+ ),+ )+ .toBe('ProtocolElementScene');+ await senderPage.bringToFront();await expect(senderPage.getByText('Outside Remotion Studio', {exact: true}),).toBeVisible();+ await senderPage.locator('#status').evaluate((element) => {+ element.textContent = '';+ });const configBeforeCatalogConfirmation = fs.readFileSync(configFile, 'utf8');await senderPage.getByRole('button', {name: 'Add catalog to Studio'})diff --git a/packages/studio-protocol/src/install-in-studio.ts b/packages/studio-protocol/src/install-in-studio.tsindex d8686efe82..eb223bf561 100644--- a/packages/studio-protocol/src/install-in-studio.ts+++ b/packages/studio-protocol/src/install-in-studio.ts@@ -154,7 +154,7 @@ export const installInStudioWithDependencies = async (if (!selected || selectedTarget === null || selectedTarget === undefined) {return failure('no-installable-target',- 'Focus a writable composition in Remotion Studio, then try again.',+ 'Focus a composition in a Remotion Studio that is not read-only, then try again.',);}diff --git a/packages/studio-protocol/src/test/install-in-studio.test.ts b/packages/studio-protocol/src/test/install-in-studio.test.tsindex a2700e1384..b0e8a744a8 100644--- a/packages/studio-protocol/src/test/install-in-studio.test.ts+++ b/packages/studio-protocol/src/test/install-in-studio.test.ts@@ -163,7 +163,8 @@ test('distinguishes a compatible Studio without an installable target', async ()).toEqual({success: false,code: 'no-installable-target',- message: 'Focus a writable composition in Remotion Studio, then try again.',+ message:+ 'Focus a composition in a Remotion Studio that is not read-only, then try again.',});});diff --git a/packages/studio-server/src/preview-server/element-install-state.ts b/packages/studio-server/src/preview-server/element-install-state.tsindex a2ede2d899..dfe25ff430 100644--- a/packages/studio-server/src/preview-server/element-install-state.ts+++ b/packages/studio-server/src/preview-server/element-install-state.ts@@ -8,7 +8,6 @@ export type ElementInstallTarget = {clientId: string;compositionFile: string | null;compositionId: string | null;- canInstall: boolean;lastFocusedAt: number | null;readOnly: boolean;studioUrl: string;@@ -142,7 +141,6 @@ export const consumeStudioProtocolTarget = ({}if (- !current.canInstall ||current.compositionFile !== issued.target.compositionFile ||current.compositionId !== issued.target.compositionId) {diff --git a/packages/studio-server/src/preview-server/routes/element-install-plan.ts b/packages/studio-server/src/preview-server/routes/element-install-plan.tsindex 1b5f575e3c..b7e50d5538 100644--- a/packages/studio-server/src/preview-server/routes/element-install-plan.ts+++ b/packages/studio-server/src/preview-server/routes/element-install-plan.ts@@ -8,6 +8,7 @@ import type {PrepareElementInstallRequest,} from '@remotion/studio-shared';import {resolveCompositionComponentWithFile} from '../../helpers/resolve-composition-component';+import {getProjectInfo} from '../project-info';import {getSafeElementInstallPaths} from './safe-element-install-path';export const normalizeElementSourceForComparison = (source: string) => {@@ -111,11 +112,14 @@ const getExpectedFileState = (};export const getElementInstallPlan = async ({- compositionFile,- compositionId,+ destination,element,+ entryPoint,remotionRoot,-}: PrepareElementInstallRequest & {remotionRoot: string}) => {+}: PrepareElementInstallRequest & {+ entryPoint: string;+ remotionRoot: string;+}) => {validateElementForInstallation(element);const componentName =@@ -126,12 +130,15 @@ export const getElementInstallPlan = async ({throw new Error('Element source must export exactly one named component');}- const location = await resolveCompositionComponentWithFile({- remotionRoot,- compositionFile,- compositionId,- });- if (!location.canAddSequence) {+ const location =+ destination.type === 'current-composition'+ ? await resolveCompositionComponentWithFile({+ remotionRoot,+ compositionFile: destination.compositionFile,+ compositionId: destination.compositionId,+ })+ : null;+ if (location !== null && !location.canAddSequence) {throw new Error('Cannot insert Element into this composition component');}@@ -143,10 +150,22 @@ export const getElementInstallPlan = async ({);}+ const destinationCompositionFile = destination.compositionFile;+ const destinationCompositionFileName =+ destinationCompositionFile === null+ ? (await getProjectInfo(remotionRoot, entryPoint)).rootFile+ : path.resolve(remotionRoot, destinationCompositionFile);+ if (destinationCompositionFileName === null) {+ throw new Error('Could not find the root file of the project');+ }++ const compositionFileName =+ location?.fileName ?? destinationCompositionFileName;+const safePaths = await getSafeElementInstallPaths({- compositionFileName: location.fileName,+ compositionFileName,elementFileName: path.resolve(- path.dirname(location.fileName),+ path.dirname(compositionFileName),derivedElementFileName,),remotionRoot,@@ -158,6 +177,7 @@ export const getElementInstallPlan = async ({return {componentName,+ destinationCompositionFileName,elementFileExists,elementFileName: safePaths.elementFileName,existingElementSource,diff --git a/packages/studio-server/src/preview-server/routes/insert-element.ts b/packages/studio-server/src/preview-server/routes/insert-element.tsindex b5f4b1ce54..f8fe4dde2e 100644--- a/packages/studio-server/src/preview-server/routes/insert-element.ts+++ b/packages/studio-server/src/preview-server/routes/insert-element.ts@@ -60,6 +60,7 @@ export const insertElementHandler: ApiHandler<position,overwriteExisting,},+ entryPoint,remotionRoot,logLevel,}) =>@@ -83,9 +84,13 @@ export const insertElementHandler: ApiHandler<);const plan = await getElementInstallPlan({- compositionFile,- compositionId,+ destination: {+ type: 'current-composition',+ compositionFile,+ compositionId,+ },element,+ entryPoint,remotionRoot,});if (@@ -171,9 +176,13 @@ export const insertElementHandler: ApiHandler<},});const finalPlan = await getElementInstallPlan({- compositionFile,- compositionId,+ destination: {+ type: 'current-composition',+ compositionFile,+ compositionId,+ },element,+ entryPoint,remotionRoot,});if (diff --git a/packages/studio-server/src/preview-server/routes/prepare-element-install.ts b/packages/studio-server/src/preview-server/routes/prepare-element-install.tsindex e42e47b9c8..3b43ef9996 100644--- a/packages/studio-server/src/preview-server/routes/prepare-element-install.ts+++ b/packages/studio-server/src/preview-server/routes/prepare-element-install.ts@@ -9,13 +9,18 @@ import {withSourceFileWriteQueue} from './source-file-write-queue';export const prepareElementInstallHandler: ApiHandler<PrepareElementInstallRequest,PrepareElementInstallResponse-> = ({input, remotionRoot}) =>+> = ({entryPoint, input, remotionRoot}) =>withSourceFileWriteQueue(async () => {try {- const plan = await getElementInstallPlan({...input, remotionRoot});+ const plan = await getElementInstallPlan({+ ...input,+ entryPoint,+ remotionRoot,+ });return {success: true,plan: {+ compositionFile: plan.destinationCompositionFileName,expectedFileState: plan.expectedFileState,filePath: plan.filePath,},diff --git a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.tsindex 84745fb32f..8b163bf5c2 100644--- a/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts+++ b/packages/studio-server/src/preview-server/studio-protocol/handle-discovery.ts@@ -48,7 +48,7 @@ const getLiveStudioTarget = (requestId: string) => {return target;};-const isInstallableTarget = (+const isElementRequestTarget = (target: ElementInstallTarget | null,): target is ElementInstallTarget & {readonly compositionFile: string;@@ -56,7 +56,6 @@ const isInstallableTarget = (readonly lastFocusedAt: number;} =>target !== null &&- target.canInstall &&target.compositionFile !== null &&target.compositionId !== null &&target.lastFocusedAt !== null;@@ -114,7 +113,7 @@ export const handleStudioProtocolDiscovery = ({setTimeout(() => {const now = Date.now();const target = getLiveStudioTarget(requestId);- const installTarget = isInstallableTarget(target) ? target : null;+ const installTarget = isElementRequestTarget(target) ? target : null;const issuedInstallTarget =installTarget === null? nulldiff --git a/packages/studio-server/src/test/element-install-state.test.ts b/packages/studio-server/src/test/element-install-state.test.tsindex 2db6f3181e..22747c1657 100644--- a/packages/studio-server/src/test/element-install-state.test.ts+++ b/packages/studio-server/src/test/element-install-state.test.ts@@ -8,14 +8,12 @@ import {} from '../preview-server/element-install-state';const updateTarget = ({- canInstall = true,clientId = 'focused-tab',compositionId = 'Main',lastFocusedAt = Date.now(),readOnly = false,requestId = 'protocol-request',}: {- readonly canInstall?: boolean;readonly clientId?: string;readonly compositionId?: string | null;readonly lastFocusedAt?: number;@@ -28,7 +26,6 @@ const updateTarget = ({compositionFile:compositionId === null ? null : `/project/src/${compositionId}.tsx`,compositionId,- canInstall,lastFocusedAt,readOnly,studioUrl: `http://localhost:3000/${compositionId ?? ''}`,@@ -107,7 +104,7 @@ test('binds install tokens to one origin, purpose and composition', () => {test('config targets are project-level, purpose-bound, single-use and invalidated by read-only mode', () => {clearElementInstallStateForTests();- updateTarget({canInstall: false, compositionId: null});+ updateTarget({compositionId: null});const selected = getElementInstallTarget('protocol-request');if (selected === null) {throw new Error('Expected a Studio target');@@ -157,7 +154,7 @@ test('config targets are project-level, purpose-bound, single-use and invalidatepurpose: 'set-license-key',target: selected,});- updateTarget({canInstall: false, compositionId: null, readOnly: true});+ updateTarget({compositionId: null, readOnly: true});expect(consumeStudioProtocolTarget({now: Date.now(),diff --git a/packages/studio-server/src/test/insert-element.test.ts b/packages/studio-server/src/test/insert-element.test.tsindex 26edc7b74a..630c1ed659 100644--- a/packages/studio-server/src/test/insert-element.test.ts+++ b/packages/studio-server/src/test/insert-element.test.ts@@ -1,6 +1,7 @@import {expect, test} from 'bun:test';import {existsSync,+ mkdirSync,mkdtempSync,readFileSync,rmSync,@@ -131,10 +132,16 @@ const makeFixture = () => {});};- const prepareInstall = () => {+ const currentDestination = {+ type: 'current-composition',+ compositionFile: 'Root.tsx',+ compositionId: 'target',+ } as const;+ const prepareInstall = (+ destination: PrepareElementInstallRequest['destination'],+ ) => {const input: PrepareElementInstallRequest = {- compositionFile: 'Root.tsx',- compositionId: 'target',+ destination,element,};@@ -171,6 +178,7 @@ const makeFixture = () => {callHandler,callHandlerWithInput,cleanup,+ currentDestination,prepareInstall,compositionFile,contentsAtMutation,@@ -184,11 +192,12 @@ const makeFixture = () => {test('plans an Element installation without changing the project', async () => {const fixture = makeFixture();try {- const response = await fixture.prepareInstall();+ const response = await fixture.prepareInstall(fixture.currentDestination);expect(response).toEqual({success: true,plan: {+ compositionFile: fixture.compositionFile,expectedFileState: {exists: false},filePath: 'lower-third.element.tsx',},@@ -202,6 +211,51 @@ test('plans an Element installation without changing the project', async () => {}});+test('plans a new-composition install without resolving the selected component', async () => {+ const fixture = makeFixture();+ try {+ writeFileSync(+ fixture.compositionFile,+ compositionSource+ .replace(+ 'const Target = () => <div>Hello</div>;',+ 'const Comp = () => <div>Hello</div>;\nexport const ThreeDCheck = Comp;',+ )+ .replace('component={Target}', 'component={ThreeDCheck}'),+ );+ const current = await fixture.prepareInstall({+ type: 'current-composition',+ compositionFile: 'Root.tsx',+ compositionId: 'target',+ });+ expect(current).toMatchObject({success: false});++ const srcDirectory = path.join(+ path.dirname(fixture.compositionFile),+ 'src',+ );+ mkdirSync(srcDirectory);+ writeFileSync(path.join(srcDirectory, 'Root.tsx'), compositionSource);+ const newComposition = await fixture.prepareInstall({+ type: 'new-composition',+ compositionFile: null,+ });+ expect(newComposition).toEqual({+ success: true,+ plan: {+ compositionFile: path.join(srcDirectory, 'Root.tsx'),+ expectedFileState: {exists: false},+ filePath: 'src/lower-third.element.tsx',+ },+ });+ expect(existsSync(path.join(srcDirectory, 'lower-third.element.tsx'))).toBe(+ false,+ );+ } finally {+ fixture.cleanup();+ }+});+test('creates a new Element file without an overwrite conflict', async () => {const fixture = makeFixture();try {@@ -317,7 +371,7 @@ test('returns a structured conflict without changing the project', async () => {test('does not overwrite a file that changed after planning', async () => {const fixture = makeFixture();try {- const planned = await fixture.prepareInstall();+ const planned = await fixture.prepareInstall(fixture.currentDestination);if (!planned.success) {throw new Error(planned.reason);}diff --git a/packages/studio-server/src/test/studio-protocol-routes.test.ts b/packages/studio-server/src/test/studio-protocol-routes.test.tsindex e6ef96761a..11fe2e85fc 100644--- a/packages/studio-server/src/test/studio-protocol-routes.test.ts+++ b/packages/studio-server/src/test/studio-protocol-routes.test.ts@@ -120,7 +120,6 @@ test('discovers an exact Studio target and delivers one install request over HTTclientId: 'focused-studio-tab',compositionFile: '/tmp/protocol-project/src/Composition.tsx',compositionId: 'Main',- canInstall: true,lastFocusedAt: Date.now(),readOnly: false,studioUrl: 'http://localhost:3000/Main',@@ -202,7 +201,10 @@ test('discovers an exact Studio target and delivers one install request over HTTcapabilities: [{type: 'install-element';- target: {id: string; compositionId: string};+ target: {+ id: string;+ compositionId: string;+ };},];};@@ -376,7 +378,6 @@ test('delivers an Element catalog request without changing config before confirmclientId: 'focused-studio-tab',compositionFile: null,compositionId: null,- canInstall: false,lastFocusedAt: Date.now(),readOnly: false,studioUrl: 'http://localhost:3000',@@ -587,7 +588,6 @@ test('opens a license key confirmation in the focused Studio project over HTTP',clientId: 'focused-studio-tab',compositionFile: null,compositionId: null,- canInstall: false,lastFocusedAt: Date.now(),readOnly: false,studioUrl: 'http://localhost:3000',diff --git a/packages/studio-server/src/test/update-element-install-target.test.ts b/packages/studio-server/src/test/update-element-install-target.test.tsindex 6014b92f84..fc491acb0d 100644--- a/packages/studio-server/src/test/update-element-install-target.test.ts+++ b/packages/studio-server/src/test/update-element-install-target.test.ts@@ -12,7 +12,6 @@ const validInput: UpdateElementInstallTargetRequest = {clientId: 'client-id',compositionFile: '/project/src/composition.tsx',compositionId: 'composition-id',- canInstall: true,lastFocusedAt: 1000,readOnly: false,studioUrl: 'http://localhost:3000/composition-id',diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex d0e5ef8c33..06a85c9254 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -945,9 +945,19 @@ export type ElementInstallExpectedFileState =sourceHash: string;};+export type ElementInstallDestination =+ | {+ type: 'current-composition';+ compositionFile: string;+ compositionId: string;+ }+ | {+ type: 'new-composition';+ compositionFile: string | null;+ };+export type PrepareElementInstallRequest = {- compositionFile: string;- compositionId: string;+ destination: ElementInstallDestination;element: ElementDragData['element'];};@@ -955,6 +965,7 @@ export type PrepareElementInstallResponse =| {success: true;plan: {+ compositionFile: string;filePath: string;expectedFileState: ElementInstallExpectedFileState;};@@ -1028,7 +1039,6 @@ export type UpdateElementInstallTargetRequest = {clientId: string;compositionFile: string | null;compositionId: string | null;- canInstall: boolean;lastFocusedAt: number | null;readOnly: boolean;studioUrl: string;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 67d849227b..a58865a777 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -52,6 +52,7 @@ export {DuplicateJsxNodeRequest,DuplicateJsxNodeResponse,EditorPickerId,+ ElementInstallDestination,ElementInstallExpectedFileState,ElementInstallRequest,ElementInstallSource,diff --git a/packages/studio/src/components/Canvas.tsx b/packages/studio/src/components/Canvas.tsxindex 413d795053..60082a31d1 100644--- a/packages/studio/src/components/Canvas.tsx+++ b/packages/studio/src/components/Canvas.tsx@@ -1,6 +1,9 @@import type {Size} from '@remotion/player';import {StudioProtocolInternals} from '@remotion/studio-protocol';-import type {ElementInstallRequest} from '@remotion/studio-shared';+import type {+ ElementInstallExpectedFileState,+ ElementInstallRequest,+} from '@remotion/studio-shared';import React, {useCallback,useContext,@@ -58,7 +61,6 @@ import {snapCompositionDropPosition,type CompositionDropPreview,} from './composition-drop-preview';-import {useConfirmationDialog} from './ConfirmationDialog';import {isFileDragEvent, isSupportedDropEvent} from './drop-handler-data';import EditorGuides from './EditorGuides';import {EditorRulers} from './EditorRuler';@@ -76,7 +78,6 @@ import {hasSvgFile,importAssets,importFigmaClipboard,- insertElement,insertSvgMarkup,type InsertElementDropPosition,} from './import-assets';@@ -90,6 +91,21 @@ import {useResolvedStack} from './Timeline/use-resolved-stack';const elementInstallDependencyIgnoreList = ['react', 'react-dom', 'remotion'];+type ElementInstallPlan = {+ readonly compositionFile: string;+ readonly filePath: string;+ readonly expectedFileState: ElementInstallExpectedFileState;+};++type ElementInstallReview = {+ readonly currentPlan: ElementInstallPlan | null;+ readonly dependenciesToReview: string[];+ readonly missingPackages: string[];+ readonly newPlan: ElementInstallPlan;+ readonly sourceIsUnverified: boolean;+ readonly sourceLabel: string;+};+const getContainerStyle = (editorZoomGestures: boolean,): React.CSSProperties => ({@@ -222,7 +238,6 @@ export const Canvas: React.FC<{initialZoom: number;} | null>(null);const keybindings = useKeybinding();- const confirm = useConfirmationDialog();const chooseSvgImportMode = useSvgImportDialog();const {setSelectedModal} = useContext(SetSelectedModalContext);const config = Internals.useUnsafeVideoConfig();@@ -248,6 +263,8 @@ export const Canvas: React.FC<{useState<ElementInstallRequest[]>([]);const [activeElementInstallRequest, setActiveElementInstallRequest] =useState<ElementInstallRequest | null>(null);+ const [elementInstallReview, setElementInstallReview] =+ useState<ElementInstallReview | null>(null);const lastFocusedAtRef = useRef<number | null>(typeof document === 'undefined' || document.hasFocus() ? Date.now() : null,);@@ -278,13 +295,15 @@ export const Canvas: React.FC<{compositionFile,compositionId: currentCompositionId,});- const canInstallElements =+ const canReceiveElementInstallRequest =previewServerClientId !== null &&!window.remotion_isReadOnlyStudio &&- compositionComponentInfo?.canAddSequence === true &¤tCompositionId !== null &&compositionFile !== null;- const canDropAssets = canInstallElements && !isAddingAsset;+ const canInsertIntoCurrentComposition =+ canReceiveElementInstallRequest &&+ compositionComponentInfo?.canAddSequence === true;+ const canDropAssets = canInsertIntoCurrentComposition && !isAddingAsset;const cannotAddSequence = compositionComponentInfo?.canAddSequence === false;const contentDimensions = useMemo(() => {if (@@ -770,16 +789,19 @@ export const Canvas: React.FC<{callApi('/api/update-element-install-target', {requestId,clientId: previewServerClientId,- compositionFile: canInstallElements ? compositionFile : null,- compositionId: canInstallElements ? currentCompositionId : null,- canInstall: canInstallElements,+ compositionFile: canReceiveElementInstallRequest+ ? compositionFile+ : null,+ compositionId: canReceiveElementInstallRequest+ ? currentCompositionId+ : null,lastFocusedAt: lastFocusedAtRef.current,readOnly: window.remotion_isReadOnlyStudio,studioUrl: window.location.href,}).catch(() => undefined);},[- canInstallElements,+ canReceiveElementInstallRequest,compositionFile,currentCompositionId,previewServerClientId,@@ -862,7 +884,7 @@ export const Canvas: React.FC<{useEffect(() => {if (- !canInstallElements ||+ !canReceiveElementInstallRequest ||compositionFile === null ||currentCompositionId === null) {@@ -889,7 +911,7 @@ export const Canvas: React.FC<{type: 'browser-studio-link',},});- }, [canInstallElements, compositionFile, currentCompositionId]);+ }, [canReceiveElementInstallRequest, compositionFile, currentCompositionId]);useEffect(() => {if (@@ -914,113 +936,111 @@ export const Canvas: React.FC<{}let canceled = false;-const handleInstallRequest = async () => {setInstallingElementName(activeElementInstallRequest.element.displayName);- const preflight = await prepareElementInstall({- compositionFile: activeElementInstallRequest.compositionFile,- compositionId: activeElementInstallRequest.compositionId,- element: activeElementInstallRequest.element,- });- if (!preflight.success) {- showNotification(- `Could not review Element installation: ${preflight.reason}`,- 4000,- );- return;- }+ try {+ const [newPreflight, currentPreflight] = await Promise.all([+ prepareElementInstall({+ destination: {+ type: 'new-composition',+ compositionFile: null,+ },+ element: activeElementInstallRequest.element,+ }),+ prepareElementInstall({+ destination: {+ type: 'current-composition',+ compositionFile: activeElementInstallRequest.compositionFile,+ compositionId: activeElementInstallRequest.compositionId,+ },+ element: activeElementInstallRequest.element,+ }),+ ]);+ if (canceled) {+ return;+ }- if (canceled) {- return;- }+ if (!newPreflight.success) {+ showNotification(+ `Could not review Element installation: ${newPreflight.reason}`,+ 4000,+ );+ setInstallingElementName(null);+ setActiveElementInstallRequest(null);+ return;+ }- const declaredDependencies = Array.from(- new Map(- activeElementInstallRequest.element.dependencies.map((dependency) => [- dependency.name,- dependency,- ]),- ).values(),- );- const missingPackages = getMissingPackages(declaredDependencies).map(- (dependency) => dependency.name,- );- const ignoredDependencies = declaredDependencies.filter(- (dependency) =>- elementInstallDependencyIgnoreList.includes(dependency.name) &&- !missingPackages.includes(dependency.name),- );- const dependenciesToReview = declaredDependencies- .filter((dependency) => !ignoredDependencies.includes(dependency))- .map((dependency) =>- dependency.version === null- ? dependency.name- : `${dependency.name}@${dependency.version}`,+ const declaredDependencies = Array.from(+ new Map(+ activeElementInstallRequest.element.dependencies.map(+ (dependency) => [dependency.name, dependency],+ ),+ ).values(),);- const {source} = activeElementInstallRequest;- const sourceLabel =- source.type === 'studio-protocol'- ? source.origin- : source.type === 'browser-studio-link'- ? (source.origin ?? 'Unverified Browser Studio link')- : 'Unverified drag-and-drop payload';- const sourceIsUnverified =- source.type === 'drag-and-drop' ||- (source.type === 'browser-studio-link' && source.origin === null);- const accepted = await confirm({- title: 'Install Element',- message: (- <ElementInstallConfirmation- displayName={activeElementInstallRequest.element.displayName}- sourceLabel={sourceLabel}- sourceIsUnverified={sourceIsUnverified}- compositionId={activeElementInstallRequest.compositionId}- filePath={preflight.plan.filePath}- overwritesExistingFile={preflight.plan.expectedFileState.exists}- dependenciesToReview={dependenciesToReview}- missingPackages={missingPackages}- sourceCode={activeElementInstallRequest.element.sourceCode}- usesBrowserDependencyResolution={- getBrowserStudioOperations() !== null- }- />- ),- confirmLabel: 'Install',- cancelLabel: 'Cancel',- });-- if (accepted && !canceled) {- await insertElement({- element: activeElementInstallRequest.element,- compositionFile: activeElementInstallRequest.compositionFile,- compositionId: activeElementInstallRequest.compositionId,- expectedFileState: preflight.plan.expectedFileState,- from: activeElementInstallRequest.from,- position: activeElementInstallRequest.position,- overwriteExisting: preflight.plan.expectedFileState.exists,+ const missingPackages = getMissingPackages(declaredDependencies).map(+ (dependency) => dependency.name,+ );+ const ignoredDependencies = declaredDependencies.filter(+ (dependency) =>+ elementInstallDependencyIgnoreList.includes(dependency.name) &&+ !missingPackages.includes(dependency.name),+ );+ const dependenciesToReview = declaredDependencies+ .filter((dependency) => !ignoredDependencies.includes(dependency))+ .map((dependency) =>+ dependency.version === null+ ? dependency.name+ : `${dependency.name}@${dependency.version}`,+ );+ const {source} = activeElementInstallRequest;+ const sourceLabel =+ source.type === 'studio-protocol'+ ? source.origin+ : source.type === 'browser-studio-link'+ ? (source.origin ?? 'Unverified Browser Studio link')+ : 'Unverified drag-and-drop payload';+ const sourceIsUnverified =+ source.type === 'drag-and-drop' ||+ (source.type === 'browser-studio-link' && source.origin === null);+ const currentPlan = currentPreflight.success+ ? currentPreflight.plan+ : null;+ setSelectedModal(null);+ setElementInstallReview({+ currentPlan,+ dependenciesToReview,+ missingPackages,+ newPlan: newPreflight.plan,+ sourceIsUnverified,+ sourceLabel,});- }- };-- handleInstallRequest()- .finally(() => {+ } catch (error) {if (canceled) {return;}+ showNotification(+ `Could not review Element installation: ${+ error instanceof Error ? error.message : String(error)+ }`,+ 4000,+ );setInstallingElementName(null);setActiveElementInstallRequest(null);- })- .catch((err) => {- setTimeout(() => {- throw err;- }, 0);- });+ }+ };+ handleInstallRequest();return () => {canceled = true;};- }, [activeElementInstallRequest, confirm]);+ }, [activeElementInstallRequest, setSelectedModal]);++ const closeElementInstallDialog = useCallback(() => {+ setElementInstallReview(null);+ setInstallingElementName(null);+ setActiveElementInstallRequest(null);+ }, []);const onDragOver = useCallback((event: DragEvent) => {@@ -1495,6 +1515,33 @@ export const Canvas: React.FC<{containerRef={canvasRef}/>)}+ {activeElementInstallRequest === null ||+ elementInstallReview === null ? null : (+ <ElementInstallConfirmation+ currentCompositionMetadata={+ config === null ||+ currentCompositionId !== activeElementInstallRequest.compositionId+ ? null+ : {+ durationInFrames: config.durationInFrames,+ fps: config.fps,+ height: config.height,+ width: config.width,+ }+ }+ currentPlan={elementInstallReview.currentPlan}+ dependenciesToReview={elementInstallReview.dependenciesToReview}+ missingPackages={elementInstallReview.missingPackages}+ newPlan={elementInstallReview.newPlan}+ onClose={closeElementInstallDialog}+ request={activeElementInstallRequest}+ sourceIsUnverified={elementInstallReview.sourceIsUnverified}+ sourceLabel={elementInstallReview.sourceLabel}+ usesBrowserDependencyResolution={+ getBrowserStudioOperations() !== null+ }+ />+ )}</>);};diff --git a/packages/studio/src/components/ElementInstallConfirmation.tsx b/packages/studio/src/components/ElementInstallConfirmation.tsxindex 876d121a6a..082f2407f3 100644--- a/packages/studio/src/components/ElementInstallConfirmation.tsx+++ b/packages/studio/src/components/ElementInstallConfirmation.tsx@@ -1,12 +1,58 @@-import React from 'react';+import {StudioProtocolInternals} from '@remotion/studio-protocol';+import type {+ ElementInstallExpectedFileState,+ ElementInstallRequest,+} from '@remotion/studio-shared';+import React, {+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import {createPortal} from 'react-dom';+import {Internals} from 'remotion';+import {ShortcutHint} from '../error-overlay/remotion-overlay/ShortcutHint';import {INPUT_BACKGROUND,LIGHT_TEXT,+ TRANSPARENT,WARNING_COLOR,WHITE,WHITE_ALPHA_12,} from '../helpers/colors';-import {WarningTriangle} from './NewComposition/ValidationMessage';+import {+ FOCUS_VISIBLE_ONLY_CLASS_NAME,+ HOVERABLE_CLASS_NAME,+ hoverableStyle,+} from '../helpers/hoverable';+import {resolvedStackToSymbolicated} from '../helpers/resolved-stack-to-symbolicated';+import {useCreateComposition} from '../helpers/use-create-composition';+import {validateCompositionName} from '../helpers/validate-new-comp-data';+import {useZIndex} from '../state/z-index';+import {Button} from './Button';+import {prepareElementInstall} from './element-install-api';+import {insertElement} from './import-assets';+import {Flex, Row, Spacing} from './layout';+import {getPortal} from './Menu/portals';+import {ModalButton} from './ModalButton';+import {ModalContainer} from './ModalContainer';+import {ModalFooterContainer} from './ModalFooter';+import {ModalHeader} from './ModalHeader';+import {+ NewCompositionFields,+ type NewCompositionFormValues,+} from './NewComposition/NewComposition';+import {+ ValidationMessage,+ WarningTriangle,+} from './NewComposition/ValidationMessage';+import {showNotification} from './Notifications/NotificationCenter';+import {+ hasResolvedStack,+ useResolvedStack,+} from './Timeline/use-resolved-stack';const container: React.CSSProperties = {display: 'flex',@@ -18,6 +64,14 @@ const container: React.CSSProperties = {lineHeight: 1.5,};+const dialogContent: React.CSSProperties = {+ ...container,+ padding: 16,+ width: 'min(640px, calc(100vw - 40px))',+ maxHeight: 'min(720px, calc(100vh - 140px))',+ overflowY: 'auto',+};+const sectionStyle: React.CSSProperties = {display: 'flex',flexDirection: 'column',@@ -42,7 +96,7 @@ const metadataStyle: React.CSSProperties = {const metadataRowStyle: React.CSSProperties = {display: 'grid',- gridTemplateColumns: '100px minmax(0, 1fr)',+ gridTemplateColumns: '120px minmax(0, 1fr)',alignItems: 'baseline',gap: 12,};@@ -199,6 +253,56 @@ const sourceCodeStyle: React.CSSProperties = {lineHeight: 'inherit',};+const destinationControlStyle: React.CSSProperties = {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 16,+};++const destinationOptionsStyle: React.CSSProperties = {+ display: 'flex',+ overflow: 'hidden',+ border: `1px solid ${WHITE_ALPHA_12}`,+ borderRadius: 4,+};++const destinationOptionStyle: React.CSSProperties = {+ appearance: 'none',+ border: 0,+ cursor: 'default',+ fontFamily: 'sans-serif',+ fontSize: 11,+ fontWeight: 400,+ lineHeight: 1.5,+ padding: '2px 7px',+};++const getDestinationOptionStyle = ({+ disabled,+ selected,+}: {+ readonly disabled: boolean;+ readonly selected: boolean;+}): React.CSSProperties => ({+ ...destinationOptionStyle,+ opacity: disabled ? 0.5 : 1,+ ...hoverableStyle({+ idleBackground: selected ? INPUT_BACKGROUND : TRANSPARENT,+ hoverBackground: selected ? INPUT_BACKGROUND : TRANSPARENT,+ idleColor: selected ? WHITE : LIGHT_TEXT,+ hoverColor: disabled ? LIGHT_TEXT : WHITE,+ }),+});++const footerStyle: React.CSSProperties = {+ minWidth: 0,+};++const cancelStyle: React.CSSProperties = {+ minWidth: 90,+};+const makeSourceControlsVisible = (sourceCode: string) => {return sourceCode.replace(/[\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g,@@ -247,116 +351,496 @@ export const ElementLibraryAddConfirmation: React.FC<{);};-export const ElementInstallConfirmation: React.FC<{- readonly displayName: string;- readonly sourceLabel: string;- readonly sourceIsUnverified: boolean;- readonly compositionId: string;+type ElementInstallPlan = {+ readonly compositionFile: string;readonly filePath: string;- readonly overwritesExistingFile: boolean;+ readonly expectedFileState: ElementInstallExpectedFileState;+};++type NewCompositionPlanState =+ | {+ readonly type: 'loading';+ readonly folderStack: string;+ }+ | {+ readonly type: 'ready';+ readonly folderStack: string | null;+ readonly plan: ElementInstallPlan;+ }+ | {+ readonly type: 'error';+ readonly folderStack: string;+ readonly reason: string;+ };++type CurrentCompositionMetadata = {+ readonly durationInFrames: number;+ readonly fps: number;+ readonly height: number;+ readonly width: number;+};++export const ElementInstallConfirmation: React.FC<{+ readonly currentCompositionMetadata: CurrentCompositionMetadata | null;+ readonly currentPlan: ElementInstallPlan | null;readonly dependenciesToReview: string[];readonly missingPackages: string[];- readonly sourceCode: string;+ readonly newPlan: ElementInstallPlan;+ readonly onClose: () => void;+ readonly request: ElementInstallRequest;+ readonly sourceIsUnverified: boolean;+ readonly sourceLabel: string;readonly usesBrowserDependencyResolution: boolean;}> = ({- displayName,- sourceLabel,- sourceIsUnverified,- compositionId,- filePath,- overwritesExistingFile,+ currentCompositionMetadata,+ currentPlan,dependenciesToReview,missingPackages,- sourceCode,+ newPlan,+ onClose,+ request,+ sourceIsUnverified,+ sourceLabel,usesBrowserDependencyResolution,}) => {- return (- <div style={container}>- <dl style={metadataStyle} aria-label="Installation details">- <div style={metadataRowStyle}>- <dt style={metadataTermStyle}>Element</dt>- <dd style={metadataDescriptionStyle}>{displayName}</dd>- </div>- <div style={metadataRowStyle}>- <dt style={metadataTermStyle}>Request source</dt>- <dd- style={- sourceIsUnverified- ? unverifiedSourceStyle- : metadataDescriptionStyle- }- >- {sourceLabel}- </dd>- </div>- <div style={metadataRowStyle}>- <dt style={metadataTermStyle}>Composition</dt>- <dd style={metadataDescriptionStyle}>- <code style={codeStyle}>{compositionId}</code>- </dd>- </div>- <div style={metadataRowStyle}>- <dt style={metadataTermStyle}>Destination</dt>- <dd style={metadataDescriptionStyle}>- <code style={codeStyle}>{filePath}</code>- </dd>- </div>- {overwritesExistingFile ? (- <div style={metadataRowStyle}>- <dt style={metadataTermStyle}>File change</dt>- <dd style={overwriteStyle}>Replace existing source file</dd>+ const {compositions} = useContext(Internals.CompositionManager);+ const {currentZIndex} = useZIndex();+ const [mode, setMode] = useState<'current-composition' | 'new-composition'>(+ currentPlan === null ? 'new-composition' : 'current-composition',+ );+ const [submitting, setSubmitting] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const [newCompositionValues, setNewCompositionValues] =+ useState<NewCompositionFormValues>(() => {+ const elementComponentName =+ StudioProtocolInternals.getElementComponentNameFromSourceCode(+ request.element.sourceCode,+ ) ?? 'Element';+ const baseName = `${elementComponentName}Composition`;+ let candidate = baseName;+ let suffix = 2;+ while (validateCompositionName(candidate, compositions) !== null) {+ candidate = `${baseName}${suffix}`;+ suffix++;+ }++ const size =+ request.element.dimensions ??+ (currentCompositionMetadata === null+ ? {width: 1920, height: 1080}+ : {+ width: currentCompositionMetadata.width,+ height: currentCompositionMetadata.height,+ });++ return {+ durationInFrames:+ request.element.durationInFrames ??+ currentCompositionMetadata?.durationInFrames ??+ 150,+ folder: {folderName: null, parentName: null, stack: null},+ fps: currentCompositionMetadata?.fps ?? 30,+ id: candidate,+ size,+ };+ });+ const selectedFolderStack = newCompositionValues.folder.stack;+ const resolvedFolderLocation = useResolvedStack(selectedFolderStack);+ const folderSymbolicatedStack = useMemo(+ () => resolvedStackToSymbolicated(resolvedFolderLocation),+ [resolvedFolderLocation],+ );+ const folderCompositionFile =+ folderSymbolicatedStack?.originalFileName ?? null;+ const [newCompositionPlanState, setNewCompositionPlanState] =+ useState<NewCompositionPlanState>({+ folderStack: null,+ type: 'ready',+ plan: newPlan,+ });++ useEffect(() => {+ if (selectedFolderStack === null) {+ setNewCompositionPlanState({+ folderStack: null,+ type: 'ready',+ plan: newPlan,+ });+ return;+ }++ if (!hasResolvedStack(selectedFolderStack)) {+ setNewCompositionPlanState({+ folderStack: selectedFolderStack,+ type: 'loading',+ });+ return;+ }++ if (folderCompositionFile === null) {+ setNewCompositionPlanState({+ folderStack: selectedFolderStack,+ type: 'error',+ reason:+ 'Could not determine where the new composition should be created.',+ });+ return;+ }++ let canceled = false;+ setNewCompositionPlanState({+ folderStack: selectedFolderStack,+ type: 'loading',+ });+ prepareElementInstall({+ destination: {+ type: 'new-composition',+ compositionFile: folderCompositionFile,+ },+ element: request.element,+ })+ .then((result) => {+ if (canceled) {+ return;+ }++ setNewCompositionPlanState(+ result.success+ ? {+ folderStack: selectedFolderStack,+ type: 'ready',+ plan: result.plan,+ }+ : {+ folderStack: selectedFolderStack,+ type: 'error',+ reason: result.reason,+ },+ );+ })+ .catch((error) => {+ if (!canceled) {+ setNewCompositionPlanState({+ folderStack: selectedFolderStack,+ type: 'error',+ reason: error instanceof Error ? error.message : String(error),+ });+ }+ });++ return () => {+ canceled = true;+ };+ }, [folderCompositionFile, newPlan, request.element, selectedFolderStack]);++ const {+ createComposition,+ heightValidationMessage,+ nameValidationMessage,+ valid: newCompositionValuesAreValid,+ widthValidationMessage,+ } = useCreateComposition({+ canvasCapture: null,+ compositions,+ durationInFrames: newCompositionValues.durationInFrames,+ folderName: newCompositionValues.folder.folderName,+ newId: newCompositionValues.id,+ parentName: newCompositionValues.folder.parentName,+ selectedFrameRate: newCompositionValues.fps,+ size: newCompositionValues.size,+ });+ const activeNewCompositionPlanState =+ newCompositionPlanState.folderStack === selectedFolderStack+ ? newCompositionPlanState+ : null;+ const selectedNewCompositionPlan =+ activeNewCompositionPlanState?.type === 'ready'+ ? activeNewCompositionPlanState.plan+ : null;+ const selectedPlan =+ mode === 'current-composition' ? currentPlan : selectedNewCompositionPlan;+ const folderTargetIsReady =+ selectedFolderStack === null ||+ (hasResolvedStack(selectedFolderStack) && folderCompositionFile !== null);+ const canSubmit =+ !submitting &&+ (mode === 'current-composition'+ ? currentPlan !== null+ : newCompositionValuesAreValid &&+ folderTargetIsReady &&+ selectedNewCompositionPlan !== null);++ const submit = useCallback(async () => {+ if (!canSubmit) {+ return;+ }++ setSubmitting(true);+ if (mode === 'new-composition') {+ if (selectedNewCompositionPlan === null) {+ setSubmitting(false);+ return;+ }++ const created = await createComposition({+ signal: new AbortController().signal,+ symbolicatedStack:+ selectedFolderStack === null ? null : folderSymbolicatedStack,+ });+ if (!created.success) {+ showNotification(+ `Could not create composition: ${created.reason}`,+ 4000,+ );+ setSubmitting(false);+ return;+ }++ await insertElement({+ compositionFile: selectedNewCompositionPlan.compositionFile,+ compositionId: newCompositionValues.id,+ element: request.element,+ expectedFileState: selectedNewCompositionPlan.expectedFileState,+ from: null,+ overwriteExisting: selectedNewCompositionPlan.expectedFileState.exists,+ position: null,+ });+ onClose();+ return;+ }++ if (currentPlan === null) {+ setSubmitting(false);+ return;+ }++ await insertElement({+ compositionFile: request.compositionFile,+ compositionId: request.compositionId,+ element: request.element,+ expectedFileState: currentPlan.expectedFileState,+ from: request.from,+ overwriteExisting: currentPlan.expectedFileState.exists,+ position: request.position,+ });+ onClose();+ }, [+ canSubmit,+ createComposition,+ currentPlan,+ folderSymbolicatedStack,+ mode,+ newCompositionValues.id,+ onClose,+ request,+ selectedFolderStack,+ selectedNewCompositionPlan,+ ]);++ const cancel = useCallback(() => {+ if (!submitting) {+ onClose();+ }+ }, [onClose, submitting]);++ const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback(+ (event) => {+ event.preventDefault();+ submit();+ },+ [submit],+ );++ return createPortal(+ <ModalContainer onOutsideClick={cancel} onEscape={cancel}>+ <ModalHeader title="Install Element" onClose={cancel} />+ <form onSubmit={onSubmit}>+ <div style={dialogContent}>+ <div style={destinationControlStyle}>+ <div style={sectionTitleStyle}>Add to</div>+ <div+ aria-label="Installation destination"+ role="group"+ style={destinationOptionsStyle}+ >+ <button+ aria-pressed={mode === 'current-composition'}+ className={`${HOVERABLE_CLASS_NAME} ${FOCUS_VISIBLE_ONLY_CLASS_NAME}`}+ disabled={currentPlan === null}+ onClick={() => setMode('current-composition')}+ style={getDestinationOptionStyle({+ disabled: currentPlan === null,+ selected: mode === 'current-composition',+ })}+ type="button"+ >+ Current composition+ </button>+ <button+ aria-pressed={mode === 'new-composition'}+ className={`${HOVERABLE_CLASS_NAME} ${FOCUS_VISIBLE_ONLY_CLASS_NAME}`}+ onClick={() => {+ setMode('new-composition');+ requestAnimationFrame(() => inputRef.current?.select());+ }}+ style={{+ ...getDestinationOptionStyle({+ disabled: false,+ selected: mode === 'new-composition',+ }),+ borderLeft: `1px solid ${WHITE_ALPHA_12}`,+ }}+ type="button"+ >+ New composition+ </button>+ </div></div>- ) : null}- </dl>- {dependenciesToReview.length > 0 ? (- <section- style={sectionStyle}- aria-labelledby="element-install-dependencies"- >- <h3 id="element-install-dependencies" style={sectionTitleStyle}>- Dependencies- </h3>- <ul style={dependencyListStyle} role="list">- {dependenciesToReview.map((packageName) => {- const willInstall = missingPackages.includes(packageName);- return (- <li key={packageName} style={dependencyRowStyle}>- <div style={dependencyNameStyle}>{packageName}</div>- <div- style={- willInstall- ? dependencyInstallStatusStyle- : dependencyInstalledStatusStyle- }- >- {willInstall ? 'Will be installed' : 'Installed'}- </div>- </li>- );- })}- </ul>- </section>- ) : null}+ {currentPlan === null ? (+ <div style={warningStyle} role="status">+ <WarningTriangle style={warningIconStyle} />+ <p style={warningDescriptionStyle}>+ Studio could not find a safe place in ā{request.compositionId}ā+ to insert the Element. Install it into a new composition+ instead.+ </p>+ </div>+ ) : null}- <div style={warningStyle}>- <WarningTriangle style={warningIconStyle} />- <p style={warningDescriptionStyle}>- This adds executable source code to your project.- {usesBrowserDependencyResolution- ? null- : ' Package lifecycle scripts may also run during installation, with access to your files and the network.'}- </p>- </div>+ {mode === 'new-composition' ? (+ <section style={sectionStyle} aria-label="New composition settings">+ <NewCompositionFields+ heightValidationMessage={heightValidationMessage}+ inputRef={inputRef}+ nameValidationMessage={nameValidationMessage}+ setValues={setNewCompositionValues}+ values={newCompositionValues}+ widthValidationMessage={widthValidationMessage}+ />+ {activeNewCompositionPlanState?.type === 'error' ? (+ <ValidationMessage+ align="flex-start"+ message={activeNewCompositionPlanState.reason}+ type="error"+ />+ ) : null}+ </section>+ ) : null}- <details style={sourceDetailsStyle}>- <summary style={sourceSummaryStyle}>Source code</summary>- <pre style={sourceCodeBlockStyle}>- <code style={sourceCodeStyle}>- {makeSourceControlsVisible(sourceCode)}- </code>- </pre>- </details>- </div>+ <dl style={metadataStyle} aria-label="Installation details">+ <div style={metadataRowStyle}>+ <dt style={metadataTermStyle}>Element</dt>+ <dd style={metadataDescriptionStyle}>+ {request.element.displayName}+ </dd>+ </div>+ <div style={metadataRowStyle}>+ <dt style={metadataTermStyle}>Request source</dt>+ <dd+ style={+ sourceIsUnverified+ ? unverifiedSourceStyle+ : metadataDescriptionStyle+ }+ >+ {sourceLabel}+ </dd>+ </div>+ <div style={metadataRowStyle}>+ <dt style={metadataTermStyle}>Composition</dt>+ <dd style={metadataDescriptionStyle}>+ <code style={codeStyle}>+ {mode === 'current-composition'+ ? request.compositionId+ : newCompositionValues.id}+ </code>+ </dd>+ </div>+ <div style={metadataRowStyle}>+ <dt style={metadataTermStyle}>Destination</dt>+ <dd style={metadataDescriptionStyle}>+ <code style={codeStyle}>+ {selectedPlan?.filePath ?? 'Reviewing destinationā¦'}+ </code>+ </dd>+ </div>+ {selectedPlan?.expectedFileState.exists ? (+ <div style={metadataRowStyle}>+ <dt style={metadataTermStyle}>File change</dt>+ <dd style={overwriteStyle}>Replace existing source file</dd>+ </div>+ ) : null}+ </dl>++ {dependenciesToReview.length > 0 ? (+ <section+ style={sectionStyle}+ aria-labelledby="element-install-dependencies"+ >+ <h3 id="element-install-dependencies" style={sectionTitleStyle}>+ Dependencies+ </h3>+ <ul style={dependencyListStyle} role="list">+ {dependenciesToReview.map((packageName) => {+ const willInstall = missingPackages.includes(packageName);+ return (+ <li key={packageName} style={dependencyRowStyle}>+ <div style={dependencyNameStyle}>{packageName}</div>+ <div+ style={+ willInstall+ ? dependencyInstallStatusStyle+ : dependencyInstalledStatusStyle+ }+ >+ {willInstall ? 'Will be installed' : 'Installed'}+ </div>+ </li>+ );+ })}+ </ul>+ </section>+ ) : null}++ <div style={warningStyle}>+ <WarningTriangle style={warningIconStyle} />+ <p style={warningDescriptionStyle}>+ This adds executable source code to your project.+ {usesBrowserDependencyResolution+ ? null+ : ' Package lifecycle scripts may also run during installation, with access to your files and the network.'}+ </p>+ </div>++ <details style={sourceDetailsStyle}>+ <summary style={sourceSummaryStyle}>Source code</summary>+ <pre style={sourceCodeBlockStyle}>+ <code style={sourceCodeStyle}>+ {makeSourceControlsVisible(request.element.sourceCode)}+ </code>+ </pre>+ </details>+ </div>+ <ModalFooterContainer style={footerStyle}>+ <Row align="center">+ <Flex />+ <Button disabled={submitting} onClick={cancel} style={cancelStyle}>+ Cancel+ </Button>+ <Spacing x={1} />+ <ModalButton+ autoFocus={mode === 'current-composition'}+ disabled={!canSubmit}+ onClick={submit}+ >+ {submitting ? 'Installingā¦' : 'Install'}+ <ShortcutHint keyToPress="āµ" cmdOrCtrl={false} />+ </ModalButton>+ </Row>+ </ModalFooterContainer>+ </form>+ </ModalContainer>,+ getPortal(currentZIndex),);};diff --git a/packages/studio/src/components/NewComposition/NewCompDuration.tsx b/packages/studio/src/components/NewComposition/NewCompDuration.tsxindex 8566e81c58..158ccec149 100644--- a/packages/studio/src/components/NewComposition/NewCompDuration.tsx+++ b/packages/studio/src/components/NewComposition/NewCompDuration.tsx@@ -32,6 +32,7 @@ export const NewCompDuration: React.FC<{<div style={rightRow}><InputAndValidationContainer><InputDragger+ aria-label="Duration in frames"type="number"value={durationInFrames}onTextChange={onDurationInFramesChanged}diff --git a/packages/studio/src/components/NewComposition/NewComposition.tsx b/packages/studio/src/components/NewComposition/NewComposition.tsxindex f7d143acf4..31b91fae96 100644--- a/packages/studio/src/components/NewComposition/NewComposition.tsx+++ b/packages/studio/src/components/NewComposition/NewComposition.tsx@@ -1,4 +1,9 @@-import type {ChangeEventHandler} from 'react';+import type {+ ChangeEventHandler,+ Dispatch,+ RefObject,+ SetStateAction,+} from 'react';import React, {useCallback,useContext,@@ -97,23 +102,42 @@ const FolderDropdownLabel: React.FC<{const rootFolderId = 'new-composition-root-folder';const folderSelectIdPrefix = 'new-composition-folder-';-const NewCompositionLoaded: React.FC<{- readonly folderName: string | null;- readonly parentName: string | null;- readonly stack: string | null;- readonly canvasCapture: CanvasCaptureImport | null;-}> = ({canvasCapture, folderName, parentName, stack}) => {- const {compositions, folders} = useContext(Internals.CompositionManager);+export type NewCompositionFormValues = {+ readonly durationInFrames: number;+ readonly folder: {+ readonly folderName: string | null;+ readonly parentName: string | null;+ readonly stack: string | null;+ };+ readonly fps: number;+ readonly id: string;+ readonly size: {+ readonly height: number;+ readonly width: number;+ };+};++export const NewCompositionFields: React.FC<{+ readonly heightValidationMessage: string | null;+ readonly inputRef: RefObject<HTMLInputElement | null>;+ readonly nameValidationMessage: string | null;+ readonly setValues: Dispatch<SetStateAction<NewCompositionFormValues>>;+ readonly values: NewCompositionFormValues;+ readonly widthValidationMessage: string | null;+}> = ({+ heightValidationMessage,+ inputRef,+ nameValidationMessage,+ setValues,+ values,+ widthValidationMessage,+}) => {+ const {folders} = useContext(Internals.CompositionManager);const {compositionSortOrder} = useContext(FolderContext);- const [selectedFolder, setSelectedFolder] = useState(() => ({- folderName,- parentName,- stack,- }));- const selectedFolderId = selectedFolder.folderName+ const selectedFolderId = values.folder.folderName? `${folderSelectIdPrefix}${getFolderId({- folderName: selectedFolder.folderName,- parentName: selectedFolder.parentName,+ folderName: values.folder.folderName,+ parentName: values.folder.parentName,})}`: rootFolderId;const folderValues = useMemo((): ComboboxValue[] => {@@ -144,13 +168,16 @@ const NewCompositionLoaded: React.FC<{id: rootFolderId,keyHint: null,label: <FolderDropdownLabel folderPath={null} indentation={0} />,- leftItem: selectedFolder.folderName === null ? <Checkmark /> : null,+ leftItem: values.folder.folderName === null ? <Checkmark /> : null,onClick: () => {- setSelectedFolder({- folderName: null,- parentName: null,- stack: null,- });+ setValues((current) => ({+ ...current,+ folder: {+ folderName: null,+ parentName: null,+ stack: null,+ },+ }));},quickSwitcherLabel: 'None',subMenu: null,@@ -183,11 +210,14 @@ const NewCompositionLoaded: React.FC<{),leftItem: selectedFolderId === id ? <Checkmark /> : null,onClick: () => {- setSelectedFolder({- folderName: folder.name,- parentName: folder.parent,- stack: folder.stack,- });+ setValues((current) => ({+ ...current,+ folder: {+ folderName: folder.name,+ parentName: folder.parent,+ stack: folder.stack,+ },+ }));},quickSwitcherLabel: folderPath,subMenu: null,@@ -200,9 +230,219 @@ const NewCompositionLoaded: React.FC<{}, [compositionSortOrder,folders,- selectedFolder.folderName,selectedFolderId,+ setValues,+ values.folder.folderName,]);++ const onWidthChanged = useCallback(+ (newValue: string) => {+ setValues((current) => ({+ ...current,+ size: {height: current.size.height, width: Number(newValue)},+ }));+ },+ [setValues],+ );+ const onWidthDirectlyChanged = useCallback(+ (newWidth: number) => {+ setValues((current) => ({+ ...current,+ size: {height: current.size.height, width: newWidth},+ }));+ },+ [setValues],+ );+ const onHeightChanged = useCallback(+ (newValue: string) => {+ setValues((current) => ({+ ...current,+ size: {height: Number(newValue), width: current.size.width},+ }));+ },+ [setValues],+ );+ const onHeightDirectlyChanged = useCallback(+ (newHeight: number) => {+ setValues((current) => ({+ ...current,+ size: {height: newHeight, width: current.size.width},+ }));+ },+ [setValues],+ );+ const onNameChange: ChangeEventHandler<HTMLInputElement> = useCallback(+ (event) => {+ setValues((current) => ({...current, id: event.target.value}));+ },+ [setValues],+ );+ const onTextFpsChange = useCallback(+ (newFps: string) => {+ setValues((current) => ({...current, fps: Number(newFps)}));+ },+ [setValues],+ );+ const onFpsChange = useCallback(+ (newFps: number) => {+ setValues((current) => ({...current, fps: newFps}));+ },+ [setValues],+ );+ const setDurationInFrames: Dispatch<SetStateAction<number>> = useCallback(+ (update) => {+ setValues((current) => ({+ ...current,+ durationInFrames:+ typeof update === 'function'+ ? update(current.durationInFrames)+ : update,+ }));+ },+ [setValues],+ );++ return (+ <>+ <div style={optionRow}>+ <div style={label}>Folder</div>+ <div style={rightRow}>+ <Combobox+ values={folderValues}+ selectedId={selectedFolderId}+ style={folderSelectStyle}+ title="Folder"+ />+ </div>+ </div>+ <div style={optionRow}>+ <div style={label}>ID</div>+ <div style={rightRow}>+ <InputAndValidationContainer>+ <RemotionInput+ ref={inputRef}+ value={values.id}+ onChange={onNameChange}+ type="text"+ autoFocus+ placeholder="Composition ID"+ status="ok"+ rightAlign+ />+ {nameValidationMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={nameValidationMessage}+ type="error"+ />+ </>+ ) : null}+ </InputAndValidationContainer>+ </div>+ </div>+ <div style={optionRow}>+ <div style={label}>Width</div>+ <div style={rightRow}>+ <InputAndValidationContainer>+ <InputDragger+ aria-label="Width"+ type="number"+ value={values.size.width}+ placeholder="Width"+ onTextChange={onWidthChanged}+ name="width"+ step={2}+ min={2}+ required+ status="ok"+ formatter={(width) => `${width}px`}+ max={100000000}+ onValueChange={onWidthDirectlyChanged}+ rightAlign={false}+ />+ {widthValidationMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={widthValidationMessage}+ type="error"+ />+ </>+ ) : null}+ </InputAndValidationContainer>+ </div>+ </div>+ <div style={optionRow}>+ <div style={label}>Height</div>+ <div style={rightRow}>+ <InputAndValidationContainer>+ <InputDragger+ aria-label="Height"+ type="number"+ value={values.size.height}+ onTextChange={onHeightChanged}+ placeholder="Height"+ name="height"+ step={2}+ required+ formatter={(height) => `${height}px`}+ min={2}+ status="ok"+ max={100000000}+ onValueChange={onHeightDirectlyChanged}+ rightAlign={false}+ />+ {heightValidationMessage ? (+ <>+ <Spacing y={1} block />+ <ValidationMessage+ align="flex-start"+ message={heightValidationMessage}+ type="error"+ />+ </>+ ) : null}+ </InputAndValidationContainer>+ </div>+ </div>+ <NewCompDuration+ durationInFrames={values.durationInFrames}+ setDurationInFrames={setDurationInFrames}+ />+ <div style={optionRow}>+ <div style={label}>FPS</div>+ <div style={rightRow}>+ <InputDragger+ aria-label="FPS"+ type="number"+ value={values.fps}+ onTextChange={onTextFpsChange}+ placeholder="Frame rate (fps)"+ name="fps"+ min={1}+ required+ status="ok"+ max={240}+ step={0.01}+ onValueChange={onFpsChange}+ rightAlign={false}+ />+ </div>+ </div>+ </>+ );+};++const NewCompositionLoaded: React.FC<{+ readonly folderName: string | null;+ readonly parentName: string | null;+ readonly stack: string | null;+ readonly canvasCapture: CanvasCaptureImport | null;+}> = ({canvasCapture, folderName, parentName, stack}) => {+ const {compositions} = useContext(Internals.CompositionManager);const resolvedComposition = Internals.useResolvedVideoConfig(null);const initialComposition =resolvedComposition?.type === 'success' ||@@ -213,9 +453,16 @@ const NewCompositionLoaded: React.FC<{initialComposition,canvasCapture?.durationInSeconds ?? null,);- const [newId, setName] = useState(() =>- getUniqueCompositionName(compositions),- );+ const [values, setValues] = useState<NewCompositionFormValues>(() => ({+ durationInFrames: initialDimensions.durationInFrames,+ folder: {folderName, parentName, stack},+ fps: initialDimensions.fps,+ id: getUniqueCompositionName(compositions),+ size: {+ height: initialDimensions.height,+ width: initialDimensions.width,+ },+ }));const inputRef = useRef<HTMLInputElement>(null);useEffect(() => {@@ -224,81 +471,21 @@ const NewCompositionLoaded: React.FC<{input.select();}, []);- const [selectedFrameRate, setFrameRate] = useState(initialDimensions.fps);- const [size, setSize] = useState(() => ({- width: initialDimensions.width,- height: initialDimensions.height,- }));- const [durationInFrames, setDurationInFrames] = useState(- initialDimensions.durationInFrames,- );-- 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 {codemod,createComposition,- heightValidationMessage: compHeightErrMessage,- nameValidationMessage: compNameErrMessage,+ heightValidationMessage,+ nameValidationMessage,valid,- widthValidationMessage: compWidthErrMessage,+ widthValidationMessage,} = useCreateComposition({compositions,- durationInFrames,- folderName: selectedFolder.folderName,- newId,- parentName: selectedFolder.parentName,- selectedFrameRate,- size,+ durationInFrames: values.durationInFrames,+ folderName: values.folder.folderName,+ newId: values.id,+ parentName: values.folder.parentName,+ selectedFrameRate: values.fps,+ size: values.size,canvasCapture:canvasCapture === null? null@@ -358,131 +545,14 @@ const NewCompositionLoaded: React.FC<{/><form onSubmit={onSubmit}><div style={content}>- <div style={optionRow}>- <div style={label}>Folder</div>- <div style={rightRow}>- <Combobox- values={folderValues}- selectedId={selectedFolderId}- style={folderSelectStyle}- title="Folder"- />- </div>- </div>- <div style={optionRow}>- <div style={label}>ID</div>- <div style={rightRow}>- <InputAndValidationContainer>- <RemotionInput- ref={inputRef}- 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}- </InputAndValidationContainer>- </div>- </div>- <div style={optionRow}>- <div style={label}>Width</div>- <div style={rightRow}>- <InputAndValidationContainer>- <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}- </InputAndValidationContainer>- </div>- </div>- <div style={optionRow}>- <div style={label}>Height</div>- <div style={rightRow}>- <InputAndValidationContainer>- <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}- </InputAndValidationContainer>- </div>- </div>- <NewCompDuration- durationInFrames={durationInFrames}- setDurationInFrames={setDurationInFrames}+ <NewCompositionFields+ heightValidationMessage={heightValidationMessage}+ inputRef={inputRef}+ nameValidationMessage={nameValidationMessage}+ setValues={setValues}+ values={values}+ widthValidationMessage={widthValidationMessage}/>- <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@@ -491,7 +561,7 @@ const NewCompositionLoaded: React.FC<{genericSubmitLabel="Add to root file"submitLabel={({relativeRootPath}) => `Add to ${relativeRootPath}`}codemod={codemod}- stack={selectedFolder.stack}+ stack={values.folder.stack}valid={valid}onSuccess={null}applyCodemod={({signal, symbolicatedStack}) =>