🎥 Make videos programmatically with React
Add composition component editor action
Cursor Agent34edb3302edc
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.tsnew file mode 100644index 0000000000..a23872c066--- /dev/null+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts@@ -0,0 +1,493 @@+import fs from 'node:fs';+import path from 'node:path';+import type {+ File,+ ImportDeclaration,+ JSXAttribute,+ JSXElement,+} from '@babel/types';+import * as recast from 'recast';+import {parseAst} from '../codemods/parse-ast';++type SourceLocation = {+ line: number;+ column: number;+};++type NodeWithLocation = {+ loc?: {+ start: {+ line: number;+ column: number;+ };+ } | null;+};++export type ResolvedCompositionComponent = {+ source: string;+ line: number;+ column: number;+};++type ImportTarget = {+ importPath: string;+ exportName: string | 'default';+};++const allowedFileExtensions = new Set(['.tsx', '.ts', '.jsx', '.js']);+const extensionsToProbe = ['.tsx', '.ts', '.jsx', '.js'];++const isInRemotionRoot = ({+ remotionRoot,+ fileName,+}: {+ remotionRoot: string;+ fileName: string;+}) => {+ const relativePath = path.relative(remotionRoot, fileName);+ return !relativePath.startsWith('..') && !path.isAbsolute(relativePath);+};++const readSourceFile = ({+ remotionRoot,+ fileName,+}: {+ remotionRoot: string;+ fileName: string;+}) => {+ const resolved = path.resolve(remotionRoot, fileName);+ if (!isInRemotionRoot({remotionRoot, fileName: resolved})) {+ throw new Error(`Not allowed to open ${fileName}`);+ }++ if (!allowedFileExtensions.has(path.extname(resolved))) {+ throw new Error(`Not allowed to open ${fileName}`);+ }++ return fs.promises.readFile(resolved, 'utf-8');+};++const getAttributeName = (attribute: JSXAttribute) => {+ if (attribute.name.type !== 'JSXIdentifier') {+ return null;+ }++ return attribute.name.name;+};++const findAttribute = (element: JSXElement, name: string) => {+ return element.openingElement.attributes.find((attribute) => {+ if (attribute.type !== 'JSXAttribute') {+ return false;+ }++ return getAttributeName(attribute) === name;+ }) as JSXAttribute | undefined;+};++const getStringAttributeValue = (element: JSXElement, name: string) => {+ const attribute = findAttribute(element, name);+ if (!attribute?.value) {+ return null;+ }++ if (attribute.value.type === 'StringLiteral') {+ return attribute.value.value;+ }++ if (+ attribute.value.type === 'JSXExpressionContainer' &&+ attribute.value.expression.type === 'StringLiteral'+ ) {+ return attribute.value.expression.value;+ }++ return null;+};++const findCompositionElement = ({+ ast,+ compositionId,+}: {+ ast: File;+ compositionId: string;+}) => {+ let found: JSXElement | null = null;++ recast.types.visit(ast, {+ visitJSXElement(astPath) {+ if (found) {+ return false;+ }++ const node = astPath.node as JSXElement;+ const openingName = node.openingElement.name;+ if (+ openingName.type === 'JSXIdentifier' &&+ (openingName.name === 'Composition' || openingName.name === 'Still') &&+ getStringAttributeValue(node, 'id') === compositionId+ ) {+ found = node;+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return found;+};++const getComponentIdentifier = (element: JSXElement) => {+ const attribute = findAttribute(element, 'component');+ if (+ !attribute?.value ||+ attribute.value.type !== 'JSXExpressionContainer' ||+ attribute.value.expression.type !== 'Identifier'+ ) {+ return null;+ }++ return attribute.value.expression.name;+};++const isRecord = (value: unknown): value is Record<string, unknown> => {+ return typeof value === 'object' && value !== null;+};++const findDynamicImportPath = (value: unknown): string | null => {+ if (!isRecord(value)) {+ return null;+ }++ if (+ value.type === 'CallExpression' &&+ isRecord(value.callee) &&+ value.callee.type === 'Import' &&+ Array.isArray(value.arguments) &&+ isRecord(value.arguments[0]) &&+ value.arguments[0].type === 'StringLiteral' &&+ typeof value.arguments[0].value === 'string'+ ) {+ return value.arguments[0].value;+ }++ for (const [key, child] of Object.entries(value)) {+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'comments' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'innerComments' ||+ key === 'extra' ||+ key === 'original'+ ) {+ continue;+ }++ if (Array.isArray(child)) {+ for (const item of child) {+ const nestedResult = findDynamicImportPath(item);+ if (nestedResult) {+ return nestedResult;+ }+ }++ continue;+ }++ const childResult = findDynamicImportPath(child);+ if (childResult) {+ return childResult;+ }+ }++ return null;+};++const getLazyImportPath = (element: JSXElement) => {+ const attribute = findAttribute(element, 'lazyComponent');+ if (!attribute?.value || attribute.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ return findDynamicImportPath(attribute.value.expression);+};++const findImportTarget = ({+ ast,+ componentName,+}: {+ ast: File;+ componentName: string;+}): ImportTarget | null => {+ let found: ImportTarget | null = null;++ recast.types.visit(ast, {+ visitImportDeclaration(astPath) {+ if (found) {+ return false;+ }++ const node = astPath.node as ImportDeclaration;+ if (typeof node.source.value !== 'string') {+ return false;+ }++ const matchingSpecifier = node.specifiers?.find((specifier) => {+ return specifier.local?.name === componentName;+ });+ if (!matchingSpecifier) {+ return false;+ }++ if (matchingSpecifier.type === 'ImportDefaultSpecifier') {+ found = {+ importPath: node.source.value,+ exportName: 'default',+ };+ return false;+ }++ if (+ matchingSpecifier.type === 'ImportSpecifier' &&+ matchingSpecifier.imported.type === 'Identifier'+ ) {+ found = {+ importPath: node.source.value,+ exportName: matchingSpecifier.imported.name,+ };+ return false;+ }++ if (+ matchingSpecifier.type === 'ImportSpecifier' &&+ matchingSpecifier.imported.type === 'StringLiteral'+ ) {+ found = {+ importPath: node.source.value,+ exportName: matchingSpecifier.imported.value,+ };+ return false;+ }++ return false;+ },+ });++ return found;+};++const resolveImportPath = ({+ importPath,+ fromFile,+}: {+ importPath: string;+ fromFile: string;+}) => {+ if (!importPath.startsWith('.')) {+ throw new Error(`Cannot resolve non-relative import ${importPath}`);+ }++ const basePath = path.resolve(path.dirname(fromFile), importPath);+ const candidates = path.extname(basePath)+ ? [basePath]+ : [+ ...extensionsToProbe.map((extension) => `${basePath}${extension}`),+ ...extensionsToProbe.map((extension) =>+ path.join(basePath, `index${extension}`),+ ),+ ];++ const existingFile = candidates.find((candidate) => {+ return fs.existsSync(candidate) && fs.statSync(candidate).isFile();+ });+ if (!existingFile) {+ throw new Error(`Could not find imported component file ${importPath}`);+ }++ return existingFile;+};++const locationFromNode = (node: NodeWithLocation): SourceLocation | null => {+ if (!node.loc) {+ return null;+ }++ return {+ line: node.loc.start.line,+ column: node.loc.start.column,+ };+};++const findLocalSymbolLocation = ({+ ast,+ name,+}: {+ ast: File;+ name: string;+}): SourceLocation | null => {+ let location: SourceLocation | null = null;++ recast.types.visit(ast, {+ visitVariableDeclarator(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id.type === 'Identifier' && node.id.name === name) {+ location = locationFromNode(node);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitFunctionDeclaration(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ location = locationFromNode(node);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ visitClassDeclaration(astPath) {+ if (location) {+ return false;+ }++ const {node} = astPath;+ if (node.id?.name === name) {+ location = locationFromNode(node);+ return false;+ }++ this.traverse(astPath);+ return undefined;+ },+ });++ return location;+};++const findDefaultExportLocation = (ast: File): SourceLocation | null => {+ let location: SourceLocation | null = null;+ let exportedIdentifier: string | null = null;++ recast.types.visit(ast, {+ visitExportDefaultDeclaration(astPath) {+ if (location || exportedIdentifier) {+ return false;+ }++ const {node} = astPath;+ if (node.declaration.type === 'Identifier') {+ exportedIdentifier = node.declaration.name;+ return false;+ }++ location = locationFromNode(node.declaration) ?? locationFromNode(node);+ return false;+ },+ });++ if (exportedIdentifier) {+ return findLocalSymbolLocation({ast, name: exportedIdentifier});+ }++ return location;+};++const getComponentLocationInFile = async ({+ remotionRoot,+ fileName,+ exportName,+}: {+ remotionRoot: string;+ fileName: string;+ exportName: string | 'default';+}): Promise<ResolvedCompositionComponent> => {+ const input = await readSourceFile({remotionRoot, fileName});+ const ast = parseAst(input);+ const location =+ exportName === 'default'+ ? findDefaultExportLocation(ast)+ : findLocalSymbolLocation({ast, name: exportName});++ return {+ source: path.relative(remotionRoot, fileName),+ line: location?.line ?? 1,+ column: location?.column ?? 0,+ };+};++export const resolveCompositionComponent = async ({+ remotionRoot,+ compositionFile,+ compositionId,+}: {+ remotionRoot: string;+ compositionFile: string;+ compositionId: string;+}): Promise<ResolvedCompositionComponent> => {+ const compositionFileName = path.resolve(remotionRoot, compositionFile);+ const input = await readSourceFile({+ remotionRoot,+ fileName: compositionFileName,+ });+ const ast = parseAst(input);+ const compositionElement = findCompositionElement({ast, compositionId});+ if (!compositionElement) {+ throw new Error(`Could not find composition "${compositionId}"`);+ }++ const lazyImportPath = getLazyImportPath(compositionElement);+ if (lazyImportPath) {+ const lazyComponentFile = resolveImportPath({+ importPath: lazyImportPath,+ fromFile: compositionFileName,+ });+ return getComponentLocationInFile({+ remotionRoot,+ fileName: lazyComponentFile,+ exportName: 'default',+ });+ }++ const componentName = getComponentIdentifier(compositionElement);+ if (!componentName) {+ throw new Error(+ `Could not find a component prop for composition "${compositionId}"`,+ );+ }++ const importTarget = findImportTarget({ast, componentName});+ if (!importTarget) {+ return getComponentLocationInFile({+ remotionRoot,+ fileName: compositionFileName,+ exportName: componentName,+ });+ }++ const importedComponentFile = resolveImportPath({+ importPath: importTarget.importPath,+ fromFile: compositionFileName,+ });++ return getComponentLocationInFile({+ remotionRoot,+ fileName: importedComponentFile,+ exportName: importTarget.exportName,+ });+};diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.tsindex 8dabe1f572..437ae78877 100644--- a/packages/studio-server/src/routes.ts+++ b/packages/studio-server/src/routes.ts@@ -27,6 +27,7 @@ import {guessEditor,launchEditor,} from './helpers/open-in-editor';+import {resolveCompositionComponent} from './helpers/resolve-composition-component';import {resolveOutputPath} from './helpers/resolve-output-path';import {allApiRoutes} from './preview-server/api-routes';import type {ApiHandler, QueueMethods} from './preview-server/api-types';@@ -270,6 +271,55 @@ const handleOpenInEditor = async (}};+const handleResolveCompositionComponent = async (+ remotionRoot: string,+ req: IncomingMessage,+ res: ServerResponse,+) => {+ if (req.method === 'OPTIONS') {+ res.statusCode = 200;+ res.end();+ return;+ }++ res.setHeader('content-type', 'application/json');+ try {+ const body = (await parseRequestBody(req)) as {+ compositionFile: string;+ compositionId: string;+ };+ if (typeof body.compositionFile !== 'string') {+ throw new TypeError('Need to pass compositionFile');+ }++ if (typeof body.compositionId !== 'string') {+ throw new TypeError('Need to pass compositionId');+ }++ const location = await resolveCompositionComponent({+ remotionRoot,+ compositionFile: body.compositionFile,+ compositionId: body.compositionId,+ });++ res.writeHead(200);+ res.end(+ JSON.stringify({+ success: true,+ location,+ }),+ );+ } catch (err) {+ res.writeHead(200);+ res.end(+ JSON.stringify({+ success: false,+ error: (err as Error).message,+ }),+ );+ }+};+const validateSameOrigin = (req: IncomingMessage): void => {const {origin, host} = req.headers;if (origin) {@@ -512,6 +562,10 @@ export const handleRoutes = ({return handleOpenInEditor(remotionRoot, request, response, logLevel);}+ if (url.pathname === '/api/resolve-composition-component') {+ return handleResolveCompositionComponent(remotionRoot, request, response);+ }+if (url.pathname === `${staticHash}/api/add-asset`) {return handleAddAsset({req: request,diff --git a/packages/studio-server/src/test/resolve-composition-component.test.ts b/packages/studio-server/src/test/resolve-composition-component.test.tsnew file mode 100644index 0000000000..a37ac5f8f2--- /dev/null+++ b/packages/studio-server/src/test/resolve-composition-component.test.ts@@ -0,0 +1,38 @@+import {expect, test} from 'bun:test';+import path from 'node:path';+import {resolveCompositionComponent} from '../helpers/resolve-composition-component';++const remotionRoot = path.join(__dirname, '..', '..', '..', 'example');++test('resolves a statically imported composition component', async () => {+ const location = await resolveCompositionComponent({+ remotionRoot,+ compositionFile: 'src/E2eTestRoot.tsx',+ compositionId: 'schema-test',+ });++ expect(location.source).toBe(path.join('src', 'SchemaTest', 'index.tsx'));+ expect(location.line).toBe(142);+});++test('resolves a lazy imported composition component', async () => {+ const location = await resolveCompositionComponent({+ remotionRoot,+ compositionFile: 'src/Root.tsx',+ compositionId: 'looped',+ });++ expect(location.source).toBe(path.join('src', 'LoopedVideo', 'index.tsx'));+ expect(location.line).toBe(4);+});++test('resolves a same-file composition component', async () => {+ const location = await resolveCompositionComponent({+ remotionRoot,+ compositionFile: 'src/NewVideo.tsx',+ compositionId: 'NewVideo',+ });++ expect(location.source).toBe(path.join('src', 'NewVideo.tsx'));+ expect(location.line).toBe(21);+});diff --git a/packages/studio/src/components/composition-menu-items.ts b/packages/studio/src/components/composition-menu-items.tsindex 49333561a9..f05c8a8601 100644--- a/packages/studio/src/components/composition-menu-items.ts+++ b/packages/studio/src/components/composition-menu-items.ts@@ -1,7 +1,10 @@import type {SetStateAction} from 'react';import type {ResolvedStackLocation, _InternalTypes} from 'remotion';import {NoReactInternals} from 'remotion/no-react';-import {openOriginalPositionInEditor} from '../helpers/open-in-editor';+import {+ openCompositionComponentInEditor,+ openOriginalPositionInEditor,+} from '../helpers/open-in-editor';import type {PreviewServerConnectionState} from '../helpers/preview-server-events';import type {ModalState} from '../state/modals';import type {ComboboxValue} from './NewComposition/ComboBox';@@ -23,13 +26,15 @@ export const getCompositionMenuItems = ({const editorName = window.remotion_editorName;const showInEditorDisabled =!composition || connectionStatus !== 'connected' || !resolvedLocation;+ const openComponentInEditorDisabled =+ showInEditorDisabled || !resolvedLocation?.source;return [editorName? {id: 'show-in-editor',keyHint: null,- label: `Show in ${editorName}`,+ label: `Show composition in ${editorName}`,leftItem: null,onClick: async () => {closeMenu();@@ -50,6 +55,34 @@ export const getCompositionMenuItems = ({disabled: showInEditorDisabled,}: null,+ editorName+ ? {+ id: 'open-component-in-editor',+ keyHint: null,+ label: `Open component in ${editorName}`,+ leftItem: null,+ onClick: async () => {+ closeMenu();+ if (!composition || !resolvedLocation?.source) {+ return;+ }++ try {+ await openCompositionComponentInEditor({+ compositionFile: resolvedLocation.source,+ compositionId: composition.id,+ });+ } catch (err) {+ showNotification((err as Error).message, 2000);+ }+ },+ quickSwitcherLabel: `Open composition component in ${editorName}`,+ subMenu: null,+ type: 'item' as const,+ value: 'open-component-in-editor',+ disabled: openComponentInEditorDisabled,+ }+ : null,editorName? {type: 'divider' as const,diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.tsindex c5df2343bd..5af1ae0dd9 100644--- a/packages/studio/src/helpers/open-in-editor.ts+++ b/packages/studio/src/helpers/open-in-editor.ts@@ -38,3 +38,38 @@ export const openOriginalPositionInEditor = async (originalScriptCode: null,});};++type ResolveCompositionComponentResponse =+ | {+ success: true;+ location: OriginalPosition;+ }+ | {+ success: false;+ error: string;+ };++export const openCompositionComponentInEditor = async ({+ 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,+ }),+ });+ const body = (await response.json()) as ResolveCompositionComponentResponse;+ if (!body.success) {+ throw new Error(body.error);+ }++ await openOriginalPositionInEditor(body.location);+};