Skip to content

🎥 Make videos programmatically with React

`@remotion/browser-studio`: Support saving sequence props (#9897)

Jonny Burger3a53377cfde7
diff --git a/bun.lock b/bun.lock
index 585a096fbc..15dcbb2c4c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -141,6 +141,7 @@
"@rspack/browser": "2.1.1",
"fflate": "0.8.2",
"react-refresh": "0.18.0",
+ "remotion": "workspace:*",
},
"devDependencies": {
"@playwright/test": "1.55.1",
diff --git a/packages/browser-studio/package.json b/packages/browser-studio/package.json
index 0b4842adc5..ceb1281a0d 100644
--- a/packages/browser-studio/package.json
+++ b/packages/browser-studio/package.json
@@ -31,7 +31,8 @@
"@remotion/studio-shared": "workspace:*",
"@rspack/browser": "2.1.1",
"fflate": "0.8.2",
- "react-refresh": "0.18.0"
+ "react-refresh": "0.18.0",
+ "remotion": "workspace:*"
},
"exports": {
".": {
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index f1db861b83..f493465f9e 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -19,6 +19,7 @@ import type {
} from '@remotion/studio-shared';
import {createBrowserStudioProjectController} from './browser-studio-project-controller';
import {makeBrowserStudioProjectArchive} from './download-project';
+import {saveSequencePropsInProject} from './save-sequence-props';
import type {VirtualProject} from './types';
export {insertSolidIntoProject} from '@remotion/studio-codemods';
@@ -230,6 +231,29 @@ export const createBrowserStudioOperations = ({
},
redo: controller.redo,
renameStaticFile: controller.renameStaticFile,
+ saveSequenceProps: (request) => {
+ try {
+ let response: Awaited<
+ ReturnType<BrowserStudioOperations['saveSequenceProps']>
+ > | null = null;
+ const firstTarget = request.edits[0] ?? request.captionPatches?.[0];
+ controller.applyMutation({
+ fileName: firstTarget?.fileName ?? 'Sequence props',
+ mutate: (project) => {
+ const result = saveSequencePropsInProject({project, request});
+ response = result.response;
+ return result.project;
+ },
+ });
+ if (response === null) {
+ throw new Error('Could not save sequence props');
+ }
+
+ return Promise.resolve(response);
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ },
resetHistory: () => {
controller.resetHistory();
refreshDefaultPropsSubscriptions();
diff --git a/packages/browser-studio/src/save-sequence-props.ts b/packages/browser-studio/src/save-sequence-props.ts
new file mode 100644
index 0000000000..5b1b9224ee
--- /dev/null
+++ b/packages/browser-studio/src/save-sequence-props.ts
@@ -0,0 +1,180 @@
+import {
+ computeSequencePropsStatusFromContent,
+ findProjectFile,
+ updateInlineCaptionPatches,
+ type SequencePropsNodeUpdate,
+ updateMultipleSequenceProps,
+} from '@remotion/studio-codemods';
+import type {
+ SaveSequencePropEdit,
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse,
+ SaveSequencePropsResult,
+} from '@remotion/studio-shared';
+import {getAllSchemaKeys, getAssetSchemaKeys} from '@remotion/studio-shared';
+import type {VirtualProject} from './types';
+
+const parseSequencePropEditValue = (
+ value: SaveSequencePropEdit['value'],
+): unknown => {
+ if (value.type === 'undefined') {
+ return undefined;
+ }
+
+ return JSON.parse(value.serialized);
+};
+
+const hasKeyframeChanges = (request: SaveSequencePropsRequest) => {
+ return (
+ (request.addedKeyframes?.length ?? 0) > 0 ||
+ (request.movedKeyframes?.sequenceKeyframes.length ?? 0) > 0 ||
+ (request.movedKeyframes?.effectKeyframes.length ?? 0) > 0
+ );
+};
+
+type FileMutation = {
+ edits: SaveSequencePropEdit[];
+ captionPatches: NonNullable<SaveSequencePropsRequest['captionPatches']>;
+};
+
+const getFileMutation = (
+ mutations: Map<string, FileMutation>,
+ absolutePath: string,
+) => {
+ const existing = mutations.get(absolutePath);
+ if (existing) {
+ return existing;
+ }
+
+ const created: FileMutation = {edits: [], captionPatches: []};
+ mutations.set(absolutePath, created);
+ return created;
+};
+
+const getStatusTargets = (request: SaveSequencePropsRequest) => {
+ return [
+ ...new Map(
+ [...request.edits, ...(request.captionPatches ?? [])].map((target) => [
+ JSON.stringify(target.nodePath),
+ target,
+ ]),
+ ).values(),
+ ];
+};
+
+export const saveSequencePropsInProject = ({
+ project,
+ request,
+}: {
+ project: VirtualProject;
+ request: SaveSequencePropsRequest;
+}): {
+ project: VirtualProject;
+ response: SaveSequencePropsResponse;
+} => {
+ if (hasKeyframeChanges(request)) {
+ throw new Error(
+ 'Browser Studio does not support saving sequence keyframes yet',
+ );
+ }
+
+ if (
+ request.edits.length === 0 &&
+ (request.captionPatches?.length ?? 0) === 0
+ ) {
+ throw new Error('No sequence prop edits to save');
+ }
+
+ const mutations = new Map<string, FileMutation>();
+ for (const edit of request.edits) {
+ const absolutePath = findProjectFile({
+ filePath: edit.fileName,
+ project,
+ });
+ getFileMutation(mutations, absolutePath).edits.push(edit);
+ }
+
+ for (const captionPatch of request.captionPatches ?? []) {
+ const absolutePath = findProjectFile({
+ filePath: captionPatch.fileName,
+ project,
+ });
+ getFileMutation(mutations, absolutePath).captionPatches.push(captionPatch);
+ }
+
+ const nextFiles = {...project.files};
+ for (const [absolutePath, mutation] of mutations) {
+ let output = project.files[absolutePath];
+ if (output === undefined) {
+ throw new Error(`Could not find ${absolutePath}`);
+ }
+
+ if (mutation.edits.length > 0) {
+ const changes: SequencePropsNodeUpdate[] = mutation.edits.map((edit) => ({
+ nodePath: edit.nodePath.nodePath,
+ updates: [
+ {
+ key: edit.key,
+ value: parseSequencePropEditValue(edit.value),
+ defaultValue:
+ edit.defaultValue === null ? null : JSON.parse(edit.defaultValue),
+ googleFont:
+ edit.sourceEdit?.type === 'google-font'
+ ? edit.sourceEdit.font
+ : null,
+ },
+ ],
+ schema: edit.schema,
+ videoConfigValues: edit.nodePath.videoConfigValues,
+ }));
+ output = updateMultipleSequenceProps({input: output, changes}).output;
+ }
+
+ for (const captionPatch of mutation.captionPatches) {
+ output = updateInlineCaptionPatches({
+ input: output,
+ nodePath: captionPatch.nodePath.nodePath,
+ patches: captionPatch.patches,
+ }).output;
+ }
+
+ nextFiles[absolutePath] = output;
+ }
+
+ const nextProject = {...project, files: nextFiles};
+ const statusTargets = getStatusTargets(request);
+ const results: SaveSequencePropsResult[] = statusTargets.map((target) => {
+ const absolutePath = findProjectFile({
+ filePath: target.fileName,
+ project: nextProject,
+ });
+ const status = computeSequencePropsStatusFromContent({
+ fileContents: nextFiles[absolutePath],
+ keys: getAllSchemaKeys(target.schema),
+ assetKeys: getAssetSchemaKeys(target.schema),
+ nodePath: target.nodePath.nodePath,
+ componentIdentity: null,
+ effects: [],
+ videoConfigValues: target.nodePath.videoConfigValues,
+ });
+
+ return {
+ fileName: target.fileName,
+ nodePath: target.nodePath,
+ props: status.props,
+ };
+ });
+ const firstResult = results[0];
+ if (!firstResult) {
+ throw new Error('Could not compute sequence prop edit status');
+ }
+
+ return {
+ project: nextProject,
+ response: {
+ canUpdate: true,
+ props: firstResult.props,
+ results,
+ },
+ };
+};
diff --git a/packages/browser-studio/src/test/browser-studio-operations.test.ts b/packages/browser-studio/src/test/browser-studio-operations.test.ts
index 0c0393ee61..98a484dfec 100644
--- a/packages/browser-studio/src/test/browser-studio-operations.test.ts
+++ b/packages/browser-studio/src/test/browser-studio-operations.test.ts
@@ -274,7 +274,7 @@ registerRoot(Root);`,
).toHaveLength(1);
});
-test('subscribes to sequence prop updates and emits virtual project events', async () => {
+test('saves sequence props with events and undo history', async () => {
const fileName = '/project/src/Composition.tsx';
let currentProject: VirtualProject = {
rootDir: '/project',
@@ -328,17 +328,37 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
});
expect(subscription.nodePath.absolutePath).toBe(fileName);
- currentProject = {
- ...currentProject,
- files: {
- ...currentProject.files,
- [fileName]: currentProject.files[fileName].replace(
- 'from={10}',
- 'from={15}',
- ),
- },
- };
- operations.resetHistory();
+ const saveResult = await operations.saveSequenceProps({
+ edits: [
+ {
+ fileName: request.fileName,
+ nodePath: subscription.nodePath,
+ key: 'from',
+ value: {type: 'json', serialized: '15'},
+ defaultValue: '0',
+ schema: {
+ from: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ },
+ durationInFrames: {
+ type: 'number',
+ default: null,
+ hiddenFromList: false,
+ },
+ },
+ sourceEdit: null,
+ },
+ ],
+ addedKeyframes: null,
+ movedKeyframes: null,
+ clientId: request.clientId,
+ undoLabel: 'Update from',
+ redoLabel: 'Update from again',
+ });
+ expect(saveResult.canUpdate).toBe(true);
+ expect(currentProject.files[fileName]).toContain('from={15}');
const update = events.findLast(
(
event,
@@ -352,6 +372,10 @@ export const Root = () => <Composition id="MyComp" component={Component} duratio
}
expect(update.result.props.from).toEqual({status: 'static', codeValue: 15});
+ expect(await operations.undo()).toEqual({success: true});
+ expect(currentProject.files[fileName]).toContain('from={10}');
+ expect(await operations.redo()).toEqual({success: true});
+ expect(currentProject.files[fileName]).toContain('from={15}');
currentProject = {
...currentProject,
diff --git a/packages/studio-codemods/src/index.ts b/packages/studio-codemods/src/index.ts
index 503927a59b..bad9250fbc 100644
--- a/packages/studio-codemods/src/index.ts
+++ b/packages/studio-codemods/src/index.ts
@@ -12,6 +12,15 @@ export {
} from './sequence-props';
export {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
export {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
+export {updateInlineCaptionPatches} from './update-inline-caption-patches';
+export {
+ type RemovedProp,
+ type SequencePropsNodeUpdate,
+ type SequencePropsNodeUpdateResult,
+ type SequencePropUpdate,
+ updateMultipleSequenceProps,
+ updateSequencePropsAst,
+} from './update-sequence-props';
export type CodemodProject = {
files: Record<string, string>;
diff --git a/packages/studio-codemods/src/sequence-props/imports.ts b/packages/studio-codemods/src/sequence-props/imports.ts
index c6a359138d..86d1c09f0b 100644
--- a/packages/studio-codemods/src/sequence-props/imports.ts
+++ b/packages/studio-codemods/src/sequence-props/imports.ts
@@ -1,4 +1,7 @@
-import type {ImportSpecifier} from '@babel/types';
+import type {File, ImportDeclaration, ImportSpecifier} from '@babel/types';
+import * as recast from 'recast';
+
+const b = recast.types.builders;
export const getImportedName = (specifier: ImportSpecifier) => {
if (specifier.imported.type === 'Identifier') {
@@ -7,3 +10,186 @@ export const getImportedName = (specifier: ImportSpecifier) => {
return specifier.imported.value;
};
+
+export const findImportDeclaration = (
+ ast: File,
+ sourcePath: string,
+): ImportDeclaration | null => {
+ for (const stmt of ast.program.body) {
+ if (
+ stmt.type === 'ImportDeclaration' &&
+ stmt.source.type === 'StringLiteral' &&
+ stmt.source.value === sourcePath
+ ) {
+ return stmt;
+ }
+ }
+
+ return null;
+};
+
+const findImportDeclarations = (
+ ast: File,
+ sourcePath: string,
+): ImportDeclaration[] => {
+ return ast.program.body.filter(
+ (stmt): stmt is ImportDeclaration =>
+ stmt.type === 'ImportDeclaration' &&
+ stmt.source.type === 'StringLiteral' &&
+ stmt.source.value === sourcePath,
+ );
+};
+
+export const insertImportDeclaration = (
+ ast: File,
+ importDeclaration: ImportDeclaration,
+) => {
+ const {body} = ast.program;
+ let lastImportIndex = -1;
+ for (let i = 0; i < body.length; i++) {
+ if (body[i].type === 'ImportDeclaration') {
+ lastImportIndex = i;
+ }
+ }
+
+ body.splice(lastImportIndex + 1, 0, importDeclaration);
+};
+
+export const normalizeImportSpacing = (input: string) => {
+ return input.replace(/(import[^\n]*\n)\n+(?=import\b)/g, '$1');
+};
+
+const hasNamespaceSpecifier = (importDeclaration: ImportDeclaration) => {
+ return importDeclaration.specifiers?.some(
+ (specifier) => specifier.type === 'ImportNamespaceSpecifier',
+ );
+};
+
+export const ensureNamedImport = ({
+ ast,
+ importedName,
+ sourcePath,
+ localName,
+}: {
+ ast: File;
+ importedName: string;
+ sourcePath: string;
+ localName: string;
+}) => {
+ const existingImports = findImportDeclarations(ast, sourcePath);
+
+ for (const existingImportDeclaration of existingImports) {
+ const matchingSpecifier = existingImportDeclaration.specifiers?.find(
+ (importSpecifierCandidate) =>
+ importSpecifierCandidate.type === 'ImportSpecifier' &&
+ getImportedName(importSpecifierCandidate) === importedName,
+ );
+
+ if (matchingSpecifier) {
+ return matchingSpecifier.local?.name ?? importedName;
+ }
+ }
+
+ const existingImport = existingImports.find(
+ (candidateImportDeclaration) =>
+ !hasNamespaceSpecifier(candidateImportDeclaration),
+ );
+
+ if (existingImport) {
+ const importSpecifier = b.importSpecifier(
+ b.identifier(importedName),
+ localName === importedName ? null : b.identifier(localName),
+ ) as unknown as ImportSpecifier;
+
+ existingImport.specifiers = [
+ ...(existingImport.specifiers ?? []),
+ importSpecifier,
+ ];
+ return localName;
+ }
+
+ const specifier = b.importSpecifier(
+ b.identifier(importedName),
+ localName === importedName ? null : b.identifier(localName),
+ ) as unknown as ImportSpecifier;
+ const importDeclaration = b.importDeclaration(
+ [specifier as never],
+ b.stringLiteral(sourcePath),
+ ) as unknown as ImportDeclaration;
+ insertImportDeclaration(ast, importDeclaration);
+ return localName;
+};
+
+export const ensureNamedImports = ({
+ ast,
+ importedNames,
+ sourcePath,
+}: {
+ ast: File;
+ importedNames: ReadonlySet<string>;
+ sourcePath: string;
+}) => {
+ if (importedNames.size === 0) {
+ return;
+ }
+
+ const existingImports = findImportDeclarations(ast, sourcePath);
+ const existingNames = new Set<string>();
+
+ for (const existingImportDeclaration of existingImports) {
+ for (const importSpecifierCandidate of existingImportDeclaration.specifiers ??
+ []) {
+ if (importSpecifierCandidate.type !== 'ImportSpecifier') {
+ continue;
+ }
+
+ const importedName = getImportedName(importSpecifierCandidate);
+ const localName = importSpecifierCandidate.local?.name ?? importedName;
+ if (localName === importedName) {
+ existingNames.add(importedName);
+ }
+ }
+ }
+
+ const existingImport = existingImports.find(
+ (candidateImportDeclaration) =>
+ !hasNamespaceSpecifier(candidateImportDeclaration),
+ );
+
+ if (existingImport) {
+ for (const importedName of importedNames) {
+ if (existingNames.has(importedName)) {
+ continue;
+ }
+
+ existingImport.specifiers = [
+ ...(existingImport.specifiers ?? []),
+ b.importSpecifier(
+ b.identifier(importedName),
+ ) as unknown as ImportSpecifier,
+ ];
+ existingNames.add(importedName);
+ }
+
+ return;
+ }
+
+ const specifiers = [...importedNames]
+ .filter((importedName) => !existingNames.has(importedName))
+ .map(
+ (importedName) =>
+ b.importSpecifier(
+ b.identifier(importedName),
+ ) as unknown as ImportSpecifier,
+ );
+
+ if (specifiers.length === 0) {
+ return;
+ }
+
+ const importDeclaration = b.importDeclaration(
+ specifiers as never,
+ b.stringLiteral(sourcePath),
+ ) as unknown as ImportDeclaration;
+ insertImportDeclaration(ast, importDeclaration);
+};
diff --git a/packages/studio-codemods/src/update-inline-caption-patches.ts b/packages/studio-codemods/src/update-inline-caption-patches.ts
new file mode 100644
index 0000000000..30b8e9840a
--- /dev/null
+++ b/packages/studio-codemods/src/update-inline-caption-patches.ts
@@ -0,0 +1,280 @@
+import type {Expression, ObjectExpression, ObjectProperty} from '@babel/types';
+import type {CaptionPatch} from '@remotion/studio-shared';
+import type {SequenceNodePath} from 'remotion';
+import {findJsxElementNodeAtNodePath} from './sequence-props';
+import {parseAst} from './sequence-props/parse-ast';
+
+const captionKeys = [
+ 'text',
+ 'startMs',
+ 'endMs',
+ 'timestampMs',
+ 'confidence',
+] as const;
+
+type CaptionKey = (typeof captionKeys)[number];
+type StaticCaption = CaptionPatch['before'];
+
+const getPropertyKey = (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 getStaticValue = (value: Expression): string | number | null => {
+ if (value.type === 'StringLiteral' || value.type === 'NumericLiteral') {
+ return value.value;
+ }
+
+ if (value.type === 'NullLiteral') {
+ return null;
+ }
+
+ throw new Error('Captions must use static literal values to be edited');
+};
+
+const getStaticCaption = (expression: ObjectExpression): StaticCaption => {
+ const values = new Map<string, string | number | null>();
+ for (const property of expression.properties) {
+ if (property.type !== 'ObjectProperty' || property.computed) {
+ throw new Error(
+ 'Captions must use static object properties to be edited',
+ );
+ }
+
+ const key = getPropertyKey(property);
+ if (key !== null && captionKeys.includes(key as CaptionKey)) {
+ values.set(key, getStaticValue(property.value as Expression));
+ }
+ }
+
+ const text = values.get('text');
+ const startMs = values.get('startMs');
+ const endMs = values.get('endMs');
+ const timestampMs = values.get('timestampMs');
+ const confidence = values.get('confidence');
+ if (
+ typeof text !== 'string' ||
+ typeof startMs !== 'number' ||
+ typeof endMs !== 'number' ||
+ (timestampMs !== null && typeof timestampMs !== 'number') ||
+ (confidence !== null && typeof confidence !== 'number')
+ ) {
+ throw new Error(
+ 'Captions must have the standard static caption shape to edit',
+ );
+ }
+
+ return {text, startMs, endMs, timestampMs, confidence};
+};
+
+const isCaptionKey = (key: string): key is CaptionKey =>
+ captionKeys.includes(key as CaptionKey);
+
+const getReplacementValue = ({
+ value,
+ previous,
+}: {
+ value: string | number | null;
+ previous: Expression;
+}): string => {
+ if (value === null || typeof value === 'number') {
+ return String(value);
+ }
+
+ if (
+ previous.type === 'StringLiteral' &&
+ typeof previous.extra?.raw === 'string' &&
+ previous.extra.raw.startsWith("'")
+ ) {
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
+ }
+
+ return JSON.stringify(value);
+};
+
+const getSourceValueRange = ({
+ input,
+ property,
+ key,
+}: {
+ input: string;
+ property: ObjectProperty;
+ key: string;
+}): {start: number; end: number} => {
+ const line = property.loc?.start.line;
+ if (line === null || line === undefined) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ const lines = input.split('\n');
+ const lineStart = lines
+ .slice(0, line - 1)
+ .reduce((length, current) => length + current.length + 1, 0);
+ const sourceLine = lines[line - 1];
+ if (sourceLine === undefined) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ const keyStart = sourceLine.indexOf(key);
+ const valueStart = sourceLine.indexOf(':', keyStart) + 1;
+ const rawValue: string =
+ property.value.type === 'StringLiteral' &&
+ typeof property.value.extra?.raw === 'string'
+ ? property.value.extra.raw
+ : property.value.type === 'StringLiteral'
+ ? JSON.stringify(property.value.value)
+ : String(getStaticValue(property.value as Expression));
+ const valueOffset = sourceLine.indexOf(rawValue, valueStart);
+ if (keyStart === -1 || valueOffset === -1) {
+ throw new Error(`Could not locate caption ${key} in the source file`);
+ }
+
+ return {
+ start: lineStart + valueOffset,
+ end: lineStart + valueOffset + rawValue.length,
+ };
+};
+
+const updateCaption = ({
+ input,
+ caption,
+ patch,
+}: {
+ input: string;
+ caption: ObjectExpression;
+ patch: CaptionPatch;
+}): {changedFields: string[]; replacements: SourceReplacement[]} => {
+ const current = getStaticCaption(caption);
+ if (!captionKeys.every((key) => current[key] === patch.before[key])) {
+ throw new Error(
+ `Caption ${patch.index} changed in the source file before this edit could be saved`,
+ );
+ }
+
+ const changedKeys = Object.keys(patch.changes);
+ if (changedKeys.length === 0 || !changedKeys.every(isCaptionKey)) {
+ throw new Error('Caption patches must change at least one caption field');
+ }
+
+ const replacements: SourceReplacement[] = [];
+ for (const key of changedKeys) {
+ const value = patch.changes[key];
+ if (
+ (key === 'text' && typeof value !== 'string') ||
+ ((key === 'startMs' || key === 'endMs') &&
+ (typeof value !== 'number' || !Number.isFinite(value))) ||
+ ((key === 'timestampMs' || key === 'confidence') &&
+ value !== null &&
+ (typeof value !== 'number' || !Number.isFinite(value)))
+ ) {
+ throw new Error(`Caption ${key} has an invalid value`);
+ }
+
+ const property = caption.properties.find((candidate) => {
+ return (
+ candidate.type === 'ObjectProperty' &&
+ !candidate.computed &&
+ getPropertyKey(candidate) === key
+ );
+ });
+ if (!property || property.type !== 'ObjectProperty') {
+ throw new Error(`Caption ${patch.index} is missing ${key}`);
+ }
+
+ const {start, end} = getSourceValueRange({input, property, key});
+ replacements.push({
+ start,
+ end,
+ value: getReplacementValue({
+ value: value as string | number | null,
+ previous: property.value as Expression,
+ }),
+ });
+ }
+
+ return {changedFields: changedKeys, replacements};
+};
+
+type SourceReplacement = {
+ start: number;
+ end: number;
+ value: string;
+};
+
+export const updateInlineCaptionPatches = ({
+ input,
+ nodePath,
+ patches,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ patches: CaptionPatch[];
+}): {output: string; logLine: number; changedFields: string[][]} => {
+ if (patches.length === 0) {
+ throw new Error('Expected at least one caption patch');
+ }
+
+ const ast = parseAst(input);
+ const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
+ if (!jsxElement) {
+ throw new Error(
+ 'Could not find a JSX element at the specified line to update',
+ );
+ }
+
+ const captionsAttribute = jsxElement.openingElement.attributes?.find(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'captions',
+ );
+ if (
+ !captionsAttribute ||
+ captionsAttribute.type !== 'JSXAttribute' ||
+ captionsAttribute.value?.type !== 'JSXExpressionContainer' ||
+ captionsAttribute.value.expression.type !== 'ArrayExpression'
+ ) {
+ throw new Error('Captions must be an inline JSX array to edit them');
+ }
+
+ const captions = captionsAttribute.value.expression.elements;
+ const changedFields: string[][] = [];
+ const replacements: SourceReplacement[] = [];
+ for (const patch of patches) {
+ if (!Number.isInteger(patch.index) || patch.index < 0) {
+ throw new Error('Caption patch index must be a non-negative integer');
+ }
+
+ const caption = captions[patch.index];
+ if (!caption || caption.type !== 'ObjectExpression') {
+ throw new Error(`Could not find inline caption ${patch.index}`);
+ }
+
+ const result = updateCaption({input, caption, patch});
+ changedFields.push(result.changedFields);
+ replacements.push(...result.replacements);
+ }
+
+ const output = replacements
+ .sort((a, b) => b.start - a.start)
+ .reduce(
+ (current, replacement) =>
+ current.slice(0, replacement.start) +
+ replacement.value +
+ current.slice(replacement.end),
+ input,
+ );
+
+ return {
+ output,
+ logLine: jsxElement.openingElement.loc?.start.line ?? 1,
+ changedFields,
+ };
+};
diff --git a/packages/studio-codemods/src/update-nested-prop.ts b/packages/studio-codemods/src/update-nested-prop.ts
new file mode 100644
index 0000000000..b9248345b4
--- /dev/null
+++ b/packages/studio-codemods/src/update-nested-prop.ts
@@ -0,0 +1,243 @@
+import type {
+ ArrayExpression,
+ AssignmentExpression,
+ ExpressionStatement,
+ Identifier,
+ JSXAttribute,
+ JSXExpressionContainer,
+ JSXOpeningElement,
+ JSXSpreadAttribute,
+ ObjectExpression,
+ ObjectProperty,
+ StringLiteral,
+ Expression,
+} from '@babel/types';
+import {stringifyDefaultProps} from '@remotion/studio-shared';
+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
+import * as recast from 'recast';
+import {parseAst} from './sequence-props/parse-ast';
+
+const b = recast.types.builders;
+
+export const parseValueExpression = (value: unknown): ExpressionKind => {
+ return (
+ (
+ parseAst(`a = ${stringifyDefaultProps({props: value, enumPaths: []})}`)
+ .program.body[0] as unknown as ExpressionStatement
+ ).expression as AssignmentExpression
+ ).right as ExpressionKind;
+};
+
+const findJsxAttribute = (
+ attributes: (JSXAttribute | JSXSpreadAttribute)[],
+ name: string,
+): {attrIndex: number; attr: JSXAttribute | undefined} => {
+ const attrIndex = attributes.findIndex((a) => {
+ if (a.type === 'JSXSpreadAttribute') {
+ return false;
+ }
+
+ if (a.name.type === 'JSXNamespacedName') {
+ return false;
+ }
+
+ return a.name.name === name;
+ });
+
+ const found = attrIndex !== -1 ? attributes[attrIndex] : undefined;
+
+ return {
+ attrIndex,
+ attr:
+ found && found.type === 'JSXAttribute'
+ ? (found as JSXAttribute)
+ : undefined,
+ };
+};
+
+const findObjectProperty = (
+ objExpr: ObjectExpression,
+ propertyName: string,
+): {propIndex: number; prop: ObjectProperty | undefined} => {
+ const propIndex = objExpr.properties.findIndex(
+ (p) =>
+ p.type === 'ObjectProperty' &&
+ (((p as ObjectProperty).key.type === 'Identifier' &&
+ ((p as ObjectProperty).key as Identifier).name === propertyName) ||
+ ((p as ObjectProperty).key.type === 'StringLiteral' &&
+ ((p as ObjectProperty).key as StringLiteral).value === propertyName)),
+ );
+
+ return {
+ propIndex,
+ prop:
+ propIndex !== -1
+ ? (objExpr.properties[propIndex] as ObjectProperty)
+ : undefined,
+ };
+};
+
+const getObjectExpression = (attr: JSXAttribute): ObjectExpression | null => {
+ const {value} = attr;
+ if (!value || value.type !== 'JSXExpressionContainer') {
+ return null;
+ }
+
+ const container = value as JSXExpressionContainer;
+ if (container.expression.type !== 'ObjectExpression') {
+ return null;
+ }
+
+ return container.expression as ObjectExpression;
+};
+
+const getOldValueString = ({
+ attr,
+ childKey,
+ defaultValue,
+}: {
+ attr: JSXAttribute | undefined;
+ childKey: string;
+ defaultValue: unknown | null;
+}): string => {
+ if (attr) {
+ const objExpr = getObjectExpression(attr);
+ if (objExpr) {
+ const {prop} = findObjectProperty(objExpr, childKey);
+ if (prop) {
+ return recast.print(prop.value).code;
+ }
+ }
+ }
+
+ if (defaultValue !== null) {
+ return JSON.stringify(defaultValue);
+ }
+
+ return '';
+};
+
+const removeNestedProp = ({
+ attr,
+ attrIndex,
+ attributes,
+ childKey,
+}: {
+ attr: JSXAttribute | undefined;
+ attrIndex: number;
+ attributes: (JSXAttribute | JSXSpreadAttribute)[];
+ childKey: string;
+}) => {
+ if (!attr) {
+ return;
+ }
+
+ const objExpr = getObjectExpression(attr);
+ if (!objExpr) {
+ return;
+ }
+
+ const {propIndex} = findObjectProperty(objExpr, childKey);
+ if (propIndex !== -1) {
+ objExpr.properties.splice(propIndex, 1);
+ }
+
+ if (objExpr.properties.length === 0 && attrIndex !== -1) {
+ attributes.splice(attrIndex, 1);
+ }
+};
+
+const setNestedProp = ({
+ attr,
+ attributes,
+ parentKey,
+ childKey,
+ value,
+ createValueExpression,
+}: {
+ attr: JSXAttribute | undefined;
+ attributes: (JSXAttribute | JSXSpreadAttribute)[];
+ parentKey: string;
+ childKey: string;
+ value: unknown;
+ createValueExpression:
+ | ((existing: Expression | null) => ExpressionKind)
+ | null;
+}) => {
+ if (attr) {
+ const objExpr = getObjectExpression(attr);
+ if (objExpr) {
+ const {prop} = findObjectProperty(objExpr, childKey);
+ const parsedValue = createValueExpression
+ ? createValueExpression((prop?.value as Expression | undefined) ?? null)
+ : parseValueExpression(value);
+ if (prop) {
+ prop.value = parsedValue as ObjectExpression | ArrayExpression;
+ } else {
+ objExpr.properties.push(
+ b.objectProperty(
+ b.identifier(childKey),
+ parsedValue,
+ ) as ObjectProperty,
+ );
+ }
+ }
+ } else {
+ const parsedValue = createValueExpression
+ ? createValueExpression(null)
+ : parseValueExpression(value);
+ const objExpr = b.objectExpression([
+ b.objectProperty(b.identifier(childKey), parsedValue),
+ ]);
+ const newAttr = b.jsxAttribute(
+ b.jsxIdentifier(parentKey),
+ b.jsxExpressionContainer(objExpr),
+ );
+
+ attributes.push(newAttr as JSXAttribute | JSXSpreadAttribute);
+ }
+};
+
+export const updateNestedProp = ({
+ node,
+ parentKey,
+ childKey,
+ value,
+ defaultValue,
+ isDefault,
+ createValueExpression,
+}: {
+ node: JSXOpeningElement;
+ parentKey: string;
+ childKey: string;
+ value: unknown;
+ defaultValue: unknown | null;
+ isDefault: boolean;
+ createValueExpression:
+ | ((existing: Expression | null) => ExpressionKind)
+ | null;
+}): string => {
+ if (!node.attributes) {
+ node.attributes = [];
+ }
+
+ const {attributes} = node;
+ const {attrIndex, attr} = findJsxAttribute(attributes, parentKey);
+
+ const oldValueString = getOldValueString({attr, childKey, defaultValue});
+
+ if (isDefault) {
+ removeNestedProp({attr, attrIndex, attributes, childKey});
+ } else {
+ setNestedProp({
+ attr,
+ attributes,
+ parentKey,
+ childKey,
+ value,
+ createValueExpression,
+ });
+ }
+
+ return oldValueString;
+};
diff --git a/packages/studio-codemods/src/update-sequence-props.ts b/packages/studio-codemods/src/update-sequence-props.ts
new file mode 100644
index 0000000000..a4a5c69b71
--- /dev/null
+++ b/packages/studio-codemods/src/update-sequence-props.ts
@@ -0,0 +1,1121 @@
+import type {
+ JSXAttribute,
+ JSXElement,
+ JSXExpressionContainer,
+ JSXFragment,
+ JSXSpreadAttribute,
+ ObjectProperty,
+ StringLiteral,
+ Expression,
+ File,
+ Statement,
+} from '@babel/types';
+import type {GoogleFontSourceEdit} from '@remotion/studio-shared';
+import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
+import * as recast from 'recast';
+import type {
+ InteractivitySchema,
+ SequenceNodePath,
+ VideoConfigValues,
+} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
+import {
+ findJsxElementNodeAtNodePath,
+ getStaticJsxChildrenAttribute,
+ getStaticJsxTextContent,
+ hasJsxChildrenAttribute,
+} from './sequence-props';
+import {
+ getCssShorthandsForUpdates,
+ type CssShorthandProperty,
+} from './sequence-props/css-shorthand-properties';
+import {ensureNamedImports} from './sequence-props/imports';
+import {parseAst, serializeAst} from './sequence-props/parse-ast';
+import {
+ parseVideoConfigNumericExpression,
+ updateVideoConfigNumericExpression,
+} from './sequence-props/video-config-numeric-expression';
+import {
+ getVideoConfigIdentifierValues,
+ type VideoConfigIdentifierValues,
+} from './sequence-props/video-config-values';
+import {parseValueExpression, updateNestedProp} from './update-nested-prop';
+
+const b = recast.types.builders;
+
+export type SequencePropUpdate = {
+ key: string;
+ value: unknown;
+ defaultValue: unknown | null;
+ googleFont?: GoogleFontSourceEdit | null;
+};
+
+const ensureImportsForUpdates = ({
+ ast,
+ updates,
+}: {
+ ast: File;
+ updates: SequencePropUpdate[];
+}) => {
+ if (
+ updates.some(
+ ({value, defaultValue}) =>
+ typeof value === 'string' &&
+ value.startsWith(NoReactInternals.FILE_TOKEN) &&
+ (defaultValue === null ||
+ JSON.stringify(value) !== JSON.stringify(defaultValue)),
+ )
+ ) {
+ ensureNamedImports({
+ ast,
+ importedNames: new Set(['staticFile']),
+ sourcePath: 'remotion',
+ });
+ }
+};
+
+export type RemovedProp = {
+ key: string;
+ valueString: string;
+};
+
+export type SequencePropsNodeUpdate = {
+ nodePath: SequenceNodePath;
+ updates: SequencePropUpdate[];
+ schema: InteractivitySchema;
+ videoConfigValues: VideoConfigValues | null;
+};
+
+export type SequencePropsNodeUpdateResult = {
+ oldValueStrings: string[];
+ logLine: number;
+ removedProps: RemovedProp[];
+};
+
+export type UpdateMultipleSequencePropsResult = {
+ output: string;
+ results: SequencePropsNodeUpdateResult[];
+};
+
+const removeVariantKey = ({
+ node,
+ variantKey,
+}: {
+ node: JSXOpeningElementLike;
+ variantKey: string;
+}) => {
+ const dotIndex = variantKey.indexOf('.');
+ if (dotIndex === -1) {
+ const idx = node.attributes?.findIndex(
+ (a) =>
+ a.type === 'JSXAttribute' &&
+ a.name.type === 'JSXIdentifier' &&
+ a.name.name === variantKey,
+ );
+ if (idx !== undefined && idx !== -1 && node.attributes) {
+ node.attributes.splice(idx, 1);
+ }
+
+ return;
+ }
+
+ updateNestedProp({
+ node,
+ parentKey: variantKey.slice(0, dotIndex),
+ childKey: variantKey.slice(dotIndex + 1),
+ value: undefined,
+ defaultValue: null,
+ isDefault: true,
+ createValueExpression: null,
+ });
+};
+
+const snapshotTopLevelAttrs = (
+ node: JSXOpeningElementLike,
+): Map<string, string> => {
+ const result = new Map<string, string>();
+ for (const a of node.attributes ?? []) {
+ if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier') {
+ const {name} = a.name;
+ const printed = recast
+ .print(a)
+ .code.replace(/\s+/g, ' ')
+ .replace(/,(\s*[}\]])/g, '$1')
+ .trim();
+
+ const prefix = `${name}=`;
+ let valueOnly = printed.startsWith(prefix)
+ ? printed.slice(prefix.length)
+ : printed;
+ if (valueOnly.startsWith('{') && valueOnly.endsWith('}')) {
+ valueOnly = valueOnly.slice(1, -1).trim();
+ }
+
+ result.set(name, valueOnly);
+ }
+ }
+
+ return result;
+};
+
+type JSXElementLike = NonNullable<
+ ReturnType<typeof findJsxElementNodeAtNodePath>
+>;
+type JSXOpeningElementLike = JSXElementLike['openingElement'];
+
+const escapeJsxText = (value: string): string => {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/{/g, '&#123;')
+ .replace(/}/g, '&#125;');
+};
+
+const findChildrenAttribute = (
+ node: JSXOpeningElementLike,
+): JSXAttribute | undefined => {
+ return node.attributes?.find((attr) => {
+ return (
+ attr.type === 'JSXAttribute' &&
+ attr.name.type === 'JSXIdentifier' &&
+ attr.name.name === 'children'
+ );
+ }) as JSXAttribute | undefined;
+};
+
+const updateJsxTextContent = ({
+ jsxElement,
+ value,
+}: {
+ jsxElement: JSXElementLike;
+ value: unknown;
+}): string => {
+ const nextValue = String(value ?? '');
+ const staticChildrenAttribute = getStaticJsxChildrenAttribute(
+ jsxElement.openingElement,
+ );
+ if (staticChildrenAttribute) {
+ const childrenAttribute = findChildrenAttribute(jsxElement.openingElement);
+ if (!childrenAttribute) {
+ throw new Error('Expected static children attribute to exist');
+ }
+
+ childrenAttribute.value = b.stringLiteral(nextValue) as StringLiteral;
+ return staticChildrenAttribute.value;
+ }
+
+ if (hasJsxChildrenAttribute(jsxElement.openingElement)) {
+ throw new Error(
+ 'Cannot update text content because the children attribute is not static text',
+ );
+ }
+
+ const staticTextContent = getStaticJsxTextContent(jsxElement);
+ if (!staticTextContent) {
+ throw new Error(
+ 'Cannot update text content because JSX children are not static text',
+ );
+ }
+
+ const canRepresentAsJsxText =
+ staticTextContent.kind === 'jsx-text' &&
+ !nextValue.includes('\n') &&
+ nextValue.trim() === nextValue;
+ if (canRepresentAsJsxText) {
+ jsxElement.children = [
+ b.jsxText(escapeJsxText(nextValue)),
+ ] as unknown as JSXElementLike['children'];
+ } else {
+ jsxElement.children = [
+ b.jsxExpressionContainer(b.stringLiteral(nextValue)),
+ ] as unknown as JSXElementLike['children'];
+ }
+
+ return staticTextContent.value;
+};
+
+const collectTopLevelIdentifierNames = (ast: File): Set<string> => {
+ const names = new Set<string>();
+ recast.types.visit(ast, {
+ visitIdentifier(path) {
+ names.add(path.node.name);
+ this.traverse(path);
+ },
+ });
+
+ return names;
+};
+
+const toSafeIdentifier = (value: string) => {
+ const sanitized = value.replace(/[^a-zA-Z0-9_$]/g, '');
+ if (!sanitized) {
+ return 'loadGoogleFont';
+ }
+
+ return /^[a-zA-Z_$]/.test(sanitized) ? sanitized : `_${sanitized}`;
+};
+
+const getSafeLoadFontIdentifier = ({
+ font,
+ usedNames,
+}: {
+ font: GoogleFontSourceEdit;
+ usedNames: Set<string>;
+}) => {
+ const baseName = toSafeIdentifier(`load${font.importName}`);
+ if (!usedNames.has(baseName)) {
+ usedNames.add(baseName);
+ return baseName;
+ }
+
+ let index = 2;
+ while (usedNames.has(`${baseName}${index}`)) {
+ index++;
+ }
+
+ const name = `${baseName}${index}`;
+ usedNames.add(name);
+ return name;
+};
+
+const getImportedLoadFontIdentifier = ({
+ ast,
+ font,
+}: {
+ ast: File;
+ font: GoogleFontSourceEdit;
+}): string | null => {
+ const moduleName = `@remotion/google-fonts/${font.importName}`;
+ for (const statement of ast.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.value !== moduleName
+ ) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.imported.type === 'Identifier' &&
+ specifier.imported.name === 'loadFont'
+ ) {
+ return specifier.local?.name ?? 'loadFont';
+ }
+ }
+ }
+
+ return null;
+};
+
+const getInsertIndexAfterImportsOrDirectives = (ast: File) => {
+ const lastImportIndex = ast.program.body.reduce(
+ (lastIndex, statement, index) => {
+ return statement.type === 'ImportDeclaration' ? index : lastIndex;
+ },
+ -1,
+ );
+ if (lastImportIndex !== -1) {
+ return lastImportIndex + 1;
+ }
+
+ return ast.program.body.findIndex((statement) => {
+ return !(
+ statement.type === 'ExpressionStatement' &&
+ 'directive' in statement &&
+ statement.directive
+ );
+ });
+};
+
+const insertAfterImportsOrDirectives = (ast: File, statement: Statement) => {
+ const insertIndex = getInsertIndexAfterImportsOrDirectives(ast);
+ ast.program.body.splice(
+ insertIndex === -1 ? ast.program.body.length : insertIndex,
+ 0,
+ statement,
+ );
+};
+
+const ensureLoadFontImport = ({
+ ast,
+ font,
+ usedNames,
+}: {
+ ast: File;
+ font: GoogleFontSourceEdit;
+ usedNames: Set<string>;
+}) => {
+ const existing = getImportedLoadFontIdentifier({ast, font});
+ if (existing) {
+ return existing;
+ }
+
+ const moduleName = `@remotion/google-fonts/${font.importName}`;
+ const localName = getSafeLoadFontIdentifier({font, usedNames});
+ const specifier = b.importSpecifier(
+ b.identifier('loadFont'),
+ b.identifier(localName),
+ );
+
+ for (const statement of ast.program.body) {
+ if (
+ statement.type === 'ImportDeclaration' &&
+ statement.source.value === moduleName &&
+ !statement.specifiers?.some(
+ (existingSpecifier) =>
+ existingSpecifier.type === 'ImportNamespaceSpecifier',
+ )
+ ) {
+ statement.specifiers = [
+ ...(statement.specifiers ?? []),
+ specifier as never,
+ ];
+ return localName;
+ }
+ }
+
+ const declaration = b.importDeclaration(
+ [specifier as never],
+ b.stringLiteral(moduleName),
+ );
+ insertAfterImportsOrDirectives(ast, declaration as Statement);
+ return localName;
+};
+
+const getStringArrayObjectProperty = ({
+ node,
+ key,
+}: {
+ node: Expression;
+ key: string;
+}): string[] | null => {
+ if (node.type !== 'ObjectExpression') {
+ return null;
+ }
+
+ const property = node.properties.find((prop) => {
+ return (
+ prop.type === 'ObjectProperty' &&
+ prop.key.type === 'Identifier' &&
+ prop.key.name === key
+ );
+ });
+ if (!property || property.type !== 'ObjectProperty') {
+ return null;
+ }
+
+ if (property.value.type !== 'ArrayExpression') {
+ return null;
+ }
+
+ const values: string[] = [];
+ for (const element of property.value.elements) {
+ if (!element || element.type !== 'StringLiteral') {
+ return null;
+ }
+
+ values.push(element.value);
+ }
+
+ return values;
+};
+
+const arraysEqual = (a: readonly string[], bValues: readonly string[]) => {
+ return (
+ a.length === bValues.length &&
+ a.every((value, index) => value === bValues[index])
+ );
+};
+
+const isMatchingLoadFontCall = ({
+ statement,
+ localName,
+ font,
+}: {
+ statement: Statement;
+ localName: string;
+ font: GoogleFontSourceEdit;
+}) => {
+ if (
+ statement.type !== 'ExpressionStatement' ||
+ statement.expression.type !== 'CallExpression' ||
+ statement.expression.callee.type !== 'Identifier' ||
+ statement.expression.callee.name !== localName
+ ) {
+ return false;
+ }
+
+ const [style, options] = statement.expression.arguments;
+ if (style?.type !== 'StringLiteral' || style.value !== font.style) {
+ return false;
+ }
+
+ if (!options || options.type !== 'ObjectExpression') {
+ return false;
+ }
+
+ const weights = getStringArrayObjectProperty({node: options, key: 'weights'});
+ const subsets = getStringArrayObjectProperty({node: options, key: 'subsets'});
+
+ return (
+ weights !== null &&
+ subsets !== null &&
+ arraysEqual(weights, font.weights) &&
+ arraysEqual(subsets, font.subsets)
+ );
+};
+
+const hasTopLevelLoadFontCall = ({
+ ast,
+ localName,
+ font,
+}: {
+ ast: File;
+ localName: string;
+ font: GoogleFontSourceEdit;
+}) => {
+ return ast.program.body.some((statement) => {
+ return isMatchingLoadFontCall({statement, localName, font});
+ });
+};
+
+const getGoogleFontImportName = (moduleName: string) => {
+ const prefix = '@remotion/google-fonts/';
+ return moduleName.startsWith(prefix) ? moduleName.slice(prefix.length) : null;
+};
+
+const normalizeFontFamilyName = (fontFamily: string) => {
+ return fontFamily.toLowerCase().replace(/[^a-z0-9]/g, '');
+};
+
+const getPrimaryFontFamilyName = (fontFamily: string) => {
+ const trimmed = fontFamily.trim();
+ if (!trimmed) {
+ return null;
+ }
+
+ const quote = trimmed[0];
+ if (quote === '"' || quote === "'") {
+ const closingQuote = trimmed.indexOf(quote, 1);
+ return closingQuote === -1
+ ? trimmed.slice(1)
+ : trimmed.slice(1, closingQuote);
+ }
+
+ return trimmed.split(',')[0].trim();
+};
+
+const collectUsedFontFamilyNames = (ast: File): Set<string> => {
+ const used = new Set<string>();
+ const add = (fontFamily: string) => {
+ const primary = getPrimaryFontFamilyName(fontFamily);
+ if (primary) {
+ used.add(normalizeFontFamilyName(primary));
+ }
+ };
+
+ recast.types.visit(ast, {
+ visitObjectProperty(path) {
+ const {node} = path;
+ if (node.key.type === 'Identifier' && node.key.name === 'fontFamily') {
+ if (node.value.type === 'StringLiteral') {
+ add(node.value.value);
+ }
+
+ if (
+ node.value.type === 'TemplateLiteral' &&
+ node.value.expressions.length === 0 &&
+ node.value.quasis.length === 1
+ ) {
+ add(
+ node.value.quasis[0].value.cooked ?? node.value.quasis[0].value.raw,
+ );
+ }
+ }
+
+ this.traverse(path);
+ },
+ visitJSXAttribute(path) {
+ const {node} = path;
+ if (
+ node.name.type === 'JSXIdentifier' &&
+ node.name.name === 'fontFamily' &&
+ node.value?.type === 'StringLiteral'
+ ) {
+ add(node.value.value);
+ }
+
+ this.traverse(path);
+ },
+ });
+
+ return used;
+};
+
+const isIdentifierImportedBySpecifier = ({
+ parent,
+ name,
+}: {
+ parent: unknown;
+ name: string;
+}) => {
+ return (
+ parent !== null &&
+ typeof parent === 'object' &&
+ 'type' in parent &&
+ parent.type === 'ImportSpecifier' &&
+ 'local' in parent &&
+ parent.local !== null &&
+ typeof parent.local === 'object' &&
+ 'type' in parent.local &&
+ parent.local.type === 'Identifier' &&
+ 'name' in parent.local &&
+ parent.local.name === name
+ );
+};
+
+const hasNonImportIdentifierReference = ({
+ ast,
+ name,
+}: {
+ ast: File;
+ name: string;
+}) => {
+ let hasReference = false;
+ recast.types.visit(ast, {
+ visitIdentifier(path) {
+ if (path.node.name !== name) {
+ this.traverse(path);
+ return;
+ }
+
+ if (isIdentifierImportedBySpecifier({parent: path.parent.node, name})) {
+ this.traverse(path);
+ return;
+ }
+
+ hasReference = true;
+ return false;
+ },
+ });
+
+ return hasReference;
+};
+
+const googleFontLoadingComment =
+ 'Remotion Studio generated Google Font loading';
+
+const hasStudioGeneratedGoogleFontLoadingComment = (statement: Statement) => {
+ return (statement.leadingComments ?? []).some((comment) =>
+ comment.value.includes(googleFontLoadingComment),
+ );
+};
+
+const isTopLevelCallToIdentifier = ({
+ statement,
+ localName,
+}: {
+ statement: Statement;
+ localName: string;
+}) => {
+ return (
+ statement.type === 'ExpressionStatement' &&
+ statement.expression.type === 'CallExpression' &&
+ statement.expression.callee.type === 'Identifier' &&
+ statement.expression.callee.name === localName
+ );
+};
+
+const removeUnusedGoogleFontSourceEdits = (ast: File) => {
+ const usedFonts = collectUsedFontFamilyNames(ast);
+ const loadFontLocalNamesToRemove = new Set<string>();
+
+ for (const statement of ast.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ typeof statement.source.value !== 'string'
+ ) {
+ continue;
+ }
+
+ const importName = getGoogleFontImportName(statement.source.value);
+ if (!importName) {
+ continue;
+ }
+
+ if (usedFonts.has(normalizeFontFamilyName(importName))) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ specifier.imported.type === 'Identifier' &&
+ specifier.imported.name === 'loadFont'
+ ) {
+ loadFontLocalNamesToRemove.add(specifier.local?.name ?? 'loadFont');
+ }
+ }
+ }
+
+ if (loadFontLocalNamesToRemove.size === 0) {
+ return;
+ }
+
+ ast.program.body = ast.program.body.filter((statement) => {
+ for (const localName of loadFontLocalNamesToRemove) {
+ if (
+ isTopLevelCallToIdentifier({statement, localName}) &&
+ hasStudioGeneratedGoogleFontLoadingComment(statement)
+ ) {
+ return false;
+ }
+ }
+
+ return true;
+ });
+
+ ast.program.body = ast.program.body.filter((statement) => {
+ if (statement.type !== 'ImportDeclaration') {
+ return true;
+ }
+
+ statement.specifiers = (statement.specifiers ?? []).filter((specifier) => {
+ return !(
+ specifier.type === 'ImportSpecifier' &&
+ specifier.imported.type === 'Identifier' &&
+ specifier.imported.name === 'loadFont' &&
+ loadFontLocalNamesToRemove.has(specifier.local?.name ?? 'loadFont') &&
+ !hasNonImportIdentifierReference({
+ ast,
+ name: specifier.local?.name ?? 'loadFont',
+ })
+ );
+ });
+
+ return statement.specifiers.length > 0;
+ });
+};
+
+const insertLoadFontCall = ({
+ ast,
+ font,
+ localName,
+}: {
+ ast: File;
+ font: GoogleFontSourceEdit;
+ localName: string;
+}) => {
+ if (hasTopLevelLoadFontCall({ast, localName, font})) {
+ return;
+ }
+
+ const call = b.expressionStatement(
+ b.callExpression(b.identifier(localName), [
+ b.stringLiteral(font.style),
+ b.objectExpression([
+ b.objectProperty(
+ b.identifier('weights'),
+ b.arrayExpression(
+ font.weights.map((weight) => b.stringLiteral(weight)),
+ ),
+ ),
+ b.objectProperty(
+ b.identifier('subsets'),
+ b.arrayExpression(
+ font.subsets.map((subset) => b.stringLiteral(subset)),
+ ),
+ ),
+ ]),
+ ]),
+ );
+ call.comments = [b.commentLine(` ${googleFontLoadingComment}`)];
+
+ insertAfterImportsOrDirectives(ast, call as Statement);
+};
+
+const applyGoogleFontSourceEdits = ({
+ ast,
+ updates,
+}: {
+ ast: File;
+ updates: SequencePropUpdate[];
+}) => {
+ const fonts = new Map<string, GoogleFontSourceEdit>();
+ let hasFontFamilyUpdate = false;
+ for (const update of updates) {
+ if (update.key === 'style.fontFamily') {
+ hasFontFamilyUpdate = true;
+ }
+
+ if (update.googleFont) {
+ fonts.set(update.googleFont.importName, update.googleFont);
+ }
+ }
+
+ const usedNames = collectTopLevelIdentifierNames(ast);
+ for (const font of fonts.values()) {
+ const localName = ensureLoadFontImport({ast, font, usedNames});
+ insertLoadFontCall({ast, font, localName});
+ }
+
+ if (hasFontFamilyUpdate) {
+ removeUnusedGoogleFontSourceEdits(ast);
+ }
+};
+
+const migrateCssShorthand = ({
+ node,
+ cssShorthand,
+}: {
+ node: JSXOpeningElementLike;
+ cssShorthand: CssShorthandProperty;
+}) => {
+ const styleAttribute = node.attributes?.find(
+ (attribute) =>
+ attribute.type === 'JSXAttribute' &&
+ attribute.name.type === 'JSXIdentifier' &&
+ attribute.name.name === 'style',
+ );
+ if (
+ styleAttribute?.type !== 'JSXAttribute' ||
+ styleAttribute.value?.type !== 'JSXExpressionContainer' ||
+ styleAttribute.value.expression.type !== 'ObjectExpression'
+ ) {
+ return;
+ }
+
+ const {properties} = styleAttribute.value.expression;
+ for (let index = 0; index < properties.length; index++) {
+ const property = properties[index];
+ if (
+ property.type !== 'ObjectProperty' ||
+ !(
+ (property.key.type === 'Identifier' &&
+ property.key.name === cssShorthand.shorthand) ||
+ (property.key.type === 'StringLiteral' &&
+ property.key.value === cssShorthand.shorthand)
+ )
+ ) {
+ continue;
+ }
+
+ const shorthandValue =
+ property.value.type === 'StringLiteral'
+ ? property.value.value
+ : property.value.type === 'NumericLiteral'
+ ? property.value.value
+ : property.value.type === 'TemplateLiteral' &&
+ property.value.expressions.length === 0
+ ? (property.value.quasis[0]?.value.cooked ?? null)
+ : null;
+ if (shorthandValue === null) {
+ continue;
+ }
+
+ const parsed = cssShorthand.parse(shorthandValue);
+ if (!parsed) {
+ continue;
+ }
+
+ properties.splice(
+ index,
+ 1,
+ ...cssShorthand.longhands.map((longhand) => {
+ const value = parsed[longhand];
+ return b.objectProperty(
+ b.identifier(longhand),
+ typeof value === 'number'
+ ? b.numericLiteral(value)
+ : b.stringLiteral(value),
+ ) as ObjectProperty;
+ }),
+ );
+ index += cssShorthand.longhands.length - 1;
+ }
+};
+
+const updateSequencePropsNode = ({
+ jsxElement,
+ updates,
+ schema,
+ videoConfigValues,
+}: {
+ jsxElement: JSXElementLike;
+ updates: SequencePropUpdate[];
+ schema: InteractivitySchema;
+ videoConfigValues: VideoConfigIdentifierValues;
+}): {
+ oldValueStrings: string[];
+ logLine: number;
+ removedProps: RemovedProp[];
+} => {
+ const node = jsxElement.openingElement;
+ const logLine = node.loc?.start.line ?? 1;
+ for (const cssShorthand of getCssShorthandsForUpdates(
+ updates.map((update) => update.key),
+ )) {
+ migrateCssShorthand({node, cssShorthand});
+ }
+
+ const oldValueStrings: string[] = [];
+ const initialAttrs = snapshotTopLevelAttrs(node);
+ const updatedTopLevelKeys = new Set(
+ updates.map(({key}) => {
+ const dot = key.indexOf('.');
+ return dot === -1 ? key : key.slice(0, dot);
+ }),
+ );
+ const createValueExpression = ({
+ existing,
+ value,
+ }: {
+ existing: Expression | null;
+ value: unknown;
+ }) => {
+ if (existing === null || typeof value !== 'number') {
+ return parseValueExpression(value);
+ }
+
+ const expression = parseVideoConfigNumericExpression({
+ node: existing,
+ videoConfigValues,
+ });
+ if (expression === null) {
+ return parseValueExpression(value);
+ }
+
+ return expression.value === value
+ ? (existing as ExpressionKind)
+ : updateVideoConfigNumericExpression({expression, value});
+ };
+
+ for (const {key, value, defaultValue} of updates) {
+ let oldValueString = '';
+
+ if (key === 'children') {
+ oldValueString = updateJsxTextContent({jsxElement, value});
+ oldValueStrings.push(oldValueString);
+ continue;
+ }
+
+ const isDefault =
+ (defaultValue === null && value === undefined) ||
+ (defaultValue !== null &&
+ JSON.stringify(value) === JSON.stringify(defaultValue));
+
+ const dotIndex = key.indexOf('.');
+ const isNested = dotIndex !== -1;
+ const parentKey = isNested ? key.slice(0, dotIndex) : key;
+ const childKey = isNested ? key.slice(dotIndex + 1) : '';
+
+ if (isNested) {
+ oldValueString = updateNestedProp({
+ node,
+ parentKey,
+ childKey,
+ value,
+ defaultValue,
+ isDefault,
+ createValueExpression: (existing) =>
+ createValueExpression({existing, value}),
+ });
+ } else {
+ const attrIndex = node.attributes?.findIndex((a) => {
+ if (a.type === 'JSXSpreadAttribute') {
+ return false;
+ }
+
+ if (a.name.type === 'JSXNamespacedName') {
+ return false;
+ }
+
+ return a.name.name === key;
+ });
+
+ const attr =
+ attrIndex !== undefined && attrIndex !== -1
+ ? node.attributes?.[attrIndex]
+ : undefined;
+
+ if (attr && attr.type !== 'JSXSpreadAttribute' && attr.value) {
+ const printed = recast.print(attr.value).code;
+ // Strip JSX expression container braces, e.g. "{30}" -> "30"
+ oldValueString =
+ printed.startsWith('{') && printed.endsWith('}')
+ ? printed.slice(1, -1)
+ : printed;
+ } else if (attr && attr.type !== 'JSXSpreadAttribute' && !attr.value) {
+ // JSX shorthand like `loop` (no value) is implicitly `true`
+ oldValueString = 'true';
+ } else if (!attr && defaultValue !== null) {
+ oldValueString = JSON.stringify(defaultValue);
+ }
+
+ if (isDefault) {
+ if (attr && attr.type !== 'JSXSpreadAttribute' && node.attributes) {
+ node.attributes.splice(attrIndex!, 1);
+ }
+ } else {
+ const existingExpression =
+ attr?.type === 'JSXAttribute' &&
+ attr.value?.type === 'JSXExpressionContainer' &&
+ attr.value.expression.type !== 'JSXEmptyExpression'
+ ? (attr.value.expression as Expression)
+ : null;
+ const parsed = createValueExpression({
+ existing: existingExpression,
+ value,
+ });
+
+ const newValue =
+ value === true ? null : b.jsxExpressionContainer(parsed);
+
+ if (!attr || attr.type === 'JSXSpreadAttribute') {
+ const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);
+
+ if (!node.attributes) {
+ node.attributes = [];
+ }
+
+ node.attributes.push(newAttr as JSXAttribute | JSXSpreadAttribute);
+ } else {
+ attr.value = newValue as
+ | JSXElement
+ | JSXExpressionContainer
+ | JSXFragment
+ | StringLiteral
+ | null
+ | undefined;
+ }
+ }
+ }
+
+ oldValueStrings.push(oldValueString);
+
+ if (!isNested) {
+ const fieldSchema = schema[key];
+ if (fieldSchema && fieldSchema.type === 'enum') {
+ const propsToDelete = NoReactInternals.findPropsToDelete({
+ schema,
+ key,
+ value,
+ });
+ for (const propToDelete of propsToDelete) {
+ removeVariantKey({node, variantKey: propToDelete});
+ }
+ }
+ }
+ }
+
+ const finalAttrNames = new Set<string>();
+ for (const a of node.attributes ?? []) {
+ if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier') {
+ finalAttrNames.add(a.name.name);
+ }
+ }
+
+ const removedProps: RemovedProp[] = [];
+ for (const [name, valueString] of initialAttrs) {
+ if (finalAttrNames.has(name) || updatedTopLevelKeys.has(name)) {
+ continue;
+ }
+
+ removedProps.push({key: name, valueString});
+ }
+
+ return {
+ oldValueStrings,
+ logLine,
+ removedProps,
+ };
+};
+
+export const updateSequencePropsAst = ({
+ input,
+ nodePath,
+ updates,
+ schema,
+ videoConfigValues,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+ updates: SequencePropUpdate[];
+ schema: InteractivitySchema;
+ videoConfigValues: VideoConfigValues | null;
+}): {
+ serialized: string;
+ oldValueStrings: string[];
+ logLine: number;
+ removedProps: RemovedProp[];
+} => {
+ const ast = parseAst(input);
+ const videoConfigIdentifierValues = getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ });
+
+ const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
+ if (!jsxElement) {
+ throw new Error(
+ 'Could not find a JSX element at the specified line to update',
+ );
+ }
+
+ const {oldValueStrings, logLine, removedProps} = updateSequencePropsNode({
+ jsxElement,
+ updates,
+ schema,
+ videoConfigValues: videoConfigIdentifierValues,
+ });
+ ensureImportsForUpdates({ast, updates});
+ applyGoogleFontSourceEdits({ast, updates});
+
+ return {
+ serialized: serializeAst(ast),
+ oldValueStrings,
+ logLine,
+ removedProps,
+ };
+};
+
+export const updateMultipleSequenceProps = ({
+ input,
+ changes,
+}: {
+ input: string;
+ changes: SequencePropsNodeUpdate[];
+}): UpdateMultipleSequencePropsResult => {
+ const ast = parseAst(input);
+ const allUpdates: SequencePropUpdate[] = [];
+ const results = changes.map(
+ ({nodePath, updates, schema, videoConfigValues}) => {
+ const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
+ if (!jsxElement) {
+ throw new Error(
+ 'Could not find a JSX element at the specified line to update',
+ );
+ }
+
+ allUpdates.push(...updates);
+ return updateSequencePropsNode({
+ jsxElement,
+ updates,
+ schema,
+ videoConfigValues: getVideoConfigIdentifierValues({
+ ast,
+ videoConfigValues,
+ }),
+ });
+ },
+ );
+ ensureImportsForUpdates({ast, updates: allUpdates});
+ applyGoogleFontSourceEdits({ast, updates: allUpdates});
+
+ return {
+ output: serializeAst(ast),
+ results,
+ };
+};
diff --git a/packages/studio-server/src/codemods/update-inline-caption-patches.ts b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
index e33d8ef9c7..414559c532 100644
--- a/packages/studio-server/src/codemods/update-inline-caption-patches.ts
+++ b/packages/studio-server/src/codemods/update-inline-caption-patches.ts
@@ -1,280 +1 @@
-import type {Expression, ObjectExpression, ObjectProperty} from '@babel/types';
-import type {CaptionPatch} from '@remotion/studio-shared';
-import type {SequenceNodePath} from 'remotion';
-import {findJsxElementNodeAtNodePath} from '../preview-server/routes/can-update-sequence-props';
-import {parseAst} from './parse-ast';
-
-const captionKeys = [
- 'text',
- 'startMs',
- 'endMs',
- 'timestampMs',
- 'confidence',
-] as const;
-
-type CaptionKey = (typeof captionKeys)[number];
-type StaticCaption = CaptionPatch['before'];
-
-const getPropertyKey = (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 getStaticValue = (value: Expression): string | number | null => {
- if (value.type === 'StringLiteral' || value.type === 'NumericLiteral') {
- return value.value;
- }
-
- if (value.type === 'NullLiteral') {
- return null;
- }
-
- throw new Error('Captions must use static literal values to be edited');
-};
-
-const getStaticCaption = (expression: ObjectExpression): StaticCaption => {
- const values = new Map<string, string | number | null>();
- for (const property of expression.properties) {
- if (property.type !== 'ObjectProperty' || property.computed) {
- throw new Error(
- 'Captions must use static object properties to be edited',
- );
- }
-
- const key = getPropertyKey(property);
- if (key !== null && captionKeys.includes(key as CaptionKey)) {
- values.set(key, getStaticValue(property.value as Expression));
- }
- }
-
- const text = values.get('text');
- const startMs = values.get('startMs');
- const endMs = values.get('endMs');
- const timestampMs = values.get('timestampMs');
- const confidence = values.get('confidence');
- if (
- typeof text !== 'string' ||
- typeof startMs !== 'number' ||
- typeof endMs !== 'number' ||
- (timestampMs !== null && typeof timestampMs !== 'number') ||
- (confidence !== null && typeof confidence !== 'number')
- ) {
- throw new Error(
- 'Captions must have the standard static caption shape to edit',
- );
- }
-
- return {text, startMs, endMs, timestampMs, confidence};
-};
-
-const isCaptionKey = (key: string): key is CaptionKey =>
- captionKeys.includes(key as CaptionKey);
-
-const getReplacementValue = ({
- value,
- previous,
-}: {
- value: string | number | null;
- previous: Expression;
-}): string => {
- if (value === null || typeof value === 'number') {
- return String(value);
- }
-
- if (
- previous.type === 'StringLiteral' &&
- typeof previous.extra?.raw === 'string' &&
- previous.extra.raw.startsWith("'")
- ) {
- return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
- }
-
- return JSON.stringify(value);
-};
-
-const getSourceValueRange = ({
- input,
- property,
- key,
-}: {
- input: string;
- property: ObjectProperty;
- key: string;
-}): {start: number; end: number} => {
- const line = property.loc?.start.line;
- if (line === null || line === undefined) {
- throw new Error(`Could not locate caption ${key} in the source file`);
- }
-
- const lines = input.split('\n');
- const lineStart = lines
- .slice(0, line - 1)
- .reduce((length, current) => length + current.length + 1, 0);
- const sourceLine = lines[line - 1];
- if (sourceLine === undefined) {
- throw new Error(`Could not locate caption ${key} in the source file`);
- }
-
- const keyStart = sourceLine.indexOf(key);
- const valueStart = sourceLine.indexOf(':', keyStart) + 1;
- const rawValue: string =
- property.value.type === 'StringLiteral' &&
- typeof property.value.extra?.raw === 'string'
- ? property.value.extra.raw
- : property.value.type === 'StringLiteral'
- ? JSON.stringify(property.value.value)
- : String(getStaticValue(property.value as Expression));
- const valueOffset = sourceLine.indexOf(rawValue, valueStart);
- if (keyStart === -1 || valueOffset === -1) {
- throw new Error(`Could not locate caption ${key} in the source file`);
- }
-
- return {
- start: lineStart + valueOffset,
- end: lineStart + valueOffset + rawValue.length,
- };
-};
-
-const updateCaption = ({
- input,
- caption,
- patch,
-}: {
- input: string;
- caption: ObjectExpression;
- patch: CaptionPatch;
-}): {changedFields: string[]; replacements: SourceReplacement[]} => {
- const current = getStaticCaption(caption);
- if (!captionKeys.every((key) => current[key] === patch.before[key])) {
- throw new Error(
- `Caption ${patch.index} changed in the source file before this edit could be saved`,
- );
- }
-
- const changedKeys = Object.keys(patch.changes);
- if (changedKeys.length === 0 || !changedKeys.every(isCaptionKey)) {
- throw new Error('Caption patches must change at least one caption field');
- }
-
- const replacements: SourceReplacement[] = [];
- for (const key of changedKeys) {
- const value = patch.changes[key];
- if (
- (key === 'text' && typeof value !== 'string') ||
- ((key === 'startMs' || key === 'endMs') &&
- (typeof value !== 'number' || !Number.isFinite(value))) ||
- ((key === 'timestampMs' || key === 'confidence') &&
- value !== null &&
- (typeof value !== 'number' || !Number.isFinite(value)))
- ) {
- throw new Error(`Caption ${key} has an invalid value`);
- }
-
- const property = caption.properties.find((candidate) => {
- return (
- candidate.type === 'ObjectProperty' &&
- !candidate.computed &&
- getPropertyKey(candidate) === key
- );
- });
- if (!property || property.type !== 'ObjectProperty') {
- throw new Error(`Caption ${patch.index} is missing ${key}`);
- }
-
- const {start, end} = getSourceValueRange({input, property, key});
- replacements.push({
- start,
- end,
- value: getReplacementValue({
- value: value as string | number | null,
- previous: property.value as Expression,
- }),
- });
- }
-
- return {changedFields: changedKeys, replacements};
-};
-
-type SourceReplacement = {
- start: number;
- end: number;
- value: string;
-};
-
-export const updateInlineCaptionPatches = ({
- input,
- nodePath,
- patches,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- patches: CaptionPatch[];
-}): {output: string; logLine: number; changedFields: string[][]} => {
- if (patches.length === 0) {
- throw new Error('Expected at least one caption patch');
- }
-
- const ast = parseAst(input);
- const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
- if (!jsxElement) {
- throw new Error(
- 'Could not find a JSX element at the specified line to update',
- );
- }
-
- const captionsAttribute = jsxElement.openingElement.attributes?.find(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'captions',
- );
- if (
- !captionsAttribute ||
- captionsAttribute.type !== 'JSXAttribute' ||
- captionsAttribute.value?.type !== 'JSXExpressionContainer' ||
- captionsAttribute.value.expression.type !== 'ArrayExpression'
- ) {
- throw new Error('Captions must be an inline JSX array to edit them');
- }
-
- const captions = captionsAttribute.value.expression.elements;
- const changedFields: string[][] = [];
- const replacements: SourceReplacement[] = [];
- for (const patch of patches) {
- if (!Number.isInteger(patch.index) || patch.index < 0) {
- throw new Error('Caption patch index must be a non-negative integer');
- }
-
- const caption = captions[patch.index];
- if (!caption || caption.type !== 'ObjectExpression') {
- throw new Error(`Could not find inline caption ${patch.index}`);
- }
-
- const result = updateCaption({input, caption, patch});
- changedFields.push(result.changedFields);
- replacements.push(...result.replacements);
- }
-
- const output = replacements
- .sort((a, b) => b.start - a.start)
- .reduce(
- (current, replacement) =>
- current.slice(0, replacement.start) +
- replacement.value +
- current.slice(replacement.end),
- input,
- );
-
- return {
- output,
- logLine: jsxElement.openingElement.loc?.start.line ?? 1,
- changedFields,
- };
-};
+export {updateInlineCaptionPatches} from '@remotion/studio-codemods';
diff --git a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
index 7a22894663..69054c708b 100644
--- a/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
+++ b/packages/studio-server/src/codemods/update-sequence-props/update-sequence-props.ts
@@ -1,96 +1,24 @@
-import type {
- JSXAttribute,
- JSXElement,
- JSXExpressionContainer,
- JSXFragment,
- JSXSpreadAttribute,
- ObjectProperty,
- StringLiteral,
- Expression,
- File,
- Statement,
-} from '@babel/types';
-import type {GoogleFontSourceEdit} from '@remotion/studio-shared';
-import type {ExpressionKind} from 'ast-types/lib/gen/kinds';
-import * as recast from 'recast';
+import {
+ type RemovedProp,
+ type SequencePropsNodeUpdate,
+ type SequencePropsNodeUpdateResult,
+ type SequencePropUpdate,
+ updateMultipleSequenceProps as updateMultipleSequencePropsUnformatted,
+ updateSequencePropsAst,
+} from '@remotion/studio-codemods';
import type {
InteractivitySchema,
SequenceNodePath,
VideoConfigValues,
} from 'remotion';
-import {NoReactInternals} from 'remotion/no-react';
-import {
- getCssShorthandsForUpdates,
- type CssShorthandProperty,
-} from '../../helpers/css-shorthand-properties';
-import {ensureNamedImports} from '../../helpers/imports';
-import {
- parseVideoConfigNumericExpression,
- updateVideoConfigNumericExpression,
-} from '../../helpers/video-config-numeric-expression';
-import {
- getVideoConfigIdentifierValues,
- type VideoConfigIdentifierValues,
-} from '../../helpers/video-config-values';
-import {
- findJsxElementNodeAtNodePath,
- getStaticJsxChildrenAttribute,
- getStaticJsxTextContent,
- hasJsxChildrenAttribute,
-} from '../../preview-server/routes/can-update-sequence-props';
import {formatFileContent} from '../format-file-content';
-import {parseAst, serializeAst} from '../parse-ast';
-import {parseValueExpression, updateNestedProp} from '../update-nested-prop';
-
-const b = recast.types.builders;
-
-export type SequencePropUpdate = {
- key: string;
- value: unknown;
- defaultValue: unknown | null;
- googleFont?: GoogleFontSourceEdit | null;
-};
-
-const ensureImportsForUpdates = ({
- ast,
- updates,
-}: {
- ast: File;
- updates: SequencePropUpdate[];
-}) => {
- if (
- updates.some(
- ({value, defaultValue}) =>
- typeof value === 'string' &&
- value.startsWith(NoReactInternals.FILE_TOKEN) &&
- (defaultValue === null ||
- JSON.stringify(value) !== JSON.stringify(defaultValue)),
- )
- ) {
- ensureNamedImports({
- ast,
- importedNames: new Set(['staticFile']),
- sourcePath: 'remotion',
- });
- }
-};
-export type RemovedProp = {
- key: string;
- valueString: string;
-};
-
-export type SequencePropsNodeUpdate = {
- nodePath: SequenceNodePath;
- updates: SequencePropUpdate[];
- schema: InteractivitySchema;
- videoConfigValues: VideoConfigValues | null;
-};
-
-export type SequencePropsNodeUpdateResult = {
- oldValueStrings: string[];
- logLine: number;
- removedProps: RemovedProp[];
+export {
+ type RemovedProp,
+ type SequencePropsNodeUpdate,
+ type SequencePropsNodeUpdateResult,
+ type SequencePropUpdate,
+ updateSequencePropsAst,
};
type PrettierConfigOverride = Record<string, unknown> | null;
@@ -109,990 +37,6 @@ type UpdateSequencePropsResult = {
removedProps: RemovedProp[];
};
-const removeVariantKey = ({
- node,
- variantKey,
-}: {
- node: JSXOpeningElementLike;
- variantKey: string;
-}) => {
- const dotIndex = variantKey.indexOf('.');
- if (dotIndex === -1) {
- const idx = node.attributes?.findIndex(
- (a) =>
- a.type === 'JSXAttribute' &&
- a.name.type === 'JSXIdentifier' &&
- a.name.name === variantKey,
- );
- if (idx !== undefined && idx !== -1 && node.attributes) {
- node.attributes.splice(idx, 1);
- }
-
- return;
- }
-
- updateNestedProp({
- node,
- parentKey: variantKey.slice(0, dotIndex),
- childKey: variantKey.slice(dotIndex + 1),
- value: undefined,
- defaultValue: null,
- isDefault: true,
- createValueExpression: null,
- });
-};
-
-const snapshotTopLevelAttrs = (
- node: JSXOpeningElementLike,
-): Map<string, string> => {
- const result = new Map<string, string>();
- for (const a of node.attributes ?? []) {
- if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier') {
- const {name} = a.name;
- const printed = recast
- .print(a)
- .code.replace(/\s+/g, ' ')
- .replace(/,(\s*[}\]])/g, '$1')
- .trim();
-
- const prefix = `${name}=`;
- let valueOnly = printed.startsWith(prefix)
- ? printed.slice(prefix.length)
- : printed;
- if (valueOnly.startsWith('{') && valueOnly.endsWith('}')) {
- valueOnly = valueOnly.slice(1, -1).trim();
- }
-
- result.set(name, valueOnly);
- }
- }
-
- return result;
-};
-
-type JSXElementLike = NonNullable<
- ReturnType<typeof findJsxElementNodeAtNodePath>
->;
-type JSXOpeningElementLike = JSXElementLike['openingElement'];
-
-const escapeJsxText = (value: string): string => {
- return value
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/{/g, '&#123;')
- .replace(/}/g, '&#125;');
-};
-
-const findChildrenAttribute = (
- node: JSXOpeningElementLike,
-): JSXAttribute | undefined => {
- return node.attributes?.find((attr) => {
- return (
- attr.type === 'JSXAttribute' &&
- attr.name.type === 'JSXIdentifier' &&
- attr.name.name === 'children'
- );
- }) as JSXAttribute | undefined;
-};
-
-const updateJsxTextContent = ({
- jsxElement,
- value,
-}: {
- jsxElement: JSXElementLike;
- value: unknown;
-}): string => {
- const nextValue = String(value ?? '');
- const staticChildrenAttribute = getStaticJsxChildrenAttribute(
- jsxElement.openingElement,
- );
- if (staticChildrenAttribute) {
- const childrenAttribute = findChildrenAttribute(jsxElement.openingElement);
- if (!childrenAttribute) {
- throw new Error('Expected static children attribute to exist');
- }
-
- childrenAttribute.value = b.stringLiteral(nextValue) as StringLiteral;
- return staticChildrenAttribute.value;
- }
-
- if (hasJsxChildrenAttribute(jsxElement.openingElement)) {
- throw new Error(
- 'Cannot update text content because the children attribute is not static text',
- );
- }
-
- const staticTextContent = getStaticJsxTextContent(jsxElement);
- if (!staticTextContent) {
- throw new Error(
- 'Cannot update text content because JSX children are not static text',
- );
- }
-
- const canRepresentAsJsxText =
- staticTextContent.kind === 'jsx-text' &&
- !nextValue.includes('\n') &&
- nextValue.trim() === nextValue;
- if (canRepresentAsJsxText) {
- jsxElement.children = [
- b.jsxText(escapeJsxText(nextValue)),
- ] as unknown as JSXElementLike['children'];
- } else {
- jsxElement.children = [
- b.jsxExpressionContainer(b.stringLiteral(nextValue)),
- ] as unknown as JSXElementLike['children'];
- }
-
- return staticTextContent.value;
-};
-
-const collectTopLevelIdentifierNames = (ast: File): Set<string> => {
- const names = new Set<string>();
- recast.types.visit(ast, {
- visitIdentifier(path) {
- names.add(path.node.name);
- this.traverse(path);
- },
- });
-
- return names;
-};
-
-const toSafeIdentifier = (value: string) => {
- const sanitized = value.replace(/[^a-zA-Z0-9_$]/g, '');
- if (!sanitized) {
- return 'loadGoogleFont';
- }
-
- return /^[a-zA-Z_$]/.test(sanitized) ? sanitized : `_${sanitized}`;
-};
-
-const getSafeLoadFontIdentifier = ({
- font,
- usedNames,
-}: {
- font: GoogleFontSourceEdit;
- usedNames: Set<string>;
-}) => {
- const baseName = toSafeIdentifier(`load${font.importName}`);
- if (!usedNames.has(baseName)) {
- usedNames.add(baseName);
- return baseName;
- }
-
- let index = 2;
- while (usedNames.has(`${baseName}${index}`)) {
- index++;
- }
-
- const name = `${baseName}${index}`;
- usedNames.add(name);
- return name;
-};
-
-const getImportedLoadFontIdentifier = ({
- ast,
- font,
-}: {
- ast: File;
- font: GoogleFontSourceEdit;
-}): string | null => {
- const moduleName = `@remotion/google-fonts/${font.importName}`;
- for (const statement of ast.program.body) {
- if (
- statement.type !== 'ImportDeclaration' ||
- statement.source.value !== moduleName
- ) {
- continue;
- }
-
- for (const specifier of statement.specifiers ?? []) {
- if (
- specifier.type === 'ImportSpecifier' &&
- specifier.imported.type === 'Identifier' &&
- specifier.imported.name === 'loadFont'
- ) {
- return specifier.local?.name ?? 'loadFont';
- }
- }
- }
-
- return null;
-};
-
-const getInsertIndexAfterImportsOrDirectives = (ast: File) => {
- const lastImportIndex = ast.program.body.reduce(
- (lastIndex, statement, index) => {
- return statement.type === 'ImportDeclaration' ? index : lastIndex;
- },
- -1,
- );
- if (lastImportIndex !== -1) {
- return lastImportIndex + 1;
- }
-
- return ast.program.body.findIndex((statement) => {
- return !(
- statement.type === 'ExpressionStatement' &&
- 'directive' in statement &&
- statement.directive
- );
- });
-};
-
-const insertAfterImportsOrDirectives = (ast: File, statement: Statement) => {
- const insertIndex = getInsertIndexAfterImportsOrDirectives(ast);
- ast.program.body.splice(
- insertIndex === -1 ? ast.program.body.length : insertIndex,
- 0,
- statement,
- );
-};
-
-const ensureLoadFontImport = ({
- ast,
- font,
- usedNames,
-}: {
- ast: File;
- font: GoogleFontSourceEdit;
- usedNames: Set<string>;
-}) => {
- const existing = getImportedLoadFontIdentifier({ast, font});
- if (existing) {
- return existing;
- }
-
- const moduleName = `@remotion/google-fonts/${font.importName}`;
- const localName = getSafeLoadFontIdentifier({font, usedNames});
- const specifier = b.importSpecifier(
- b.identifier('loadFont'),
- b.identifier(localName),
- );
-
- for (const statement of ast.program.body) {
- if (
- statement.type === 'ImportDeclaration' &&
- statement.source.value === moduleName &&
- !statement.specifiers?.some(
- (existingSpecifier) =>
- existingSpecifier.type === 'ImportNamespaceSpecifier',
- )
- ) {
- statement.specifiers = [
- ...(statement.specifiers ?? []),
- specifier as never,
- ];
- return localName;
- }
- }
-
- const declaration = b.importDeclaration(
- [specifier as never],
- b.stringLiteral(moduleName),
- );
- insertAfterImportsOrDirectives(ast, declaration as Statement);
- return localName;
-};
-
-const getStringArrayObjectProperty = ({
- node,
- key,
-}: {
- node: Expression;
- key: string;
-}): string[] | null => {
- if (node.type !== 'ObjectExpression') {
- return null;
- }
-
- const property = node.properties.find((prop) => {
- return (
- prop.type === 'ObjectProperty' &&
- prop.key.type === 'Identifier' &&
- prop.key.name === key
- );
- });
- if (!property || property.type !== 'ObjectProperty') {
- return null;
- }
-
- if (property.value.type !== 'ArrayExpression') {
- return null;
- }
-
- const values: string[] = [];
- for (const element of property.value.elements) {
- if (!element || element.type !== 'StringLiteral') {
- return null;
- }
-
- values.push(element.value);
- }
-
- return values;
-};
-
-const arraysEqual = (a: readonly string[], bValues: readonly string[]) => {
- return (
- a.length === bValues.length &&
- a.every((value, index) => value === bValues[index])
- );
-};
-
-const isMatchingLoadFontCall = ({
- statement,
- localName,
- font,
-}: {
- statement: Statement;
- localName: string;
- font: GoogleFontSourceEdit;
-}) => {
- if (
- statement.type !== 'ExpressionStatement' ||
- statement.expression.type !== 'CallExpression' ||
- statement.expression.callee.type !== 'Identifier' ||
- statement.expression.callee.name !== localName
- ) {
- return false;
- }
-
- const [style, options] = statement.expression.arguments;
- if (style?.type !== 'StringLiteral' || style.value !== font.style) {
- return false;
- }
-
- if (!options || options.type !== 'ObjectExpression') {
- return false;
- }
-
- const weights = getStringArrayObjectProperty({node: options, key: 'weights'});
- const subsets = getStringArrayObjectProperty({node: options, key: 'subsets'});
-
- return (
- weights !== null &&
- subsets !== null &&
- arraysEqual(weights, font.weights) &&
- arraysEqual(subsets, font.subsets)
- );
-};
-
-const hasTopLevelLoadFontCall = ({
- ast,
- localName,
- font,
-}: {
- ast: File;
- localName: string;
- font: GoogleFontSourceEdit;
-}) => {
- return ast.program.body.some((statement) => {
- return isMatchingLoadFontCall({statement, localName, font});
- });
-};
-
-const getGoogleFontImportName = (moduleName: string) => {
- const prefix = '@remotion/google-fonts/';
- return moduleName.startsWith(prefix) ? moduleName.slice(prefix.length) : null;
-};
-
-const normalizeFontFamilyName = (fontFamily: string) => {
- return fontFamily.toLowerCase().replace(/[^a-z0-9]/g, '');
-};
-
-const getPrimaryFontFamilyName = (fontFamily: string) => {
- const trimmed = fontFamily.trim();
- if (!trimmed) {
- return null;
- }
-
- const quote = trimmed[0];
- if (quote === '"' || quote === "'") {
- const closingQuote = trimmed.indexOf(quote, 1);
- return closingQuote === -1
- ? trimmed.slice(1)
- : trimmed.slice(1, closingQuote);
- }
-
- return trimmed.split(',')[0].trim();
-};
-
-const collectUsedFontFamilyNames = (ast: File): Set<string> => {
- const used = new Set<string>();
- const add = (fontFamily: string) => {
- const primary = getPrimaryFontFamilyName(fontFamily);
- if (primary) {
- used.add(normalizeFontFamilyName(primary));
- }
- };
-
- recast.types.visit(ast, {
- visitObjectProperty(path) {
- const {node} = path;
- if (node.key.type === 'Identifier' && node.key.name === 'fontFamily') {
- if (node.value.type === 'StringLiteral') {
- add(node.value.value);
- }
-
- if (
- node.value.type === 'TemplateLiteral' &&
- node.value.expressions.length === 0 &&
- node.value.quasis.length === 1
- ) {
- add(
- node.value.quasis[0].value.cooked ?? node.value.quasis[0].value.raw,
- );
- }
- }
-
- this.traverse(path);
- },
- visitJSXAttribute(path) {
- const {node} = path;
- if (
- node.name.type === 'JSXIdentifier' &&
- node.name.name === 'fontFamily' &&
- node.value?.type === 'StringLiteral'
- ) {
- add(node.value.value);
- }
-
- this.traverse(path);
- },
- });
-
- return used;
-};
-
-const isIdentifierImportedBySpecifier = ({
- parent,
- name,
-}: {
- parent: unknown;
- name: string;
-}) => {
- return (
- parent !== null &&
- typeof parent === 'object' &&
- 'type' in parent &&
- parent.type === 'ImportSpecifier' &&
- 'local' in parent &&
- parent.local !== null &&
- typeof parent.local === 'object' &&
- 'type' in parent.local &&
- parent.local.type === 'Identifier' &&
- 'name' in parent.local &&
- parent.local.name === name
- );
-};
-
-const hasNonImportIdentifierReference = ({
- ast,
- name,
-}: {
- ast: File;
- name: string;
-}) => {
- let hasReference = false;
- recast.types.visit(ast, {
- visitIdentifier(path) {
- if (path.node.name !== name) {
- this.traverse(path);
- return;
- }
-
- if (isIdentifierImportedBySpecifier({parent: path.parent.node, name})) {
- this.traverse(path);
- return;
- }
-
- hasReference = true;
- return false;
- },
- });
-
- return hasReference;
-};
-
-const googleFontLoadingComment =
- 'Remotion Studio generated Google Font loading';
-
-const hasStudioGeneratedGoogleFontLoadingComment = (statement: Statement) => {
- return (statement.leadingComments ?? []).some((comment) =>
- comment.value.includes(googleFontLoadingComment),
- );
-};
-
-const isTopLevelCallToIdentifier = ({
- statement,
- localName,
-}: {
- statement: Statement;
- localName: string;
-}) => {
- return (
- statement.type === 'ExpressionStatement' &&
- statement.expression.type === 'CallExpression' &&
- statement.expression.callee.type === 'Identifier' &&
- statement.expression.callee.name === localName
- );
-};
-
-const removeUnusedGoogleFontSourceEdits = (ast: File) => {
- const usedFonts = collectUsedFontFamilyNames(ast);
- const loadFontLocalNamesToRemove = new Set<string>();
-
- for (const statement of ast.program.body) {
- if (
- statement.type !== 'ImportDeclaration' ||
- typeof statement.source.value !== 'string'
- ) {
- continue;
- }
-
- const importName = getGoogleFontImportName(statement.source.value);
- if (!importName) {
- continue;
- }
-
- if (usedFonts.has(normalizeFontFamilyName(importName))) {
- continue;
- }
-
- for (const specifier of statement.specifiers ?? []) {
- if (
- specifier.type === 'ImportSpecifier' &&
- specifier.imported.type === 'Identifier' &&
- specifier.imported.name === 'loadFont'
- ) {
- loadFontLocalNamesToRemove.add(specifier.local?.name ?? 'loadFont');
- }
- }
- }
-
- if (loadFontLocalNamesToRemove.size === 0) {
- return;
- }
-
- ast.program.body = ast.program.body.filter((statement) => {
- for (const localName of loadFontLocalNamesToRemove) {
- if (
- isTopLevelCallToIdentifier({statement, localName}) &&
- hasStudioGeneratedGoogleFontLoadingComment(statement)
- ) {
- return false;
- }
- }
-
- return true;
- });
-
- ast.program.body = ast.program.body.filter((statement) => {
- if (statement.type !== 'ImportDeclaration') {
- return true;
- }
-
- statement.specifiers = (statement.specifiers ?? []).filter((specifier) => {
- return !(
- specifier.type === 'ImportSpecifier' &&
- specifier.imported.type === 'Identifier' &&
- specifier.imported.name === 'loadFont' &&
- loadFontLocalNamesToRemove.has(specifier.local?.name ?? 'loadFont') &&
- !hasNonImportIdentifierReference({
- ast,
- name: specifier.local?.name ?? 'loadFont',
- })
- );
- });
-
- return statement.specifiers.length > 0;
- });
-};
-
-const insertLoadFontCall = ({
- ast,
- font,
- localName,
-}: {
- ast: File;
- font: GoogleFontSourceEdit;
- localName: string;
-}) => {
- if (hasTopLevelLoadFontCall({ast, localName, font})) {
- return;
- }
-
- const call = b.expressionStatement(
- b.callExpression(b.identifier(localName), [
- b.stringLiteral(font.style),
- b.objectExpression([
- b.objectProperty(
- b.identifier('weights'),
- b.arrayExpression(
- font.weights.map((weight) => b.stringLiteral(weight)),
- ),
- ),
- b.objectProperty(
- b.identifier('subsets'),
- b.arrayExpression(
- font.subsets.map((subset) => b.stringLiteral(subset)),
- ),
- ),
- ]),
- ]),
- );
- call.comments = [b.commentLine(` ${googleFontLoadingComment}`)];
-
- insertAfterImportsOrDirectives(ast, call as Statement);
-};
-
-const applyGoogleFontSourceEdits = ({
- ast,
- updates,
-}: {
- ast: File;
- updates: SequencePropUpdate[];
-}) => {
- const fonts = new Map<string, GoogleFontSourceEdit>();
- let hasFontFamilyUpdate = false;
- for (const update of updates) {
- if (update.key === 'style.fontFamily') {
- hasFontFamilyUpdate = true;
- }
-
- if (update.googleFont) {
- fonts.set(update.googleFont.importName, update.googleFont);
- }
- }
-
- const usedNames = collectTopLevelIdentifierNames(ast);
- for (const font of fonts.values()) {
- const localName = ensureLoadFontImport({ast, font, usedNames});
- insertLoadFontCall({ast, font, localName});
- }
-
- if (hasFontFamilyUpdate) {
- removeUnusedGoogleFontSourceEdits(ast);
- }
-};
-
-const migrateCssShorthand = ({
- node,
- cssShorthand,
-}: {
- node: JSXOpeningElementLike;
- cssShorthand: CssShorthandProperty;
-}) => {
- const styleAttribute = node.attributes?.find(
- (attribute) =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'style',
- );
- if (
- styleAttribute?.type !== 'JSXAttribute' ||
- styleAttribute.value?.type !== 'JSXExpressionContainer' ||
- styleAttribute.value.expression.type !== 'ObjectExpression'
- ) {
- return;
- }
-
- const {properties} = styleAttribute.value.expression;
- for (let index = 0; index < properties.length; index++) {
- const property = properties[index];
- if (
- property.type !== 'ObjectProperty' ||
- !(
- (property.key.type === 'Identifier' &&
- property.key.name === cssShorthand.shorthand) ||
- (property.key.type === 'StringLiteral' &&
- property.key.value === cssShorthand.shorthand)
- )
- ) {
- continue;
- }
-
- const shorthandValue =
- property.value.type === 'StringLiteral'
- ? property.value.value
- : property.value.type === 'NumericLiteral'
- ? property.value.value
- : property.value.type === 'TemplateLiteral' &&
- property.value.expressions.length === 0
- ? (property.value.quasis[0]?.value.cooked ?? null)
- : null;
- if (shorthandValue === null) {
- continue;
- }
-
- const parsed = cssShorthand.parse(shorthandValue);
- if (!parsed) {
- continue;
- }
-
- properties.splice(
- index,
- 1,
- ...cssShorthand.longhands.map((longhand) => {
- const value = parsed[longhand];
- return b.objectProperty(
- b.identifier(longhand),
- typeof value === 'number'
- ? b.numericLiteral(value)
- : b.stringLiteral(value),
- ) as ObjectProperty;
- }),
- );
- index += cssShorthand.longhands.length - 1;
- }
-};
-
-const updateSequencePropsNode = ({
- jsxElement,
- updates,
- schema,
- videoConfigValues,
-}: {
- jsxElement: JSXElementLike;
- updates: SequencePropUpdate[];
- schema: InteractivitySchema;
- videoConfigValues: VideoConfigIdentifierValues;
-}): {
- oldValueStrings: string[];
- logLine: number;
- removedProps: RemovedProp[];
-} => {
- const node = jsxElement.openingElement;
- const logLine = node.loc?.start.line ?? 1;
- for (const cssShorthand of getCssShorthandsForUpdates(
- updates.map((update) => update.key),
- )) {
- migrateCssShorthand({node, cssShorthand});
- }
-
- const oldValueStrings: string[] = [];
- const initialAttrs = snapshotTopLevelAttrs(node);
- const updatedTopLevelKeys = new Set(
- updates.map(({key}) => {
- const dot = key.indexOf('.');
- return dot === -1 ? key : key.slice(0, dot);
- }),
- );
- const createValueExpression = ({
- existing,
- value,
- }: {
- existing: Expression | null;
- value: unknown;
- }) => {
- if (existing === null || typeof value !== 'number') {
- return parseValueExpression(value);
- }
-
- const expression = parseVideoConfigNumericExpression({
- node: existing,
- videoConfigValues,
- });
- if (expression === null) {
- return parseValueExpression(value);
- }
-
- return expression.value === value
- ? (existing as ExpressionKind)
- : updateVideoConfigNumericExpression({expression, value});
- };
-
- for (const {key, value, defaultValue} of updates) {
- let oldValueString = '';
-
- if (key === 'children') {
- oldValueString = updateJsxTextContent({jsxElement, value});
- oldValueStrings.push(oldValueString);
- continue;
- }
-
- const isDefault =
- (defaultValue === null && value === undefined) ||
- (defaultValue !== null &&
- JSON.stringify(value) === JSON.stringify(defaultValue));
-
- const dotIndex = key.indexOf('.');
- const isNested = dotIndex !== -1;
- const parentKey = isNested ? key.slice(0, dotIndex) : key;
- const childKey = isNested ? key.slice(dotIndex + 1) : '';
-
- if (isNested) {
- oldValueString = updateNestedProp({
- node,
- parentKey,
- childKey,
- value,
- defaultValue,
- isDefault,
- createValueExpression: (existing) =>
- createValueExpression({existing, value}),
- });
- } else {
- const attrIndex = node.attributes?.findIndex((a) => {
- if (a.type === 'JSXSpreadAttribute') {
- return false;
- }
-
- if (a.name.type === 'JSXNamespacedName') {
- return false;
- }
-
- return a.name.name === key;
- });
-
- const attr =
- attrIndex !== undefined && attrIndex !== -1
- ? node.attributes?.[attrIndex]
- : undefined;
-
- if (attr && attr.type !== 'JSXSpreadAttribute' && attr.value) {
- const printed = recast.print(attr.value).code;
- // Strip JSX expression container braces, e.g. "{30}" -> "30"
- oldValueString =
- printed.startsWith('{') && printed.endsWith('}')
- ? printed.slice(1, -1)
- : printed;
- } else if (attr && attr.type !== 'JSXSpreadAttribute' && !attr.value) {
- // JSX shorthand like `loop` (no value) is implicitly `true`
- oldValueString = 'true';
- } else if (!attr && defaultValue !== null) {
- oldValueString = JSON.stringify(defaultValue);
- }
-
- if (isDefault) {
- if (attr && attr.type !== 'JSXSpreadAttribute' && node.attributes) {
- node.attributes.splice(attrIndex!, 1);
- }
- } else {
- const existingExpression =
- attr?.type === 'JSXAttribute' &&
- attr.value?.type === 'JSXExpressionContainer' &&
- attr.value.expression.type !== 'JSXEmptyExpression'
- ? (attr.value.expression as Expression)
- : null;
- const parsed = createValueExpression({
- existing: existingExpression,
- value,
- });
-
- const newValue =
- value === true ? null : b.jsxExpressionContainer(parsed);
-
- if (!attr || attr.type === 'JSXSpreadAttribute') {
- const newAttr = b.jsxAttribute(b.jsxIdentifier(key), newValue);
-
- if (!node.attributes) {
- node.attributes = [];
- }
-
- node.attributes.push(newAttr as JSXAttribute | JSXSpreadAttribute);
- } else {
- attr.value = newValue as
- | JSXElement
- | JSXExpressionContainer
- | JSXFragment
- | StringLiteral
- | null
- | undefined;
- }
- }
- }
-
- oldValueStrings.push(oldValueString);
-
- if (!isNested) {
- const fieldSchema = schema[key];
- if (fieldSchema && fieldSchema.type === 'enum') {
- const propsToDelete = NoReactInternals.findPropsToDelete({
- schema,
- key,
- value,
- });
- for (const propToDelete of propsToDelete) {
- removeVariantKey({node, variantKey: propToDelete});
- }
- }
- }
- }
-
- const finalAttrNames = new Set<string>();
- for (const a of node.attributes ?? []) {
- if (a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier') {
- finalAttrNames.add(a.name.name);
- }
- }
-
- const removedProps: RemovedProp[] = [];
- for (const [name, valueString] of initialAttrs) {
- if (finalAttrNames.has(name) || updatedTopLevelKeys.has(name)) {
- continue;
- }
-
- removedProps.push({key: name, valueString});
- }
-
- return {
- oldValueStrings,
- logLine,
- removedProps,
- };
-};
-
-export const updateSequencePropsAst = ({
- input,
- nodePath,
- updates,
- schema,
- videoConfigValues,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- updates: SequencePropUpdate[];
- schema: InteractivitySchema;
- videoConfigValues: VideoConfigValues | null;
-}): {
- serialized: string;
- oldValueStrings: string[];
- logLine: number;
- removedProps: RemovedProp[];
-} => {
- const ast = parseAst(input);
- const videoConfigIdentifierValues = getVideoConfigIdentifierValues({
- ast,
- videoConfigValues,
- });
-
- const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
- if (!jsxElement) {
- throw new Error(
- 'Could not find a JSX element at the specified line to update',
- );
- }
-
- const {oldValueStrings, logLine, removedProps} = updateSequencePropsNode({
- jsxElement,
- updates,
- schema,
- videoConfigValues: videoConfigIdentifierValues,
- });
- ensureImportsForUpdates({ast, updates});
- applyGoogleFontSourceEdits({ast, updates});
-
- return {
- serialized: serializeAst(ast),
- oldValueStrings,
- logLine,
- removedProps,
- };
-};
-
export const updateMultipleSequenceProps = async ({
input,
changes,
@@ -1102,42 +46,14 @@ export const updateMultipleSequenceProps = async ({
changes: SequencePropsNodeUpdate[];
prettierConfigOverride: PrettierConfigOverride;
}): Promise<UpdateMultipleSequencePropsResult> => {
- const ast = parseAst(input);
- const allUpdates: SequencePropUpdate[] = [];
- const results = changes.map(
- ({nodePath, updates, schema, videoConfigValues}) => {
- const jsxElement = findJsxElementNodeAtNodePath(ast, nodePath);
- if (!jsxElement) {
- throw new Error(
- 'Could not find a JSX element at the specified line to update',
- );
- }
-
- allUpdates.push(...updates);
- return updateSequencePropsNode({
- jsxElement,
- updates,
- schema,
- videoConfigValues: getVideoConfigIdentifierValues({
- ast,
- videoConfigValues,
- }),
- });
- },
- );
- ensureImportsForUpdates({ast, updates: allUpdates});
- applyGoogleFontSourceEdits({ast, updates: allUpdates});
-
+ const {output: unformattedOutput, results} =
+ updateMultipleSequencePropsUnformatted({input, changes});
const {output, formatted} = await formatFileContent({
- input: serializeAst(ast),
+ input: unformattedOutput,
prettierConfigOverride,
});
- return {
- output,
- formatted,
- results,
- };
+ return {output, formatted, results};
};
export const updateSequenceProps = async ({
@@ -1163,17 +79,10 @@ export const updateSequenceProps = async ({
schema,
videoConfigValues,
});
-
const {output, formatted} = await formatFileContent({
input: serialized,
prettierConfigOverride,
});
- return {
- output,
- oldValueStrings,
- formatted,
- logLine,
- removedProps,
- };
+ return {output, oldValueStrings, formatted, logLine, removedProps};
};
diff --git a/packages/studio-shared/.npmignore b/packages/studio-shared/.npmignore
index bdb3cbdea9..11bea63340 100644
--- a/packages/studio-shared/.npmignore
+++ b/packages/studio-shared/.npmignore
@@ -5,4 +5,5 @@ dist/test
eslint.config.mjs
.prettierrc.js
.turbo
-tsconfig.tsbuildinfo
\ No newline at end of file
+tsconfig.tsbuildinfo
+bundle.ts
diff --git a/packages/studio-shared/bundle.ts b/packages/studio-shared/bundle.ts
new file mode 100644
index 0000000000..6451c47238
--- /dev/null
+++ b/packages/studio-shared/bundle.ts
@@ -0,0 +1,35 @@
+import {buildPackage} from '../.monorepo/builder';
+
+await buildPackage({
+ formats: {
+ esm: 'build',
+ cjs: 'use-tsc',
+ },
+ external: 'dependencies',
+ entrypoints: [
+ {
+ path: 'src/index.ts',
+ target: 'browser',
+ },
+ {
+ path: 'src/studio-entry-points.ts',
+ target: 'browser',
+ },
+ {
+ path: 'src/studio-html.ts',
+ target: 'browser',
+ },
+ {
+ path: 'src/keyframe-easing-presets.ts',
+ target: 'browser',
+ },
+ {
+ path: 'src/keyframe-interpolation-function.ts',
+ target: 'browser',
+ },
+ {
+ path: 'src/parse-spring-easing-config.ts',
+ target: 'browser',
+ },
+ ],
+});
diff --git a/packages/studio-shared/package.json b/packages/studio-shared/package.json
index 68a9e875dd..07807b7726 100644
--- a/packages/studio-shared/package.json
+++ b/packages/studio-shared/package.json
@@ -6,12 +6,13 @@
"version": "4.0.501",
"description": "Internal package for shared objects between the Studio backend and frontend",
"main": "dist",
+ "module": "dist/esm/index.mjs",
"scripts": {
"lint": "eslint src",
"test": "bun test src",
"formatting": "oxfmt src --check",
"format": "oxfmt src",
- "make": "tsgo -d"
+ "make": "tsgo -d && bun --env-file=../.env.bundle bundle.ts"
},
"author": "Jonny Burger <[email protected]>",
"contributors": [],
@@ -33,27 +34,61 @@
"access": "public"
},
"exports": {
- ".": "./dist/index.js",
+ ".": {
+ "types": "./dist/index.d.ts",
+ "require": "./dist/index.js",
+ "module": "./dist/esm/index.mjs",
+ "import": "./dist/esm/index.mjs"
+ },
"./studio-entry-points": {
"types": "./dist/studio-entry-points.d.ts",
- "default": "./dist/studio-entry-points.js"
+ "require": "./dist/studio-entry-points.js",
+ "module": "./dist/esm/studio-entry-points.mjs",
+ "import": "./dist/esm/studio-entry-points.mjs"
},
"./studio-html": {
"types": "./dist/studio-html.d.ts",
- "default": "./dist/studio-html.js"
+ "require": "./dist/studio-html.js",
+ "module": "./dist/esm/studio-html.mjs",
+ "import": "./dist/esm/studio-html.mjs"
},
"./keyframe-easing-presets": {
"types": "./dist/keyframe-easing-presets.d.ts",
- "default": "./dist/keyframe-easing-presets.js"
+ "require": "./dist/keyframe-easing-presets.js",
+ "module": "./dist/esm/keyframe-easing-presets.mjs",
+ "import": "./dist/esm/keyframe-easing-presets.mjs"
},
"./keyframe-interpolation-function": {
"types": "./dist/keyframe-interpolation-function.d.ts",
- "default": "./dist/keyframe-interpolation-function.js"
+ "require": "./dist/keyframe-interpolation-function.js",
+ "module": "./dist/esm/keyframe-interpolation-function.mjs",
+ "import": "./dist/esm/keyframe-interpolation-function.mjs"
},
"./parse-spring-easing-config": {
"types": "./dist/parse-spring-easing-config.d.ts",
- "default": "./dist/parse-spring-easing-config.js"
+ "require": "./dist/parse-spring-easing-config.js",
+ "module": "./dist/esm/parse-spring-easing-config.mjs",
+ "import": "./dist/esm/parse-spring-easing-config.mjs"
},
"./package.json": "./package.json"
+ },
+ "typesVersions": {
+ ">=1.0": {
+ "studio-entry-points": [
+ "./dist/studio-entry-points.d.ts"
+ ],
+ "studio-html": [
+ "./dist/studio-html.d.ts"
+ ],
+ "keyframe-easing-presets": [
+ "./dist/keyframe-easing-presets.d.ts"
+ ],
+ "keyframe-interpolation-function": [
+ "./dist/keyframe-interpolation-function.d.ts"
+ ],
+ "parse-spring-easing-config": [
+ "./dist/parse-spring-easing-config.d.ts"
+ ]
+ }
}
}
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index 77b4571c1d..79f033ba54 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -10,6 +10,8 @@ import type {
RedoResponse,
RenameStaticFileRequest,
RenameStaticFileResponse,
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse,
SubscribeToDefaultPropsRequest,
SubscribeToDefaultPropsResponse,
SubscribeToSequencePropsRequest,
@@ -46,6 +48,9 @@ export type BrowserStudioOperations = {
renameStaticFile: (
request: RenameStaticFileRequest,
) => Promise<RenameStaticFileResponse>;
+ saveSequenceProps: (
+ request: SaveSequencePropsRequest,
+ ) => Promise<SaveSequencePropsResponse>;
subscribeToDefaultProps: (
request: SubscribeToDefaultPropsRequest,
) => Promise<SubscribeToDefaultPropsResponse>;
diff --git a/packages/studio/src/components/Timeline/save-sequence-prop.ts b/packages/studio/src/components/Timeline/save-sequence-prop.ts
index c8efa41f32..75d761ee3e 100644
--- a/packages/studio/src/components/Timeline/save-sequence-prop.ts
+++ b/packages/studio/src/components/Timeline/save-sequence-prop.ts
@@ -9,7 +9,7 @@ import type {
SequencePropsSubscriptionKey,
InteractivitySchema,
} from 'remotion';
-import {callApi} from '../call-api';
+import {saveSequenceProps as saveSequencePropsApi} from '../sequence-props-api';
import type {AddSequenceKeyframeChange} from './call-add-keyframe';
import {
applyOptimisticKeyframeMoves,
@@ -89,7 +89,7 @@ export const saveInlineCaptionPatches = ({
schema,
}),
apiCall: () =>
- callApi('/api/save-sequence-props', {
+ saveSequencePropsApi({
edits: [],
captionPatches: [{fileName, nodePath, schema, patches}],
addedKeyframes: null,
@@ -148,7 +148,7 @@ export const saveSequenceProps = ({
schema: change.schema,
}),
apiCall: () =>
- callApi('/api/save-sequence-props', {
+ saveSequencePropsApi({
edits: [
{
fileName: change.fileName,
@@ -200,7 +200,7 @@ export const saveSequenceProps = ({
);
}
- return callApi('/api/save-sequence-props', {
+ return saveSequencePropsApi({
edits: changes.map((change) => {
return {
fileName: change.fileName,
diff --git a/packages/studio/src/components/sequence-props-api.ts b/packages/studio/src/components/sequence-props-api.ts
index c6001a764a..c742f79002 100644
--- a/packages/studio/src/components/sequence-props-api.ts
+++ b/packages/studio/src/components/sequence-props-api.ts
@@ -1,4 +1,6 @@
import type {
+ SaveSequencePropsRequest,
+ SaveSequencePropsResponse,
SubscribeToSequencePropsRequest,
SubscribeToSequencePropsResponse,
UnsubscribeFromSequencePropsRequest,
@@ -6,6 +8,15 @@ import type {
import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
import {callApi} from './call-api';
+export const saveSequenceProps = (
+ request: SaveSequencePropsRequest,
+): Promise<SaveSequencePropsResponse> => {
+ const browserStudioOperations = getBrowserStudioOperations();
+ return browserStudioOperations
+ ? browserStudioOperations.saveSequenceProps(request)
+ : callApi('/api/save-sequence-props', request);
+};
+
export const subscribeToSequenceProps = (
request: SubscribeToSequencePropsRequest,
): Promise<SubscribeToSequencePropsResponse> => {
diff --git a/packages/studio/src/test/browser-studio-sequence-props.test.ts b/packages/studio/src/test/browser-studio-sequence-props.test.ts
index 1e8e68d86b..04eda25b27 100644
--- a/packages/studio/src/test/browser-studio-sequence-props.test.ts
+++ b/packages/studio/src/test/browser-studio-sequence-props.test.ts
@@ -1,5 +1,6 @@
import {afterEach, expect, test} from 'bun:test';
import {
+ saveSequenceProps,
subscribeToSequenceProps,
unsubscribeFromSequenceProps,
} from '../components/sequence-props-api';
@@ -19,7 +20,7 @@ afterEach(() => {
Reflect.deleteProperty(globalThis, 'window');
});
-test('routes sequence prop subscriptions through Browser Studio operations', async () => {
+test('routes sequence prop operations through Browser Studio', async () => {
const calls: string[] = [];
const nodePath = {
absolutePath: '/project/src/Composition.tsx',
@@ -34,6 +35,20 @@ test('routes sequence prop subscriptions through Browser Studio operations', asy
},
};
const operations = makeBrowserStudioOperations({
+ saveSequenceProps: (request) => {
+ calls.push(`save:${request.clientId}:${request.edits[0]?.fileName}`);
+ return Promise.resolve({
+ canUpdate: true,
+ props: {from: {status: 'static', codeValue: 15}},
+ results: [
+ {
+ fileName: 'src/Composition.tsx',
+ nodePath,
+ props: {from: {status: 'static', codeValue: 15}},
+ },
+ ],
+ });
+ },
subscribeToSequenceProps: (request) => {
calls.push(`subscribe:${request.clientId}:${request.fileName}`);
return Promise.resolve({
@@ -70,6 +85,30 @@ test('routes sequence prop subscriptions through Browser Studio operations', asy
videoConfigValues: nodePath.videoConfigValues,
});
expect(subscription.success).toBe(true);
+ await saveSequenceProps({
+ edits: [
+ {
+ fileName: 'src/Composition.tsx',
+ nodePath,
+ key: 'from',
+ value: {type: 'json', serialized: '15'},
+ defaultValue: '0',
+ schema: {
+ from: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ },
+ },
+ sourceEdit: null,
+ },
+ ],
+ addedKeyframes: null,
+ movedKeyframes: null,
+ clientId: 'browser-studio',
+ undoLabel: 'Update from',
+ redoLabel: 'Update from again',
+ });
await unsubscribeFromSequenceProps({
fileName: 'src/Composition.tsx',
nodePath,
@@ -80,6 +119,7 @@ test('routes sequence prop subscriptions through Browser Studio operations', asy
});
expect(calls).toEqual([
'subscribe:browser-studio:src/Composition.tsx',
+ 'save: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.ts
index 4f236add55..9883de6000 100644
--- a/packages/studio/src/test/make-browser-studio-operations.ts
+++ b/packages/studio/src/test/make-browser-studio-operations.ts
@@ -18,6 +18,7 @@ export const makeBrowserStudioOperations = (
insertSolid: () => unusedOperation('insertSolid'),
redo: () => unusedOperation('redo'),
renameStaticFile: () => unusedOperation('renameStaticFile'),
+ saveSequenceProps: () => unusedOperation('saveSequenceProps'),
subscribeToDefaultProps: () => unusedOperation('subscribeToDefaultProps'),
subscribeToEvent: () => unusedOperation('subscribeToEvent'),
subscribeToSequenceProps: () => unusedOperation('subscribeToSequenceProps'),