Skip to content

🎥 Make videos programmatically with React

Use sequence prop codemod for video source replacement

Jonny Burger064da8b64ed1
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index c217990d10..e5834825e7 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -27,6 +27,7 @@ import {
updateEffectKeyframes,
updateEffectProps as updateEffectPropsCodemod,
updateJsxNodeKeyframes,
+ updateJsxNodeProps,
type CodemodNodeResult,
type CompositionDestination,
type EffectKeyframeUpdate,
@@ -62,6 +63,7 @@ import type {
SequenceNodePath,
SequencePropsSubscriptionKey,
} from 'remotion';
+import {NoReactInternals} from 'remotion/no-react';
import {createBrowserStudioProjectController} from './browser-studio-project-controller';
import {makeBrowserStudioProjectArchive} from './download-project';
import {downloadRemoteAssetInBrowserStudio} from './download-remote-asset';
@@ -80,7 +82,6 @@ const {
getRootFileForProject,
insertBasicCaptions: insertBasicCaptionsCodemod,
insertJsxElementIntoProjectWithNodePathRemappings,
- replaceVideoSource: replaceVideoSourceCodemod,
JsxElementIdentityMismatchError,
JsxElementNotFoundAtLocationError,
pasteEffects: pasteEffectsCodemod,
@@ -2008,25 +2009,23 @@ export const createBrowserStudioOperations = ({
try {
const project = getProject();
const absolutePath = findProjectFile({filePath: fileName, project});
- const result = replaceVideoSourceCodemod({
- input: project.files[absolutePath],
- nodePath,
- src,
+ const result = updateJsxNodeProps({
+ project,
+ node: {filePath: absolutePath, nodePath},
+ updates: [
+ {
+ key: 'src',
+ value: `${NoReactInternals.FILE_TOKEN}${src.split('/').map(encodeURIComponent).join('/')}`,
+ defaultValue: null,
+ },
+ ],
});
const nodePathMutation = controller.applyMutation({
undoRedoNavigation: null,
timelineSelection: null,
fileName: absolutePath,
- mutate: () => ({
- ...project,
- files: {...project.files, [absolutePath]: result.output},
- }),
- nodePathMutationFiles: [
- {
- absolutePath,
- remappings: result.nodePathRemappings,
- },
- ],
+ mutate: () => result.project,
+ nodePathMutationFiles: getNodePathMutationFiles(result),
});
if (nodePathMutation === null) {
throw new Error('Could not replace video source');
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index a7ca0f2e2b..1b756abb67 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -20,7 +20,6 @@ import {
getFolderFile,
getRootFileForProject,
} from './internals';
-import {replaceVideoSource} from './replace-video-source';
import {computeSequencePropsSubscriptionFromContent} from './sequence-props';
import {JsxElementIdentityMismatchError} from './sequence-props/jsx-component-identity';
import {JsxElementNotFoundAtLocationError} from './sequence-props/jsx-element-not-found-at-location-error';
@@ -175,7 +174,6 @@ export const CodemodsInternals = {
insertBasicCaptions,
insertJsxElementIntoComposition,
insertJsxElementIntoProjectWithNodePathRemappings,
- replaceVideoSource,
pasteEffects,
resolveCompositionComponent,
resolveCompositionComponentWithFile,
diff --git a/packages/codemods/src/replace-video-source.ts b/packages/codemods/src/replace-video-source.ts
deleted file mode 100644
index 38d178daf1..0000000000
--- a/packages/codemods/src/replace-video-source.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import type {JSXAttribute, JSXElement} from '@babel/types';
-import type {SequenceNodePathRemapping} from '@remotion/studio-shared';
-import * as recast from 'recast';
-import type {SequenceNodePath} from 'remotion';
-import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';
-import {
- captureJsxNodePaths,
- getNodePathRemappings,
-} from './get-node-path-remappings';
-import {recastLocToOffset} from './recast-loc-to-offset';
-import {ensureNamedImport, getImportedName} from './sequence-props/imports';
-import {parseAst} from './sequence-props/parse-ast';
-import {
- applySourceEdits,
- captureImportSnapshots,
- getInsertImportSourceEdits,
-} from './source-edits';
-import {getPreferredQuote} from './source-style';
-
-export const replaceVideoSource = ({
- input,
- nodePath,
- src,
- prettierConfigOverride = null,
-}: {
- input: string;
- nodePath: SequenceNodePath;
- src: string;
- prettierConfigOverride?: Record<string, unknown> | null;
-}): {
- output: string;
- logLine: number;
- nodePathRemappings: SequenceNodePathRemapping[];
-} => {
- const ast = parseAst(input);
- const captured = captureJsxNodePaths(ast);
- const importSnapshots = captureImportSnapshots(ast);
- const videoPath = findJsxElementPathForDeletion(ast, nodePath);
- if (!videoPath) {
- throw new Error('Could not find the selected video element');
- }
-
- const video = videoPath.node as JSXElement;
- if (video.openingElement.name.type !== 'JSXIdentifier') {
- throw new Error('The selected video tag cannot be updated');
- }
-
- const tagName = video.openingElement.name.name;
- const importedVideo = ast.program.body.some(
- (statement) =>
- statement.type === 'ImportDeclaration' &&
- statement.importKind !== 'type' &&
- (statement.source.value === 'remotion' ||
- statement.source.value === '@remotion/media') &&
- statement.specifiers.some(
- (specifier) =>
- specifier.type === 'ImportSpecifier' &&
- specifier.local.name === tagName &&
- [
- 'Video',
- 'Html5Video',
- 'OffthreadVideo',
- 'experimental_Video',
- ].includes(getImportedName(specifier)),
- ),
- );
- if (!importedVideo) {
- throw new Error('The selected element is not a Remotion Video');
- }
-
- const srcAttribute = video.openingElement.attributes.find(
- (attribute): attribute is JSXAttribute =>
- attribute.type === 'JSXAttribute' &&
- attribute.name.type === 'JSXIdentifier' &&
- attribute.name.name === 'src',
- );
- if (!srcAttribute?.value?.loc) {
- throw new Error(`<${tagName}> has no src attribute`);
- }
-
- let staticFileLocalName = 'staticFile';
- let suffix = 1;
- while (new RegExp(`\\b${staticFileLocalName}\\b`).test(input)) {
- staticFileLocalName = `remotionStaticFile${suffix++}`;
- }
-
- staticFileLocalName = ensureNamedImport({
- ast,
- importedName: 'staticFile',
- localName: staticFileLocalName,
- sourcePath: 'remotion',
- });
- const stringLiteral = recast.prettyPrint(
- recast.types.builders.stringLiteral(src),
- {
- quote: getPreferredQuote(input, prettierConfigOverride),
- },
- ).code;
- const output = applySourceEdits({
- input,
- edits: [
- ...getInsertImportSourceEdits({
- ast,
- input,
- prettierConfigOverride,
- snapshots: importSnapshots,
- }),
- {
- start: recastLocToOffset(input, srcAttribute.value.loc.start),
- end: recastLocToOffset(input, srcAttribute.value.loc.end),
- replacement: `{${staticFileLocalName}(${stringLiteral})}`,
- },
- ],
- });
- const {nodePathRemappings} = getNodePathRemappings({ast, captured, output});
- return {
- output,
- logLine: video.openingElement.loc?.start.line ?? 1,
- nodePathRemappings,
- };
-};
diff --git a/packages/studio-server/src/preview-server/routes/replace-video-source.ts b/packages/studio-server/src/preview-server/routes/replace-video-source.ts
index 9d7db7f4a3..dcb9895787 100644
--- a/packages/studio-server/src/preview-server/routes/replace-video-source.ts
+++ b/packages/studio-server/src/preview-server/routes/replace-video-source.ts
@@ -1,10 +1,11 @@
import {readFileSync} from 'node:fs';
-import {CodemodsInternals} from '@remotion/codemods';
+import {updateJsxNodeProps} from '@remotion/codemods';
import {RenderInternals} from '@remotion/renderer';
import type {
ReplaceVideoSourceRequest,
ReplaceVideoSourceResponse,
} from '@remotion/studio-shared';
+import {NoReactInternals} from 'remotion/no-react';
import {writeFileAndNotifyFileWatchers} from '../../file-watcher';
import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';
import type {ApiHandler} from '../api-types';
@@ -32,12 +33,25 @@ export const replaceVideoSourceHandler: ApiHandler<
action: 'modify',
});
const fileContents = readFileSync(absolutePath, 'utf-8');
- const {output, logLine, nodePathRemappings} =
- CodemodsInternals.replaceVideoSource({
- input: fileContents,
- nodePath,
- src,
- });
+ const result = updateJsxNodeProps({
+ project: {
+ files: {[absolutePath]: fileContents},
+ rootDir: remotionRoot,
+ },
+ node: {filePath: absolutePath, nodePath},
+ updates: [
+ {
+ key: 'src',
+ value: `${NoReactInternals.FILE_TOKEN}${src.split('/').map(encodeURIComponent).join('/')}`,
+ defaultValue: null,
+ },
+ ],
+ });
+ const output = result.project.files[absolutePath];
+ const {logLine} = result;
+ const nodePathRemappings = result.nodePathRemappings.map(
+ ({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),
+ );
const nodePathMutation = broadcastSequenceNodePathMutation(
[{absolutePath, remappings: nodePathRemappings}],
null,