🎥 Make videos programmatically with React
`@remotion/browser-studio`: Support sequence prop subscriptions (#9883)
Jonny Burger9cbe92183160
diff --git a/.github/workflows/push.yml b/.github/workflows/push.ymlindex ffc53a0941..bb0d7e604a 100644--- a/.github/workflows/push.yml+++ b/.github/workflows/push.yml@@ -111,6 +111,9 @@ jobs:- name: Test web rendererrun: |bun run testwebrenderer+ - name: Test Browser Studio+ run: |+ bun run testbrowserstudiossr-tests:runs-on: ubuntu-latesttimeout-minutes: 30diff --git a/bun.lock b/bun.lockindex d4471a9a27..44990a657b 100644--- a/bun.lock+++ b/bun.lock@@ -143,8 +143,10 @@"react-refresh": "0.18.0",},"devDependencies": {+ "@playwright/test": "1.55.1","@remotion/eslint-config-internal": "workspace:*","@remotion/studio": "workspace:*",+ "@rspack/core": "1.7.11","@rspack/plugin-react-refresh": "1.6.1","@types/react": "catalog:","@types/react-dom": "catalog:",@@ -1709,7 +1711,11 @@"version": "4.0.501","dependencies": {"@babel/parser": "7.24.1",+ "@babel/types": "7.24.0","@remotion/studio-shared": "workspace:*",+ "ast-types": "0.16.1",+ "recast": "0.23.11",+ "remotion": "workspace:*",},"devDependencies": {"@remotion/eslint-config-internal": "workspace:*",@@ -4337,7 +4343,7 @@"@rspack/core": ["@rspack/[email protected]", "", { "dependencies": { "@module-federation/runtime-tools": "0.22.0", "@rspack/binding": "1.7.11", "@rspack/lite-tapable": "1.1.0" }, "peerDependencies": { "@swc/helpers": ">=0.5.1" }, "optionalPeers": ["@swc/helpers"] }, "sha512-rsD9b+Khmot5DwCMiB3cqTQo53ioPG3M/A7BySu8+0+RS7GCxKm+Z+mtsjtG/vsu4Tn2tcqCdZtA3pgLoJB+ew=="],- "@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-1OnyWChLGE46YzWyjlmYJssOu/Y0STAnnr2ueKPqDCYTf63GJMs0mxNnCul4dNiVqHYPKv3/fxrTY3IpqoVwZQ=="],+ "@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-E2B0JhYFmVAwdDiG14+DW0Di4Ze4Jg10Pc4/lILUrd5DRCaklduz2OvJ5HYQ6G+hd+WTzqQb3QnDNfK4yvAFYw=="],"@rspack/plugin-react-refresh": ["@rspack/[email protected]", "", { "dependencies": { "error-stack-parser": "^2.1.4", "html-entities": "^2.6.0" }, "peerDependencies": { "react-refresh": ">=0.10.0 <1.0.0", "webpack-hot-middleware": "2.x" }, "optionalPeers": ["webpack-hot-middleware"] }, "sha512-eqqW5645VG3CzGzFgNg5HqNdHVXY+567PGjtDhhrM8t67caxmsSzRmT5qfoEIfBcGgFkH9vEg7kzXwmCYQdQDw=="],@@ -9895,12 +9901,12 @@"@rspack/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@emnapi/core": "^1.5.0", "@emnapi/runtime": "^1.5.0", "@tybys/wasm-util": "^0.10.1" } }, "sha512-SeDnOO0Tk7Okiq6DbXmmBODgOAb9dp9gjlphokTUxmt8U3liIP1ZsozBahH69j/RJv+Rfs6IwUKHTgQYJ/HBAw=="],+ "@rspack/browser/@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-1OnyWChLGE46YzWyjlmYJssOu/Y0STAnnr2ueKPqDCYTf63GJMs0mxNnCul4dNiVqHYPKv3/fxrTY3IpqoVwZQ=="],+"@rspack/browser/memfs": ["[email protected]", "", { "dependencies": { "@jsonjoy.com/fs-core": "4.57.7", "@jsonjoy.com/fs-fsa": "4.57.7", "@jsonjoy.com/fs-node": "4.57.7", "@jsonjoy.com/fs-node-builtins": "4.57.7", "@jsonjoy.com/fs-node-to-fsa": "4.57.7", "@jsonjoy.com/fs-node-utils": "4.57.7", "@jsonjoy.com/fs-print": "4.57.7", "@jsonjoy.com/fs-snapshot": "4.57.7", "@jsonjoy.com/json-pack": "^1.11.0", "@jsonjoy.com/util": "^1.9.0", "glob-to-regex.js": "^1.0.1", "thingies": "^2.5.0", "tree-dump": "^1.0.3", "tslib": "^2.0.0" } }, "sha512-YZPphUQZSRGk6ddPlsNuMbztrLwsbUATFNZcqKscSbSJZ4g0+Y3vSZLJ/rfnGZaB1FFhC7SrywZXev6i8lnHgg=="],"@rspack/browser/webpack-sources": ["[email protected]", "", {}, "sha512-HPuy+uuoTCaaoEoI1LQ3JN9+vrPBvEesnnX1jADHy728cHSMlq4wUc4afYqahq2B1mhQVZxCXOkNTnXltr+2vQ=="],- "@rspack/core/@rspack/lite-tapable": ["@rspack/[email protected]", "", {}, "sha512-E2B0JhYFmVAwdDiG14+DW0Di4Ze4Jg10Pc4/lILUrd5DRCaklduz2OvJ5HYQ6G+hd+WTzqQb3QnDNfK4yvAFYw=="],-"@shikijs/primitive/@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-qzbeRooUTPnLE+sHD/Z8DStmaDgnbbc/pMrU203950aRqjX/6AFHeDYT+j00y2lPdz0ywJKx7o/7qnqTivtlXg=="],"@shopify/react-native-skia/react": ["[email protected]", "", {}, "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ=="],diff --git a/package.json b/package.jsonindex 5577fa93fb..296312ca12 100644--- a/package.json+++ b/package.json@@ -16,6 +16,7 @@"teste2e": "turbo run teste2e --no-update-notifier","testwebcodecs": "turbo run testwebcodecs --no-update-notifier","testwebrenderer": "turbo run testwebrenderer --concurrency=1 --no-update-notifier",+ "testbrowserstudio": "turbo run testbrowserstudio --concurrency=1 --no-update-notifier","testlayoututils": "turbo run testlayoututils --concurrency=1 --no-update-notifier","testeffectsvisual": "turbo run testeffectsvisual --concurrency=1 --no-update-notifier","testlambda": "turbo run testlambda --concurrency=1 --no-update-notifier",diff --git a/packages/browser-studio/e2e/app.tsx b/packages/browser-studio/e2e/app.tsxnew file mode 100644index 0000000000..6c841417d2--- /dev/null+++ b/packages/browser-studio/e2e/app.tsx@@ -0,0 +1,18 @@+import {+ BrowserStudio,+ createBlankTemplateProject,+} from '@remotion/browser-studio';+import {createRoot} from 'react-dom/client';++const root = document.getElementById('root');+if (!root) {+ throw new Error('Could not find root element');+}++createRoot(root).render(+ <BrowserStudio+ iframeSrc="/frame.html"+ project={createBlankTemplateProject()}+ readOnly={false}+ />,+);diff --git a/packages/browser-studio/e2e/browser-studio.test.ts b/packages/browser-studio/e2e/browser-studio.test.tsnew file mode 100644index 0000000000..bd4e69a2be--- /dev/null+++ b/packages/browser-studio/e2e/browser-studio.test.ts@@ -0,0 +1,40 @@+import {expect, test} from '@playwright/test';++test('loads the Browser Studio canvas and enables Visual Mode', async ({+ page,+}) => {+ const pageErrors: Error[] = [];+ let rejectPageError: (error: Error) => void = () => undefined;+ const pageError = new Promise<never>((_resolve, reject) => {+ rejectPageError = reject;+ });+ page.on('pageerror', (error) => {+ pageErrors.push(error);+ rejectPageError(error);+ });++ await Promise.race([+ (async () => {+ await page.goto('/');+ const studio = page.frameLocator('iframe');+ await expect(+ studio.getByTitle('/project').getByText('MyComp'),+ ).toBeVisible();+ await expect(+ studio.locator('.remotion-studio-composition-container'),+ ).toBeVisible();++ await studio.locator('[data-compname="MyComp"]').click();+ await studio.locator('[data-sidebar-toggle="right"]').click();+ await expect(+ studio.getByRole('button', {name: 'Inspector'}),+ ).toBeVisible();+ await studio.getByRole('button', {name: 'Add Solid'}).click();+ await expect(studio.getByText('<Solid>', {exact: true})).toBeVisible();+ await expect(studio.locator('svg[viewBox="0 0 24 16"]')).toBeVisible();+ })(),+ pageError,+ ]);++ expect(pageErrors).toEqual([]);+});diff --git a/packages/browser-studio/e2e/server.ts b/packages/browser-studio/e2e/server.tsnew file mode 100644index 0000000000..efe2c43065--- /dev/null+++ b/packages/browser-studio/e2e/server.ts@@ -0,0 +1,102 @@+import path from 'node:path';+import {rspack} from '@rspack/core';++const port = Number(process.env.PORT ?? 62338);+const outputPath = path.join(import.meta.dir, '..', 'dist', 'e2e');++const compile = () =>+ new Promise<void>((resolve, reject) => {+ const compiler = rspack({+ context: import.meta.dir,+ devtool: 'source-map',+ entry: './app.tsx',+ mode: 'development',+ module: {+ rules: [+ {+ test: /\.tsx?$/,+ use: [+ {+ loader: 'builtin:swc-loader',+ options: {+ jsc: {+ parser: {syntax: 'typescript', tsx: true},+ transform: {react: {runtime: 'automatic'}},+ },+ },+ },+ ],+ },+ ],+ },+ output: {+ clean: true,+ filename: 'app.js',+ path: outputPath,+ },+ resolve: {extensions: ['.tsx', '.ts', '.jsx', '.js']},+ });++ compiler.run((error, stats) => {+ compiler.close(() => undefined);+ if (error) {+ reject(error);+ return;+ }++ if (stats?.hasErrors()) {+ reject(new Error(stats.toString({colors: true})));+ return;+ }++ resolve();+ });+ });++const document = (body: string, script: string | null) => `<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <style>html, body, #root { height: 100%; margin: 0; width: 100%; }</style>+ </head>+ <body>${body}${script ? `<script src="${script}"></script>` : ''}</body>+</html>`;++await compile();++Bun.serve({+ port,+ async fetch(request) {+ const url = new URL(request.url);+ const headers = {+ 'Cross-Origin-Embedder-Policy': 'credentialless',+ 'Cross-Origin-Opener-Policy': 'same-origin',+ };++ if (url.pathname === '/') {+ return new Response(document('<div id="root"></div>', '/app.js'), {+ headers: {...headers, 'Content-Type': 'text/html'},+ });+ }++ if (url.pathname === '/frame.html') {+ return new Response(document('', null), {+ headers: {...headers, 'Content-Type': 'text/html'},+ });+ }++ const filePath = path.join(outputPath, url.pathname);+ if (!filePath.startsWith(outputPath)) {+ return new Response('Not found', {status: 404});+ }++ const file = Bun.file(filePath);+ if (!(await file.exists())) {+ return new Response('Not found', {status: 404});+ }++ return new Response(file, {headers});+ },+});++process.stdout.write(`Browser Studio E2E server: http://127.0.0.1:${port}\n`);diff --git a/packages/browser-studio/eslint.config.mjs b/packages/browser-studio/eslint.config.mjsindex ab29acaba0..4d3b831bea 100644--- a/packages/browser-studio/eslint.config.mjs+++ b/packages/browser-studio/eslint.config.mjs@@ -4,4 +4,5 @@ const config = remotionFlatConfig({react: true});export default {...config,+ files: [...config.files, 'e2e/**/*.ts', 'e2e/**/*.tsx', 'playwright.config.ts'],};diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.jsonindex 9283630129..0b4842adc5 100644--- a/packages/browser-studio/package.json+++ b/packages/browser-studio/package.json@@ -13,9 +13,10 @@"scripts": {"dev": "bun src/dev/server.ts","test": "bun test src/test",- "formatting": "oxfmt src --check",- "format": "oxfmt src",- "lint": "eslint src",+ "testbrowserstudio": "playwright test",+ "formatting": "oxfmt src e2e playwright.config.ts --check",+ "format": "oxfmt src e2e playwright.config.ts",+ "lint": "eslint src e2e playwright.config.ts","watch": "tsgo -w","make": "tsgo && bun --env-file=../.env.bundle bundle.ts"},@@ -46,6 +47,8 @@"./package.json": "./package.json"},"devDependencies": {+ "@playwright/test": "1.55.1",+ "@rspack/core": "1.7.11","@rspack/plugin-react-refresh": "1.6.1","@remotion/studio": "workspace:*","@remotion/eslint-config-internal": "workspace:*",diff --git a/packages/browser-studio/playwright.config.ts b/packages/browser-studio/playwright.config.tsnew file mode 100644index 0000000000..345c35e103--- /dev/null+++ b/packages/browser-studio/playwright.config.ts@@ -0,0 +1,31 @@+import {defineConfig, devices} from '@playwright/test';++const port = 62338;++export default defineConfig({+ testDir: './e2e',+ outputDir: './dist/e2e-test-results',+ timeout: 90_000,+ expect: {+ timeout: 60_000,+ },+ fullyParallel: false,+ workers: 1,+ retries: 0,+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ trace: 'on-first-retry',+ },+ projects: [+ {+ name: 'chromium',+ use: {...devices['Desktop Chrome']},+ },+ ],+ webServer: {+ command: `PORT=${port} bun e2e/server.ts`,+ url: `http://127.0.0.1:${port}`,+ reuseExistingServer: !process.env.CI,+ timeout: 120_000,+ },+});diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex cb75cc62f3..f1db861b83 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -1,13 +1,21 @@import {+ computeSequencePropsStatusFromContent,+ computeSequencePropsSubscriptionFromContent,+ findProjectFile,getCanUpdateDefaultPropsForProject,getCompositionComponentInfo,getCompositionFile,insertSolidIntoProject,+ JsxElementIdentityMismatchError,+ JsxElementNotFoundAtLocationError,} from '@remotion/studio-codemods';import type {BrowserStudioOperations,EventSourceEvent,InsertJsxElementResponse,+ SubscribeToSequencePropsRequest,+ SubscribeToSequencePropsResponse,+ UnsubscribeFromSequencePropsRequest,} from '@remotion/studio-shared';import {createBrowserStudioProjectController} from './browser-studio-project-controller';import {makeBrowserStudioProjectArchive} from './download-project';@@ -20,6 +28,40 @@ export type BrowserStudioOperationsController = BrowserStudioOperations & {resetHistory: () => void;};+type SuccessfulSequencePropsSubscription = Extract<+ SubscribeToSequencePropsResponse,+ {success: true}+>;++type SequencePropsSubscription = {+ request: SubscribeToSequencePropsRequest;+ result: SuccessfulSequencePropsSubscription;+ refCount: number;+ effectChain: string;+};++const getEffectChain = (result: SuccessfulSequencePropsSubscription) =>+ result.status.effects+ .map((effect) => (effect.canUpdate ? effect.callee : false))+ .join(',');++const makeSequencePropsSubscriptionKey = ({+ clientId,+ fileName,+ nodePath,+ sequenceKeys,+ assetKeys,+ effectKeys,+}: UnsubscribeFromSequencePropsRequest) =>+ JSON.stringify({+ clientId,+ fileName,+ nodePath,+ sequenceKeys,+ assetKeys,+ effectKeys,+ });+export const createBrowserStudioOperations = ({dependencyVersions,getStaticFiles,@@ -35,13 +77,19 @@ export const createBrowserStudioOperations = ({}): BrowserStudioOperationsController => {const defaultPropsSubscriptions = new Map<string, Set<string>>();const lastDefaultPropsResults = new Map<string, string>();+ const sequencePropsSubscriptions = new Map<+ string,+ SequencePropsSubscription+ >();let refreshDefaultPropsSubscriptions = () => undefined;+ let refreshSequencePropsSubscriptions = () => undefined;const controller = createBrowserStudioProjectController({getStaticFiles,getProject,onProjectChange: (project) => {onProjectChange(project);refreshDefaultPropsSubscriptions();+ refreshSequencePropsSubscriptions();},});@@ -68,6 +116,81 @@ export const createBrowserStudioOperations = ({}};+ const getSequencePropsSubscription = (+ request: SubscribeToSequencePropsRequest,+ ): SubscribeToSequencePropsResponse => {+ try {+ const project = getProject();+ const absolutePath = findProjectFile({+ filePath: request.fileName,+ project,+ });+ return computeSequencePropsSubscriptionFromContent({+ fileContents: project.files[absolutePath],+ absolutePath,+ line: request.line,+ preferredNodePath: request.nodePath,+ componentIdentity: request.componentIdentity,+ keys: request.keys,+ assetKeys: request.assetKeys,+ effects: request.effects,+ videoConfigValues: request.videoConfigValues,+ });+ } catch {+ return {+ success: false,+ status: {canUpdate: false, reason: 'error'},+ };+ }+ };++ refreshSequencePropsSubscriptions = () => {+ for (const subscription of sequencePropsSubscriptions.values()) {+ const {request, result} = subscription;+ try {+ const project = getProject();+ const absolutePath = findProjectFile({+ filePath: request.fileName,+ project,+ });+ const nextStatus = computeSequencePropsStatusFromContent({+ fileContents: project.files[absolutePath],+ nodePath: result.nodePath.nodePath,+ componentIdentity: request.componentIdentity,+ keys: request.keys,+ assetKeys: request.assetKeys,+ effects: request.effects,+ videoConfigValues: request.videoConfigValues,+ });+ const nextEffectChain = nextStatus.effects+ .map((effect) => (effect.canUpdate ? effect.callee : false))+ .join(',');+ if (nextEffectChain !== subscription.effectChain) {+ continue;+ }++ controller.emitEvent({+ type: 'sequence-props-updated',+ fileName: request.fileName,+ nodePath: result.nodePath,+ result: nextStatus,+ });+ } catch (error) {+ if (+ error instanceof JsxElementNotFoundAtLocationError ||+ error instanceof JsxElementIdentityMismatchError+ ) {+ controller.emitEvent({+ type: 'lost-node-path',+ fileName: request.fileName,+ line: request.line,+ column: request.column,+ });+ }+ }+ }+ };+return {deleteStaticFile: controller.deleteStaticFile,downloadProject: () =>@@ -110,6 +233,7 @@ export const createBrowserStudioOperations = ({resetHistory: () => {controller.resetHistory();refreshDefaultPropsSubscriptions();+ refreshSequencePropsSubscriptions();},subscribeToDefaultProps: ({clientId, compositionId}) => {const clients =@@ -121,6 +245,34 @@ export const createBrowserStudioOperations = ({return Promise.resolve(result);},subscribeToEvent: controller.subscribeToEvent,+ subscribeToSequenceProps: (request) => {+ const result = getSequencePropsSubscription(request);+ if (!result.success) {+ return Promise.resolve(result);+ }++ const key = makeSequencePropsSubscriptionKey({+ clientId: request.clientId,+ fileName: request.fileName,+ nodePath: result.nodePath,+ sequenceKeys: request.keys,+ assetKeys: request.assetKeys,+ effectKeys: request.effects,+ });+ const existing = sequencePropsSubscriptions.get(key);+ if (existing) {+ existing.refCount++;+ return Promise.resolve(result);+ }++ sequencePropsSubscriptions.set(key, {+ request,+ result,+ refCount: 1,+ effectChain: getEffectChain(result),+ });+ return Promise.resolve(result);+ },undo: controller.undo,unsubscribeFromDefaultProps: ({clientId, compositionId}) => {const clients = defaultPropsSubscriptions.get(compositionId);@@ -132,6 +284,20 @@ export const createBrowserStudioOperations = ({return Promise.resolve(undefined);},+ unsubscribeFromSequenceProps: (request) => {+ const key = makeSequencePropsSubscriptionKey(request);+ const subscription = sequencePropsSubscriptions.get(key);+ if (!subscription) {+ return Promise.resolve(undefined);+ }++ subscription.refCount--;+ if (subscription.refCount <= 0) {+ sequencePropsSubscriptions.delete(key);+ }++ return Promise.resolve(undefined);+ },writeStaticFile: controller.writeStaticFile,};};diff --git a/packages/browser-studio/src/browser-studio-worker.ts b/packages/browser-studio/src/browser-studio-worker.tsindex 2385bd5fe2..96af00b787 100644--- a/packages/browser-studio/src/browser-studio-worker.ts+++ b/packages/browser-studio/src/browser-studio-worker.ts@@ -299,6 +299,8 @@ const createCompiler = async ({react: {development: true,refresh: true,+ importSource:+ browserStudioVirtualFilePaths.jsxImportSource,runtime: 'automatic',},},@@ -321,6 +323,8 @@ const createCompiler = async ({react: {development: true,refresh: true,+ importSource:+ browserStudioVirtualFilePaths.jsxImportSource,runtime: 'automatic',},},diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.tsindex 7199ed1872..0c0393ee61 100644--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts@@ -273,3 +273,123 @@ registerRoot(Root);`,events.filter((event) => event.type === 'default-props-updatable-changed'),).toHaveLength(1);});++test('subscribes to sequence prop updates and emits virtual project events', async () => {+ const fileName = '/project/src/Composition.tsx';+ let currentProject: VirtualProject = {+ rootDir: '/project',+ entryPoint: '/project/src/index.tsx',+ files: {+ '/project/src/index.tsx': `import {registerRoot} from 'remotion';+import {Root} from './Composition';+registerRoot(Root);`,+ [fileName]: `import {Composition, Sequence} from 'remotion';+export const Component = () => <Sequence from={10} durationInFrames={20} />;+export const Root = () => <Composition id="MyComp" component={Component} durationInFrames={60} fps={30} width={1280} height={720} />;`,+ },+ };+ const operations = createBrowserStudioOperations({+ dependencyVersions: {},+ getStaticFiles: null,+ getProject: () => currentProject,+ onProjectChange: (nextProject) => {+ currentProject = nextProject;+ },+ });+ const events: EventSourceEvent[] = [];+ operations.subscribeToEvent((event) => events.push(event));++ const request = {+ fileName: 'src/Composition.tsx',+ line: 2,+ column: 31,+ nodePath: null,+ componentIdentity: 'dev.remotion.remotion.Sequence',+ keys: ['from', 'durationInFrames'],+ assetKeys: [],+ effects: [],+ clientId: 'browser-studio',+ videoConfigValues: {+ durationInFrames: 60,+ fps: 30,+ height: 720,+ width: 1280,+ },+ };+ const subscription = await operations.subscribeToSequenceProps(request);+ expect(subscription.success).toBe(true);+ if (!subscription.success) {+ throw new Error('Expected sequence props subscription to succeed');+ }++ expect(subscription.status.props).toEqual({+ from: {status: 'static', codeValue: 10},+ durationInFrames: {status: 'static', codeValue: 20},+ });+ expect(subscription.nodePath.absolutePath).toBe(fileName);++ currentProject = {+ ...currentProject,+ files: {+ ...currentProject.files,+ [fileName]: currentProject.files[fileName].replace(+ 'from={10}',+ 'from={15}',+ ),+ },+ };+ operations.resetHistory();+ const update = events.findLast(+ (+ event,+ ): event is Extract<EventSourceEvent, {type: 'sequence-props-updated'}> =>+ event.type === 'sequence-props-updated',+ );+ expect(update?.fileName).toBe('src/Composition.tsx');+ expect(update?.result.canUpdate).toBe(true);+ if (!update?.result.canUpdate) {+ throw new Error('Expected updated sequence props to be editable');+ }++ expect(update.result.props.from).toEqual({status: 'static', codeValue: 15});++ currentProject = {+ ...currentProject,+ files: {+ ...currentProject.files,+ [fileName]: currentProject.files[fileName].replace(+ '<Sequence from={15} durationInFrames={20} />',+ '<div />',+ ),+ },+ };+ operations.resetHistory();+ expect(events.findLast((event) => event.type === 'lost-node-path')).toEqual({+ type: 'lost-node-path',+ fileName: 'src/Composition.tsx',+ line: 2,+ column: 31,+ });++ await operations.unsubscribeFromSequenceProps({+ fileName: request.fileName,+ nodePath: subscription.nodePath,+ clientId: request.clientId,+ sequenceKeys: request.keys.slice(),+ assetKeys: [],+ effectKeys: [],+ });+ const sequenceEventCount = events.filter(+ (event) =>+ event.type === 'sequence-props-updated' ||+ event.type === 'lost-node-path',+ ).length;+ operations.resetHistory();+ expect(+ events.filter(+ (event) =>+ event.type === 'sequence-props-updated' ||+ event.type === 'lost-node-path',+ ),+ ).toHaveLength(sequenceEventCount);+});diff --git a/packages/browser-studio/src/virtual-files.ts b/packages/browser-studio/src/virtual-files.tsindex e3456aaa07..425d615d27 100644--- a/packages/browser-studio/src/virtual-files.ts+++ b/packages/browser-studio/src/virtual-files.ts@@ -6,6 +6,9 @@ export const browserStudioVirtualFilePaths = {setupEnvironment: '/__remotion_browser_studio__/setup-environment.ts',setupSequenceStackTraces:'/__remotion_browser_studio__/setup-sequence-stack-traces.ts',+ jsxRuntime: '/__remotion_browser_studio__/jsx-runtime.ts',+ jsxDevRuntime: '/__remotion_browser_studio__/jsx-dev-runtime.ts',+ jsxImportSource: '/__remotion_browser_studio__',reactShim: '/__remotion_browser_studio__/react-shim.js',};@@ -35,19 +38,16 @@ const getInjectedReactRefreshFiles = () => {};const setupSequenceStackTraces = `import React from 'react';-import JsxRuntimeDev from 'react/jsx-dev-runtime';-import JsxRuntime from 'react/jsx-runtime';import {Internals} from 'remotion';const componentsToAddStacksTo = Internals.getComponentsToAddStacksTo();const sequenceComponent = Internals.getSequenceComponent();+const internalStackProp = Internals.REMOTION_INTERNAL_STACK_PROP;+const browserStudioOriginalSourcePrefix = 'browser-studio-original://';const originalCreateElement = React.createElement;-const originalJsx = JsxRuntime.jsx;-const originalJsxs = JsxRuntime.jsxs;-const originalJsxDev = JsxRuntimeDev.jsxDEV;-const enableProxy = (api, isCreateElement) => {+export const enableProxy = (api, isCreateElement, sourceArgumentIndex) => {return new Proxy(api, {apply(target, thisArg, argArray) {if (componentsToAddStacksTo.includes(argArray[0])) {@@ -57,9 +57,25 @@ const enableProxy = (api, isCreateElement) => {? props?.children: rest: props?.children;- const newProps = props?.stack+ const source =+ sourceArgumentIndex === null ? null : argArray[sourceArgumentIndex];+ const stack =+ source &&+ typeof source.fileName === 'string' &&+ typeof source.lineNumber === 'number' &&+ typeof source.columnNumber === 'number'+ ? 'Error\\n at browserStudioOriginal (' ++ browserStudioOriginalSourcePrefix ++ encodeURIComponent(source.fileName) ++ ':' ++ source.lineNumber ++ ':' ++ source.columnNumber ++ ')'+ : new Error().stack;+ const newProps = props?.[internalStackProp]? {...props}- : {...(props ?? {}), stack: new Error().stack};+ : {...(props ?? {}), [internalStackProp]: stack};if (first === sequenceComponent) {newProps._remotionInternalSingleChildComponent =Internals.getSingleChildComponent(children);@@ -73,10 +89,29 @@ const enableProxy = (api, isCreateElement) => {});};-React.createElement = enableProxy(originalCreateElement, true);-JsxRuntime.jsx = enableProxy(originalJsx, false);-JsxRuntime.jsxs = enableProxy(originalJsxs, false);-JsxRuntimeDev.jsxDEV = enableProxy(originalJsxDev, false);+React.createElement = enableProxy(originalCreateElement, true, null);+`;++const jsxRuntime = `import {+ Fragment,+ jsx as originalJsx,+ jsxs as originalJsxs,+} from 'react/jsx-runtime';+import {enableProxy} from './setup-sequence-stack-traces';++export {Fragment};+export const jsx = enableProxy(originalJsx, false, null);+export const jsxs = enableProxy(originalJsxs, false, null);+`;++const jsxDevRuntime = `import {+ Fragment,+ jsxDEV as originalJsxDev,+} from 'react/jsx-dev-runtime';+import {enableProxy} from './setup-sequence-stack-traces';++export {Fragment};+export const jsxDEV = enableProxy(originalJsxDev, false, 4);`;const reactShim = `import * as React from 'react';@@ -119,6 +154,8 @@ export const getBrowserStudioVirtualFiles = (): Record<string, string> => {getInjectedSetupEnvironment(),[browserStudioVirtualFilePaths.setupSequenceStackTraces]:setupSequenceStackTraces,+ [browserStudioVirtualFilePaths.jsxRuntime]: jsxRuntime,+ [browserStudioVirtualFilePaths.jsxDevRuntime]: jsxDevRuntime,[browserStudioVirtualFilePaths.reactShim]: reactShim,};};diff --git a/packages/studio-codemods/package.json b/packages/studio-codemods/package.jsonindex b4fc004f45..89000b7ea8 100644--- a/packages/studio-codemods/package.json+++ b/packages/studio-codemods/package.json@@ -25,7 +25,11 @@},"dependencies": {"@babel/parser": "7.24.1",- "@remotion/studio-shared": "workspace:*"+ "@babel/types": "7.24.0",+ "@remotion/studio-shared": "workspace:*",+ "ast-types": "0.16.1",+ "recast": "0.23.11",+ "remotion": "workspace:*"},"exports": {".": {diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.tsindex 14879ea99e..503927a59b 100644--- a/packages/studio-codemods/src/index.ts+++ b/packages/studio-codemods/src/index.ts@@ -6,6 +6,12 @@ import type {} from '@remotion/studio-shared';export {findSearchPosition} from './find-search-position';+export {+ computeSequencePropsStatusFromContent,+ computeSequencePropsSubscriptionFromContent,+} from './sequence-props';+export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';+export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';export type CodemodProject = {files: Record<string, string>;@@ -157,7 +163,7 @@ const stripSourceProtocol = (filePath: string) => {.split(/[?#]/, 1)[0];};-const findProjectFile = ({+export const findProjectFile = ({filePath,project,}: {diff --git a/packages/studio-codemods/src/sequence-props.ts b/packages/studio-codemods/src/sequence-props.tsnew file mode 100644index 0000000000..78859a26cd--- /dev/null+++ b/packages/studio-codemods/src/sequence-props.ts@@ -0,0 +1,1430 @@+import type {+ CallExpression,+ Expression,+ File,+ JSXAttribute,+ JSXElement,+ JSXOpeningElement,+ NewExpression,+ ObjectExpression,+ ObjectProperty,+ TSAsExpression,+ UnaryExpression,+} from '@babel/types';+import type {SubscribeToSequencePropsResponse} from '@remotion/studio-shared';+import {LINEAR_KEYFRAME_EASING} from '@remotion/studio-shared/keyframe-easing-presets';+import {isKeyframeInterpolationFunction} from '@remotion/studio-shared/keyframe-interpolation-function';+import type {NodePath} from 'ast-types';+import * as recast from 'recast';+import type {+ CanUpdateSequencePropsResponseTrue,+ CanUpdateSequencePropStatus,+ ExtrapolateType,+ InterpolateOutputOption,+ JsxComponentIdentity,+ SequenceNodePath,+ VideoConfigNumericExpression,+ VideoConfigValues,+} from 'remotion';+import {NoReactInternals} from 'remotion/no-react';+import {computeEffectPropStatus} from './sequence-props/can-update-effect-props';+import {getCssShorthandForLonghand} from './sequence-props/css-shorthand-properties';+import {getAstNodePath} from './sequence-props/get-ast-node-path';+import {toImportAgnosticNodePath} from './sequence-props/import-agnostic-node-path';+import {+ getJsxComponentIdentity,+ jsxComponentIdentitiesMatch,+ JsxElementIdentityMismatchError,+} from './sequence-props/jsx-component-identity';+import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';+import {parseAst} from './sequence-props/parse-ast';+import {parseBorderRadiusShorthand} from './sequence-props/parse-border-radius-shorthand';+import {parseKeyframeEasingExpression} from './sequence-props/parse-keyframe-easing-expression';+import {parseVideoConfigNumericExpression} from './sequence-props/video-config-numeric-expression';+import {+ getVideoConfigIdentifierValues,+ type VideoConfigIdentifierValues,+} from './sequence-props/video-config-values';++type CanUpdatePropStatus = CanUpdateSequencePropStatus;+type KeyframedPropStatus = Extract<CanUpdatePropStatus, {status: 'keyframed'}>;+type PropKeyframes = KeyframedPropStatus['keyframes'];+type PropEasing = KeyframedPropStatus['easing'];+type PropClamping = KeyframedPropStatus['clamping'];+type PropPosterize = KeyframedPropStatus['posterize'];+type PropOutput = KeyframedPropStatus['output'];+type PropInterpolationFunction = KeyframedPropStatus['interpolationFunction'];++const staticStatus = (+ codeValue: unknown,+ numericExpression: VideoConfigNumericExpression | null,+): CanUpdatePropStatus => ({+ status: 'static',+ codeValue,+ ...(numericExpression === null || numericExpression.type === 'literal'+ ? {}+ : {numericExpression}),+});++const computedStatus = (): CanUpdatePropStatus => ({+ status: 'computed',+});++// Mirrors the encoding that staticFile() from "remotion" applies at runtime+const encodeStaticFilePath = (path: string): string => {+ return path.split('/').map(encodeURIComponent).join('/');+};++type SpecialValueCall =+ | {type: 'static-file'; value: string}+ | {type: 'date'; value: string};++// Detects calls that the Studio knows how to serialize back to source:+// staticFile("...") and new Date("...")+const getSpecialValueCall = (node: Expression): SpecialValueCall | null => {+ if (node.type === 'CallExpression') {+ const call = node as CallExpression;+ if (+ call.callee.type === 'Identifier' &&+ call.callee.name === 'staticFile' &&+ call.arguments.length === 1 &&+ call.arguments[0].type === 'StringLiteral'+ ) {+ return {type: 'static-file', value: call.arguments[0].value};+ }++ return null;+ }++ if (node.type === 'NewExpression') {+ const newExpr = node as NewExpression;+ if (+ newExpr.callee.type === 'Identifier' &&+ newExpr.callee.name === 'Date' &&+ newExpr.arguments.length === 1 &&+ newExpr.arguments[0].type === 'StringLiteral'+ ) {+ return {type: 'date', value: newExpr.arguments[0].value};+ }++ return null;+ }++ return null;+};++type StaticValueOptions = {+ allowSpecialValues: boolean;+};++const defaultStaticValueOptions: StaticValueOptions = {+ allowSpecialValues: false,+};++export const isStaticValue = (+ node: Expression,+ options: StaticValueOptions = defaultStaticValueOptions,+): boolean => {+ if (options.allowSpecialValues && getSpecialValueCall(node) !== null) {+ return true;+ }++ switch (node.type) {+ case 'NumericLiteral':+ case 'StringLiteral':+ case 'BooleanLiteral':+ case 'NullLiteral':+ return true;+ case 'UnaryExpression':+ return (+ ((node as UnaryExpression).operator === '-' ||+ (node as UnaryExpression).operator === '+') &&+ (node as UnaryExpression).argument.type === 'NumericLiteral'+ );+ case 'TSAsExpression':+ return isStaticValue(+ (node as TSAsExpression).expression as Expression,+ options,+ );+ case 'ArrayExpression':+ return (+ node as Extract<Expression, {type: 'ArrayExpression'}>+ ).elements.every(+ (el) =>+ el !== null &&+ el.type !== 'SpreadElement' &&+ isStaticValue(el, options),+ );+ case 'ObjectExpression':+ return (node as ObjectExpression).properties.every(+ (prop) =>+ prop.type === 'ObjectProperty' &&+ isStaticValue((prop as ObjectProperty).value as Expression, options),+ );+ default:+ return false;+ }+};++export const extractStaticValue = (+ node: Expression,+ options: StaticValueOptions = defaultStaticValueOptions,+): unknown => {+ if (options.allowSpecialValues) {+ const specialValue = getSpecialValueCall(node);+ if (specialValue !== null) {+ if (specialValue.type === 'static-file') {+ return `${NoReactInternals.FILE_TOKEN}${encodeStaticFilePath(specialValue.value)}`;+ }++ return `${NoReactInternals.DATE_TOKEN}${specialValue.value}`;+ }+ }++ switch (node.type) {+ case 'NumericLiteral':+ case 'StringLiteral':+ case 'BooleanLiteral':+ return (node as {value: unknown}).value;+ case 'NullLiteral':+ return null;+ case 'UnaryExpression': {+ const un = node as UnaryExpression;+ if (un.argument.type === 'NumericLiteral') {+ const val = (un.argument as {value: number}).value;+ return un.operator === '-' ? -val : val;+ }++ return undefined;+ }++ case 'TSAsExpression':+ return extractStaticValue(+ (node as TSAsExpression).expression as Expression,+ options,+ );+ case 'ArrayExpression':+ return (+ node as Extract<Expression, {type: 'ArrayExpression'}>+ ).elements.map((el) => {+ if (el === null || el.type === 'SpreadElement') {+ return undefined;+ }++ return extractStaticValue(el, options);+ });+ case 'ObjectExpression': {+ const obj = node as ObjectExpression;+ const result: Record<string, unknown> = {};+ for (const prop of obj.properties) {+ if (prop.type === 'ObjectProperty') {+ const p = prop as ObjectProperty;+ const key =+ p.key.type === 'Identifier'+ ? (p.key as {name: string}).name+ : p.key.type === 'StringLiteral' ||+ p.key.type === 'NumericLiteral'+ ? String((p.key as {value: unknown}).value)+ : undefined;+ if (key !== undefined) {+ result[key] = extractStaticValue(p.value as Expression, options);+ }+ }+ }++ return result;+ }++ default:+ return undefined;+ }+};++const getNumericValue = (node: Expression): number | null => {+ if (node.type === 'NumericLiteral') {+ return node.value;+ }++ if (+ node.type === 'UnaryExpression' &&+ (node.operator === '-' || node.operator === '+') &&+ node.argument.type === 'NumericLiteral'+ ) {+ return node.operator === '-' ? -node.argument.value : node.argument.value;+ }++ if (node.type === 'TSAsExpression') {+ return getNumericValue(node.expression as Expression);+ }++ return null;+};++const getExtrapolateType = (node: Expression): ExtrapolateType | null => {+ if (node.type === 'StringLiteral') {+ if (+ node.value === 'extend' ||+ node.value === 'identity' ||+ node.value === 'clamp' ||+ node.value === 'wrap'+ ) {+ return node.value;+ }++ return null;+ }++ if (node.type === 'TSAsExpression') {+ return getExtrapolateType(node.expression as Expression);+ }++ return null;+};++const getInterpolateOutputOption = (+ node: Expression,+): InterpolateOutputOption | null => {+ if (node.type === 'StringLiteral') {+ if (node.value === 'linear' || node.value === 'perceptual-scale') {+ return node.value;+ }++ return null;+ }++ if (node.type === 'TSAsExpression') {+ return getInterpolateOutputOption(node.expression as Expression);+ }++ return null;+};++const getKeyframeEasing = (node: Expression): PropEasing[number] | null =>+ parseKeyframeEasingExpression(node);++const getKeyframeEasingArray = ({+ easingNode,+ segments,+}: {+ easingNode: Expression;+ segments: number;+}): PropEasing | null => {+ if (segments === 0) {+ return [];+ }++ if (easingNode.type === 'TSAsExpression') {+ return getKeyframeEasingArray({+ easingNode: easingNode.expression as Expression,+ segments,+ });+ }++ if (easingNode.type === 'ArrayExpression') {+ if (easingNode.elements.length !== segments) {+ return null;+ }++ const parsed = easingNode.elements.map((element) => {+ if (!element || element.type === 'SpreadElement') {+ return null;+ }++ return getKeyframeEasing(element);+ });++ if (parsed.some((value) => value === null)) {+ return null;+ }++ return parsed as PropEasing;+ }++ const easing = getKeyframeEasing(easingNode);+ if (!easing) {+ return null;+ }++ return new Array(segments).fill(easing) as PropEasing;+};++const getInterpolationMetadata = (+ interpolationFunction: PropInterpolationFunction,+ callExpression: CallExpression,+ keyframeCount: number,+): {+ easing: PropEasing;+ clamping: PropClamping;+ posterize: PropPosterize;+ output: PropOutput;+} | null => {+ const segments = Math.max(0, keyframeCount - 1);+ const defaultClamping: PropClamping =+ interpolationFunction === 'interpolateColors'+ ? {+ left: 'clamp',+ right: 'clamp',+ }+ : {+ left: 'extend',+ right: 'extend',+ };+ const defaults = {+ easing: Array.from({length: segments}, () => LINEAR_KEYFRAME_EASING),+ clamping: defaultClamping,+ posterize: undefined,+ output: undefined,+ };++ const optionsArg = callExpression.arguments[3];+ if (!optionsArg) {+ return defaults;+ }++ if (optionsArg.type !== 'ObjectExpression') {+ return null;+ }++ let {easing} = defaults;+ let {clamping}: {clamping: PropClamping} = defaults;+ let posterize: PropPosterize;+ let {output}: {output: PropOutput} = defaults;++ for (const property of optionsArg.properties) {+ if (property.type !== 'ObjectProperty' || property.computed) {+ return null;+ }++ const key =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;++ if (!key) {+ return null;+ }++ const value = property.value as Expression;++ if (key === 'easing') {+ const parsedEasing = getKeyframeEasingArray({+ easingNode: value,+ segments,+ });+ if (!parsedEasing) {+ return null;+ }++ easing = parsedEasing;+ continue;+ }++ if (key === 'extrapolateLeft' || key === 'extrapolateRight') {+ if (interpolationFunction === 'interpolateColors') {+ return null;+ }++ const extrapolateType = getExtrapolateType(value);+ if (!extrapolateType) {+ return null;+ }++ clamping =+ key === 'extrapolateLeft'+ ? {...clamping, left: extrapolateType}+ : {...clamping, right: extrapolateType};+ continue;+ }++ if (key === 'posterize') {+ const parsedPosterize = getNumericValue(value);+ if (+ parsedPosterize === null ||+ !Number.isFinite(parsedPosterize) ||+ parsedPosterize <= 0+ ) {+ return null;+ }++ posterize = parsedPosterize;+ continue;+ }++ if (key === 'output') {+ if (interpolationFunction === 'interpolateColors') {+ return null;+ }++ const parsedOutput = getInterpolateOutputOption(value);+ if (!parsedOutput) {+ return null;+ }++ output = parsedOutput;+ continue;+ }++ return null;+ }++ return {+ easing,+ clamping,+ posterize,+ output,+ };+};++const isUseCurrentFrameCall = (node: Expression): boolean => {+ return (+ node.type === 'CallExpression' &&+ node.callee.type === 'Identifier' &&+ node.callee.name === 'useCurrentFrame' &&+ node.arguments.length === 0+ );+};++const isCurrentFrameIdentifier = (node: Expression, ast: File): boolean => {+ if (node.type === 'TSAsExpression') {+ return isCurrentFrameIdentifier(node.expression as Expression, ast);+ }++ if (node.type !== 'Identifier') {+ return false;+ }++ let hasUseCurrentFrameDeclaration = false;+ let hasOtherDeclaration = false;++ recast.types.visit(ast, {+ visitVariableDeclarator(p) {+ const {id, init} = p.node;+ if (id.type !== 'Identifier' || id.name !== node.name) {+ return this.traverse(p);+ }++ if (init && isUseCurrentFrameCall(init as Expression)) {+ hasUseCurrentFrameDeclaration = true;+ } else {+ hasOtherDeclaration = true;+ }++ return false;+ },+ });++ return hasUseCurrentFrameDeclaration && !hasOtherDeclaration;+};++const getInterpolationKeyframes = (+ node: Expression,+ ast: File,+ videoConfigValues: VideoConfigIdentifierValues,+):+ | {+ keyframes: PropKeyframes;+ easing: PropEasing;+ clamping: PropClamping;+ posterize: PropPosterize;+ output: PropOutput;+ interpolationFunction: PropInterpolationFunction;+ }+ | undefined => {+ if (node.type === 'TSAsExpression') {+ return getInterpolationKeyframes(+ node.expression as Expression,+ ast,+ videoConfigValues,+ );+ }++ if (+ node.type === 'CallExpression' &&+ node.callee.type === 'Identifier' &&+ node.callee.name === 'String' &&+ node.arguments.length === 1 &&+ node.arguments[0].type !== 'ArgumentPlaceholder' &&+ node.arguments[0].type !== 'JSXNamespacedName' &&+ node.arguments[0].type !== 'SpreadElement'+ ) {+ const interpolation = getInterpolationKeyframes(+ node.arguments[0] as Expression,+ ast,+ videoConfigValues,+ );+ if (!interpolation) {+ return undefined;+ }++ return {+ ...interpolation,+ keyframes: interpolation.keyframes.map((keyframe) => ({+ ...keyframe,+ value: String(keyframe.value),+ })),+ };+ }++ if (node.type !== 'CallExpression') {+ return undefined;+ }++ const callExpression = node as CallExpression;+ if (+ callExpression.callee.type !== 'Identifier' ||+ !isKeyframeInterpolationFunction(callExpression.callee.name)+ ) {+ return undefined;+ }++ const interpolationFunction = callExpression.callee.name;++ const frameArg = callExpression.arguments[0];+ const inputArg = callExpression.arguments[1];+ const outputArg = callExpression.arguments[2];+ if (+ !frameArg ||+ frameArg.type === 'SpreadElement' ||+ !isCurrentFrameIdentifier(frameArg as Expression, ast) ||+ !inputArg ||+ !outputArg ||+ inputArg.type !== 'ArrayExpression' ||+ outputArg.type !== 'ArrayExpression'+ ) {+ return undefined;+ }++ if (inputArg.elements.length !== outputArg.elements.length) {+ return undefined;+ }++ const keyframes: PropKeyframes = [];+ for (let i = 0; i < inputArg.elements.length; i++) {+ const inputElement = inputArg.elements[i];+ const outputElement = outputArg.elements[i];+ if (+ !inputElement ||+ !outputElement ||+ inputElement.type === 'SpreadElement' ||+ outputElement.type === 'SpreadElement'+ ) {+ return undefined;+ }++ const frameExpression = parseVideoConfigNumericExpression({+ node: inputElement,+ videoConfigValues,+ });+ if (frameExpression === null || !isStaticValue(outputElement)) {+ return undefined;+ }++ keyframes.push({+ frame: frameExpression.value,+ value: extractStaticValue(outputElement),+ ...(frameExpression.type === 'literal' ? {} : {frameExpression}),+ });+ }++ if (keyframes.length === 0) {+ return undefined;+ }++ const metadata = getInterpolationMetadata(+ interpolationFunction,+ callExpression,+ keyframes.length,+ );+ if (!metadata) {+ return undefined;+ }++ return {+ interpolationFunction,+ keyframes,+ easing: metadata.easing,+ clamping: metadata.clamping,+ posterize: metadata.posterize,+ output: metadata.output,+ };+};++export const getComputedStatus = (+ node: Expression,+ ast: File,+ videoConfigValues: VideoConfigIdentifierValues,+): CanUpdatePropStatus => {+ const interpolation = getInterpolationKeyframes(node, ast, videoConfigValues);+ if (!interpolation) {+ return computedStatus();+ }++ return {+ status: 'keyframed',+ interpolationFunction: interpolation.interpolationFunction,+ keyframes: interpolation.keyframes,+ easing: interpolation.easing,+ clamping: interpolation.clamping,+ posterize: interpolation.posterize,+ output: interpolation.output,+ };+};++const getPropsStatus = (+ jsxElement: JSXOpeningElement,+ ast: File,+ videoConfigValues: VideoConfigIdentifierValues,+ assetKeys: string[],+): Record<string, CanUpdatePropStatus> => {+ const props: Record<string, CanUpdatePropStatus> = {};++ for (const attr of jsxElement.attributes) {+ if (attr.type === 'JSXSpreadAttribute') {+ continue;+ }++ if (attr.name.type === 'JSXNamespacedName') {+ continue;+ }++ const {name} = attr.name;+ if (typeof name !== 'string') {+ continue;+ }++ const {value} = attr as JSXAttribute;++ if (!value) {+ props[name] = staticStatus(true, null);+ continue;+ }++ if (value.type === 'StringLiteral') {+ props[name] = staticStatus((value as {value: string}).value, null);+ continue;+ }++ if (value.type === 'JSXExpressionContainer') {+ const {expression} = value;+ const staticValueOptions = {+ allowSpecialValues: assetKeys.includes(name),+ };+ if (expression.type === 'JSXEmptyExpression') {+ props[name] = computedStatus();+ continue;+ }++ if (!isStaticValue(expression, staticValueOptions)) {+ const numericExpression = parseVideoConfigNumericExpression({+ node: expression,+ videoConfigValues,+ });+ props[name] = numericExpression+ ? staticStatus(numericExpression.value, numericExpression)+ : getComputedStatus(expression, ast, videoConfigValues);+ continue;+ }++ props[name] = staticStatus(+ extractStaticValue(expression, staticValueOptions),+ null,+ );+ continue;+ }++ props[name] = computedStatus();+ }++ return props;+};++const getNodePathForRecastPath = (+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ recastPath: any,+ ast: File,+): SequenceNodePath => {+ const segments: Array<string | number> = [];+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let current: any = recastPath;+ while (current && current.parentPath) {+ segments.unshift(current.name);+ current = current.parentPath;+ }++ // Recast paths start with "root" which doesn't correspond to a real AST property+ if (segments.length > 0 && segments[0] === 'root') {+ return toImportAgnosticNodePath({ast, nodePath: segments.slice(1)});+ }++ return toImportAgnosticNodePath({ast, nodePath: segments});+};++export const findJsxElementPathAtNodePath = (+ ast: File,+ nodePath: SequenceNodePath,+): NodePath | null => {+ const current = getAstNodePath(ast, nodePath);+ if (!current) {+ return null;+ }++ if (recast.types.namedTypes.JSXOpeningElement.check(current.value)) {+ return current;+ }++ return null;+};++export const findJsxElementAtNodePath = (+ ast: File,+ nodePath: SequenceNodePath,+): JSXOpeningElement | null => {+ const current = findJsxElementPathAtNodePath(ast, nodePath);+ return current ? (current.value as unknown as JSXOpeningElement) : null;+};++export const findJsxElementNodeAtNodePath = (+ ast: File,+ nodePath: SequenceNodePath,+): JSXElement | null => {+ const current = findJsxElementPathAtNodePath(ast, nodePath);+ if (!current) {+ return null;+ }++ if (recast.types.namedTypes.JSXElement.check(current.parentPath?.value)) {+ return current.parentPath.value as unknown as JSXElement;+ }++ return null;+};++export type StaticJsxTextContent =+ | {kind: 'jsx-text'; value: string}+ | {kind: 'string-expression'; value: string};++const findJsxChildrenAttribute = (+ jsxElement: JSXOpeningElement,+): JSXAttribute | null => {+ const childrenAttr = jsxElement.attributes.find((attr) => {+ return (+ attr.type === 'JSXAttribute' &&+ attr.name.type === 'JSXIdentifier' &&+ attr.name.name === 'children'+ );+ });++ return childrenAttr && childrenAttr.type === 'JSXAttribute'+ ? childrenAttr+ : null;+};++export const getStaticJsxChildrenAttribute = (+ jsxElement: JSXOpeningElement,+): StaticJsxTextContent | null => {+ const childrenAttr = findJsxChildrenAttribute(jsxElement);+ if (!childrenAttr?.value) {+ return null;+ }++ if (childrenAttr.value.type === 'StringLiteral') {+ return {kind: 'jsx-text', value: childrenAttr.value.value};+ }++ if (+ childrenAttr.value.type === 'JSXExpressionContainer' &&+ childrenAttr.value.expression.type === 'StringLiteral'+ ) {+ return {+ kind: 'string-expression',+ value: childrenAttr.value.expression.value,+ };+ }++ return null;+};++export const hasJsxChildrenAttribute = (+ jsxElement: JSXOpeningElement,+): boolean => findJsxChildrenAttribute(jsxElement) !== null;++export const getStaticJsxTextContent = (+ jsxElement: JSXElement,+): StaticJsxTextContent | null => {+ const meaningfulChildren = jsxElement.children.filter((candidate) => {+ return !(candidate.type === 'JSXText' && candidate.value.trim() === '');+ });++ if (meaningfulChildren.length === 0) {+ return {kind: 'jsx-text', value: ''};+ }++ if (meaningfulChildren.length !== 1) {+ return null;+ }++ const child = meaningfulChildren[0];+ if (child.type === 'JSXText') {+ return {+ kind: 'jsx-text',+ value: child.value.includes('\n') ? child.value.trim() : child.value,+ };+ }++ if (+ child.type === 'JSXExpressionContainer' &&+ child.expression.type === 'StringLiteral'+ ) {+ return {kind: 'string-expression', value: child.expression.value};+ }++ return null;+};++export const findNodePathForJsxElement = (+ ast: File,+ target: JSXOpeningElement,+): SequenceNodePath | null => {+ let foundPath: SequenceNodePath | null = null;++ recast.types.visit(ast, {+ visitJSXOpeningElement(p) {+ if (p.node === target) {+ foundPath = getNodePathForRecastPath(p, ast);+ return false;+ }++ return this.traverse(p);+ },+ });++ return foundPath;+};++export const lineColumnToNodePath = (+ ast: File,+ targetLine: number,+): SequenceNodePath | null => {+ let foundPath: SequenceNodePath | null = null;++ recast.types.visit(ast, {+ visitJSXOpeningElement(p) {+ const {node} = p;+ if (node.loc && node.loc.start.line === targetLine) {+ foundPath = getNodePathForRecastPath(p, ast);+ return false;+ }++ return this.traverse(p);+ },+ });++ return foundPath;+};++const PIXEL_VALUE_REGEX = /^-?\d+(\.\d+)?px$/;++const isSupportedTranslateValue = (value: string): boolean => {+ const parts = value.split(/\s+/);+ if (parts.length === 1 || parts.length === 2) {+ return parts.every((part) => PIXEL_VALUE_REGEX.test(part));+ }++ return false;+};++const validateStyleValue = (childKey: string, value: unknown): boolean => {+ if (childKey === 'translate' && typeof value === 'string') {+ return isSupportedTranslateValue(value);+ }++ return true;+};++const getObjectPropertyName = (property: ObjectProperty): string | null => {+ if (property.key.type === 'Identifier') {+ return property.key.name;+ }++ if (property.key.type === 'StringLiteral') {+ return property.key.value;+ }++ return null;+};++const BORDER_RADIUS_SHORTHAND = 'borderRadius';+const BORDER_RADIUS_LONGHANDS = [+ 'borderTopLeftRadius',+ 'borderTopRightRadius',+ 'borderBottomRightRadius',+ 'borderBottomLeftRadius',+] as const;+const BORDER_RADIUS_PROPERTIES = new Set<string>([+ BORDER_RADIUS_SHORTHAND,+ ...BORDER_RADIUS_LONGHANDS,+]);++const hasMixedBorderRadiusRepresentation = (+ jsxElement: JSXOpeningElement,+): boolean => {+ const style = jsxElement.attributes.find(+ (attribute) =>+ attribute.type === 'JSXAttribute' &&+ attribute.name.type !== 'JSXNamespacedName' &&+ attribute.name.name === 'style',+ );+ if (+ !style ||+ style.type !== 'JSXAttribute' ||+ style.value?.type !== 'JSXExpressionContainer' ||+ style.value.expression.type !== 'ObjectExpression'+ ) {+ return false;+ }++ let hasShorthand = false;+ let hasLonghand = false;+ for (const property of style.value.expression.properties) {+ if (property.type !== 'ObjectProperty') {+ continue;+ }++ const name = getObjectPropertyName(property);+ hasShorthand ||= name === BORDER_RADIUS_SHORTHAND;+ hasLonghand ||= BORDER_RADIUS_LONGHANDS.some(+ (longhand) => longhand === name,+ );+ }++ return hasShorthand && hasLonghand;+};++const getUniformBorderRadius = (value: unknown): number | null => {+ const parsed = parseBorderRadiusShorthand(value);+ if (!parsed) {+ return null;+ }++ const values = Object.values(parsed);+ return values.every((radius) => radius === values[0]) ? values[0] : null;+};++const getBorderRadiusShorthandStatus = ({+ propValue,+ ast,+ videoConfigValues,+}: {+ propValue: Expression;+ ast: File;+ videoConfigValues: VideoConfigIdentifierValues;+}): CanUpdatePropStatus => {+ if (isStaticValue(propValue)) {+ const uniform = getUniformBorderRadius(extractStaticValue(propValue));+ return uniform === null ? computedStatus() : staticStatus(uniform, null);+ }++ const numericExpression = parseVideoConfigNumericExpression({+ node: propValue,+ videoConfigValues,+ });+ if (numericExpression !== null && numericExpression.value >= 0) {+ return staticStatus(numericExpression.value, numericExpression);+ }++ const computed = getComputedStatus(propValue, ast, videoConfigValues);+ if (+ computed.status === 'keyframed' &&+ computed.interpolationFunction === 'interpolate' &&+ computed.keyframes.every(+ (keyframe) =>+ typeof keyframe.value === 'number' &&+ Number.isFinite(keyframe.value) &&+ keyframe.value >= 0,+ )+ ) {+ return computed;+ }++ return computedStatus();+};++const getNestedPropStatus = ({+ jsxElement,+ ast,+ parentKey,+ childKey,+ videoConfigValues,+ allowSpecialValues,+}: {+ jsxElement: JSXOpeningElement;+ ast: File;+ parentKey: string;+ childKey: string;+ videoConfigValues: VideoConfigIdentifierValues;+ allowSpecialValues: boolean;+}): CanUpdatePropStatus => {+ const attr = jsxElement.attributes.find(+ (a) =>+ a.type !== 'JSXSpreadAttribute' &&+ a.name.type !== 'JSXNamespacedName' &&+ a.name.name === parentKey,+ ) as JSXAttribute | undefined;++ if (!attr || !attr.value) {+ // Parent attribute doesn't exist, nested prop can be added+ return staticStatus(undefined, null);+ }++ if (attr.value.type !== 'JSXExpressionContainer') {+ return computedStatus();+ }++ const {expression} = attr.value;+ if (+ expression.type === 'JSXEmptyExpression' ||+ expression.type !== 'ObjectExpression'+ ) {+ // Parent is not an object literal (e.g. style={myStyles})+ return computedStatus();+ }++ const objExpr = expression as ObjectExpression;+ const cssShorthand = getCssShorthandForLonghand({+ parentKey,+ longhand: childKey,+ });+ if (+ cssShorthand &&+ objExpr.properties.some((property) => {+ if (property.type !== 'ObjectProperty') {+ return false;+ }++ const propertyName = getObjectPropertyName(property);+ return (+ propertyName !== null &&+ cssShorthand.isUnsupportedProperty(propertyName)+ );+ })+ ) {+ return computedStatus();+ }++ let prop: ObjectProperty | undefined;+ for (let index = objExpr.properties.length - 1; index >= 0; index--) {+ const candidate = objExpr.properties[index];+ if (candidate.type === 'SpreadElement') {+ return computedStatus();+ }++ if (+ candidate.type === 'ObjectProperty' &&+ (getObjectPropertyName(candidate) === childKey ||+ getObjectPropertyName(candidate) === cssShorthand?.shorthand)+ ) {+ prop = candidate;+ break;+ }+ }++ if (+ prop &&+ cssShorthand &&+ getObjectPropertyName(prop) === cssShorthand.shorthand+ ) {+ const shorthandValue = prop.value as Expression;+ if (!isStaticValue(shorthandValue, {allowSpecialValues: false})) {+ return computedStatus();+ }++ const staticShorthandValue = extractStaticValue(shorthandValue, {+ allowSpecialValues: false,+ });+ const parsed = cssShorthand.parse(staticShorthandValue);+ return parsed ? staticStatus(parsed[childKey], null) : computedStatus();+ }++ if (!prop) {+ // Property not set in the object, can be added+ return staticStatus(undefined, null);+ }++ const propValue = prop.value as Expression;+ if (parentKey === 'style' && childKey === BORDER_RADIUS_SHORTHAND) {+ return getBorderRadiusShorthandStatus({+ propValue,+ ast,+ videoConfigValues,+ });+ }++ const staticValueOptions = {allowSpecialValues};+ if (!isStaticValue(propValue, staticValueOptions)) {+ const numericExpression = parseVideoConfigNumericExpression({+ node: propValue,+ videoConfigValues,+ });+ return numericExpression+ ? staticStatus(numericExpression.value, numericExpression)+ : getComputedStatus(propValue, ast, videoConfigValues);+ }++ const propStatus = extractStaticValue(propValue, staticValueOptions);+ if (!validateStyleValue(childKey, propStatus)) {+ return computedStatus();+ }++ return staticStatus(propStatus, null);+};++const computeEffectsForJsx = ({+ ast,+ jsxElement,+ effects,+ videoConfigValues,+}: {+ ast: File;+ jsxElement: JSXOpeningElement;+ effects: string[][];+ videoConfigValues: VideoConfigIdentifierValues;+}) => {+ return effects.map((effect, effectIndex) =>+ computeEffectPropStatus({+ ast,+ jsx: jsxElement,+ effectIndex,+ keys: effect,+ videoConfigValues,+ }),+ );+};++const computeSequenceOnlyPropsRecord = ({+ jsxElement,+ jsxElementNode,+ ast,+ keys,+ assetKeys,+ videoConfigValues,+}: {+ jsxElement: JSXOpeningElement;+ jsxElementNode: JSXElement;+ ast: File;+ keys: string[];+ assetKeys: string[];+ videoConfigValues: VideoConfigIdentifierValues;+}): Record<string, CanUpdatePropStatus> => {+ const allProps = getPropsStatus(+ jsxElement,+ ast,+ videoConfigValues,+ assetKeys,+ );+ const filteredProps: Record<string, CanUpdatePropStatus> = {};+ const mixedBorderRadius = hasMixedBorderRadiusRepresentation(jsxElement);+ for (const key of keys) {+ if (+ mixedBorderRadius &&+ key.startsWith('style.') &&+ BORDER_RADIUS_PROPERTIES.has(key.slice('style.'.length))+ ) {+ filteredProps[key] = computedStatus();+ continue;+ }++ if (key === 'children') {+ const staticChildrenAttribute = getStaticJsxChildrenAttribute(jsxElement);+ if (staticChildrenAttribute) {+ filteredProps[key] = staticStatus(staticChildrenAttribute.value, null);+ continue;+ }++ if (hasJsxChildrenAttribute(jsxElement)) {+ filteredProps[key] = computedStatus();+ continue;+ }++ const staticTextContent = getStaticJsxTextContent(jsxElementNode);+ filteredProps[key] = staticTextContent+ ? staticStatus(staticTextContent.value, null)+ : computedStatus();+ continue;+ }++ const dotIndex = key.indexOf('.');+ if (dotIndex !== -1) {+ filteredProps[key] = getNestedPropStatus({+ jsxElement,+ ast,+ parentKey: key.slice(0, dotIndex),+ childKey: key.slice(dotIndex + 1),+ videoConfigValues,+ allowSpecialValues: assetKeys.includes(key),+ });+ } else if (key in allProps) {+ filteredProps[key] = allProps[key];+ } else {+ filteredProps[key] = staticStatus(undefined, null);+ }+ }++ return filteredProps;+};++export const computeSequencePropsStatusFromContent = ({+ fileContents,+ nodePath,+ componentIdentity,+ keys,+ assetKeys = [],+ effects,+ videoConfigValues,+}: {+ fileContents: string;+ nodePath: SequenceNodePath;+ componentIdentity: JsxComponentIdentity | null;+ keys: string[];+ assetKeys?: string[];+ effects: string[][];+ videoConfigValues: VideoConfigValues | null;+}): CanUpdateSequencePropsResponseTrue => {+ const ast = parseAst(fileContents);+ const videoConfigIdentifierValues = getVideoConfigIdentifierValues({+ ast,+ videoConfigValues,+ });++ const jsxElementNode = findJsxElementNodeAtNodePath(ast, nodePath);+ const jsxElement = jsxElementNode?.openingElement ?? null;++ if (!jsxElement || !jsxElementNode) {+ throw new JsxElementNotFoundAtLocationError();+ }++ if (+ !jsxComponentIdentitiesMatch({+ expected: componentIdentity,+ actual: getJsxComponentIdentity({ast, jsxElement}),+ })+ ) {+ throw new JsxElementIdentityMismatchError();+ }++ const filteredProps = computeSequenceOnlyPropsRecord({+ jsxElement,+ jsxElementNode,+ ast,+ keys,+ assetKeys,+ videoConfigValues: videoConfigIdentifierValues,+ });+ const effectsStatuses = computeEffectsForJsx({+ ast,+ jsxElement,+ effects,+ videoConfigValues: videoConfigIdentifierValues,+ });++ return {+ canUpdate: true as const,+ props: filteredProps,+ effects: effectsStatuses,+ };+};++export const computeSequencePropsSubscriptionFromContent = ({+ fileContents,+ absolutePath,+ line,+ preferredNodePath,+ componentIdentity,+ keys,+ assetKeys = [],+ effects,+ videoConfigValues,+}: {+ fileContents: string;+ absolutePath: string;+ line: number;+ preferredNodePath: SequenceNodePath | null;+ componentIdentity: JsxComponentIdentity | null;+ keys: string[];+ assetKeys?: string[];+ effects: string[][];+ videoConfigValues: VideoConfigValues;+}): SubscribeToSequencePropsResponse => {+ if (preferredNodePath) {+ try {+ return {+ success: true,+ status: computeSequencePropsStatusFromContent({+ fileContents,+ nodePath: preferredNodePath,+ componentIdentity,+ keys,+ assetKeys,+ effects,+ videoConfigValues,+ }),+ nodePath: {+ absolutePath,+ nodePath: preferredNodePath,+ sequenceKeys: keys,+ effectKeys: effects,+ videoConfigValues,+ },+ };+ } catch (error) {+ if (+ !(+ error instanceof JsxElementIdentityMismatchError ||+ error instanceof JsxElementNotFoundAtLocationError+ )+ ) {+ return {+ success: false,+ status: {canUpdate: false, reason: 'error'},+ };+ }+ }+ }++ try {+ const ast = parseAst(fileContents);+ const resolvedNodePath = lineColumnToNodePath(ast, line);+ if (!resolvedNodePath) {+ return {+ success: false,+ status: {canUpdate: false, reason: 'not-found'},+ };+ }++ return {+ success: true,+ status: computeSequencePropsStatusFromContent({+ fileContents,+ nodePath: resolvedNodePath,+ componentIdentity,+ keys,+ assetKeys,+ effects,+ videoConfigValues,+ }),+ nodePath: {+ absolutePath,+ nodePath: resolvedNodePath,+ sequenceKeys: keys,+ effectKeys: effects,+ videoConfigValues,+ },+ };+ } catch {+ return {+ success: false,+ status: {canUpdate: false, reason: 'error'},+ };+ }+};diff --git a/packages/studio-codemods/src/sequence-props/can-update-effect-props.ts b/packages/studio-codemods/src/sequence-props/can-update-effect-props.tsnew file mode 100644index 0000000000..1f3c96b048--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/can-update-effect-props.ts@@ -0,0 +1,328 @@+import type {+ CallExpression,+ Expression,+ File,+ JSXAttribute,+ JSXOpeningElement,+ ObjectExpression,+ ObjectProperty,+} from '@babel/types';+import type {+ CanUpdateEffectPropsResponse,+ CanUpdateSequencePropStatus,+ SequenceNodePath,+ InteractivitySchema,+ VideoConfigValues,+} from 'remotion';+import {+ extractStaticValue,+ findJsxElementAtNodePath,+ getComputedStatus,+ isStaticValue,+} from '../sequence-props';+import {+ enumerateEffectArrayElements,+ type EffectArrayElement,+} from './effect-array-elements';+import {parseAst} from './parse-ast';+import {parseVideoConfigNumericExpression} from './video-config-numeric-expression';+import {+ getVideoConfigIdentifierValues,+ type VideoConfigIdentifierValues,+} from './video-config-values';++const staticStatus = (codeValue: unknown): CanUpdateSequencePropStatus => ({+ status: 'static',+ codeValue,+});++const findEffectsAttr = (jsx: JSXOpeningElement): JSXAttribute | null => {+ for (const attr of jsx.attributes) {+ if (attr.type !== 'JSXAttribute') {+ continue;+ }++ if (attr.name.type === 'JSXIdentifier' && attr.name.name === 'effects') {+ return attr;+ }+ }++ return null;+};++const getEffectsArrayElements = (+ attr: JSXAttribute | null,+): EffectArrayElement[] | null => {+ if (!attr || !attr.value || attr.value.type !== 'JSXExpressionContainer') {+ return null;+ }++ const expr = attr.value.expression as Expression;+ if (expr.type !== 'ArrayExpression') {+ return null;+ }++ return enumerateEffectArrayElements(expr);+};++const getImportedName = (specifier: {+ readonly imported?: {+ readonly type: string;+ readonly name?: string;+ readonly value?: string;+ };+}) => {+ if (!specifier.imported) {+ return null;+ }++ if (specifier.imported.type === 'Identifier') {+ return specifier.imported.name ?? null;+ }++ return specifier.imported.value ?? null;+};++const resolveEffectImport = ({+ ast,+ call,+ fallbackCallee,+}: {+ ast: File;+ call: CallExpression;+ fallbackCallee: string;+}): {callee: string; importPath: string | null} => {+ const {callee} = call;++ if (callee.type === 'Identifier') {+ const localName = callee.name;+ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration') {+ continue;+ }++ const matchingSpecifier = node.specifiers?.find((specifier) => {+ return (+ specifier.type === 'ImportSpecifier' &&+ specifier.local?.name === localName+ );+ });++ if (matchingSpecifier?.type === 'ImportSpecifier') {+ return {+ callee: getImportedName(matchingSpecifier) ?? fallbackCallee,+ importPath: String(node.source.value),+ };+ }+ }+ }++ if (+ callee.type === 'MemberExpression' &&+ callee.object.type === 'Identifier' &&+ callee.property.type === 'Identifier' &&+ !callee.computed+ ) {+ const namespaceName = callee.object.name;+ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration') {+ continue;+ }++ const matchingSpecifier = node.specifiers?.find((specifier) => {+ return (+ specifier.type === 'ImportNamespaceSpecifier' &&+ specifier.local?.name === namespaceName+ );+ });++ if (matchingSpecifier) {+ return {+ callee: callee.property.name,+ importPath: String(node.source.value),+ };+ }+ }+ }++ return {callee: fallbackCallee, importPath: null};+};++const getPropsFromObjectExpression = ({+ ast,+ objExpr,+ keys,+ videoConfigValues,+}: {+ ast: File;+ objExpr: ObjectExpression;+ keys: string[];+ videoConfigValues: VideoConfigIdentifierValues;+}): Record<string, CanUpdateSequencePropStatus> => {+ const out: Record<string, CanUpdateSequencePropStatus> = {};++ for (const key of keys) {+ const prop = objExpr.properties.find(+ (p) =>+ p.type === 'ObjectProperty' &&+ ((p.key.type === 'Identifier' && p.key.name === key) ||+ (p.key.type === 'StringLiteral' &&+ (p.key as {value: string}).value === key)),+ ) as ObjectProperty | undefined;++ if (!prop) {+ out[key] = staticStatus(undefined);+ continue;+ }++ const valueExpr = prop.value as Expression;+ if (!isStaticValue(valueExpr)) {+ const numericExpression = parseVideoConfigNumericExpression({+ node: valueExpr,+ videoConfigValues,+ });+ out[key] = numericExpression+ ? {+ status: 'static',+ codeValue: numericExpression.value,+ ...(numericExpression.type === 'literal'+ ? {}+ : {numericExpression}),+ }+ : getComputedStatus(valueExpr, ast, videoConfigValues);+ continue;+ }++ out[key] = {+ status: 'static',+ codeValue: extractStaticValue(valueExpr),+ };+ }++ return out;+};++export const computeEffectPropStatus = ({+ ast,+ jsx,+ effectIndex,+ keys,+ videoConfigValues,+}: {+ ast: File;+ jsx: JSXOpeningElement;+ effectIndex: number;+ keys: string[];+ videoConfigValues: VideoConfigIdentifierValues;+}): CanUpdateEffectPropsResponse => {+ const attr = findEffectsAttr(jsx);+ const elements = getEffectsArrayElements(attr);++ if (!elements) {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-found',+ };+ }++ if (effectIndex < 0 || effectIndex >= elements.length) {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-found',+ };+ }++ const target = elements[effectIndex];+ if (target.kind !== 'call') {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'not-call-expression',+ };+ }++ const call: CallExpression = target.node;+ const effectImport = resolveEffectImport({+ ast,+ call,+ fallbackCallee: target.callee,+ });+ if (call.arguments.length === 0) {+ const emptyProps: Record<string, CanUpdateSequencePropStatus> = {};+ for (const key of keys) {+ emptyProps[key] = staticStatus(undefined);+ }++ return {+ canUpdate: true,+ callee: effectImport.callee,+ importPath: effectImport.importPath,+ effectIndex,+ props: emptyProps,+ };+ }++ const firstArg = call.arguments[0];+ if (firstArg.type !== 'ObjectExpression') {+ return {+ canUpdate: false,+ effectIndex,+ reason: 'computed',+ };+ }++ const resolvedProps = getPropsFromObjectExpression({+ ast,+ objExpr: firstArg as ObjectExpression,+ keys,+ videoConfigValues,+ });++ return {+ canUpdate: true,+ effectIndex,+ callee: effectImport.callee,+ importPath: effectImport.importPath,+ props: resolvedProps,+ };+};++export const computeEffectPropsStatusesFromContent = ({+ fileContents,+ sequenceNodePath,+ effects,+ keysFor,+ videoConfigValues,+}: {+ fileContents: string;+ sequenceNodePath: SequenceNodePath;+ effects: InteractivitySchema[];+ keysFor: (effect: InteractivitySchema) => string[];+ videoConfigValues: VideoConfigValues | null;+}): CanUpdateEffectPropsResponse[] => {+ const ast = parseAst(fileContents);+ const videoConfigIdentifierValues = getVideoConfigIdentifierValues({+ ast,+ videoConfigValues,+ });+ const jsx = findJsxElementAtNodePath(ast, sequenceNodePath);+ if (!jsx) {+ return effects.map((_effect, effectIndex) => ({+ canUpdate: false as const,+ effectIndex,+ reason: 'not-found' as const,+ }));+ }++ return effects.map((effect, effectIndex) =>+ computeEffectPropStatus({+ ast,+ jsx,+ effectIndex,+ keys: keysFor(effect),+ videoConfigValues: videoConfigIdentifierValues,+ }),+ );+};diff --git a/packages/studio-codemods/src/sequence-props/css-shorthand-properties.ts b/packages/studio-codemods/src/sequence-props/css-shorthand-properties.tsnew file mode 100644index 0000000000..fe40107b75--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/css-shorthand-properties.ts@@ -0,0 +1,92 @@+import {parseBackgroundShorthand} from './parse-background-shorthand';+import {parseBorderRadiusShorthand} from './parse-border-radius-shorthand';+import {parseBorderShorthand} from './parse-border-shorthand';++type ParsedCssShorthand = Readonly<Record<string, string | number>>;++export type CssShorthandProperty = {+ readonly parentKey: string;+ readonly shorthand: string;+ readonly longhands: readonly string[];+ readonly parse: (value: unknown) => ParsedCssShorthand | null;+ readonly isUnsupportedProperty: (propertyName: string) => boolean;+};++const borderSidePropertyRegex =+ /^border(?:Top|Right|Bottom|Left)(?:Width|Style|Color)?$/;++const borderShorthand = {+ parentKey: 'style',+ shorthand: 'border',+ longhands: ['borderWidth', 'borderStyle', 'borderColor'],+ parse: (value) =>+ typeof value === 'string' ? parseBorderShorthand(value) : null,+ isUnsupportedProperty: (propertyName: string) =>+ borderSidePropertyRegex.test(propertyName),+} as const satisfies CssShorthandProperty;++const borderRadiusShorthand = {+ parentKey: 'style',+ shorthand: 'borderRadius',+ longhands: [+ 'borderTopLeftRadius',+ 'borderTopRightRadius',+ 'borderBottomRightRadius',+ 'borderBottomLeftRadius',+ ],+ parse: parseBorderRadiusShorthand,+ isUnsupportedProperty: (propertyName: string) =>+ /^border(?:StartStart|StartEnd|EndStart|EndEnd)Radius$/.test(propertyName),+} as const satisfies CssShorthandProperty;++const backgroundShorthand = {+ parentKey: 'style',+ shorthand: 'background',+ longhands: [+ 'backgroundColor',+ 'backgroundImage',+ 'backgroundPosition',+ 'backgroundSize',+ 'backgroundRepeat',+ 'backgroundOrigin',+ 'backgroundClip',+ 'backgroundAttachment',+ ],+ parse: (value) =>+ typeof value === 'string' ? parseBackgroundShorthand(value) : null,+ isUnsupportedProperty: () => false,+} as const satisfies CssShorthandProperty;++export const cssShorthandProperties = [+ backgroundShorthand,+ borderShorthand,+ borderRadiusShorthand,+] as const satisfies readonly CssShorthandProperty[];++export const getCssShorthandForLonghand = ({+ parentKey,+ longhand,+}: {+ parentKey: string;+ longhand: string;+}): CssShorthandProperty | null => {+ return (+ cssShorthandProperties.find(+ (property) =>+ property.parentKey === parentKey &&+ (property.longhands as readonly string[]).includes(longhand),+ ) ?? null+ );+};++export const getCssShorthandsForUpdates = (+ updateKeys: readonly string[],+): CssShorthandProperty[] => {+ return cssShorthandProperties.filter((property) =>+ updateKeys.some((key) =>+ property.longhands.some(+ (longhand) => key === `${property.parentKey}.${longhand}`,+ ),+ ),+ );+};diff --git a/packages/studio-codemods/src/sequence-props/effect-array-elements.ts b/packages/studio-codemods/src/sequence-props/effect-array-elements.tsnew file mode 100644index 0000000000..12a5590f4f--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/effect-array-elements.ts@@ -0,0 +1,55 @@+import type {ArrayExpression, CallExpression} from '@babel/types';++const getCalleeName = (call: CallExpression): string | null => {+ const {callee} = call;+ if (callee.type === 'Identifier') {+ return callee.name;+ }++ if (+ callee.type === 'MemberExpression' &&+ !callee.computed &&+ callee.property.type === 'Identifier'+ ) {+ return callee.property.name;+ }++ return null;+};++export type EffectArrayElement =+ | {kind: 'call'; callee: string; node: CallExpression}+ | {kind: 'unsupported'; reason: 'not-call-expression' | 'spread'};++export const enumerateEffectArrayElements = (+ arr: ArrayExpression,+): EffectArrayElement[] => {+ const out: EffectArrayElement[] = [];+ for (const el of arr.elements) {+ if (el === null) {+ out.push({kind: 'unsupported', reason: 'not-call-expression'});+ continue;+ }++ if (el.type === 'SpreadElement') {+ out.push({kind: 'unsupported', reason: 'spread'});+ continue;+ }++ if (el.type !== 'CallExpression') {+ out.push({kind: 'unsupported', reason: 'not-call-expression'});+ continue;+ }++ const call = el as CallExpression;+ const callee = getCalleeName(call);+ if (callee === null) {+ out.push({kind: 'unsupported', reason: 'not-call-expression'});+ continue;+ }++ out.push({kind: 'call', callee, node: call});+ }++ return out;+};diff --git a/packages/studio-codemods/src/sequence-props/get-ast-node-path.ts b/packages/studio-codemods/src/sequence-props/get-ast-node-path.tsnew file mode 100644index 0000000000..cc1ca00ee0--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/get-ast-node-path.ts@@ -0,0 +1,25 @@+import type {File} from '@babel/types';+import type {NodePath} from 'ast-types';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import {fromImportAgnosticNodePath} from './import-agnostic-node-path';++export const getAstNodePath = (+ ast: File,+ nodePath: SequenceNodePath,+): NodePath | null => {+ const resolvedNodePath = fromImportAgnosticNodePath({ast, nodePath});+ if (!resolvedNodePath) {+ return null;+ }++ let current = new recast.types.NodePath(ast);+ for (const segment of resolvedNodePath) {+ current = current.get(segment);+ if (current.value === null || current.value === undefined) {+ return null;+ }+ }++ return current;+};diff --git a/packages/studio-codemods/src/sequence-props/import-agnostic-node-path.ts b/packages/studio-codemods/src/sequence-props/import-agnostic-node-path.tsnew file mode 100644index 0000000000..5200e7dab4--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/import-agnostic-node-path.ts@@ -0,0 +1,289 @@+import type {File, Node} from '@babel/types';+import type {SequenceNodePath} from 'remotion';++type ArrayContext = {+ parent: Node;+ property: string;+};++type IgnoredNodePredicate = (node: Node, context: ArrayContext) => boolean;++const getActualIndex = ({+ items,+ agnosticIndex,+ shouldIgnore,+ context,+}: {+ items: Node[];+ agnosticIndex: number;+ shouldIgnore: IgnoredNodePredicate;+ context: ArrayContext;+}): number | null => {+ let seenIncludedNodes = 0;+ for (let i = 0; i < items.length; i++) {+ if (shouldIgnore(items[i], context)) {+ continue;+ }++ if (seenIncludedNodes === agnosticIndex) {+ return i;+ }++ seenIncludedNodes++;+ }++ return null;+};++const getAgnosticIndex = ({+ items,+ actualIndex,+ shouldIgnore,+ context,+}: {+ items: Node[];+ actualIndex: number;+ shouldIgnore: IgnoredNodePredicate;+ context: ArrayContext;+}): number | null => {+ if (actualIndex < 0 || actualIndex >= items.length) {+ return null;+ }++ let seenIncludedNodes = 0;+ for (let i = 0; i <= actualIndex; i++) {+ if (shouldIgnore(items[i], context)) {+ continue;+ }++ if (i === actualIndex) {+ return seenIncludedNodes;+ }++ seenIncludedNodes++;+ }++ return null;+};++const getUseCurrentFrameLocalNames = (ast: File): Set<string> => {+ const names = new Set(['useCurrentFrame']);+ for (const statement of ast.program.body) {+ if (+ statement.type !== 'ImportDeclaration' ||+ statement.source.value !== 'remotion'+ ) {+ continue;+ }++ for (const specifier of statement.specifiers) {+ if (+ specifier.type === 'ImportSpecifier' &&+ specifier.imported.type === 'Identifier' &&+ specifier.imported.name === 'useCurrentFrame'+ ) {+ names.add(specifier.local?.name ?? 'useCurrentFrame');+ }+ }+ }++ return names;+};++const getGoogleFontLoadFontLocalNames = (ast: File): Set<string> => {+ const names = new Set<string>();+ for (const statement of ast.program.body) {+ if (+ statement.type !== 'ImportDeclaration' ||+ typeof statement.source.value !== 'string' ||+ !statement.source.value.startsWith('@remotion/google-fonts/')+ ) {+ continue;+ }++ for (const specifier of statement.specifiers) {+ if (+ specifier.type === 'ImportSpecifier' &&+ specifier.imported.type === 'Identifier' &&+ specifier.imported.name === 'loadFont'+ ) {+ names.add(specifier.local?.name ?? 'loadFont');+ }+ }+ }++ return names;+};++const isUseCurrentFrameCall = (+ node: Node | null | undefined,+ useCurrentFrameLocalNames: ReadonlySet<string>,+): boolean => {+ return (+ node?.type === 'CallExpression' &&+ node.callee.type === 'Identifier' &&+ useCurrentFrameLocalNames.has(node.callee.name)+ );+};++const isUseCurrentFrameStatement = (+ node: Node,+ useCurrentFrameLocalNames: ReadonlySet<string>,+): boolean => {+ if (node.type === 'ExpressionStatement') {+ return isUseCurrentFrameCall(node.expression, useCurrentFrameLocalNames);+ }++ if (node.type !== 'VariableDeclaration' || node.declarations.length !== 1) {+ return false;+ }++ return isUseCurrentFrameCall(+ node.declarations[0].init,+ useCurrentFrameLocalNames,+ );+};++const isGoogleFontLoadFontStatement = (+ node: Node,+ googleFontLoadFontLocalNames: ReadonlySet<string>,+): boolean => {+ return (+ node.type === 'ExpressionStatement' &&+ node.expression.type === 'CallExpression' &&+ node.expression.callee.type === 'Identifier' &&+ googleFontLoadFontLocalNames.has(node.expression.callee.name)+ );+};++const getIgnoredNodePredicate = (ast: File): IgnoredNodePredicate => {+ const useCurrentFrameLocalNames = getUseCurrentFrameLocalNames(ast);+ const googleFontLoadFontLocalNames = getGoogleFontLoadFontLocalNames(ast);+ return (node, {parent, property}) => {+ if (parent.type === 'Program' && property === 'body') {+ return (+ node.type === 'ImportDeclaration' ||+ isGoogleFontLoadFontStatement(node, googleFontLoadFontLocalNames)+ );+ }++ if (parent.type === 'BlockStatement' && property === 'body') {+ return isUseCurrentFrameStatement(node, useCurrentFrameLocalNames);+ }++ return false;+ };+};++const getChild = (value: unknown, segment: string | number): unknown => {+ if (value === null || value === undefined) {+ return null;+ }++ if (Array.isArray(value)) {+ return value[segment as number] ?? null;+ }++ if (typeof value !== 'object') {+ return null;+ }++ return (value as Record<string, unknown>)[segment] ?? null;+};++const transformNodePathIndices = ({+ ast,+ nodePath,+ direction,+}: {+ ast: File;+ nodePath: SequenceNodePath;+ direction: 'to-agnostic' | 'from-agnostic';+}): SequenceNodePath | null => {+ const shouldIgnore = getIgnoredNodePredicate(ast);+ const transformed: SequenceNodePath = [];+ let current: unknown = ast;+ let arrayContext: ArrayContext | null = null;++ for (const segment of nodePath) {+ if (typeof segment === 'string') {+ const parent = current;+ current = getChild(current, segment);+ if (+ Array.isArray(current) &&+ parent &&+ typeof parent === 'object' &&+ 'type' in parent+ ) {+ arrayContext = {parent: parent as Node, property: segment};+ } else {+ arrayContext = null;+ }++ transformed.push(segment);+ continue;+ }++ if (!Array.isArray(current) || !arrayContext) {+ current = getChild(current, segment);+ transformed.push(segment);+ continue;+ }++ const mappedIndex =+ direction === 'to-agnostic'+ ? getAgnosticIndex({+ items: current as Node[],+ actualIndex: segment,+ shouldIgnore,+ context: arrayContext,+ })+ : getActualIndex({+ items: current as Node[],+ agnosticIndex: segment,+ shouldIgnore,+ context: arrayContext,+ });+ if (mappedIndex === null) {+ if (direction === 'from-agnostic') {+ return null;+ }++ current = getChild(current, segment);+ transformed.push(segment);+ continue;+ }++ current = getChild(+ current,+ direction === 'to-agnostic' ? segment : mappedIndex,+ );+ arrayContext = null;+ transformed.push(mappedIndex);+ }++ return transformed;+};++export const toImportAgnosticNodePath = ({+ ast,+ nodePath,+}: {+ ast: File;+ nodePath: SequenceNodePath;+}): SequenceNodePath => {+ return (+ transformNodePathIndices({ast, nodePath, direction: 'to-agnostic'}) ??+ nodePath+ );+};++export const fromImportAgnosticNodePath = ({+ ast,+ nodePath,+}: {+ ast: File;+ nodePath: SequenceNodePath;+}): SequenceNodePath | null => {+ return transformNodePathIndices({ast, nodePath, direction: 'from-agnostic'});+};diff --git a/packages/studio-codemods/src/sequence-props/imports.ts b/packages/studio-codemods/src/sequence-props/imports.tsnew file mode 100644index 0000000000..c6a359138d--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/imports.ts@@ -0,0 +1,9 @@+import type {ImportSpecifier} from '@babel/types';++export const getImportedName = (specifier: ImportSpecifier) => {+ if (specifier.imported.type === 'Identifier') {+ return specifier.imported.name;+ }++ return specifier.imported.value;+};diff --git a/packages/studio-codemods/src/sequence-props/jsx-component-identity.ts b/packages/studio-codemods/src/sequence-props/jsx-component-identity.tsnew file mode 100644index 0000000000..c6407f27bb--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/jsx-component-identity.ts@@ -0,0 +1,189 @@+import type {+ File,+ JSXIdentifier,+ JSXMemberExpression,+ JSXOpeningElement,+} from '@babel/types';+import type {JsxComponentIdentity} from 'remotion';+import {getImportedName} from './imports';++export class JsxElementIdentityMismatchError extends Error {+ constructor() {+ super('JSX element identity changed');+ }+}++const jsxMemberToString = (+ expr: JSXMemberExpression | JSXIdentifier,+): string => {+ if (expr.type === 'JSXIdentifier') {+ return expr.name;+ }++ return `${jsxMemberToString(expr.object)}.${expr.property.name}`;+};++const getJsxRootIdentifier = (+ expr: JSXMemberExpression | JSXIdentifier,+): JSXIdentifier => {+ if (expr.type === 'JSXIdentifier') {+ return expr;+ }++ return getJsxRootIdentifier(expr.object);+};++const getTagName = (node: JSXOpeningElement): string | null => {+ if (node.name.type === 'JSXIdentifier') {+ return node.name.name;+ }++ if (node.name.type === 'JSXMemberExpression') {+ return jsxMemberToString(node.name);+ }++ return null;+};++const getMemberPath = (tagName: string): string => {+ const dotIndex = tagName.indexOf('.');+ return dotIndex === -1 ? '' : tagName.slice(dotIndex + 1);+};++const getMemberPathAfterImportName = ({+ tagName,+ importName,+}: {+ tagName: string;+ importName: string;+}): string => {+ const parts = tagName.split('.');+ const importNameIndex = parts.indexOf(importName);+ if (importNameIndex === -1) {+ return getMemberPath(tagName);+ }++ return parts.slice(importNameIndex + 1).join('.');+};++const sourcePathToIdentityPrefix = (sourcePath: string): string | null => {+ if (sourcePath === 'remotion') {+ return 'dev.remotion.remotion';+ }++ if (sourcePath.startsWith('@remotion/')) {+ const packageName = sourcePath+ .slice('@remotion/'.length)+ .replace(/-([a-z])/g, (_, char: string) => char.toUpperCase());+ return `dev.remotion.${packageName}`;+ }++ return null;+};++const makeImportedIdentity = ({+ sourcePath,+ importName,+ memberPath,+}: {+ sourcePath: string;+ importName: string;+ memberPath: string;+}): JsxComponentIdentity | null => {+ const prefix = sourcePathToIdentityPrefix(sourcePath);+ if (prefix === null) {+ return null;+ }++ return [prefix, importName, memberPath].filter(Boolean).join('.');+};++export const getJsxComponentIdentity = ({+ ast,+ jsxElement,+}: {+ ast: File;+ jsxElement: JSXOpeningElement;+}): JsxComponentIdentity | null => {+ const tagName = getTagName(jsxElement);+ if (tagName === null) {+ return null;+ }++ const rootIdentifier =+ jsxElement.name.type === 'JSXIdentifier'+ ? jsxElement.name+ : jsxElement.name.type === 'JSXMemberExpression'+ ? getJsxRootIdentifier(jsxElement.name)+ : null;+ if (rootIdentifier === null) {+ return tagName;+ }++ for (const node of ast.program.body) {+ if (node.type !== 'ImportDeclaration') {+ continue;+ }++ const sourcePath = String(node.source.value);+ for (const specifier of node.specifiers) {+ if (+ specifier.type === 'ImportSpecifier' &&+ specifier.local?.name === rootIdentifier.name+ ) {+ const importName = getImportedName(specifier);+ return makeImportedIdentity({+ sourcePath,+ importName,+ memberPath: getMemberPath(tagName),+ });+ }++ if (+ specifier.type === 'ImportNamespaceSpecifier' &&+ specifier.local.name === rootIdentifier.name+ ) {+ const [importName, ...members] = getMemberPath(tagName).split('.');+ if (!importName) {+ return null;+ }++ return makeImportedIdentity({+ sourcePath,+ importName,+ memberPath: members.join('.'),+ });+ }++ if (+ specifier.type === 'ImportDefaultSpecifier' &&+ specifier.local.name === rootIdentifier.name+ ) {+ return makeImportedIdentity({+ sourcePath,+ importName: 'default',+ memberPath: getMemberPathAfterImportName({+ tagName,+ importName: rootIdentifier.name,+ }),+ });+ }+ }+ }++ return tagName;+};++export const jsxComponentIdentitiesMatch = ({+ expected,+ actual,+}: {+ expected: JsxComponentIdentity | null;+ actual: JsxComponentIdentity | null;+}): boolean => {+ if (expected === null) {+ return true;+ }++ return expected === actual;+};diff --git a/packages/studio-codemods/src/sequence-props/jsx-element-not-found-at-location-error.ts b/packages/studio-codemods/src/sequence-props/jsx-element-not-found-at-location-error.tsnew file mode 100644index 0000000000..09b9e2e895--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/jsx-element-not-found-at-location-error.ts@@ -0,0 +1,8 @@+export class JsxElementNotFoundAtLocationError extends Error {+ constructor() {+ super(+ 'Cannot compute sequence props status: Could not find a JSX element at the specified location',+ );+ this.name = 'JsxElementNotFoundAtLocationError';+ }+}diff --git a/packages/studio-codemods/src/sequence-props/parse-ast.ts b/packages/studio-codemods/src/sequence-props/parse-ast.tsnew file mode 100644index 0000000000..eeb71e4efa--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/parse-ast.ts@@ -0,0 +1,19 @@+import type {File} from '@babel/types';+import * as recast from 'recast';+import * as tsParser from 'recast/parsers/babel-ts';++const normalizeImportSpacing = (input: string) =>+ input.replace(/(import[^\n]*\n)\n+(?=import\b)/g, '$1');++export const parseAst = (input: string) => {+ return recast.parse(input, {+ parser: tsParser,+ }) as File;+};++export const serializeAst = (ast: File) => {+ const raw = recast.print(ast, {+ parser: tsParser,+ }).code;+ return normalizeImportSpacing(raw.replace(/\r\n/g, '\n'));+};diff --git a/packages/studio-codemods/src/sequence-props/parse-background-shorthand.ts b/packages/studio-codemods/src/sequence-props/parse-background-shorthand.tsnew file mode 100644index 0000000000..d44f4ebea9--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/parse-background-shorthand.ts@@ -0,0 +1,57 @@+import {NoReactInternals} from 'remotion/no-react';++export type ParsedBackgroundShorthand = {+ backgroundAttachment: string;+ backgroundClip: string;+ backgroundColor: string;+ backgroundImage: string;+ backgroundOrigin: string;+ backgroundPosition: string;+ backgroundRepeat: string;+ backgroundSize: string;+};++const CSS_WIDE_KEYWORDS = new Set([+ 'inherit',+ 'initial',+ 'revert',+ 'revert-layer',+ 'unset',+]);++const makeColorOnlyBackground = (+ backgroundColor: string,+): ParsedBackgroundShorthand => {+ return {+ backgroundColor,+ backgroundImage: 'none',+ backgroundPosition: '0% 0%',+ backgroundSize: 'auto auto',+ backgroundRepeat: 'repeat',+ backgroundOrigin: 'padding-box',+ backgroundClip: 'border-box',+ backgroundAttachment: 'scroll',+ };+};++export const parseBackgroundShorthand = (+ value: string,+): ParsedBackgroundShorthand | null => {+ const trimmed = value.trim();+ const lowerCaseValue = trimmed.toLowerCase();++ if (trimmed === '' || CSS_WIDE_KEYWORDS.has(lowerCaseValue)) {+ return null;+ }++ if (lowerCaseValue === 'none') {+ return makeColorOnlyBackground('transparent');+ }++ try {+ NoReactInternals.processColor(trimmed);+ return makeColorOnlyBackground(trimmed);+ } catch {+ return null;+ }+};diff --git a/packages/studio-codemods/src/sequence-props/parse-border-radius-shorthand.ts b/packages/studio-codemods/src/sequence-props/parse-border-radius-shorthand.tsnew file mode 100644index 0000000000..c982ae36ff--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/parse-border-radius-shorthand.ts@@ -0,0 +1,69 @@+export type ParsedBorderRadiusShorthand = {+ borderTopLeftRadius: number;+ borderTopRightRadius: number;+ borderBottomRightRadius: number;+ borderBottomLeftRadius: number;+};++const parsePixelRadius = (value: string): number | null => {+ if (value === '0') {+ return 0;+ }++ const match = value.match(/^(\d+(?:\.\d+)?|\.\d+)px$/i);+ return match ? Number(match[1]) : null;+};++const expandBorderRadius = (+ values: readonly number[],+): readonly [number, number, number, number] => {+ if (values.length === 1) {+ return [values[0], values[0], values[0], values[0]];+ }++ if (values.length === 2) {+ return [values[0], values[1], values[0], values[1]];+ }++ if (values.length === 3) {+ return [values[0], values[1], values[2], values[1]];+ }++ return [values[0], values[1], values[2], values[3]];+};++export const parseBorderRadiusShorthand = (+ value: unknown,+): ParsedBorderRadiusShorthand | null => {+ let values: readonly number[];+ if (typeof value === 'number') {+ if (!Number.isFinite(value) || value < 0) {+ return null;+ }++ values = [value];+ } else if (typeof value === 'string') {+ const tokens = value.trim().split(/\s+/);+ if (tokens.length < 1 || tokens.length > 4) {+ return null;+ }++ const parsed = tokens.map(parsePixelRadius);+ if (parsed.some((radius) => radius === null)) {+ return null;+ }++ values = parsed as number[];+ } else {+ return null;+ }++ const [topLeft, topRight, bottomRight, bottomLeft] =+ expandBorderRadius(values);+ return {+ borderTopLeftRadius: topLeft,+ borderTopRightRadius: topRight,+ borderBottomRightRadius: bottomRight,+ borderBottomLeftRadius: bottomLeft,+ };+};diff --git a/packages/studio-codemods/src/sequence-props/parse-border-shorthand.ts b/packages/studio-codemods/src/sequence-props/parse-border-shorthand.tsnew file mode 100644index 0000000000..04df7a961c--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/parse-border-shorthand.ts@@ -0,0 +1,169 @@+export type ParsedBorderShorthand = {+ borderWidth: number;+ borderStyle: string;+ borderColor: string;+};++const BORDER_STYLES = new Set([+ 'none',+ 'hidden',+ 'dotted',+ 'dashed',+ 'solid',+ 'double',+ 'groove',+ 'ridge',+ 'inset',+ 'outset',+]);++const CSS_WIDE_KEYWORDS = new Set([+ 'inherit',+ 'initial',+ 'revert',+ 'revert-layer',+ 'unset',+]);++const BORDER_WIDTH_KEYWORDS: Record<string, number> = {+ // Chromium resolves these CSS keywords to these pixel values.+ thin: 1,+ medium: 3,+ thick: 5,+};++const splitCssWhitespace = (value: string): string[] | null => {+ const parts: string[] = [];+ let current = '';+ let parenthesisDepth = 0;+ let quote: '"' | "'" | null = null;++ for (const char of value.trim()) {+ if (quote !== null) {+ current += char;+ if (char === quote) {+ quote = null;+ }++ continue;+ }++ if (char === '"' || char === "'") {+ quote = char;+ current += char;+ continue;+ }++ if (char === '(') {+ parenthesisDepth++;+ current += char;+ continue;+ }++ if (char === ')') {+ parenthesisDepth--;+ if (parenthesisDepth < 0) {+ return null;+ }++ current += char;+ continue;+ }++ if (/\s/.test(char) && parenthesisDepth === 0) {+ if (current !== '') {+ parts.push(current);+ current = '';+ }++ continue;+ }++ current += char;+ }++ if (quote !== null || parenthesisDepth !== 0) {+ return null;+ }++ if (current !== '') {+ parts.push(current);+ }++ return parts;+};++const parsePixelWidth = (token: string): number | null => {+ if (token === '0') {+ return 0;+ }++ const match = token.match(/^(\d+(?:\.\d+)?|\.\d+)px$/i);+ if (!match) {+ return null;+ }++ return Number(match[1]);+};++export const parseBorderShorthand = (+ value: string,+): ParsedBorderShorthand | null => {+ const tokens = splitCssWhitespace(value);+ if (!tokens || tokens.length === 0) {+ return null;+ }++ let borderWidth: number | null = null;+ let borderStyle: string | null = null;+ let borderColor: string | null = null;++ for (const token of tokens) {+ const lowerCaseToken = token.toLowerCase();+ if (CSS_WIDE_KEYWORDS.has(lowerCaseToken)) {+ return null;+ }++ if (BORDER_STYLES.has(lowerCaseToken)) {+ if (borderStyle !== null) {+ return null;+ }++ borderStyle = lowerCaseToken;+ continue;+ }++ const width = parsePixelWidth(token);+ if (width !== null) {+ if (borderWidth !== null) {+ return null;+ }++ borderWidth = width;+ continue;+ }++ const keywordWidth = BORDER_WIDTH_KEYWORDS[lowerCaseToken];+ if (keywordWidth !== undefined) {+ if (borderWidth !== null) {+ return null;+ }++ borderWidth = keywordWidth;+ continue;+ }++ if (borderColor === null) {+ borderColor = token;+ continue;+ }++ return null;+ }++ return {+ borderWidth: borderWidth ?? BORDER_WIDTH_KEYWORDS.medium,+ borderStyle: borderStyle ?? 'none',+ borderColor: borderColor ?? 'currentColor',+ };+};diff --git a/packages/studio-codemods/src/sequence-props/parse-keyframe-easing-expression.ts b/packages/studio-codemods/src/sequence-props/parse-keyframe-easing-expression.tsnew file mode 100644index 0000000000..ccf9e06134--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/parse-keyframe-easing-expression.ts@@ -0,0 +1,198 @@+import type {CallExpression, Expression} from '@babel/types';+import {+ CUBIC_KEYFRAME_EASING,+ EASE_KEYFRAME_EASING,+ getBackKeyframeEasing,+ getOutKeyframeEasing,+ getPolyKeyframeEasing,+ LINEAR_KEYFRAME_EASING,+ QUAD_KEYFRAME_EASING,+} from '@remotion/studio-shared/keyframe-easing-presets';+import {parseSpringEasingConfig} from '@remotion/studio-shared/parse-spring-easing-config';+import type {CanUpdateSequencePropStatusEasing} from 'remotion';++const getNumericValue = (node: Expression): number | null => {+ if (node.type === 'NumericLiteral') {+ return node.value;+ }++ if (+ node.type === 'UnaryExpression' &&+ (node.operator === '-' || node.operator === '+') &&+ node.argument.type === 'NumericLiteral'+ ) {+ return node.operator === '-' ? -node.argument.value : node.argument.value;+ }++ if (node.type === 'TSAsExpression') {+ return getNumericValue(node.expression as Expression);+ }++ return null;+};++const getExpressionArgument = (+ arg: CallExpression['arguments'][number] | undefined,+): Expression | null => {+ if (+ arg === undefined ||+ arg.type === 'ArgumentPlaceholder' ||+ arg.type === 'JSXNamespacedName' ||+ arg.type === 'SpreadElement'+ ) {+ return null;+ }++ return arg as Expression;+};++const getMemberExpressionKeyframeEasing = (+ name: string,+): CanUpdateSequencePropStatusEasing | null => {+ if (name === 'linear') {+ return LINEAR_KEYFRAME_EASING;+ }++ if (name === 'ease') {+ return EASE_KEYFRAME_EASING;+ }++ if (name === 'quad') {+ return QUAD_KEYFRAME_EASING;+ }++ if (name === 'cubic') {+ return CUBIC_KEYFRAME_EASING;+ }++ return null;+};++export const parseKeyframeEasingExpression = (+ node: Expression,+): CanUpdateSequencePropStatusEasing | null => {+ if (node.type === 'TSAsExpression') {+ return parseKeyframeEasingExpression(node.expression as Expression);+ }++ if (+ node.type === 'MemberExpression' &&+ node.object.type === 'Identifier' &&+ node.object.name === 'Easing' &&+ node.property.type === 'Identifier' &&+ node.computed === false+ ) {+ return getMemberExpressionKeyframeEasing(node.property.name);+ }++ if (+ node.type !== 'CallExpression' ||+ node.callee.type !== 'MemberExpression' ||+ node.callee.object.type !== 'Identifier' ||+ node.callee.object.name !== 'Easing' ||+ node.callee.property.type !== 'Identifier' ||+ node.callee.computed+ ) {+ return null;+ }++ const propertyName = node.callee.property.name;++ if (propertyName === 'spring') {+ if (node.arguments.length > 1) {+ return null;+ }++ if (node.arguments.length === 0) {+ return parseSpringEasingConfig(undefined);+ }++ const springConfig = getExpressionArgument(node.arguments[0]);+ return springConfig ? parseSpringEasingConfig(springConfig) : null;+ }++ if (propertyName === 'bezier') {+ if (node.arguments.length !== 4) {+ return null;+ }++ const values = node.arguments.map((arg) => {+ const expression = getExpressionArgument(arg);+ return expression ? getNumericValue(expression) : null;+ });++ if (values.some((value) => value === null)) {+ return null;+ }++ const [x1, y1, x2, y2] = values as [number, number, number, number];+ return {type: 'bezier', x1, y1, x2, y2};+ }++ if (propertyName === 'back') {+ if (node.arguments.length > 1) {+ return null;+ }++ if (node.arguments.length === 0) {+ return getBackKeyframeEasing();+ }++ const expression = getExpressionArgument(node.arguments[0]);+ if (!expression) {+ return null;+ }++ const s = getNumericValue(expression);+ if (s === null) {+ return null;+ }++ return getBackKeyframeEasing(s);+ }++ if (propertyName === 'poly') {+ if (node.arguments.length !== 1) {+ return null;+ }++ const expression = getExpressionArgument(node.arguments[0]);+ const n = expression ? getNumericValue(expression) : null;+ return n === null ? null : getPolyKeyframeEasing(n);+ }++ if (propertyName === 'in') {+ if (node.arguments.length !== 1) {+ return null;+ }++ const expression = getExpressionArgument(node.arguments[0]);+ return expression ? parseKeyframeEasingExpression(expression) : null;+ }++ if (propertyName === 'out') {+ if (node.arguments.length !== 1) {+ return null;+ }++ const expression = getExpressionArgument(node.arguments[0]);+ const easing = expression+ ? parseKeyframeEasingExpression(expression)+ : null;+ return easing ? getOutKeyframeEasing(easing) : null;+ }++ if (propertyName === 'inOut') {+ if (node.arguments.length !== 1) {+ return null;+ }++ const expression = getExpressionArgument(node.arguments[0]);+ const easing = expression+ ? parseKeyframeEasingExpression(expression)+ : null;+ return easing?.type === 'linear' ? easing : null;+ }++ return null;+};diff --git a/packages/studio-codemods/src/sequence-props/video-config-numeric-expression.ts b/packages/studio-codemods/src/sequence-props/video-config-numeric-expression.tsnew file mode 100644index 0000000000..78d7aa87d3--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/video-config-numeric-expression.ts@@ -0,0 +1,206 @@+import type {Expression} from '@babel/types';+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';+import * as recast from 'recast';+import type {VideoConfigNumericExpression} from 'remotion';+import type {VideoConfigIdentifierValues} from './video-config-values';++const b = recast.types.builders;++const getNumericLiteral = (node: Expression): number | null => {+ if (node.type === 'NumericLiteral') {+ return Number.isFinite(node.value) ? node.value : null;+ }++ if (+ node.type === 'UnaryExpression' &&+ (node.operator === '-' || node.operator === '+') &&+ node.argument.type === 'NumericLiteral'+ ) {+ const value =+ node.operator === '-' ? -node.argument.value : node.argument.value;+ return Number.isFinite(value) ? value : null;+ }++ if (node.type === 'TSAsExpression') {+ return getNumericLiteral(node.expression as Expression);+ }++ return null;+};++const getVideoConfigValue = ({+ node,+ videoConfigValues,+}: {+ node: Expression;+ videoConfigValues: VideoConfigIdentifierValues;+}): {identifier: string; value: number} | null => {+ if (node.type === 'TSAsExpression') {+ return getVideoConfigValue({+ node: node.expression as Expression,+ videoConfigValues,+ });+ }++ if (node.type !== 'Identifier') {+ return null;+ }++ const value = videoConfigValues[node.name];+ if (value === undefined || !Number.isFinite(value)) {+ return null;+ }++ return {identifier: node.name, value};+};++export const parseVideoConfigNumericExpression = ({+ node,+ videoConfigValues,+}: {+ node: Expression;+ videoConfigValues: VideoConfigIdentifierValues;+}): VideoConfigNumericExpression | null => {+ if (node.type === 'TSAsExpression') {+ return parseVideoConfigNumericExpression({+ node: node.expression as Expression,+ videoConfigValues,+ });+ }++ const literal = getNumericLiteral(node);+ if (literal !== null) {+ return {type: 'literal', value: literal};+ }++ const videoConfigValue = getVideoConfigValue({node, videoConfigValues});+ if (videoConfigValue !== null) {+ return {type: 'video-config-value', ...videoConfigValue};+ }++ if (node.type !== 'BinaryExpression') {+ return null;+ }++ const left = node.left as Expression;+ const right = node.right as Expression;+ if (node.operator === '-') {+ const minuend = getVideoConfigValue({+ node: left,+ videoConfigValues,+ });+ const subtrahend = getNumericLiteral(right);+ if (minuend === null || subtrahend === null) {+ return null;+ }++ const resolvedValue = minuend.value - subtrahend;+ if (!Number.isFinite(resolvedValue)) {+ return null;+ }++ return {+ type: 'video-config-subtraction',+ identifier: minuend.identifier,+ minuend: minuend.value,+ subtrahend,+ value: resolvedValue,+ };+ }++ if (node.operator !== '*') {+ return null;+ }++ const leftNumber = getNumericLiteral(left);+ const rightNumber = getNumericLiteral(right);+ const leftVideoConfig = getVideoConfigValue({+ node: left,+ videoConfigValues,+ });+ const rightVideoConfig = getVideoConfigValue({+ node: right,+ videoConfigValues,+ });++ const factorPosition =+ leftNumber !== null && rightVideoConfig !== null+ ? 'left'+ : rightNumber !== null && leftVideoConfig !== null+ ? 'right'+ : null;+ if (factorPosition === null) {+ return null;+ }++ const multiplier = factorPosition === 'left' ? leftNumber! : rightNumber!;+ const configValue =+ factorPosition === 'left' ? rightVideoConfig! : leftVideoConfig!;+ const value = multiplier * configValue.value;+ if (!Number.isFinite(value)) {+ return null;+ }++ return {+ type: 'video-config-multiplication',+ identifier: configValue.identifier,+ multiplier,+ multiplicand: configValue.value,+ factorPosition,+ value,+ };+};++const numericExpression = (value: number): ExpressionKind => {+ if (value < 0) {+ return b.unaryExpression('-', b.numericLiteral(-value), true);+ }++ return b.numericLiteral(value);+};++export const updateVideoConfigNumericExpression = ({+ expression,+ value,+}: {+ expression: VideoConfigNumericExpression;+ value: number;+}): ExpressionKind => {+ if (!Number.isFinite(value)) {+ return numericExpression(value);+ }++ if (expression.type === 'video-config-value') {+ return value === expression.value+ ? b.identifier(expression.identifier)+ : numericExpression(value);+ }++ if (expression.type === 'video-config-subtraction') {+ const subtrahend = expression.minuend - value;+ if (!Number.isFinite(subtrahend)) {+ return numericExpression(value);+ }++ return b.binaryExpression(+ '-',+ b.identifier(expression.identifier),+ numericExpression(subtrahend),+ );+ }++ if (expression.type !== 'video-config-multiplication' || value === 0) {+ return numericExpression(value);+ }++ const multiplier = value / expression.multiplicand;+ if (!Number.isFinite(multiplier) || multiplier === 0) {+ return numericExpression(value);+ }++ const factor = numericExpression(multiplier);+ const identifier = b.identifier(expression.identifier);+ return expression.factorPosition === 'left'+ ? b.binaryExpression('*', factor, identifier)+ : b.binaryExpression('*', identifier, factor);+};diff --git a/packages/studio-codemods/src/sequence-props/video-config-values.ts b/packages/studio-codemods/src/sequence-props/video-config-values.tsnew file mode 100644index 0000000000..b956051351--- /dev/null+++ b/packages/studio-codemods/src/sequence-props/video-config-values.ts@@ -0,0 +1,69 @@+import type {File} from '@babel/types';+import * as recast from 'recast';+import type {VideoConfigValues} from 'remotion';++export type VideoConfigIdentifierValues = Record<string, number>;++export const getVideoConfigIdentifierValues = ({+ ast,+ videoConfigValues,+}: {+ ast: File;+ videoConfigValues: VideoConfigValues | null;+}): VideoConfigIdentifierValues => {+ if (videoConfigValues === null) {+ return {};+ }++ const candidates = new Map<string, number>();+ const otherDeclarations = new Set<string>();++ recast.types.visit(ast, {+ visitVariableDeclarator(path) {+ const {id, init} = path.node;+ const isVideoConfigDeclaration =+ id.type === 'ObjectPattern' &&+ init?.type === 'CallExpression' &&+ init.callee.type === 'Identifier' &&+ init.callee.name === 'useVideoConfig' &&+ init.arguments.length === 0;++ if (isVideoConfigDeclaration) {+ for (const property of id.properties) {+ if (+ property.type !== 'ObjectProperty' ||+ property.computed ||+ property.value.type !== 'Identifier'+ ) {+ continue;+ }++ const configKey =+ property.key.type === 'Identifier'+ ? property.key.name+ : property.key.type === 'StringLiteral'+ ? property.key.value+ : null;+ if (configKey === null || !(configKey in videoConfigValues)) {+ continue;+ }++ const value = videoConfigValues[configKey as keyof VideoConfigValues];+ if (Number.isFinite(value)) {+ candidates.set(property.value.name, value);+ }+ }+ } else if (id.type === 'Identifier') {+ otherDeclarations.add(id.name);+ }++ this.traverse(path);+ },+ });++ for (const identifier of otherDeclarations) {+ candidates.delete(identifier);+ }++ return Object.fromEntries(candidates);+};diff --git a/packages/studio-shared/package.json b/packages/studio-shared/package.jsonindex 5d6bb959eb..16efe665cf 100644--- a/packages/studio-shared/package.json+++ b/packages/studio-shared/package.json@@ -42,6 +42,18 @@"types": "./dist/studio-html.d.ts","default": "./dist/studio-html.js"},+ "./keyframe-easing-presets": {+ "types": "./dist/keyframe-easing-presets.d.ts",+ "default": "./dist/keyframe-easing-presets.js"+ },+ "./keyframe-interpolation-function": {+ "types": "./dist/keyframe-interpolation-function.d.ts",+ "default": "./dist/keyframe-interpolation-function.js"+ },+ "./parse-spring-easing-config": {+ "types": "./dist/parse-spring-easing-config.d.ts",+ "default": "./dist/parse-spring-easing-config.js"+ },"./package.json": "./package.json"}}diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex f16f7e36cd..77b4571c1d 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -12,8 +12,11 @@ import type {RenameStaticFileResponse,SubscribeToDefaultPropsRequest,SubscribeToDefaultPropsResponse,+ SubscribeToSequencePropsRequest,+ SubscribeToSequencePropsResponse,UndoResponse,UnsubscribeFromDefaultPropsRequest,+ UnsubscribeFromSequencePropsRequest,} from './api-requests';import type {EventSourceEvent} from './event-source-event';@@ -46,11 +49,17 @@ export type BrowserStudioOperations = {subscribeToDefaultProps: (request: SubscribeToDefaultPropsRequest,) => Promise<SubscribeToDefaultPropsResponse>;+ subscribeToSequenceProps: (+ request: SubscribeToSequencePropsRequest,+ ) => Promise<SubscribeToSequencePropsResponse>;subscribeToEvent: (listener: (event: EventSourceEvent) => void) => () => void;undo: () => Promise<UndoResponse>;unsubscribeFromDefaultProps: (request: UnsubscribeFromDefaultPropsRequest,) => Promise<undefined>;+ unsubscribeFromSequenceProps: (+ request: UnsubscribeFromSequencePropsRequest,+ ) => Promise<undefined>;writeStaticFile: (request: WriteStaticFileRequest) => Promise<void>;};diff --git a/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts b/packages/studio/src/components/Timeline/TimelineStack/get-stack.tsindex 66e5934e0b..cdd73e1ba0 100644--- a/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts+++ b/packages/studio/src/components/Timeline/TimelineStack/get-stack.ts@@ -7,6 +7,7 @@ import {const traceMapCache: Partial<Record<string, TraceMap>> = {};const traceMapPromises: Partial<Record<string, Promise<TraceMap>>> = {};+const browserStudioOriginalSourcePrefix = 'browser-studio-original://';const getSourceMapCache = async (fileName: string) => {if (traceMapCache[fileName]) {@@ -44,6 +45,16 @@ export const getOriginalLocationFromStack = async (return null;}+ if (location.fileName.startsWith(browserStudioOriginalSourcePrefix)) {+ return {+ column: location.columnNumber,+ line: location.lineNumber,+ source: decodeURIComponent(+ location.fileName.slice(browserStudioOriginalSourcePrefix.length),+ ),+ };+ }+const map = await getSourceMapCache(location.fileName);const originalPosition = getOriginalPosition(map,diff --git a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts b/packages/studio/src/components/Timeline/sequence-props-subscription-store.tsindex 02afd64830..12348abd86 100644--- a/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts+++ b/packages/studio/src/components/Timeline/sequence-props-subscription-store.ts@@ -6,7 +6,10 @@ import type {VideoConfigValues,} from 'remotion';import {Internals} from 'remotion';-import {callApi} from '../call-api';+import {+ subscribeToSequenceProps,+ unsubscribeFromSequenceProps,+} from '../sequence-props-api';type Key = string;@@ -31,9 +34,7 @@ const makeKey = ({}): Key =>`${fileName}\0${line}\0${column}\0${componentIdentity ?? ''}\0${sequenceKeys.join('\0')}\0${assetKeys.join('\0')}\0${effectKeys.map((keys) => keys.join('\0')).join('\0\0')}\0${JSON.stringify(videoConfigValues)}`;-type SubscribeResult = Awaited<- ReturnType<typeof callApi<'/api/subscribe-to-sequence-props'>>->;+type SubscribeResult = Awaited<ReturnType<typeof subscribeToSequenceProps>>;type ApplyResult = (result: SubscribeResult) => void;@@ -88,7 +89,7 @@ export const acquireSequencePropsSubscription = ({let entry = entries.get(key);if (!entry) {- const promise = callApi('/api/subscribe-to-sequence-props', {+ const promise = subscribeToSequenceProps({fileName,line,column,@@ -163,7 +164,7 @@ export const acquireSequencePropsSubscription = ({return;}- return callApi('/api/unsubscribe-from-sequence-props', {+ return unsubscribeFromSequenceProps({fileName: acquired.fileName,nodePath: result.nodePath,clientId: acquired.clientId,diff --git a/packages/studio/src/components/sequence-props-api.ts b/packages/studio/src/components/sequence-props-api.tsnew file mode 100644index 0000000000..c6001a764a--- /dev/null+++ b/packages/studio/src/components/sequence-props-api.ts@@ -0,0 +1,25 @@+import type {+ SubscribeToSequencePropsRequest,+ SubscribeToSequencePropsResponse,+ UnsubscribeFromSequencePropsRequest,+} from '@remotion/studio-shared';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {callApi} from './call-api';++export const subscribeToSequenceProps = (+ request: SubscribeToSequencePropsRequest,+): Promise<SubscribeToSequencePropsResponse> => {+ const browserStudioOperations = getBrowserStudioOperations();+ return browserStudioOperations+ ? browserStudioOperations.subscribeToSequenceProps(request)+ : callApi('/api/subscribe-to-sequence-props', request);+};++export const unsubscribeFromSequenceProps = (+ request: UnsubscribeFromSequencePropsRequest,+): Promise<undefined> => {+ const browserStudioOperations = getBrowserStudioOperations();+ return browserStudioOperations+ ? browserStudioOperations.unsubscribeFromSequenceProps(request)+ : callApi('/api/unsubscribe-from-sequence-props', request);+};diff --git a/packages/studio/src/test/browser-studio-sequence-props.test.ts b/packages/studio/src/test/browser-studio-sequence-props.test.tsnew file mode 100644index 0000000000..1e8e68d86b--- /dev/null+++ b/packages/studio/src/test/browser-studio-sequence-props.test.ts@@ -0,0 +1,85 @@+import {afterEach, expect, test} from 'bun:test';+import {+ subscribeToSequenceProps,+ unsubscribeFromSequenceProps,+} from '../components/sequence-props-api';+import {makeBrowserStudioOperations} from './make-browser-studio-operations';++const originalWindowDescriptor = Object.getOwnPropertyDescriptor(+ globalThis,+ 'window',+);++afterEach(() => {+ if (originalWindowDescriptor) {+ Object.defineProperty(globalThis, 'window', originalWindowDescriptor);+ return;+ }++ Reflect.deleteProperty(globalThis, 'window');+});++test('routes sequence prop subscriptions through Browser Studio operations', async () => {+ const calls: string[] = [];+ const nodePath = {+ absolutePath: '/project/src/Composition.tsx',+ nodePath: ['program', 'body', 1],+ sequenceKeys: ['from'],+ effectKeys: [],+ videoConfigValues: {+ durationInFrames: 60,+ fps: 30,+ height: 720,+ width: 1280,+ },+ };+ const operations = makeBrowserStudioOperations({+ subscribeToSequenceProps: (request) => {+ calls.push(`subscribe:${request.clientId}:${request.fileName}`);+ return Promise.resolve({+ success: true,+ nodePath,+ status: {+ canUpdate: true,+ props: {from: {status: 'static', codeValue: 10}},+ effects: [],+ },+ });+ },+ unsubscribeFromSequenceProps: (request) => {+ calls.push(`unsubscribe:${request.clientId}:${request.fileName}`);+ return Promise.resolve(undefined);+ },+ });++ Object.defineProperty(globalThis, 'window', {+ configurable: true,+ value: {remotion_browserStudio: operations},+ });++ const subscription = await subscribeToSequenceProps({+ fileName: 'src/Composition.tsx',+ line: 2,+ column: 0,+ nodePath: null,+ componentIdentity: 'dev.remotion.remotion.Sequence',+ keys: ['from'],+ assetKeys: [],+ effects: [],+ clientId: 'browser-studio',+ videoConfigValues: nodePath.videoConfigValues,+ });+ expect(subscription.success).toBe(true);+ await unsubscribeFromSequenceProps({+ fileName: 'src/Composition.tsx',+ nodePath,+ clientId: 'browser-studio',+ sequenceKeys: ['from'],+ assetKeys: [],+ effectKeys: [],+ });+ expect(calls).toEqual([+ 'subscribe:browser-studio:src/Composition.tsx',+ 'unsubscribe:browser-studio:src/Composition.tsx',+ ]);+});diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.tsindex b3895307a1..4f236add55 100644--- a/packages/studio/src/test/make-browser-studio-operations.ts+++ b/packages/studio/src/test/make-browser-studio-operations.ts@@ -20,9 +20,12 @@ export const makeBrowserStudioOperations = (renameStaticFile: () => unusedOperation('renameStaticFile'),subscribeToDefaultProps: () => unusedOperation('subscribeToDefaultProps'),subscribeToEvent: () => unusedOperation('subscribeToEvent'),+ subscribeToSequenceProps: () => unusedOperation('subscribeToSequenceProps'),undo: () => unusedOperation('undo'),unsubscribeFromDefaultProps: () =>unusedOperation('unsubscribeFromDefaultProps'),+ unsubscribeFromSequenceProps: () =>+ unusedOperation('unsubscribeFromSequenceProps'),writeStaticFile: () => unusedOperation('writeStaticFile'),...overrides,};diff --git a/turbo.json b/turbo.jsonindex e3da40f272..508ed306ca 100644--- a/turbo.json+++ b/turbo.json@@ -30,6 +30,9 @@"testwebrenderer": {"dependsOn": ["@remotion/web-renderer#make"]},+ "testbrowserstudio": {+ "dependsOn": ["@remotion/browser-studio#make"]+ },"testlayoututils": {"dependsOn": ["@remotion/layout-utils#make"]},