🎥 Make videos programmatically with React
@remotion/studio: Prefetch composition component info
JonnyBurger6353df7bd599
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsindex a23872c066..85706b7968 100644--- a/packages/studio-server/src/helpers/resolve-composition-component.ts+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -6,6 +6,7 @@ import type {JSXAttribute,JSXElement,} from '@babel/types';+import type {namedTypes} from 'ast-types';import * as recast from 'recast';import {parseAst} from '../codemods/parse-ast';@@ -27,6 +28,7 @@ export type ResolvedCompositionComponent = {source: string;line: number;column: number;+ canAddSequence: boolean;};type ImportTarget = {@@ -408,6 +410,300 @@ const findDefaultExportLocation = (ast: File): SourceLocation | null => {return location;};+type LocalComponentDeclaration =+ | namedTypes.VariableDeclarator+ | namedTypes.FunctionDeclaration+ | namedTypes.ClassDeclaration;++type FunctionLikeNode =+ | namedTypes.ArrowFunctionExpression+ | namedTypes.FunctionExpression+ | namedTypes.FunctionDeclaration;++type DefaultExportDeclaration =+ namedTypes.ExportDefaultDeclaration['declaration'];++const findLocalComponentDeclaration = ({+ ast,+ name,+}: {+ ast: File;+ name: string;+}): LocalComponentDeclaration | null => {+ let declaration: LocalComponentDeclaration | null = null;++ recast.types.visit(ast, {+ visitVariableDeclarator(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id.type === 'Identifier' && node.id.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitFunctionDeclaration(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitClassDeclaration(astPath) {+ if (declaration) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ declaration = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return declaration;+};++const getTopLevelReturnStatement = (+ statements: namedTypes.Statement[],+): namedTypes.ReturnStatement | null => {+ const returnStatements: namedTypes.ReturnStatement[] = [];+ for (const statement of statements) {+ if (recast.types.namedTypes.ReturnStatement.check(statement)) {+ returnStatements.push(statement);+ }+ }++ if (returnStatements.length !== 1) {+ return null;+ }++ const singleReturn = returnStatements[0];+ const finalStatement = statements.at(-1);+ if (singleReturn !== finalStatement) {+ return null;+ }++ return singleReturn;+};++const getReturnedJsxFromFunction = (+ fn: FunctionLikeNode,+): namedTypes.JSXElement | namedTypes.JSXFragment | null => {+ if (fn.type === 'ArrowFunctionExpression') {+ if (fn.body.type === 'JSXElement' || fn.body.type === 'JSXFragment') {+ return fn.body;+ }++ if (fn.body.type !== 'BlockStatement') {+ return null;+ }++ const arrowReturnStatement = getTopLevelReturnStatement(fn.body.body);+ if (!arrowReturnStatement?.argument) {+ return null;+ }++ return arrowReturnStatement.argument.type === 'JSXElement' ||+ arrowReturnStatement.argument.type === 'JSXFragment'+ ? arrowReturnStatement.argument+ : null;+ }++ if (fn.body.type !== 'BlockStatement') {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(fn.body.body);+ if (!returnStatement?.argument) {+ return null;+ }++ return returnStatement.argument.type === 'JSXElement' ||+ returnStatement.argument.type === 'JSXFragment'+ ? returnStatement.argument+ : null;+};++const findRenderMethod = (+ declaration: namedTypes.ClassDeclaration,+): namedTypes.ClassMethod | null => {+ const renderMethod = declaration.body.body.find((member) => {+ return (+ member.type === 'ClassMethod' &&+ member.kind === 'method' &&+ member.key.type === 'Identifier' &&+ member.key.name === 'render'+ );+ });++ return renderMethod?.type === 'ClassMethod' ? renderMethod : null;+};++const getComponentRootNode = (+ declaration: LocalComponentDeclaration | DefaultExportDeclaration,+): namedTypes.JSXElement | namedTypes.JSXFragment | null => {+ if (declaration.type === 'VariableDeclarator') {+ if (+ !declaration.init ||+ (declaration.init.type !== 'ArrowFunctionExpression' &&+ declaration.init.type !== 'FunctionExpression')+ ) {+ return null;+ }++ return getReturnedJsxFromFunction(declaration.init);+ }++ if (+ declaration.type === 'ArrowFunctionExpression' ||+ declaration.type === 'FunctionExpression' ||+ declaration.type === 'FunctionDeclaration'+ ) {+ return getReturnedJsxFromFunction(declaration);+ }++ if (declaration.type !== 'ClassDeclaration') {+ return null;+ }++ const renderMethod = findRenderMethod(declaration);+ if (!renderMethod) {+ return null;+ }++ const returnStatement = getTopLevelReturnStatement(renderMethod.body.body);+ if (!returnStatement?.argument) {+ return null;+ }++ return returnStatement.argument.type === 'JSXElement' ||+ returnStatement.argument.type === 'JSXFragment'+ ? returnStatement.argument+ : null;+};++const createSequenceElement = (): namedTypes.JSXElement => {+ return recast.types.builders.jsxElement(+ recast.types.builders.jsxOpeningElement(+ recast.types.builders.jsxIdentifier('Sequence'),+ [],+ ),+ recast.types.builders.jsxClosingElement(+ recast.types.builders.jsxIdentifier('Sequence'),+ ),+ [],+ );+};++const getDefaultExportDeclaration = (+ ast: File,+): LocalComponentDeclaration | DefaultExportDeclaration | null => {+ let declaration: DefaultExportDeclaration | null = null;+ let identifierName: string | null = null;++ recast.types.visit(ast, {+ visitExportDefaultDeclaration(astPath) {+ if (declaration || identifierName) {+ return false;+ }++ const {node} = astPath;+ if (node.declaration.type === 'Identifier') {+ identifierName = node.declaration.name;+ return false;+ }++ declaration = node.declaration;+ return false;+ },+ });++ if (identifierName) {+ return findLocalComponentDeclaration({ast, name: identifierName});+ }++ return declaration;+};++const getDeclarationByExportName = ({+ ast,+ exportName,+}: {+ ast: File;+ exportName: string | 'default';+}): LocalComponentDeclaration | DefaultExportDeclaration | null => {+ if (exportName === 'default') {+ return getDefaultExportDeclaration(ast);+ }++ return findLocalComponentDeclaration({ast, name: exportName});+};++const canAddSequenceToComponent = ({+ ast,+ exportName,+}: {+ ast: File;+ exportName: string | 'default';+}): boolean => {+ const declaration = getDeclarationByExportName({ast, exportName});+ if (!declaration) {+ return false;+ }++ const rootNode = getComponentRootNode(declaration);+ if (!rootNode) {+ return false;+ }++ if (rootNode.type === 'JSXElement') {+ if (rootNode.openingElement.selfClosing) {+ return false;+ }++ if (!rootNode.children) {+ return false;+ }++ rootNode.children.push(createSequenceElement());+ try {+ recast.print(ast);+ return true;+ } catch {+ return false;+ }+ }++ if (!rootNode.children) {+ return false;+ }++ rootNode.children.push(createSequenceElement());+ try {+ recast.print(ast);+ return true;+ } catch {+ return false;+ }+};+const getComponentLocationInFile = async ({remotionRoot,fileName,@@ -419,15 +715,21 @@ const getComponentLocationInFile = async ({}): Promise<ResolvedCompositionComponent> => {const input = await readSourceFile({remotionRoot, fileName});const ast = parseAst(input);+ const astForSequenceSimulation = parseAst(input);const location =exportName === 'default'? findDefaultExportLocation(ast): findLocalSymbolLocation({ast, name: exportName});+ const canAddSequence = canAddSequenceToComponent({+ ast: astForSequenceSimulation,+ exportName,+ });return {source: path.relative(remotionRoot, fileName),line: location?.line ?? 1,column: location?.column ?? 0,+ canAddSequence,};};diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex 437ae78877..23ecba039f 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -4,8 +4,8 @@ import type {IncomingMessage, ServerResponse} from 'node:http';import path, {join} from 'node:path';import {URLSearchParams} from 'node:url';import {BundlerInternals} from '@remotion/bundler';-import {RenderInternals} from '@remotion/renderer';import type {LogLevel} from '@remotion/renderer';+import {RenderInternals} from '@remotion/renderer';import type {ApiRoutes,CompletedClientRender,@@ -271,7 +271,7 @@ const handleOpenInEditor = async (}};-const handleResolveCompositionComponent = async (+const handleGetCompositionComponentInfo = async (remotionRoot: string,req: IncomingMessage,res: ServerResponse,@@ -307,6 +307,7 @@ const handleResolveCompositionComponent = async (JSON.stringify({success: true,location,+ canAddSequence: location.canAddSequence,}),);} catch (err) {@@ -562,8 +563,8 @@ export const handleRoutes = ({return handleOpenInEditor(remotionRoot, request, response, logLevel);}- if (url.pathname === '/api/resolve-composition-component') {- return handleResolveCompositionComponent(remotionRoot, request, response);+ if (url.pathname === '/api/composition-component-info') {+ return handleGetCompositionComponentInfo(remotionRoot, request, response);}if (url.pathname === `${staticHash}/api/add-asset`) {diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsindex a37ac5f8f2..fc00068903 100644--- a/packages/studio-server/src/test/resolve-composition-component.test.ts+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -1,4 +1,6 @@import {expect, test} from 'bun:test';+import fs from 'node:fs/promises';+import os from 'node:os';import path from 'node:path';import {resolveCompositionComponent} from '../helpers/resolve-composition-component';@@ -13,6 +15,7 @@ test('resolves a statically imported composition component', async () => {expect(location.source).toBe(path.join('src', 'SchemaTest', 'index.tsx'));expect(location.line).toBe(142);+ expect(location.canAddSequence).toBe(true);});test('resolves a lazy imported composition component', async () => {@@ -24,6 +27,7 @@ test('resolves a lazy imported composition component', async () => {expect(location.source).toBe(path.join('src', 'LoopedVideo', 'index.tsx'));expect(location.line).toBe(4);+ expect(location.canAddSequence).toBe(true);});test('resolves a same-file composition component', async () => {@@ -35,4 +39,187 @@ test('resolves a same-file composition component', async () => {expect(location.source).toBe(path.join('src', 'NewVideo.tsx'));expect(location.line).toBe(21);+ expect(location.canAddSequence).toBe(false);+});++test('bails out if component has no JSX return', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ 'export const MyComp: React.FC = () => {',+ '\tthrow new Error("hello");',+ '};',+ '',+ ].join('\n'),+ );++ const location = await resolveCompositionComponent({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ });+ expect(location.source).toBe('MyComp.tsx');+ expect(location.canAddSequence).toBe(false);+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('supports adding a sequence to fragment return', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ 'export const MyComp: React.FC = () => {',+ '\treturn <>hello</>;',+ '};',+ '',+ ].join('\n'),+ );++ const location = await resolveCompositionComponent({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ });+ expect(location.source).toBe('MyComp.tsx');+ expect(location.canAddSequence).toBe(true);+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('supports adding a sequence to JSX element return', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ 'export const MyComp: React.FC = () => {',+ '\treturn <div>hello</div>;',+ '};',+ '',+ ].join('\n'),+ );++ const location = await resolveCompositionComponent({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ });+ expect(location.source).toBe('MyComp.tsx');+ expect(location.canAddSequence).toBe(true);+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('canAddSequence=true for default-exported function component', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import MyComp from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ 'const MyComp: React.FC = () => {',+ '\treturn <section>hello</section>;',+ '};',+ '',+ 'export default MyComp;',+ '',+ ].join('\n'),+ );++ const location = await resolveCompositionComponent({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ });+ expect(location.source).toBe('MyComp.tsx');+ expect(location.canAddSequence).toBe(true);+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }+});++test('canAddSequence=false for self-closing root JSX return', async () => {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'remotion-resolve-'));+ try {+ await fs.writeFile(+ path.join(tempDir, 'Root.tsx'),+ [+ "import {Composition} from 'remotion';",+ "import {MyComp} from './MyComp';",+ 'export const RemotionRoot = () => {',+ '\treturn <Composition id="test" component={MyComp} />;',+ '};',+ '',+ ].join('\n'),+ );+ await fs.writeFile(+ path.join(tempDir, 'MyComp.tsx'),+ [+ 'export const MyComp: React.FC = () => {',+ '\treturn <div />;',+ '};',+ '',+ ].join('\n'),+ );++ const location = await resolveCompositionComponent({+ remotionRoot: tempDir,+ compositionFile: 'Root.tsx',+ compositionId: 'test',+ });+ expect(location.source).toBe('MyComp.tsx');+ expect(location.canAddSequence).toBe(false);+ } finally {+ await fs.rm(tempDir, {recursive: true, force: true});+ }});diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.tsindex 1f3b605cf0..8d8cabb0db 100644--- a/packages/studio/src/helpers/open-in-editor.ts+++ b/packages/studio/src/helpers/open-in-editor.ts@@ -49,33 +49,101 @@ type ResolveCompositionComponentResponse =| {success: true;location: ResolvedCompositionComponentLocation;+ canAddSequence: boolean;}| {success: false;error: string;};-export const openCompositionComponentInEditor = async ({+const componentResolutionCache = new Map<+ string,+ Promise<{+ location: ResolvedCompositionComponentLocation;+ canAddSequence: boolean;+ }>+>();++const getComponentResolutionCacheKey = ({compositionFile,compositionId,}: {compositionFile: string;compositionId: string;}) => {- const response = await fetch(`/api/resolve-composition-component`, {- method: 'post',- headers: {- 'content-type': 'application/json',- },- body: JSON.stringify({- compositionFile,- compositionId,- }),+ return `${compositionFile}::${compositionId}`;+};++const loadCompositionComponentInfo = async ({+ compositionFile,+ compositionId,+}: {+ compositionFile: string;+ compositionId: string;+}) => {+ const cacheKey = getComponentResolutionCacheKey({+ compositionFile,+ compositionId,});- const body = (await response.json()) as ResolveCompositionComponentResponse;- if (!body.success) {- throw new Error(body.error);+ const existing = componentResolutionCache.get(cacheKey);+ if (existing) {+ return existing;+ }++ const promise = (async () => {+ const response = await fetch(`/api/composition-component-info`, {+ method: 'post',+ headers: {+ 'content-type': 'application/json',+ },+ body: JSON.stringify({+ compositionFile,+ compositionId,+ }),+ });+ const body = (await response.json()) as ResolveCompositionComponentResponse;+ if (!body.success) {+ throw new Error(body.error);+ }++ return {+ location: body.location,+ canAddSequence: body.canAddSequence,+ };+ })();+ componentResolutionCache.set(cacheKey, promise);++ try {+ return await promise;+ } catch (err) {+ componentResolutionCache.delete(cacheKey);+ throw err;}+};- await openOriginalPositionInEditor(body.location);+export const preloadCompositionComponentInfo = ({+ compositionFile,+ compositionId,+}: {+ compositionFile: string;+ compositionId: string;+}) => {+ loadCompositionComponentInfo({+ compositionFile,+ compositionId,+ }).catch(() => undefined);+};++export const openCompositionComponentInEditor = async ({+ compositionFile,+ compositionId,+}: {+ compositionFile: string;+ compositionId: string;+}) => {+ const info = await loadCompositionComponentInfo({+ compositionFile,+ compositionId,+ });+ await openOriginalPositionInEditor(info.location);};diff --git a/packages/studio/src/helpers/use-menu-structure.tsx b/packages/studio/src/helpers/use-menu-structure.tsxindex 78c8c8bb34..8eabf4fe24 100644--- a/packages/studio/src/helpers/use-menu-structure.tsx+++ b/packages/studio/src/helpers/use-menu-structure.tsx@@ -1,4 +1,4 @@-import {useContext, useMemo} from 'react';+import {useContext, useEffect, useMemo} from 'react';import {Internals} from 'remotion';import {NoReactInternals} from 'remotion/no-react';import {restartStudio} from '../api/restart-studio';@@ -30,7 +30,7 @@ import {checkFullscreenSupport} from './check-fullscreen-support';import {StudioServerConnectionCtx} from './client-id';import {getGitMenuItem} from './get-git-menu-item';import {useMobileLayout} from './mobile-layout';-import {openInEditor} from './open-in-editor';+import {openInEditor, preloadCompositionComponentInfo} from './open-in-editor';import {pickColor} from './pick-color';import {SHOW_BROWSER_RENDERING} from './show-browser-rendering';import {areKeyboardShortcutsDisabled} from './use-keybinding';@@ -231,6 +231,23 @@ export const useMenuStructure = (const resolvedCompositionLocation = useResolvedStack(currentComposition?.stack ?? null,);++ useEffect(() => {+ if (+ type !== 'connected' ||+ !window.remotion_editorName ||+ !currentComposition ||+ !resolvedCompositionLocation?.source+ ) {+ return;+ }++ preloadCompositionComponentInfo({+ compositionFile: resolvedCompositionLocation.source,+ compositionId: currentComposition.id,+ });+ }, [currentComposition, resolvedCompositionLocation?.source, type]);+const structure = useMemo((): Structure => {let struct: Structure = [{