Skip to content

🎥 Make videos programmatically with React

`@remotion/browser-studio`: Enable adding solids (#9790)

Jonny Burger19778b9ebbc2
diff --git a/bun.lock b/bun.lock
index 4b7abf1c92..3d0f7044b2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -133,11 +133,13 @@
"name": "@remotion/browser-studio",
"version": "4.0.500",
"dependencies": {
+ "@remotion/studio-codemods": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
},
"devDependencies": {
"@remotion/eslint-config-internal": "workspace:*",
+ "@remotion/studio": "workspace:*",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@typescript/native-preview": "catalog:",
@@ -1695,6 +1697,19 @@
"react-dom": ">=16.8.0",
},
},
+ "packages/studio-codemods": {
+ "name": "@remotion/studio-codemods",
+ "version": "4.0.500",
+ "dependencies": {
+ "@babel/parser": "7.24.1",
+ "@remotion/studio-shared": "workspace:*",
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:",
+ },
+ },
"packages/studio-server": {
"name": "@remotion/studio-server",
"version": "4.0.500",
@@ -1704,6 +1719,7 @@
"@remotion/bundler": "workspace:*",
"@remotion/drag-and-drop": "workspace:*",
"@remotion/renderer": "workspace:*",
+ "@remotion/studio-codemods": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"@svgr/core": "8.1.0",
"@svgr/plugin-jsx": "8.1.0",
@@ -4196,6 +4212,8 @@
"@remotion/studio": ["@remotion/studio@workspace:packages/studio"],
+ "@remotion/studio-codemods": ["@remotion/studio-codemods@workspace:packages/studio-codemods"],
+
"@remotion/studio-server": ["@remotion/studio-server@workspace:packages/studio-server"],
"@remotion/studio-shared": ["@remotion/studio-shared@workspace:packages/studio-shared"],
diff --git a/packages/browser-studio/bundle.ts b/packages/browser-studio/bundle.ts
index 3cff354c2a..4c95ca3394 100644
--- a/packages/browser-studio/bundle.ts
+++ b/packages/browser-studio/bundle.ts
@@ -2,6 +2,7 @@ import path from 'path';
import {build} from 'bun';
import {getBrowserStudioDependencyVersionsForBuild} from './src/dev/get-dependency-versions-for-build';
import {getBrowserStudioSetupEnvironmentForBuild} from './src/dev/get-setup-environment-for-build';
+import {studioRenderEntryExternal} from './src/dev/studio-render-entry-external';
if (process.env.NODE_ENV !== 'production') {
throw new Error('This script must be run using NODE_ENV=production');
@@ -11,7 +12,11 @@ console.time('Generated.');
const dependencyVersions = getBrowserStudioDependencyVersionsForBuild();
const setupEnvironment = getBrowserStudioSetupEnvironmentForBuild();
const output = await build({
- entrypoints: ['src/index.tsx', 'src/browser-studio-worker.ts'],
+ entrypoints: [
+ 'src/index.tsx',
+ 'src/browser-studio-worker.ts',
+ 'src/browser-studio-render-entry.ts',
+ ],
naming: '[name].mjs',
define: {
__BROWSER_STUDIO_DEPENDENCY_VERSIONS__: JSON.stringify(dependencyVersions),
@@ -21,10 +26,7 @@ const output = await build({
'@remotion/studio-shared/studio-entry-points',
'@remotion/studio-shared/studio-html',
'@rspack/browser',
- 'react',
- 'react-dom',
- 'react/jsx-runtime',
- 'react/jsx-dev-runtime',
+ ...studioRenderEntryExternal,
],
});
diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.json
index 7a037f54a6..43a7543192 100644
--- a/packages/browser-studio/package.json
+++ b/packages/browser-studio/package.json
@@ -26,6 +26,7 @@
"url": "https://github.com/remotion-dev/remotion/issues"
},
"dependencies": {
+ "@remotion/studio-codemods": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1"
},
@@ -43,6 +44,7 @@
"./package.json": "./package.json"
},
"devDependencies": {
+ "@remotion/studio": "workspace:*",
"@remotion/eslint-config-internal": "workspace:*",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsx
index 5dc4b93914..ca6617ae77 100644
--- a/packages/browser-studio/src/BrowserStudio.tsx
+++ b/packages/browser-studio/src/BrowserStudio.tsx
@@ -1,5 +1,6 @@
import {studioHtml} from '@remotion/studio-shared/studio-html';
-import React, {useEffect, useMemo, useRef, useState} from 'react';
+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import {createBrowserStudioOperations} from './browser-studio-operations';
import {browserStudioDependencyVersions} from './dependency-versions';
import {Spinner} from './Spinner';
import type {
@@ -13,6 +14,11 @@ const makeInitialState = (): CompileState => ({
status: 'idle',
});
+const localStudioRenderEntry = new URL(
+ './browser-studio-render-entry.mjs',
+ import.meta.url,
+).href;
+
const containerStyle: React.CSSProperties = {
backgroundColor: '#111111',
color: '#ffffff',
@@ -72,13 +78,49 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
iframeSrc,
dependencyResolver,
onCompileStateChange,
+ onProjectChange,
}) => {
const [state, setState] = useState<CompileState>(makeInitialState);
const [iframeHtml, setIframeHtml] = useState<string | null>(null);
const [iframeLoaded, setIframeLoaded] = useState(false);
const iframeRef = useRef<HTMLIFrameElement | null>(null);
- const projectKey = useMemo(() => JSON.stringify(project), [project]);
+ const incomingProjectKey = useMemo(() => JSON.stringify(project), [project]);
+ const [editedProject, setEditedProject] = useState<{
+ project: BrowserStudioProps['project'];
+ sourceKey: string;
+ } | null>(null);
+ const activeProject =
+ editedProject?.sourceKey === incomingProjectKey
+ ? editedProject.project
+ : project;
+ const activeProjectRef = useRef(activeProject);
+ activeProjectRef.current = activeProject;
+
+ const updateProject = useCallback(
+ (nextProject: BrowserStudioProps['project']) => {
+ activeProjectRef.current = nextProject;
+ setEditedProject({
+ project: nextProject,
+ sourceKey: incomingProjectKey,
+ });
+ onProjectChange?.(nextProject);
+ },
+ [incomingProjectKey, onProjectChange],
+ );
+
+ const browserStudioOperations = useMemo(
+ () =>
+ createBrowserStudioOperations({
+ getProject: () => activeProjectRef.current,
+ onProjectChange: updateProject,
+ }),
+ [updateProject],
+ );
+
+ useEffect(() => {
+ setIframeLoaded(false);
+ }, [iframeSrc]);
useEffect(() => {
let cleanupBundle: string | null = null;
@@ -93,8 +135,6 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
onCompileStateChange?.(nextState);
};
- setIframeHtml(null);
- setIframeLoaded(false);
setCompileState({status: 'compiling'});
const worker = new Worker(
@@ -135,12 +175,12 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
numberOfAudioTags: 0,
packageManager: 'unknown',
projectName: 'template-blank',
- publicFiles: makeStaticFiles(project.publicFiles),
+ publicFiles: makeStaticFiles(activeProject.publicFiles),
publicFolderExists: null,
fileSystemPlatform: null,
publicPath: '',
readOnlyStudio: readOnly,
- remotionRoot: project.rootDir,
+ remotionRoot: activeProject.rootDir,
renderDefaults: undefined,
renderQueue: [],
sampleRate: null,
@@ -171,14 +211,23 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
const request: BrowserStudioWorkerCompileRequest = {
type: 'compile',
- dependencyResolutions: dependencyResolver
- ? Object.fromEntries(
- Object.entries(browserStudioDependencyVersions).map(
- ([name, version]) => [name, dependencyResolver({name, version})],
- ),
- )
- : {},
- project,
+ dependencyResolutions: Object.fromEntries(
+ Object.entries(browserStudioDependencyVersions).map(
+ ([name, version]) => {
+ const customResolution = dependencyResolver?.({name, version});
+ if (customResolution) {
+ return [name, customResolution];
+ }
+
+ if (name === '@remotion/studio') {
+ return [name, {url: localStudioRenderEntry}];
+ }
+
+ return [name, null];
+ },
+ ),
+ ),
+ project: activeProject,
};
worker.postMessage(request);
@@ -195,8 +244,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
dependencyResolver,
iframeSrc,
onCompileStateChange,
- project,
- projectKey,
+ activeProject,
readOnly,
]);
@@ -210,15 +258,17 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
}
const iframe = iframeRef.current;
+ const contentWindow = iframe?.contentWindow;
const contentDocument = iframe?.contentDocument;
- if (!contentDocument) {
+ if (!contentWindow || !contentDocument) {
return;
}
contentDocument.open();
contentDocument.write(iframeHtml);
+ contentWindow.remotion_browserStudio = browserStudioOperations;
contentDocument.close();
- }, [iframeHtml, iframeLoaded, iframeSrc]);
+ }, [browserStudioOperations, iframeHtml, iframeLoaded, iframeSrc]);
return (
<div style={containerStyle}>
@@ -233,7 +283,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
title="Remotion Studio"
/>
) : null}
- {state.status === 'compiling' ? (
+ {state.status === 'compiling' && iframeHtml === null ? (
<div style={overlayStyle}>
<Spinner duration={0.5} size={14} />
</div>
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
new file mode 100644
index 0000000000..9449e22aa6
--- /dev/null
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -0,0 +1,45 @@
+import {
+ getCompositionComponentInfo,
+ getCompositionFile,
+ insertSolidIntoProject,
+} from '@remotion/studio-codemods';
+import type {
+ BrowserStudioOperations,
+ InsertJsxElementResponse,
+} from '@remotion/studio-shared';
+import type {VirtualProject} from './types';
+
+export {insertSolidIntoProject} from '@remotion/studio-codemods';
+
+export const createBrowserStudioOperations = ({
+ getProject,
+ onProjectChange,
+}: {
+ getProject: () => VirtualProject;
+ onProjectChange: (project: VirtualProject) => void;
+}): BrowserStudioOperations => {
+ return {
+ getCompositionFile: (compositionId) =>
+ getCompositionFile({compositionId, project: getProject()}),
+ getCompositionComponentInfo: (request) =>
+ Promise.resolve(
+ getCompositionComponentInfo({project: getProject(), request}),
+ ),
+ insertSolid: (request) => {
+ try {
+ const project = insertSolidIntoProject({
+ project: getProject(),
+ request,
+ });
+ onProjectChange(project);
+ return Promise.resolve({success: true});
+ } catch (error) {
+ return Promise.resolve({
+ success: false,
+ reason: error instanceof Error ? error.message : String(error),
+ stack: error instanceof Error ? (error.stack ?? '') : '',
+ } satisfies InsertJsxElementResponse);
+ }
+ },
+ };
+};
diff --git a/packages/browser-studio/src/browser-studio-render-entry.ts b/packages/browser-studio/src/browser-studio-render-entry.ts
new file mode 100644
index 0000000000..5f23ac7089
--- /dev/null
+++ b/packages/browser-studio/src/browser-studio-render-entry.ts
@@ -0,0 +1 @@
+import '@remotion/studio/renderEntry';
diff --git a/packages/browser-studio/src/browser-studio-worker.ts b/packages/browser-studio/src/browser-studio-worker.ts
index 9968a40e16..40ea65b305 100644
--- a/packages/browser-studio/src/browser-studio-worker.ts
+++ b/packages/browser-studio/src/browser-studio-worker.ts
@@ -114,6 +114,47 @@ const applyDependencyResolution = ({
}
};
+const isBarePackageImport = (request: string) => {
+ return (
+ !request.startsWith('.') &&
+ !request.startsWith('/') &&
+ !request.startsWith('http://') &&
+ !request.startsWith('https://') &&
+ !request.includes('!')
+ );
+};
+
+const getVersionedPackageRequest = (request: string, version: string) => {
+ if (!request.startsWith('@')) {
+ const slashIndex = request.indexOf('/');
+ if (slashIndex === -1) {
+ return `${request}@${version}`;
+ }
+
+ return `${request.slice(0, slashIndex)}@${version}${request.slice(slashIndex)}`;
+ }
+
+ const secondSlashIndex = request.indexOf('/', request.indexOf('/') + 1);
+ if (secondSlashIndex === -1) {
+ return `${request}@${version}`;
+ }
+
+ return `${request.slice(0, secondSlashIndex)}@${version}${request.slice(secondSlashIndex)}`;
+};
+
+const getPackageName = (request: string) => {
+ if (request.startsWith('@')) {
+ return request.split('/').slice(0, 2).join('/');
+ }
+
+ return request.split('/')[0];
+};
+
+const externalizeSharedReactDependencies = (url: URL) => {
+ url.searchParams.set('dev', '');
+ url.searchParams.set('external', 'react,react-dom');
+};
+
const compileProject = async ({
project,
dependencyResolutions,
@@ -155,7 +196,7 @@ const compileProject = async ({
},
experiments: {
buildHttp: {
- allowedUris: ['https://esm.sh/'],
+ allowedUris: ['https://esm.sh/', `${self.location.origin}/`],
cacheLocation: false,
},
},
@@ -226,9 +267,30 @@ const compileProject = async ({
},
plugins: [
new BrowserHttpImportEsmPlugin({
- dependencyUrl: resolvedUrls,
+ dependencyUrl: ({request}) => {
+ if (!isBarePackageImport(request)) {
+ return undefined;
+ }
+
+ const packageName = getPackageName(request);
+ const resolvedUrl = resolvedUrls[packageName];
+ if (resolvedUrl) {
+ return resolvedUrl;
+ }
+
+ const version = resolvedVersions[packageName] ?? 'latest';
+ const url = new URL(
+ getVersionedPackageRequest(request, version),
+ 'https://esm.sh/',
+ );
+ externalizeSharedReactDependencies(url);
+ return url.href;
+ },
dependencyVersions: resolvedVersions,
domain: 'https://esm.sh',
+ postprocess: ({url}) => {
+ externalizeSharedReactDependencies(url);
+ },
}),
new rspack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
],
diff --git a/packages/browser-studio/src/dev/server.ts b/packages/browser-studio/src/dev/server.ts
index e3a86a13b2..90f9861f4b 100644
--- a/packages/browser-studio/src/dev/server.ts
+++ b/packages/browser-studio/src/dev/server.ts
@@ -3,6 +3,7 @@ import {fileURLToPath} from 'url';
import {build} from 'bun';
import {getBrowserStudioDependencyVersionsForBuild} from './get-dependency-versions-for-build';
import {getBrowserStudioSetupEnvironmentForBuild} from './get-setup-environment-for-build';
+import {studioRenderEntryExternal} from './studio-render-entry-external';
const port = Number(process.env.PORT ?? 62338);
const outDir = path.join(import.meta.dir, '..', '..', 'dist', 'dev');
@@ -84,6 +85,21 @@ const buildDevAssets = async () => {
process.exit(1);
}
+ const studioRenderEntryOutput = await build({
+ entrypoints: ['src/browser-studio-render-entry.ts'],
+ external: studioRenderEntryExternal,
+ format: 'esm',
+ naming: '[name].mjs',
+ outdir: outDir,
+ sourcemap: 'linked',
+ target: 'browser',
+ });
+
+ if (!studioRenderEntryOutput.success) {
+ process.stderr.write(`${studioRenderEntryOutput.logs.join('\n')}\n`);
+ process.exit(1);
+ }
+
const rspackBrowserEntry = fileURLToPath(
import.meta.resolve('@rspack/browser'),
);
diff --git a/packages/browser-studio/src/dev/studio-render-entry-external.ts b/packages/browser-studio/src/dev/studio-render-entry-external.ts
new file mode 100644
index 0000000000..f8ce899b92
--- /dev/null
+++ b/packages/browser-studio/src/dev/studio-render-entry-external.ts
@@ -0,0 +1,16 @@
+export const studioRenderEntryExternal = [
+ '@jridgewell/trace-mapping',
+ '@remotion/canvas-capture',
+ '@remotion/media-utils',
+ '@remotion/player',
+ '@remotion/renderer',
+ '@remotion/studio-shared',
+ '@remotion/timeline-utils',
+ '@remotion/web-renderer',
+ '@remotion/zod-types',
+ 'mediabunny',
+ 'react',
+ 'react-dom',
+ 'remotion',
+ 'zod',
+];
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
new file mode 100644
index 0000000000..990fc281f3
--- /dev/null
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -0,0 +1,143 @@
+import {expect, test} from 'bun:test';
+import {
+ createBrowserStudioOperations,
+ insertSolidIntoProject,
+} from '../browser-studio-operations';
+import {createBlankTemplateProject} from '../templates/blank';
+import type {VirtualProject} from '../types';
+
+const insertSolid = (
+ project: VirtualProject,
+ compositionFile = '/project/src/Composition.tsx',
+) => {
+ return insertSolidIntoProject({
+ project,
+ request: {
+ compositionFile,
+ compositionId: 'MyComp',
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ from: null,
+ },
+ });
+};
+
+test('adds a Solid to the blank Browser Studio project', () => {
+ const project = createBlankTemplateProject();
+ const updated = insertSolid(project);
+ const composition = updated.files['/project/src/Composition.tsx'];
+
+ expect(composition).toContain(
+ 'import { CalculateMetadataFunction, Composition, Solid } from "remotion";',
+ );
+ expect(composition).toContain(
+ '<Solid width={1280} height={720} color="gray"',
+ );
+ expect(composition).toContain("style={{position: 'absolute'}}");
+ expect(project.files['/project/src/Composition.tsx']).not.toContain('<Solid');
+});
+
+test('adds multiple Solids without duplicating the import', () => {
+ const once = insertSolid(createBlankTemplateProject());
+ const twice = insertSolid(once);
+ const composition = twice.files['/project/src/Composition.tsx'];
+
+ expect(composition.match(/\bSolid\b/g)).toHaveLength(3);
+ expect(composition.match(/<Solid /g)).toHaveLength(2);
+});
+
+test('resolves an imported composition component', async () => {
+ const project: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.tsx',
+ files: {
+ '/project/src/index.tsx': `import {Composition, registerRoot} from 'remotion';
+import {MyComponent} from './MyComponent';
+
+const Root = () => <Composition id="MyComp" component={MyComponent} durationInFrames={60} fps={30} width={1280} height={720} />;
+registerRoot(Root);
+`,
+ '/project/src/MyComponent.tsx': `import {AbsoluteFill} from 'remotion';
+
+export const MyComponent = () => <AbsoluteFill>Existing</AbsoluteFill>;
+`,
+ },
+ };
+ const updated = insertSolid(project, 'src/index.tsx');
+
+ expect(updated.files['/project/src/index.tsx']).toBe(
+ project.files['/project/src/index.tsx'],
+ );
+ expect(updated.files['/project/src/MyComponent.tsx']).toContain(
+ '<Solid width={1280}',
+ );
+
+ let currentProject = project;
+ const operations = createBrowserStudioOperations({
+ getProject: () => currentProject,
+ onProjectChange: (nextProject) => {
+ currentProject = nextProject;
+ },
+ });
+ expect(operations.getCompositionFile('MyComp')).toBe('src/index.tsx');
+ expect(operations.getCompositionFile('Unknown')).toBeNull();
+
+ const info = await operations.getCompositionComponentInfo({
+ compositionFile: 'src/index.tsx',
+ compositionId: 'MyComp',
+ });
+
+ expect(info).toEqual({
+ canAddSequence: true,
+ location: {
+ source: 'src/MyComponent.tsx',
+ line: 3,
+ column: 13,
+ },
+ });
+
+ const result = await operations.insertSolid({
+ compositionFile: 'src/index.tsx',
+ compositionId: 'MyComp',
+ from: null,
+ element: {
+ type: 'solid',
+ width: 1280,
+ height: 720,
+ position: null,
+ },
+ });
+ expect(result).toEqual({success: true});
+ expect(currentProject.files['/project/src/MyComponent.tsx']).toContain(
+ '<Solid width={1280}',
+ );
+});
+
+test('wraps a self-closing root and aliases conflicting bindings', () => {
+ const project: VirtualProject = {
+ rootDir: '/project',
+ entryPoint: '/project/src/index.tsx',
+ files: {
+ '/project/src/index.tsx': `import {AbsoluteFill, Composition, registerRoot} from 'remotion';
+
+const Solid = () => null;
+const Sequence = () => null;
+const MyComponent = () => <AbsoluteFill />;
+const Root = () => <Composition id="MyComp" component={MyComponent} durationInFrames={60} fps={30} width={1280} height={720} />;
+registerRoot(Root);
+`,
+ },
+ };
+ const updated = insertSolid(project, '/project/src/index.tsx');
+ const output = updated.files['/project/src/index.tsx'];
+
+ expect(output).toContain(
+ "import {AbsoluteFill, Composition, registerRoot, Solid as RemotionSolid, Sequence as RemotionSequence} from 'remotion';",
+ );
+ expect(output).toContain('<RemotionSequence>');
+ expect(output).toContain('<RemotionSolid width={1280}');
+});
diff --git a/packages/browser-studio/src/types.ts b/packages/browser-studio/src/types.ts
index 34a5afdb18..15a66148dd 100644
--- a/packages/browser-studio/src/types.ts
+++ b/packages/browser-studio/src/types.ts
@@ -53,6 +53,7 @@ export type BrowserStudioProps = {
iframeSrc?: string;
dependencyResolver?: BrowserStudioDependencyResolver;
onCompileStateChange?: (state: CompileState) => void;
+ onProjectChange?: (project: VirtualProject) => void;
};
export type BrowserStudioWorkerCompileRequest = {
diff --git a/packages/browser-studio/tsconfig.json b/packages/browser-studio/tsconfig.json
index 3caa43bcc3..2521f2bc8d 100644
--- a/packages/browser-studio/tsconfig.json
+++ b/packages/browser-studio/tsconfig.json
@@ -12,5 +12,9 @@
"emitDeclarationOnly": true
},
"include": ["src"],
- "references": [{"path": "../studio-shared"}]
+ "references": [
+ {"path": "../studio"},
+ {"path": "../studio-codemods"},
+ {"path": "../studio-shared"}
+ ]
}
diff --git a/packages/cli/src/list-of-remotion-packages.ts b/packages/cli/src/list-of-remotion-packages.ts
index 460f34ea01..e2a2fd6b1e 100644
--- a/packages/cli/src/list-of-remotion-packages.ts
+++ b/packages/cli/src/list-of-remotion-packages.ts
@@ -70,6 +70,7 @@ export const listOfRemotionPackages = [
'@remotion/serverless-client',
'@remotion/skills',
'@remotion/skills-evals',
+ '@remotion/studio-codemods',
'@remotion/studio-server',
'@remotion/studio-shared',
'@remotion/studio',
diff --git a/packages/create-video/src/list-of-remotion-packages.ts b/packages/create-video/src/list-of-remotion-packages.ts
index 460f34ea01..e2a2fd6b1e 100644
--- a/packages/create-video/src/list-of-remotion-packages.ts
+++ b/packages/create-video/src/list-of-remotion-packages.ts
@@ -70,6 +70,7 @@ export const listOfRemotionPackages = [
'@remotion/serverless-client',
'@remotion/skills',
'@remotion/skills-evals',
+ '@remotion/studio-codemods',
'@remotion/studio-server',
'@remotion/studio-shared',
'@remotion/studio',
diff --git a/packages/studio-codemods/.npmignore b/packages/studio-codemods/.npmignore
new file mode 100644
index 0000000000..b01c0f0056
--- /dev/null
+++ b/packages/studio-codemods/.npmignore
@@ -0,0 +1,10 @@
+dist/test/**
+src
+eslint.config.mjs
+tsconfig.tsbuildinfo
+*.tgz
+.turbo
+tsconfig.json
+.prettierrc.js
+bundle.ts
+dist/cjs/test/
diff --git a/packages/studio-codemods/README.md b/packages/studio-codemods/README.md
new file mode 100644
index 0000000000..1fdb1735ab
--- /dev/null
+++ b/packages/studio-codemods/README.md
@@ -0,0 +1,5 @@
+# @remotion/studio-codemods
+
+Shared codemods used internally by the Remotion Studio server and Browser Studio.
+
+This package is an internal implementation detail of Remotion Studio.
diff --git a/packages/studio-codemods/bundle.ts b/packages/studio-codemods/bundle.ts
new file mode 100644
index 0000000000..9f211bbc9d
--- /dev/null
+++ b/packages/studio-codemods/bundle.ts
@@ -0,0 +1,40 @@
+import path from 'path';
+import {build} from 'bun';
+
+if (process.env.NODE_ENV !== 'production') {
+ throw new Error('This script must be run using NODE_ENV=production');
+}
+
+const external = ['@remotion/studio-shared'];
+
+console.time('Generated.');
+const esmOutput = await build({
+ entrypoints: ['src/index.ts'],
+ naming: '[name].mjs',
+ external,
+});
+const cjsOutput = await build({
+ entrypoints: ['src/index.ts'],
+ naming: '[name].cjs',
+ format: 'cjs',
+ external,
+});
+
+for (const output of [esmOutput, cjsOutput]) {
+ if (!output.success) {
+ console.log(output.logs.join('\n'));
+ process.exit(1);
+ }
+}
+
+for (const file of esmOutput.outputs) {
+ const str = await file.text();
+ await Bun.write(path.join('dist', 'esm', file.path), str);
+}
+
+for (const file of cjsOutput.outputs) {
+ const str = await file.text();
+ await Bun.write(path.join('dist', file.path), str);
+}
+
+console.timeEnd('Generated.');
diff --git a/packages/studio-codemods/eslint.config.mjs b/packages/studio-codemods/eslint.config.mjs
new file mode 100644
index 0000000000..04fd4fac11
--- /dev/null
+++ b/packages/studio-codemods/eslint.config.mjs
@@ -0,0 +1,7 @@
+import {remotionFlatConfig} from '@remotion/eslint-config-internal';
+
+const config = remotionFlatConfig({react: false});
+
+export default {
+ ...config,
+};
diff --git a/packages/studio-codemods/package.json b/packages/studio-codemods/package.json
new file mode 100644
index 0000000000..277d388bfd
--- /dev/null
+++ b/packages/studio-codemods/package.json
@@ -0,0 +1,52 @@
+{
+ "name": "@remotion/studio-codemods",
+ "version": "4.0.500",
+ "description": "Shared codemods for Remotion Studio",
+ "main": "dist/index.cjs",
+ "types": "dist/index.d.ts",
+ "module": "dist/esm/index.mjs",
+ "repository": {
+ "url": "https://github.com/remotion-dev/remotion/tree/main/packages/studio-codemods"
+ },
+ "type": "module",
+ "scripts": {
+ "test": "bun test src/test",
+ "formatting": "oxfmt src --check",
+ "format": "oxfmt src",
+ "lint": "eslint src",
+ "watch": "tsgo -w",
+ "make": "tsgo && bun --env-file=../.env.bundle bundle.ts"
+ },
+ "author": "Jonny Burger <[email protected]>",
+ "contributors": [],
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/remotion-dev/remotion/issues"
+ },
+ "dependencies": {
+ "@babel/parser": "7.24.1",
+ "@remotion/studio-shared": "workspace:*"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "require": "./dist/index.cjs",
+ "module": "./dist/esm/index.mjs",
+ "import": "./dist/esm/index.mjs"
+ },
+ "./package.json": "./package.json"
+ },
+ "devDependencies": {
+ "@remotion/eslint-config-internal": "workspace:*",
+ "@typescript/native-preview": "catalog:",
+ "eslint": "catalog:"
+ },
+ "keywords": [
+ "remotion",
+ "studio",
+ "codemod"
+ ],
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
new file mode 100644
index 0000000000..08a8e40453
--- /dev/null
+++ b/packages/studio-codemods/src/index.ts
@@ -0,0 +1,1193 @@
+import {parse} from '@babel/parser';
+import type {
+ CompositionComponentInfoRequest,
+ InsertJsxElementRequest,
+} from '@remotion/studio-shared';
+
+export type CodemodProject = {
+ files: Record<string, string>;
+ rootDir: string;
+};
+
+type AstNode = {
+ type: string;
+ start?: number | null;
+ end?: number | null;
+ loc?: {
+ start: {line: number; column: number};
+ end: {line: number; column: number};
+ } | null;
+ [key: string]: unknown;
+};
+
+type ResolvedComponent = {
+ canAddSequence: boolean;
+ declaration: AstNode;
+ exportName: string | 'default';
+ filePath: string;
+ root: AstNode;
+ source: string;
+};
+
+type TextEdit = {
+ end: number;
+ start: number;
+ text: string;
+};
+
+const isAstNode = (value: unknown): value is AstNode => {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'type' in value &&
+ typeof value.type === 'string'
+ );
+};
+
+const getNode = (node: AstNode, key: string): AstNode | null => {
+ const value = node[key];
+ return isAstNode(value) ? value : null;
+};
+
+const getNodes = (node: AstNode, key: string): AstNode[] => {
+ const value = node[key];
+ return Array.isArray(value) ? value.filter(isAstNode) : [];
+};
+
+const getString = (node: AstNode | null, key: string): string | null => {
+ if (!node) {
+ return null;
+ }
+
+ const value = node[key];
+ return typeof value === 'string' ? value : null;
+};
+
+const getPosition = (node: AstNode, key: 'start' | 'end'): number => {
+ const value = node[key];
+ if (typeof value !== 'number') {
+ throw new Error(`Could not determine the ${key} of a source node`);
+ }
+
+ return value;
+};
+
+const visit = (
+ value: unknown,
+ visitor: (node: AstNode) => boolean | void,
+): boolean => {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (visit(item, visitor)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ if (!isAstNode(value)) {
+ return false;
+ }
+
+ if (visitor(value)) {
+ return true;
+ }
+
+ for (const [key, child] of Object.entries(value)) {
+ if (
+ key === 'loc' ||
+ key === 'start' ||
+ key === 'end' ||
+ key === 'extra' ||
+ key === 'comments'
+ ) {
+ continue;
+ }
+
+ if (visit(child, visitor)) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+const parseSource = (source: string): AstNode => {
+ return parse(source, {
+ errorRecovery: false,
+ plugins: ['decorators-legacy', 'jsx', 'typescript', 'importAttributes'],
+ sourceType: 'module',
+ }) as unknown as AstNode;
+};
+
+const normalizePath = (input: string) => {
+ const hasLeadingSlash = input.startsWith('/');
+ const parts: string[] = [];
+
+ for (const part of input.replaceAll('\\', '/').split('/')) {
+ if (!part || part === '.') {
+ continue;
+ }
+
+ if (part === '..') {
+ parts.pop();
+ continue;
+ }
+
+ parts.push(part);
+ }
+
+ return `${hasLeadingSlash ? '/' : ''}${parts.join('/')}`;
+};
+
+const dirname = (filePath: string) => {
+ const normalized = normalizePath(filePath);
+ const lastSlash = normalized.lastIndexOf('/');
+ return lastSlash === -1 ? '' : normalized.slice(0, lastSlash);
+};
+
+const stripSourceProtocol = (filePath: string) => {
+ return filePath
+ .replace(/^webpack:\/\/\/?/, '/')
+ .replace(/^file:\/\//, '')
+ .split(/[?#]/, 1)[0];
+};
+
+const findProjectFile = ({
+ filePath,
+ project,
+}: {
+ filePath: string;
+ project: CodemodProject;
+}) => {
+ const normalizedInput = normalizePath(stripSourceProtocol(filePath));
+ const rootDir = normalizePath(project.rootDir);
+ const candidates = [
+ normalizedInput,
+ normalizePath(`/${normalizedInput}`),
+ normalizePath(`${rootDir}/${normalizedInput.replace(/^\//, '')}`),
+ ];
+ const normalizedFiles = new Map(
+ Object.keys(project.files).map((key) => [normalizePath(key), key]),
+ );
+
+ for (const candidate of candidates) {
+ const match = normalizedFiles.get(candidate);
+ if (match) {
+ return match;
+ }
+ }
+
+ const suffix = `/${normalizedInput.replace(/^\//, '')}`;
+ const suffixMatches = [...normalizedFiles.entries()].filter(([key]) =>
+ key.endsWith(suffix),
+ );
+ if (suffixMatches.length === 1) {
+ return suffixMatches[0][1];
+ }
+
+ throw new Error(`Could not find source file "${filePath}"`);
+};
+
+const resolveImportFile = ({
+ fromFile,
+ importPath,
+ project,
+}: {
+ fromFile: string;
+ importPath: string;
+ project: CodemodProject;
+}) => {
+ if (!importPath.startsWith('.')) {
+ throw new Error(`Cannot resolve package import "${importPath}"`);
+ }
+
+ const basePath = normalizePath(`${dirname(fromFile)}/${importPath}`);
+ const candidates = [
+ basePath,
+ ...['.tsx', '.ts', '.jsx', '.js'].map(
+ (extension) => `${basePath}${extension}`,
+ ),
+ ...['.tsx', '.ts', '.jsx', '.js'].map(
+ (extension) => `${basePath}/index${extension}`,
+ ),
+ ];
+ const normalizedFiles = new Map(
+ Object.keys(project.files).map((key) => [normalizePath(key), key]),
+ );
+
+ for (const candidate of candidates) {
+ const match = normalizedFiles.get(candidate);
+ if (match) {
+ return match;
+ }
+ }
+
+ throw new Error(`Could not find imported component file "${importPath}"`);
+};
+
+const jsxName = (name: AstNode | null): string | null => {
+ if (!name) {
+ return null;
+ }
+
+ if (name.type === 'JSXIdentifier') {
+ return getString(name, 'name');
+ }
+
+ if (name.type === 'JSXMemberExpression') {
+ const object = jsxName(getNode(name, 'object'));
+ const property = jsxName(getNode(name, 'property'));
+ return object && property ? `${object}.${property}` : null;
+ }
+
+ return null;
+};
+
+const getJsxAttribute = (openingElement: AstNode, name: string) => {
+ return (
+ getNodes(openingElement, 'attributes').find((attribute) => {
+ return (
+ attribute.type === 'JSXAttribute' &&
+ jsxName(getNode(attribute, 'name')) === name
+ );
+ }) ?? null
+ );
+};
+
+const jsxAttributeString = (attribute: AstNode | null) => {
+ const value = attribute ? getNode(attribute, 'value') : null;
+ if (!value) {
+ return null;
+ }
+
+ if (value.type === 'StringLiteral') {
+ return getString(value, 'value');
+ }
+
+ if (value.type !== 'JSXExpressionContainer') {
+ return null;
+ }
+
+ const expression = getNode(value, 'expression');
+ return expression?.type === 'StringLiteral'
+ ? getString(expression, 'value')
+ : null;
+};
+
+const jsxAttributeIdentifier = (attribute: AstNode | null) => {
+ const value = attribute ? getNode(attribute, 'value') : null;
+ const expression =
+ value?.type === 'JSXExpressionContainer'
+ ? getNode(value, 'expression')
+ : null;
+
+ return expression?.type === 'Identifier'
+ ? getString(expression, 'name')
+ : null;
+};
+
+const findDynamicImport = (attribute: AstNode | null) => {
+ let importPath: string | null = null;
+ const value = attribute ? getNode(attribute, 'value') : null;
+ visit(value, (node) => {
+ if (node.type === 'ImportExpression') {
+ const source = getNode(node, 'source');
+ if (source?.type === 'StringLiteral') {
+ importPath = getString(source, 'value');
+ return true;
+ }
+ }
+
+ if (
+ node.type === 'CallExpression' &&
+ getNode(node, 'callee')?.type === 'Import'
+ ) {
+ const argument = getNodes(node, 'arguments')[0];
+ if (argument?.type === 'StringLiteral') {
+ importPath = getString(argument, 'value');
+ return true;
+ }
+ }
+
+ return false;
+ });
+
+ return importPath;
+};
+
+const findCompositionElement = ({
+ ast,
+ compositionId,
+}: {
+ ast: AstNode;
+ compositionId: string;
+}) => {
+ let result: AstNode | null = null;
+ visit(ast, (node) => {
+ if (node.type !== 'JSXOpeningElement') {
+ return false;
+ }
+
+ const name = jsxName(getNode(node, 'name'));
+ if (
+ name !== 'Composition' &&
+ name !== 'Still' &&
+ !name?.endsWith('.Composition') &&
+ !name?.endsWith('.Still')
+ ) {
+ return false;
+ }
+
+ if (jsxAttributeString(getJsxAttribute(node, 'id')) === compositionId) {
+ result = node;
+ return true;
+ }
+
+ return false;
+ });
+
+ return result;
+};
+
+const programStatements = (ast: AstNode) => {
+ const program = ast.type === 'File' ? getNode(ast, 'program') : ast;
+ if (!program || program.type !== 'Program') {
+ throw new Error('Could not parse source file');
+ }
+
+ return getNodes(program, 'body');
+};
+
+const unwrapDeclaration = (statement: AstNode) => {
+ if (
+ statement.type === 'ExportNamedDeclaration' &&
+ getNode(statement, 'declaration')
+ ) {
+ return getNode(statement, 'declaration');
+ }
+
+ return statement;
+};
+
+const findNamedDeclaration = (ast: AstNode, name: string) => {
+ for (const statement of programStatements(ast)) {
+ const declaration = unwrapDeclaration(statement);
+ if (!declaration) {
+ continue;
+ }
+
+ if (
+ (declaration.type === 'FunctionDeclaration' ||
+ declaration.type === 'ClassDeclaration') &&
+ getString(getNode(declaration, 'id'), 'name') === name
+ ) {
+ return declaration;
+ }
+
+ if (declaration.type === 'VariableDeclaration') {
+ const variable = getNodes(declaration, 'declarations').find(
+ (item) => getString(getNode(item, 'id'), 'name') === name,
+ );
+ if (variable) {
+ return variable;
+ }
+ }
+ }
+
+ return null;
+};
+
+const findDefaultDeclaration = (ast: AstNode) => {
+ for (const statement of programStatements(ast)) {
+ if (statement.type !== 'ExportDefaultDeclaration') {
+ continue;
+ }
+
+ const declaration = getNode(statement, 'declaration');
+ if (declaration?.type === 'Identifier') {
+ const name = getString(declaration, 'name');
+ return name ? findNamedDeclaration(ast, name) : null;
+ }
+
+ return declaration;
+ }
+
+ return null;
+};
+
+const findImport = ({ast, localName}: {ast: AstNode; localName: string}) => {
+ for (const statement of programStatements(ast)) {
+ if (statement.type !== 'ImportDeclaration') {
+ continue;
+ }
+
+ const source = getString(getNode(statement, 'source'), 'value');
+ for (const specifier of getNodes(statement, 'specifiers')) {
+ if (getString(getNode(specifier, 'local'), 'name') !== localName) {
+ continue;
+ }
+
+ if (specifier.type === 'ImportDefaultSpecifier') {
+ return {exportName: 'default' as const, importPath: source};
+ }
+
+ if (specifier.type === 'ImportSpecifier') {
+ const imported = getNode(specifier, 'imported');
+ return {
+ exportName:
+ getString(imported, 'name') ?? getString(imported, 'value'),
+ importPath: source,
+ };
+ }
+ }
+ }
+
+ return null;
+};
+
+const unwrapExpression = (node: AstNode | null): AstNode | null => {
+ let current = node;
+ while (
+ current &&
+ (current.type === 'TSAsExpression' ||
+ current.type === 'TSSatisfiesExpression' ||
+ current.type === 'TypeCastExpression' ||
+ current.type === 'ParenthesizedExpression')
+ ) {
+ current = getNode(current, 'expression');
+ }
+
+ return current;
+};
+
+const getReturnedRoot = (declaration: AstNode) => {
+ let fn: AstNode | null = declaration;
+ if (declaration.type === 'VariableDeclarator') {
+ fn = unwrapExpression(getNode(declaration, 'init'));
+ }
+
+ if (
+ !fn ||
+ (fn.type !== 'ArrowFunctionExpression' &&
+ fn.type !== 'FunctionExpression' &&
+ fn.type !== 'FunctionDeclaration')
+ ) {
+ return null;
+ }
+
+ const body = unwrapExpression(getNode(fn, 'body'));
+ if (!body) {
+ return null;
+ }
+
+ if (body.type !== 'BlockStatement') {
+ return body;
+ }
+
+ const statements = getNodes(body, 'body');
+ const returnStatements = statements.filter(
+ (statement) => statement.type === 'ReturnStatement',
+ );
+ if (
+ returnStatements.length !== 1 ||
+ returnStatements[0] !== statements.at(-1)
+ ) {
+ return null;
+ }
+
+ return unwrapExpression(getNode(returnStatements[0], 'argument'));
+};
+
+const isCanvasRoot = (root: AstNode) => {
+ if (root.type !== 'JSXElement') {
+ return false;
+ }
+
+ const openingElement = getNode(root, 'openingElement');
+ const name = jsxName(getNode(openingElement ?? root, 'name'));
+ return (
+ name === 'ThreeCanvas' ||
+ name === 'RiveCanvas' ||
+ name === 'SkiaCanvas' ||
+ name === 'canvas'
+ );
+};
+
+const canAddToRoot = (root: AstNode | null): root is AstNode => {
+ if (!root) {
+ return false;
+ }
+
+ if (root.type === 'NullLiteral') {
+ return true;
+ }
+
+ return (
+ (root.type === 'JSXElement' || root.type === 'JSXFragment') &&
+ !isCanvasRoot(root)
+ );
+};
+
+const resolveReExport = ({
+ ast,
+ exportName,
+ filePath,
+ project,
+}: {
+ ast: AstNode;
+ exportName: string;
+ filePath: string;
+ project: CodemodProject;
+}): {exportName: string | 'default'; filePath: string} | null => {
+ for (const statement of programStatements(ast)) {
+ if (
+ statement.type !== 'ExportNamedDeclaration' ||
+ !getNode(statement, 'source')
+ ) {
+ continue;
+ }
+
+ const importPath = getString(getNode(statement, 'source'), 'value');
+ for (const specifier of getNodes(statement, 'specifiers')) {
+ const exported =
+ getString(getNode(specifier, 'exported'), 'name') ??
+ getString(getNode(specifier, 'exported'), 'value');
+ if (exported !== exportName) {
+ continue;
+ }
+
+ const imported =
+ getString(getNode(specifier, 'local'), 'name') ??
+ getString(getNode(specifier, 'local'), 'value');
+ if (!importPath || !imported) {
+ return null;
+ }
+
+ return {
+ exportName: imported,
+ filePath: resolveImportFile({fromFile: filePath, importPath, project}),
+ };
+ }
+ }
+
+ return null;
+};
+
+const resolveComponentDeclaration = ({
+ exportName,
+ filePath,
+ project,
+ visited,
+}: {
+ exportName: string | 'default';
+ filePath: string;
+ project: CodemodProject;
+ visited: Set<string>;
+}): {
+ ast: AstNode;
+ declaration: AstNode;
+ exportName: string | 'default';
+ filePath: string;
+ source: string;
+} => {
+ const key = `${filePath}:${exportName}`;
+ if (visited.has(key)) {
+ throw new Error(
+ `Circular component export while resolving "${exportName}"`,
+ );
+ }
+
+ visited.add(key);
+ const source = project.files[filePath];
+ if (typeof source !== 'string') {
+ throw new Error(`Could not read source file "${filePath}"`);
+ }
+
+ const ast = parseSource(source);
+ const declaration =
+ exportName === 'default'
+ ? findDefaultDeclaration(ast)
+ : findNamedDeclaration(ast, exportName);
+ if (declaration) {
+ return {ast, declaration, exportName, filePath, source};
+ }
+
+ if (exportName !== 'default') {
+ const reExport = resolveReExport({
+ ast,
+ exportName,
+ filePath,
+ project,
+ });
+ if (reExport) {
+ return resolveComponentDeclaration({
+ ...reExport,
+ project,
+ visited,
+ });
+ }
+ }
+
+ throw new Error(`Could not find composition component "${exportName}"`);
+};
+
+const resolveCompositionComponent = ({
+ compositionFile,
+ compositionId,
+ project,
+}: {
+ compositionFile: string;
+ compositionId: string;
+ project: CodemodProject;
+}): ResolvedComponent => {
+ const registrationFile = findProjectFile({
+ filePath: compositionFile,
+ project,
+ });
+ const registrationSource = project.files[registrationFile];
+ if (typeof registrationSource !== 'string') {
+ throw new Error(`Could not read source file "${registrationFile}"`);
+ }
+
+ const registrationAst = parseSource(registrationSource);
+ const compositionElement = findCompositionElement({
+ ast: registrationAst,
+ compositionId,
+ });
+ if (!compositionElement) {
+ throw new Error(`Could not find composition "${compositionId}"`);
+ }
+
+ const lazyImportPath = findDynamicImport(
+ getJsxAttribute(compositionElement, 'lazyComponent'),
+ );
+ let componentFile = registrationFile;
+ let exportName: string | 'default';
+ if (lazyImportPath) {
+ componentFile = resolveImportFile({
+ fromFile: registrationFile,
+ importPath: lazyImportPath,
+ project,
+ });
+ exportName = 'default';
+ } else {
+ const componentName = jsxAttributeIdentifier(
+ getJsxAttribute(compositionElement, 'component'),
+ );
+ if (!componentName) {
+ throw new Error(
+ `Could not find a component prop for composition "${compositionId}"`,
+ );
+ }
+
+ const componentImport = findImport({
+ ast: registrationAst,
+ localName: componentName,
+ });
+ if (componentImport?.importPath && componentImport.exportName) {
+ componentFile = resolveImportFile({
+ fromFile: registrationFile,
+ importPath: componentImport.importPath,
+ project,
+ });
+ exportName = componentImport.exportName;
+ } else {
+ exportName = componentName;
+ }
+ }
+
+ const resolved = resolveComponentDeclaration({
+ exportName,
+ filePath: componentFile,
+ project,
+ visited: new Set(),
+ });
+ const root = getReturnedRoot(resolved.declaration);
+
+ return {
+ canAddSequence: canAddToRoot(root),
+ declaration: resolved.declaration,
+ exportName: resolved.exportName,
+ filePath: resolved.filePath,
+ root:
+ root ??
+ (() => {
+ throw new Error('Composition component does not return JSX');
+ })(),
+ source: resolved.source,
+ };
+};
+
+const collectBindings = (ast: AstNode) => {
+ const bindings = new Set<string>();
+ visit(ast, (node) => {
+ if (
+ node.type === 'VariableDeclarator' ||
+ node.type === 'FunctionDeclaration' ||
+ node.type === 'ClassDeclaration' ||
+ node.type === 'ImportSpecifier' ||
+ node.type === 'ImportDefaultSpecifier' ||
+ node.type === 'ImportNamespaceSpecifier'
+ ) {
+ const identifier = node.type.startsWith('Import')
+ ? getNode(node, 'local')
+ : getNode(node, 'id');
+ const name = getString(identifier, 'name');
+ if (name) {
+ bindings.add(name);
+ }
+ }
+
+ return false;
+ });
+
+ return bindings;
+};
+
+const findImportedLocalName = ({
+ ast,
+ importedName,
+}: {
+ ast: AstNode;
+ importedName: string;
+}) => {
+ for (const statement of programStatements(ast)) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ getString(getNode(statement, 'source'), 'value') !== 'remotion'
+ ) {
+ continue;
+ }
+
+ for (const specifier of getNodes(statement, 'specifiers')) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ (getString(getNode(specifier, 'imported'), 'name') ??
+ getString(getNode(specifier, 'imported'), 'value')) === importedName
+ ) {
+ return getString(getNode(specifier, 'local'), 'name');
+ }
+ }
+ }
+
+ return null;
+};
+
+const chooseLocalName = ({
+ ast,
+ candidates,
+ importedName,
+}: {
+ ast: AstNode;
+ candidates: string[];
+ importedName: string;
+}) => {
+ const existing = findImportedLocalName({ast, importedName});
+ if (existing) {
+ return {addImport: false, localName: existing};
+ }
+
+ const bindings = collectBindings(ast);
+ const localName = candidates.find((candidate) => !bindings.has(candidate));
+ if (!localName) {
+ throw new Error(
+ `Cannot add <${importedName}> because all supported local names are defined`,
+ );
+ }
+
+ return {addImport: true, localName};
+};
+
+const getImportEdit = ({
+ ast,
+ imports,
+}: {
+ ast: AstNode;
+ imports: {importedName: string; localName: string}[];
+}): TextEdit | null => {
+ if (imports.length === 0) {
+ return null;
+ }
+
+ const specifiers = imports
+ .map(({importedName, localName}) =>
+ importedName === localName
+ ? importedName
+ : `${importedName} as ${localName}`,
+ )
+ .join(', ');
+ const existingImport = programStatements(ast).find(
+ (statement) =>
+ statement.type === 'ImportDeclaration' &&
+ getString(getNode(statement, 'source'), 'value') === 'remotion' &&
+ getString(statement, 'importKind') !== 'type' &&
+ !getNodes(statement, 'specifiers').some(
+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',
+ ),
+ );
+ if (existingImport) {
+ const existingSpecifiers = getNodes(existingImport, 'specifiers');
+ const namedSpecifiers = existingSpecifiers.filter(
+ (specifier) => specifier.type === 'ImportSpecifier',
+ );
+ const lastNamedSpecifier = namedSpecifiers.at(-1);
+ if (lastNamedSpecifier) {
+ const end = getPosition(lastNamedSpecifier, 'end');
+ return {end, start: end, text: `, ${specifiers}`};
+ }
+
+ const defaultSpecifier = existingSpecifiers.find(
+ (specifier) => specifier.type === 'ImportDefaultSpecifier',
+ );
+ if (defaultSpecifier) {
+ const end = getPosition(defaultSpecifier, 'end');
+ return {end, start: end, text: `, {${specifiers}}`};
+ }
+ }
+
+ const firstImport = programStatements(ast).find(
+ (statement) => statement.type === 'ImportDeclaration',
+ );
+ const start = firstImport ? getPosition(firstImport, 'start') : 0;
+
+ return {
+ end: start,
+ start,
+ text: `import {${specifiers}} from 'remotion';\n`,
+ };
+};
+
+const lineIndentAt = (source: string, position: number) => {
+ const lineStart = source.lastIndexOf('\n', position - 1) + 1;
+ return source.slice(lineStart, position).match(/^\s*/)?.[0] ?? '';
+};
+
+const indentationUnit = (source: string) => {
+ if (/^\t+/m.test(source)) {
+ return '\t';
+ }
+
+ const indentation = source.match(/^([ ]+)\S/m)?.[1].length;
+ return ' '.repeat(indentation && indentation > 1 ? indentation : 2);
+};
+
+const roundCoordinate = (value: number) => {
+ const rounded = Math.round(value * 10) / 10;
+ return Object.is(rounded, -0) ? 0 : rounded;
+};
+
+const solidElement = ({
+ height,
+ localName,
+ position,
+ width,
+}: {
+ height: number;
+ localName: string;
+ position: {x: number; y: number} | null;
+ width: number;
+}) => {
+ const translate = position
+ ? `, translate: '${roundCoordinate(position.x)}px ${roundCoordinate(position.y)}px'`
+ : '';
+
+ return `<${localName} width={${width}} height={${height}} color="gray" style={{position: 'absolute'${translate}}} />`;
+};
+
+const appendToJsxRoot = ({
+ element,
+ root,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const closing =
+ root.type === 'JSXFragment'
+ ? getNode(root, 'closingFragment')
+ : getNode(root, 'closingElement');
+ if (!closing) {
+ throw new Error('Composition component root does not accept children');
+ }
+
+ const closingStart = getPosition(closing, 'start');
+ const lineStart = source.lastIndexOf('\n', closingStart - 1) + 1;
+ const beforeClosing = source.slice(lineStart, closingStart);
+ const closingIndent = beforeClosing.match(/^\s*$/)
+ ? beforeClosing
+ : lineIndentAt(source, getPosition(root, 'start'));
+
+ if (/^\s*$/.test(beforeClosing) && lineStart > 0) {
+ return {
+ start: lineStart,
+ end: closingStart,
+ text: `${closingIndent}${unit}${element}\n${closingIndent}`,
+ };
+ }
+
+ return {
+ start: closingStart,
+ end: closingStart,
+ text: `\n${closingIndent}${unit}${element}\n${closingIndent}`,
+ };
+};
+
+const replaceNullRoot = ({
+ element,
+ root,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const indent = lineIndentAt(source, getPosition(root, 'start'));
+ return {
+ start: getPosition(root, 'start'),
+ end: getPosition(root, 'end'),
+ text: `(\n${indent}${unit}<>\n${indent}${unit}${unit}${element}\n${indent}${unit}</>\n${indent})`,
+ };
+};
+
+const replaceSelfClosingRoot = ({
+ element,
+ root,
+ sequenceLocalName,
+ source,
+ unit,
+}: {
+ element: string;
+ root: AstNode;
+ sequenceLocalName: string;
+ source: string;
+ unit: string;
+}): TextEdit => {
+ const start = getPosition(root, 'start');
+ const indent = lineIndentAt(source, start);
+ const original = source.slice(start, getPosition(root, 'end'));
+
+ return {
+ start,
+ end: getPosition(root, 'end'),
+ text: [
+ '<>',
+ `${indent}${unit}<${sequenceLocalName}>`,
+ `${indent}${unit}${unit}${original}`,
+ `${indent}${unit}</${sequenceLocalName}>`,
+ `${indent}${unit}${element}`,
+ `${indent}</>`,
+ ].join('\n'),
+ };
+};
+
+const applyTextEdits = (source: string, edits: TextEdit[]) => {
+ const sorted = [...edits].sort((a, b) => b.start - a.start);
+ let output = source;
+ let previousStart = source.length + 1;
+
+ for (const edit of sorted) {
+ if (edit.end > previousStart) {
+ throw new Error('Overlapping source edits');
+ }
+
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
+ previousStart = edit.start;
+ }
+
+ return output;
+};
+
+export const insertSolidIntoSource = ({
+ exportName,
+ height,
+ position,
+ source,
+ width,
+}: {
+ exportName: string | 'default';
+ height: number;
+ position: {x: number; y: number} | null;
+ source: string;
+ width: number;
+}): {output: string; line: number} => {
+ const ast = parseSource(source);
+ const declaration =
+ exportName === 'default'
+ ? findDefaultDeclaration(ast)
+ : findNamedDeclaration(ast, exportName);
+ if (!declaration) {
+ throw new Error(`Could not find composition component "${exportName}"`);
+ }
+
+ const root = getReturnedRoot(declaration);
+ if (!canAddToRoot(root)) {
+ throw new Error(
+ 'Cannot insert JSX element into this composition component',
+ );
+ }
+
+ const solidImport = chooseLocalName({
+ ast,
+ candidates: ['Solid', 'RemotionSolid'],
+ importedName: 'Solid',
+ });
+ const openingElement =
+ root.type === 'JSXElement' ? getNode(root, 'openingElement') : null;
+ const isSelfClosing = openingElement?.selfClosing === true;
+ const sequenceImport = isSelfClosing
+ ? chooseLocalName({
+ ast,
+ candidates: ['Sequence', 'RemotionSequence'],
+ importedName: 'Sequence',
+ })
+ : null;
+ const imports = [
+ ...(solidImport.addImport
+ ? [{importedName: 'Solid', localName: solidImport.localName}]
+ : []),
+ ...(sequenceImport?.addImport
+ ? [{importedName: 'Sequence', localName: sequenceImport.localName}]
+ : []),
+ ];
+ const unit = indentationUnit(source);
+ const element = solidElement({
+ height,
+ localName: solidImport.localName,
+ position,
+ width,
+ });
+ const rootEdit =
+ root.type === 'NullLiteral'
+ ? replaceNullRoot({
+ element,
+ root,
+ source,
+ unit,
+ })
+ : isSelfClosing && sequenceImport
+ ? replaceSelfClosingRoot({
+ element,
+ root,
+ sequenceLocalName: sequenceImport.localName,
+ source,
+ unit,
+ })
+ : appendToJsxRoot({
+ element,
+ root,
+ source,
+ unit,
+ });
+ const importEdit = getImportEdit({ast, imports});
+ return {
+ line: root.loc?.start.line ?? 1,
+ output: applyTextEdits(source, [
+ rootEdit,
+ ...(importEdit ? [importEdit] : []),
+ ]),
+ };
+};
+
+export const insertSolidIntoProject = <Project extends CodemodProject>({
+ project,
+ request,
+}: {
+ project: Project;
+ request: InsertJsxElementRequest;
+}): Project => {
+ if (request.element.type !== 'solid') {
+ throw new Error('This codemod only supports adding <Solid>');
+ }
+
+ if (request.from !== null) {
+ throw new Error(
+ 'This codemod only supports adding <Solid> at the current root',
+ );
+ }
+
+ const resolved = resolveCompositionComponent({
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ project,
+ });
+ const {output} = insertSolidIntoSource({
+ exportName: resolved.exportName,
+ height: request.element.height,
+ position: request.element.position,
+ source: resolved.source,
+ width: request.element.width,
+ });
+
+ return {
+ ...project,
+ files: {
+ ...project.files,
+ [resolved.filePath]: output,
+ },
+ };
+};
+
+const relativeToRoot = (filePath: string, rootDir: string) => {
+ const normalizedFile = normalizePath(filePath);
+ const normalizedRoot = normalizePath(rootDir).replace(/\/$/, '');
+ if (normalizedFile.startsWith(`${normalizedRoot}/`)) {
+ return normalizedFile.slice(normalizedRoot.length + 1);
+ }
+
+ return normalizedFile.replace(/^\//, '');
+};
+
+export const getCompositionComponentInfo = ({
+ project,
+ request,
+}: {
+ project: CodemodProject;
+ request: CompositionComponentInfoRequest;
+}) => {
+ const resolved = resolveCompositionComponent({
+ compositionFile: request.compositionFile,
+ compositionId: request.compositionId,
+ project,
+ });
+
+ return {
+ canAddSequence: resolved.canAddSequence,
+ location: {
+ source: relativeToRoot(resolved.filePath, project.rootDir),
+ line: resolved.declaration.loc?.start.line ?? 1,
+ column: resolved.declaration.loc?.start.column ?? 0,
+ },
+ };
+};
+
+export const getCompositionFile = ({
+ compositionId,
+ project,
+}: {
+ compositionId: string;
+ project: CodemodProject;
+}) => {
+ for (const [filePath, source] of Object.entries(project.files)) {
+ if (typeof source !== 'string') {
+ continue;
+ }
+
+ try {
+ const ast = parseSource(source);
+ if (findCompositionElement({ast, compositionId})) {
+ return relativeToRoot(filePath, project.rootDir);
+ }
+ } catch {
+ // Ignore files that are not parseable source modules.
+ }
+ }
+
+ return null;
+};
diff --git a/packages/studio-codemods/src/test/insert-solid.test.ts b/packages/studio-codemods/src/test/insert-solid.test.ts
new file mode 100644
index 0000000000..09163b385f
--- /dev/null
+++ b/packages/studio-codemods/src/test/insert-solid.test.ts
@@ -0,0 +1,23 @@
+import {expect, test} from 'bun:test';
+import {insertSolidIntoSource} from '..';
+
+test('inserts a Solid into a component source file', () => {
+ const result = insertSolidIntoSource({
+ exportName: 'MyComposition',
+ height: 720,
+ position: null,
+ source: `import {AbsoluteFill} from 'remotion';
+
+export const MyComposition = () => <AbsoluteFill>Existing</AbsoluteFill>;
+`,
+ width: 1280,
+ });
+
+ expect(result.output).toContain(
+ "import {AbsoluteFill, Solid} from 'remotion';",
+ );
+ expect(result.output).toContain(
+ '<Solid width={1280} height={720} color="gray"',
+ );
+ expect(result.line).toBe(3);
+});
diff --git a/packages/studio-codemods/tsconfig.json b/packages/studio-codemods/tsconfig.json
new file mode 100644
index 0000000000..3b7a483a1b
--- /dev/null
+++ b/packages/studio-codemods/tsconfig.json
@@ -0,0 +1,15 @@
+{
+ "extends": "../tsconfig.settings.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "skipLibCheck": true,
+ "target": "ES2022",
+ "module": "es2020",
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "emitDeclarationOnly": true
+ },
+ "include": ["src"],
+ "references": [{"path": "../studio-shared"}]
+}
diff --git a/packages/studio-server/package.json b/packages/studio-server/package.json
index 46a5f2c6b4..863aae5b2d 100644
--- a/packages/studio-server/package.json
+++ b/packages/studio-server/package.json
@@ -35,6 +35,7 @@
"recast": "0.23.11",
"@remotion/bundler": "workspace:*",
"@remotion/renderer": "workspace:*",
+ "@remotion/studio-codemods": "workspace:*",
"@remotion/studio-shared": "workspace:*",
"memfs": "3.4.3",
"open": "8.4.2"
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index ddd98e34e2..6d9752e6f9 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -17,6 +17,7 @@ import type {
VariableDeclaration,
} from '@babel/types';
import type {ComponentProp} from '@remotion/drag-and-drop';
+import {insertSolidIntoSource} from '@remotion/studio-codemods';
import {
isUrl,
type InsertableCompositionElement,
@@ -2305,61 +2306,76 @@ export const insertJsxElementIntoComposition = async ({
remotionRoot,
fileName: location.fileName,
});
- const ast = parseAst(input);
- if (
- element.type === 'composition' &&
- element.compositionId === compositionId
- ) {
- throw new Error('Cannot insert a composition into itself');
- }
+ let finalFile: string;
+ let logLine: number;
+ if (element.type === 'solid' && from === null && wrapInSequence === null) {
+ const inserted = insertSolidIntoSource({
+ exportName: location.exportName,
+ height: element.height,
+ position: element.position,
+ source: input,
+ width: element.width,
+ });
+ finalFile = inserted.output;
+ logLine = inserted.line;
+ } else {
+ const ast = parseAst(input);
+ if (
+ element.type === 'composition' &&
+ element.compositionId === compositionId
+ ) {
+ throw new Error('Cannot insert a composition into itself');
+ }
- const sequenceWrapper =
- element.type === 'composition'
- ? {
- dimensions: {width: element.width, height: element.height},
- durationInFrames: element.durationInFrames,
- name: element.compositionId,
- position: element.position,
- from,
- }
- : from === null ||
- element.type === 'asset' ||
- element.type === 'svg' ||
- element.type === 'component'
- ? wrapInSequence
- : {
- dimensions: null,
- durationInFrames: null,
- name: null,
+ const sequenceWrapper =
+ element.type === 'composition'
+ ? {
+ dimensions: {width: element.width, height: element.height},
+ durationInFrames: element.durationInFrames,
+ name: element.compositionId,
position: element.position,
from,
- };
- const elementToInsert = await createInsertableJsxElement({
- addPositionStyleToComponent: sequenceWrapper === null,
- ast,
- destinationFileName: location.fileName,
- element,
- from,
- remotionRoot,
- });
- const finalElementToInsert = sequenceWrapper
- ? createSequenceWrappedElement({
- child: elementToInsert,
- dimensions: sequenceWrapper.dimensions,
- durationInFrames: sequenceWrapper.durationInFrames ?? null,
- from: sequenceWrapper.from,
- name: sequenceWrapper.name,
- position: sequenceWrapper.position,
- sequenceLocalName: ensureSequenceImport(ast),
- })
- : elementToInsert;
- const logLine = addElementToComponentRoot({
- ast,
- exportName: location.exportName,
- element: finalElementToInsert,
- });
+ }
+ : from === null ||
+ element.type === 'asset' ||
+ element.type === 'svg' ||
+ element.type === 'component'
+ ? wrapInSequence
+ : {
+ dimensions: null,
+ durationInFrames: null,
+ name: null,
+ position: element.position,
+ from,
+ };
+ const elementToInsert = await createInsertableJsxElement({
+ addPositionStyleToComponent: sequenceWrapper === null,
+ ast,
+ destinationFileName: location.fileName,
+ element,
+ from,
+ remotionRoot,
+ });
+ const finalElementToInsert = sequenceWrapper
+ ? createSequenceWrappedElement({
+ child: elementToInsert,
+ dimensions: sequenceWrapper.dimensions,
+ durationInFrames: sequenceWrapper.durationInFrames ?? null,
+ from: sequenceWrapper.from,
+ name: sequenceWrapper.name,
+ position: sequenceWrapper.position,
+ sequenceLocalName: ensureSequenceImport(ast),
+ })
+ : elementToInsert;
+ logLine = addElementToComponentRoot({
+ ast,
+ exportName: location.exportName,
+ element: finalElementToInsert,
+ });
+
+ finalFile = serializeAst(ast);
+ }
- const finalFile = serializeAst(ast);
const {output, formatted} = await formatFileContent({
input: finalFile,
prettierConfigOverride,
diff --git a/packages/studio-server/tsconfig.json b/packages/studio-server/tsconfig.json
index ec8b7b5a74..0ecedd46b3 100644
--- a/packages/studio-server/tsconfig.json
+++ b/packages/studio-server/tsconfig.json
@@ -27,6 +27,9 @@
{
"path": "../studio-shared"
},
+ {
+ "path": "../studio-codemods"
+ },
{
"path": "../renderer"
},
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
new file mode 100644
index 0000000000..ad2c686559
--- /dev/null
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -0,0 +1,22 @@
+import type {
+ CompositionComponentInfoRequest,
+ CompositionComponentInfoResponse,
+ InsertJsxElementRequest,
+ InsertJsxElementResponse,
+} from './api-requests';
+
+export type BrowserStudioOperations = {
+ getCompositionFile: (compositionId: string) => string | null;
+ getCompositionComponentInfo: (
+ request: CompositionComponentInfoRequest,
+ ) => Promise<CompositionComponentInfoResponse>;
+ insertSolid: (
+ request: InsertJsxElementRequest,
+ ) => Promise<InsertJsxElementResponse>;
+};
+
+declare global {
+ interface Window {
+ remotion_browserStudio?: BrowserStudioOperations;
+ }
+}
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index 458fa65f69..5c80b3f391 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -1,4 +1,5 @@
export {splitAnsi, stripAnsi} from './ansi';
+export type {BrowserStudioOperations} from './browser-studio-operations';
export {
AddEffectKeyframeRequest,
AddEffectKeyframeResponse,
diff --git a/packages/studio-shared/src/package-info.ts b/packages/studio-shared/src/package-info.ts
index 925efa3a23..fd5ad45d82 100644
--- a/packages/studio-shared/src/package-info.ts
+++ b/packages/studio-shared/src/package-info.ts
@@ -72,6 +72,7 @@ const allPackages = [
'serverless-client',
'skills',
'skills-evals',
+ 'studio-codemods',
'studio-server',
'studio-shared',
'studio',
@@ -162,6 +163,7 @@ export const descriptions: {[key in Pkgs]: string | null} = {
bundler: 'Bundle Remotion compositions using Webpack',
'browser-studio': 'Run Remotion Studio in the browser',
'canvas-capture': 'Capture HTML-in-canvas content as a video',
+ 'studio-codemods': 'Shared codemods for Remotion Studio',
'studio-server': 'Run a Remotion Studio with a server backend',
'install-whisper-cpp': 'Helpers for installing and using Whisper.cpp',
'whisper-web': 'Helpers for using Whisper.cpp in browser using WASM',
@@ -328,6 +330,7 @@ export const installableMap: {[key in Pkgs]: boolean} = {
'promo-pages': false,
streaming: false,
serverless: false,
+ 'studio-codemods': false,
'studio-server': false,
'studio-shared': false,
studio: true,
@@ -385,6 +388,7 @@ export const apiDocs: {[key in Pkgs]: string | null} = {
bundler: 'https://www.remotion.dev/docs/bundler',
'browser-studio': null,
'canvas-capture': null,
+ 'studio-codemods': null,
'lambda-client': null,
'serverless-client': null,
'studio-server': null,
diff --git a/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx b/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
index e7ce7e337e..93e0ccb9f3 100644
--- a/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/CompositionInspector.tsx
@@ -59,7 +59,10 @@ const CompositionActions: React.FC<{
insertSolid,
} = useCompositionActions();
- if (readOnlyStudio || (!canShowInsertAsset && !canShowInsertSolid)) {
+ if (
+ (readOnlyStudio && !canShowInsertSolid) ||
+ (!canShowInsertAsset && !canShowInsertSolid)
+ ) {
return null;
}
diff --git a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts b/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
index 7707120d2c..7ee29e623d 100644
--- a/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
+++ b/packages/studio/src/components/InspectorPanel/use-composition-actions.ts
@@ -1,5 +1,7 @@
+import type {InsertJsxElementRequest} from '@remotion/studio-shared';
import {useCallback, useContext, useMemo, useState} from 'react';
import {Internals} from 'remotion';
+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';
import {useCachedCompositionComponentInfo} from '../../helpers/open-in-editor';
@@ -18,6 +20,8 @@ export const useCompositionActions = () => {
const {previewServerState} = useContext(StudioServerConnectionCtx);
const previewConnected = previewServerState.type === 'connected';
const previewInteractive = previewConnected && isStudioInteractivityEnabled();
+ const browserStudioOperations = getBrowserStudioOperations();
+ const browserStudioCanInsertSolid = browserStudioOperations !== null;
const currentCompositionId =
canvasContent?.type === 'composition' ? canvasContent.compositionId : null;
@@ -35,15 +39,20 @@ export const useCompositionActions = () => {
const resolvedCompositionLocation = useResolvedStack(
currentComposition?.stack ?? null,
);
- const compositionFile = resolvedCompositionLocation?.source ?? null;
+ const compositionFile =
+ resolvedCompositionLocation?.source ??
+ (currentCompositionId
+ ? (browserStudioOperations?.getCompositionFile(currentCompositionId) ??
+ null)
+ : null);
const compositionComponentInfo = useCachedCompositionComponentInfo({
compositionFile,
compositionId: currentCompositionId,
});
const canShowInsertSolid =
- previewInteractive &&
- !window.remotion_isReadOnlyStudio &&
+ (previewInteractive || browserStudioCanInsertSolid) &&
+ (!window.remotion_isReadOnlyStudio || browserStudioCanInsertSolid) &&
compositionComponentInfo?.canAddSequence === true &&
currentCompositionId !== null &&
compositionFile !== null &&
@@ -70,7 +79,7 @@ export const useCompositionActions = () => {
setIsAddingSolid(true);
try {
- const result = await callApi('/api/insert-jsx-element', {
+ const request: InsertJsxElementRequest = {
compositionFile,
compositionId: currentCompositionId,
from: null,
@@ -80,7 +89,10 @@ export const useCompositionActions = () => {
height: videoConfig.height,
position: null,
},
- });
+ };
+ const result = browserStudioOperations
+ ? await browserStudioOperations.insertSolid(request)
+ : await callApi('/api/insert-jsx-element', request);
if (result.success) {
showNotification('Added <Solid> to source file', 2000);
@@ -93,7 +105,13 @@ export const useCompositionActions = () => {
} finally {
setIsAddingSolid(false);
}
- }, [canInsertSolid, compositionFile, currentCompositionId, videoConfig]);
+ }, [
+ browserStudioOperations,
+ canInsertSolid,
+ compositionFile,
+ currentCompositionId,
+ videoConfig,
+ ]);
const insertAsset = useCallback(async () => {
if (
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 61fe2d65a9..2896ddbe80 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -1,5 +1,7 @@
+import type {InsertJsxElementRequest} from '@remotion/studio-shared';
import React, {useCallback, useContext, useMemo, useState} from 'react';
import {Internals} from 'remotion';
+import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {calculateTimeline} from '../../helpers/calculate-timeline';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {BACKGROUND} from '../../helpers/colors';
@@ -70,6 +72,8 @@ const TimelineContextMenuArea: React.FC<{
const {previewServerState} = useContext(StudioServerConnectionCtx);
const previewConnected = previewServerState.type === 'connected';
const previewInteractive = previewConnected && isStudioInteractivityEnabled();
+ const browserStudioOperations = getBrowserStudioOperations();
+ const browserStudioCanInsertSolid = browserStudioOperations !== null;
const currentCompositionId =
canvasContent?.type === 'composition' ? canvasContent.compositionId : null;
@@ -87,14 +91,19 @@ const TimelineContextMenuArea: React.FC<{
const resolvedCompositionLocation = useResolvedStack(
currentComposition?.stack ?? null,
);
- const compositionFile = resolvedCompositionLocation?.source ?? null;
+ const compositionFile =
+ resolvedCompositionLocation?.source ??
+ (currentCompositionId
+ ? (browserStudioOperations?.getCompositionFile(currentCompositionId) ??
+ null)
+ : null);
const compositionComponentInfo = useCachedCompositionComponentInfo({
compositionFile,
compositionId: currentCompositionId,
});
const canInsertSolid =
- previewInteractive &&
+ (previewInteractive || browserStudioCanInsertSolid) &&
compositionComponentInfo?.canAddSequence === true &&
currentCompositionId !== null &&
compositionFile !== null &&
@@ -121,7 +130,7 @@ const TimelineContextMenuArea: React.FC<{
setIsAddingSolid(true);
try {
- const result = await callApi('/api/insert-jsx-element', {
+ const request: InsertJsxElementRequest = {
compositionFile,
compositionId: currentCompositionId,
from: null,
@@ -131,7 +140,10 @@ const TimelineContextMenuArea: React.FC<{
height: videoConfig.height,
position: null,
},
- });
+ };
+ const result = browserStudioOperations
+ ? await browserStudioOperations.insertSolid(request)
+ : await callApi('/api/insert-jsx-element', request);
if (result.success) {
showNotification('Added <Solid> to source file', 2000);
@@ -144,7 +156,13 @@ const TimelineContextMenuArea: React.FC<{
} finally {
setIsAddingSolid(false);
}
- }, [canInsertSolid, compositionFile, currentCompositionId, videoConfig]);
+ }, [
+ browserStudioOperations,
+ canInsertSolid,
+ compositionFile,
+ currentCompositionId,
+ videoConfig,
+ ]);
const insertAsset = useCallback(async () => {
if (
diff --git a/packages/studio/src/helpers/browser-studio-operations.ts b/packages/studio/src/helpers/browser-studio-operations.ts
new file mode 100644
index 0000000000..0965b663ff
--- /dev/null
+++ b/packages/studio/src/helpers/browser-studio-operations.ts
@@ -0,0 +1,10 @@
+import type {BrowserStudioOperations} from '@remotion/studio-shared';
+
+export const getBrowserStudioOperations =
+ (): BrowserStudioOperations | null => {
+ if (typeof window === 'undefined') {
+ return null;
+ }
+
+ return window.remotion_browserStudio ?? null;
+ };
diff --git a/packages/studio/src/helpers/open-in-editor.ts b/packages/studio/src/helpers/open-in-editor.ts
index 73610b68f8..5417821f93 100644
--- a/packages/studio/src/helpers/open-in-editor.ts
+++ b/packages/studio/src/helpers/open-in-editor.ts
@@ -2,12 +2,13 @@ import type {
CompositionComponentInfoResponse,
SymbolicatedStackFrame,
} from '@remotion/studio-shared';
-import {useSyncExternalStore} from 'react';
+import {useEffect, useSyncExternalStore} from 'react';
import {callApi} from '../components/call-api';
import type {
CodePosition,
OriginalPosition,
} from '../error-overlay/react-overlay/utils/get-source-map';
+import {getBrowserStudioOperations} from './browser-studio-operations';
export const openInEditor = (stack: SymbolicatedStackFrame) => {
const {
@@ -122,7 +123,7 @@ export const useCachedCompositionComponentInfo = ({
compositionFile: string | null;
compositionId: string | null;
}) => {
- return useSyncExternalStore(
+ const result = useSyncExternalStore(
subscribeToCompositionComponentInfo,
() => {
if (compositionFile === null || compositionId === null) {
@@ -136,6 +137,23 @@ export const useCachedCompositionComponentInfo = ({
},
() => null,
);
+
+ useEffect(() => {
+ if (
+ !getBrowserStudioOperations() ||
+ compositionFile === null ||
+ compositionId === null
+ ) {
+ return;
+ }
+
+ preloadCompositionComponentInfo({
+ compositionFile,
+ compositionId,
+ });
+ }, [compositionFile, compositionId]);
+
+ return result;
};
export const loadCompositionComponentInfo = async ({
@@ -155,10 +173,14 @@ export const loadCompositionComponentInfo = async ({
}
const promise = (async () => {
- const body = await callApi('/api/composition-component-info', {
+ const request = {
compositionFile,
compositionId,
- });
+ };
+ const browserStudioOperations = getBrowserStudioOperations();
+ const body = browserStudioOperations
+ ? await browserStudioOperations.getCompositionComponentInfo(request)
+ : await callApi('/api/composition-component-info', request);
const result = {
location: body.location,
diff --git a/tsconfig.json b/tsconfig.json
index 9a0b7fe62f..39696e9574 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -198,6 +198,9 @@
{
"path": "./packages/studio"
},
+ {
+ "path": "./packages/studio-codemods"
+ },
{
"path": "./packages/studio-server"
},