Skip to content

🎥 Make videos programmatically with React

@remotion/codemods: Expose JSX node deletion

JonnyBurger6252082737f7
diff --git a/packages/codemods/README.md b/packages/codemods/README.md
index 784396354b..142568dd9f 100644
--- a/packages/codemods/README.md
+++ b/packages/codemods/README.md
@@ -8,21 +8,34 @@ Codemods for editing Remotion projects without a filesystem dependency.
import {addSolid} from '@remotion/codemods';
const result = addSolid({
- project: {
- rootDir: '/',
- files: {
- 'src/Root.tsx': rootSource,
- 'src/Video.tsx': videoSource,
- },
- },
- compositionFile: 'src/Root.tsx',
- compositionId: 'MyComposition',
- width: 1920,
- height: 1080,
+ project: {
+ rootDir: '/',
+ files: {
+ 'src/Root.tsx': rootSource,
+ 'src/Video.tsx': videoSource,
+ },
+ },
+ compositionFile: 'src/Root.tsx',
+ compositionId: 'MyComposition',
+ width: 1920,
+ height: 1080,
});
console.log(result.project.files);
console.log(result.changes);
```
+Mounted JSX elements can be deleted using the same node paths that Remotion
+Canvas and Studio use:
+
+```tsx
+import {deleteJsxNode} from '@remotion/codemods';
+
+const removed = await deleteJsxNode({
+ project: result.project,
+ filePath: result.insertedNode.filePath,
+ nodePath: result.insertedNode.nodePath,
+});
+```
+
See the [documentation](https://www.remotion.dev/docs/codemods).
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index 2730660c8a..48f9bbcf8b 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -267,6 +267,7 @@ export const findProjectFile = ({
const rootDir = normalizePath(project.rootDir);
const candidates = [
normalizedInput,
+ normalizePath(normalizedInput.replace(/^\/+/, '')),
normalizePath(`/${normalizedInput}`),
normalizePath(`${rootDir}/${normalizedInput.replace(/^\//, '')}`),
];
@@ -956,7 +957,7 @@ const getNodePathRemappings = ({
visitJSXOpeningElement(path) {
before.push({
nodePath: getNodePathForRecastPath(path, astBefore),
- signature: recast.print(path.node as JSXOpeningElement).code,
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
});
return this.traverse(path);
},
@@ -965,7 +966,7 @@ const getNodePathRemappings = ({
visitJSXOpeningElement(path) {
after.push({
nodePath: getNodePathForRecastPath(path, astAfter),
- signature: recast.print(path.node as JSXOpeningElement).code,
+ signature: recast.prettyPrint(path.node as JSXOpeningElement).code,
});
return this.traverse(path);
},
diff --git a/packages/codemods/src/public.ts b/packages/codemods/src/public.ts
index 2023bbcd53..330956346d 100644
--- a/packages/codemods/src/public.ts
+++ b/packages/codemods/src/public.ts
@@ -1,4 +1,9 @@
-import {insertSolidIntoProject} from './index';
+import type {SequenceNodePath} from 'remotion';
+import {deleteJsxNode as deleteJsxNodeFromSource} from './delete-jsx-node';
+import {
+ findProjectFile,
+ insertSolidIntoProjectWithNodePathRemappings,
+} from './index';
export type CodemodProject = {
files: Record<string, string>;
@@ -16,6 +21,28 @@ export type CodemodResult<Project extends CodemodProject> = {
changes: CodemodFileChange[];
};
+const getCodemodResult = <Project extends CodemodProject>({
+ project,
+ nextProject,
+}: {
+ project: Project;
+ nextProject: Project;
+}): CodemodResult<Project> => {
+ const filePaths = new Set([
+ ...Object.keys(project.files),
+ ...Object.keys(nextProject.files),
+ ]);
+ const changes = [...filePaths].flatMap((filePath): CodemodFileChange[] => {
+ const previousContents = project.files[filePath] ?? null;
+ const nextContents = nextProject.files[filePath] ?? null;
+ return previousContents === nextContents
+ ? []
+ : [{filePath, previousContents, nextContents}];
+ });
+
+ return {changes, project: nextProject};
+};
+
export type AddSolidOptions<Project extends CodemodProject> = {
project: Project;
compositionId: string;
@@ -26,6 +53,14 @@ export type AddSolidOptions<Project extends CodemodProject> = {
position?: {x: number; y: number};
};
+export type AddSolidResult<Project extends CodemodProject> =
+ CodemodResult<Project> & {
+ insertedNode: {
+ filePath: string;
+ nodePath: SequenceNodePath;
+ };
+ };
+
export const addSolid = <Project extends CodemodProject>({
project,
compositionId,
@@ -34,8 +69,8 @@ export const addSolid = <Project extends CodemodProject>({
height,
from,
position,
-}: AddSolidOptions<Project>): CodemodResult<Project> => {
- const nextProject = insertSolidIntoProject({
+}: AddSolidOptions<Project>): AddSolidResult<Project> => {
+ const insertion = insertSolidIntoProjectWithNodePathRemappings({
project,
request: {
compositionFile,
@@ -49,17 +84,45 @@ export const addSolid = <Project extends CodemodProject>({
from: from ?? null,
},
});
- const filePaths = new Set([
- ...Object.keys(project.files),
- ...Object.keys(nextProject.files),
- ]);
- const changes = [...filePaths].flatMap((filePath): CodemodFileChange[] => {
- const previousContents = project.files[filePath] ?? null;
- const nextContents = nextProject.files[filePath] ?? null;
- return previousContents === nextContents
- ? []
- : [{filePath, previousContents, nextContents}];
+ const insertedNodePath = insertion.nodePathRemappings.find(
+ (remapping) => remapping.oldNodePath === null,
+ )?.newNodePath;
+ if (!insertedNodePath) {
+ throw new Error('Could not determine the inserted JSX node path');
+ }
+
+ return {
+ ...getCodemodResult({nextProject: insertion.project, project}),
+ insertedNode: {
+ filePath: insertion.filePath,
+ nodePath: insertedNodePath,
+ },
+ };
+};
+
+export type DeleteJsxNodeOptions<Project extends CodemodProject> = {
+ project: Project;
+ filePath: string;
+ nodePath: SequenceNodePath;
+};
+
+export const deleteJsxNode = async <Project extends CodemodProject>({
+ project,
+ filePath,
+ nodePath,
+}: DeleteJsxNodeOptions<Project>): Promise<CodemodResult<Project>> => {
+ const resolvedFilePath = findProjectFile({filePath, project});
+ const {output} = await deleteJsxNodeFromSource({
+ input: project.files[resolvedFilePath],
+ nodePath,
});
+ const nextProject = {
+ ...project,
+ files: {
+ ...project.files,
+ [resolvedFilePath]: output,
+ },
+ };
- return {changes, project: nextProject};
+ return getCodemodResult({nextProject, project});
};
diff --git a/packages/codemods/src/test/public-api.test.ts b/packages/codemods/src/test/public-api.test.ts
index 3ad32a489e..76ef9408c7 100644
--- a/packages/codemods/src/test/public-api.test.ts
+++ b/packages/codemods/src/test/public-api.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {addSolid} from '../public';
+import {addSolid, deleteJsxNode} from '../public';
const makeProject = () => ({
entryPoint: 'src/index.ts',
@@ -35,6 +35,8 @@ test('addSolid() immutably updates a virtual project', () => {
expect(result.project.files['src/Video.tsx']).toContain(
'<Solid width={1280} height={720}',
);
+ expect(result.insertedNode.filePath).toBe('src/Video.tsx');
+ expect(result.insertedNode.nodePath.length).toBeGreaterThan(0);
expect(result.changes).toEqual([
{
filePath: 'src/Video.tsx',
@@ -43,3 +45,34 @@ test('addSolid() immutably updates a virtual project', () => {
},
]);
});
+
+test('deleteJsxNode() deletes the Sequence wrapper identified by a node path', async () => {
+ const project = makeProject();
+ const added = addSolid({
+ compositionFile: 'src/Root.tsx',
+ compositionId: 'Demo',
+ from: 10,
+ height: 720,
+ project,
+ width: 1280,
+ });
+ const sourceWithSolid = added.project.files['src/Video.tsx'];
+ expect(sourceWithSolid).toContain('<Sequence from={10}');
+ const result = await deleteJsxNode({
+ filePath: `/${added.insertedNode.filePath}`,
+ nodePath: added.insertedNode.nodePath,
+ project: added.project,
+ });
+
+ expect(result.project.entryPoint).toBe('src/index.ts');
+ expect(result.project).not.toBe(added.project);
+ expect(added.project.files['src/Video.tsx']).toContain('<Solid');
+ expect(result.project.files['src/Video.tsx']).not.toContain('<Solid');
+ expect(result.changes).toEqual([
+ {
+ filePath: 'src/Video.tsx',
+ previousContents: sourceWithSolid,
+ nextContents: result.project.files['src/Video.tsx'],
+ },
+ ]);
+});
diff --git a/packages/docs/docs/codemods/add-solid.mdx b/packages/docs/docs/codemods/add-solid.mdx
index f230decead..0e32bdb327 100644
--- a/packages/docs/docs/codemods/add-solid.mdx
+++ b/packages/docs/docs/codemods/add-solid.mdx
@@ -29,6 +29,7 @@ const result = addSolid({
console.log(result.project.files);
console.log(result.changes);
+console.log(result.insertedNode);
```
The input project is not mutated.
@@ -77,6 +78,10 @@ A new project containing the transformed source. Unchanged project fields are pr
An array describing each changed file with its `filePath`, `previousContents`, and `nextContents`.
+### insertedNode
+
+The `filePath` and `nodePath` of the inserted JSX element. Pass these values to [`deleteJsxNode()`](/docs/codemods/delete-jsx-node) to remove the element again.
+
## Compatibility
<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />
@@ -84,4 +89,5 @@ An array describing each changed file with its `filePath`, `previousContents`, a
## See also
- [`<Solid>`](/docs/solid)
+- [`deleteJsxNode()`](/docs/codemods/delete-jsx-node)
- [`@remotion/browser-bundler`](/docs/browser-bundler)
diff --git a/packages/docs/docs/codemods/delete-jsx-node.mdx b/packages/docs/docs/codemods/delete-jsx-node.mdx
new file mode 100644
index 0000000000..afff31f5eb
--- /dev/null
+++ b/packages/docs/docs/codemods/delete-jsx-node.mdx
@@ -0,0 +1,74 @@
+---
+image: /generated/articles-docs-codemods-delete-jsx-node.png
+title: 'deleteJsxNode()'
+crumb: '@remotion/codemods'
+---
+
+# deleteJsxNode()<AvailableFrom v="4.0.527" />
+
+Deletes the JSX element identified by a mounted layer's node path.
+
+The API uses the same source-editing routine as Remotion Studio. It works with any JSX layer, including [`<Sequence>`](/docs/sequence) and [`<Solid>`](/docs/solid).
+
+:::warning
+
+_Draft API_: This API is not yet stable. We are in the experimental phase of this package and reserve to change it at any time.
+
+:::
+
+```ts twoslash title="delete-jsx-node.ts"
+import {deleteJsxNode, type CodemodProject} from '@remotion/codemods';
+import type {SequenceNodePath} from 'remotion';
+
+declare const project: CodemodProject;
+declare const nodePath: SequenceNodePath;
+
+const result = await deleteJsxNode({
+ project,
+ filePath: 'src/Video.tsx',
+ nodePath,
+});
+
+console.log(result.project.files);
+console.log(result.changes);
+```
+
+The input project is not mutated.
+
+## Options
+
+Pass an object with the following properties.
+
+### project
+
+An in-memory Remotion project containing `rootDir` and a `files` record.
+
+### filePath
+
+The source file containing the JSX element. Absolute paths emitted by a mounted layer and project-relative paths are both accepted.
+
+### nodePath
+
+The `SequenceNodePath` identifying the JSX element to delete. Canvas layers expose it as `nodePathInfo.sequenceSubscriptionKey.nodePath`.
+
+## Return value
+
+A promise resolving to an object with the following properties.
+
+### project
+
+A new project containing the transformed source. Unchanged project fields are preserved.
+
+### changes
+
+An array describing each changed file with its `filePath`, `previousContents`, and `nextContents`.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />
+
+## See also
+
+- [`addSolid()`](/docs/codemods/add-solid)
+- [`<Sequence>`](/docs/sequence)
+- [`@remotion/canvas`](/docs/canvas)
diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsx
index 190b000f87..4c52f7c957 100644
--- a/packages/docs/docs/codemods/table-of-contents.tsx
+++ b/packages/docs/docs/codemods/table-of-contents.tsx
@@ -9,6 +9,10 @@ export const TableOfContents: React.FC = () => {
<strong>addSolid()</strong>
<div>Add a Solid to a composition source file</div>
</TOCItem>
+ <TOCItem link="/docs/codemods/delete-jsx-node">
+ <strong>deleteJsxNode()</strong>
+ <div>Delete a mounted JSX layer from its source file</div>
+ </TOCItem>
</Grid>
);
};
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 1f5dc53922..650ef93421 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -2039,7 +2039,7 @@ const sidebars: SidebarsConfig = {
type: 'doc',
id: 'codemods/index',
},
- items: ['codemods/add-solid'],
+ items: ['codemods/add-solid', 'codemods/delete-jsx-node'],
},
],
};
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index f1db391337..1b29406f5c 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1413,6 +1413,15 @@ export const articles = [
noAi: false,
slug: 'codemods/add-solid',
},
+ {
+ id: 'codemods/delete-jsx-node',
+ title: 'deleteJsxNode()',
+ relativePath: 'docs/codemods/delete-jsx-node.mdx',
+ compId: 'articles-docs-codemods-delete-jsx-node',
+ crumb: '@remotion/codemods',
+ noAi: false,
+ slug: 'codemods/delete-jsx-node',
+ },
{
id: 'codemods/index',
title: '@remotion/codemods',
diff --git a/packages/docs/static/generated/articles-docs-codemods-delete-jsx-node.png b/packages/docs/static/generated/articles-docs-codemods-delete-jsx-node.png
new file mode 100644
index 0000000000..98f8ae3f43
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-delete-jsx-node.png differ
diff --git a/packages/player-example/e2e/browser-bundler.test.ts b/packages/player-example/e2e/browser-bundler.test.ts
index 14520cab9b..697c573d8a 100644
--- a/packages/player-example/e2e/browser-bundler.test.ts
+++ b/packages/player-example/e2e/browser-bundler.test.ts
@@ -62,6 +62,17 @@ test('Fast Refresh preserves an isolated Canvas, video state and editor focus th
await expect(
composition.getByRole('button', {name: 'Clicks: 2', exact: true}),
).toBeVisible();
+ await page.getByRole('button', {name: 'Remove Solid', exact: true}).click();
+ await expect(page.getByRole('status')).toHaveText('Up to date');
+ await expect(
+ mountedLayers.getByRole('heading', {name: 'Layers (5)'}),
+ ).toBeVisible();
+ await expect(page.getByRole('textbox', {name: 'Video.tsx'})).not.toHaveValue(
+ /<Solid width=\{1280\} height=\{720\}/,
+ );
+ await expect(
+ composition.getByRole('button', {name: 'Clicks: 2', exact: true}),
+ ).toBeVisible();
const playbackRate = composition.getByRole('button', {
name: 'Change playback rate',
exact: true,
@@ -98,7 +109,7 @@ test('Fast Refresh preserves an isolated Canvas, video state and editor focus th
await expect(frame).toHaveText(pausedFrame);
await expect(playbackRate).toHaveText('1.5x');
await expect(
- mountedLayers.getByRole('heading', {name: 'Layers (6)'}),
+ mountedLayers.getByRole('heading', {name: 'Layers (5)'}),
).toBeVisible();
await expect(
composition.getByRole('button', {name: 'Play video', exact: true}),
diff --git a/packages/player-example/src/BrowserBundlerExample.tsx b/packages/player-example/src/BrowserBundlerExample.tsx
index a6a53e08b4..5dd0674ebd 100644
--- a/packages/player-example/src/BrowserBundlerExample.tsx
+++ b/packages/player-example/src/BrowserBundlerExample.tsx
@@ -3,9 +3,10 @@ import {
createBrowserBundler,
type VirtualProject,
} from '@remotion/browser-bundler';
-import {addSolid} from '@remotion/codemods';
+import {addSolid, deleteJsxNode} from '@remotion/codemods';
import Link from 'next/link';
import React, {useCallback, useEffect, useRef, useState} from 'react';
+import type {SequenceNodePath} from 'remotion';
import type {BrowserBundlerPreview} from './browser-bundler-preview/bridge';
const initialSource = `import React, {useState} from 'react';
@@ -117,6 +118,10 @@ export const BrowserBundlerExample: React.FC = () => {
const [state, setState] = useState<CompilationState>({type: 'loading'});
const [progress, setProgress] = useState<string | null>(null);
const [warnings, setWarnings] = useState<string[]>([]);
+ const [insertedSolid, setInsertedSolid] = useState<{
+ filePath: string;
+ nodePath: SequenceNodePath;
+ } | null>(null);
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const sessionRef = useRef<CompilationSession | null>(null);
@@ -373,6 +378,7 @@ export const BrowserBundlerExample: React.FC = () => {
}
setSource(nextSource);
+ setInsertedSolid(result.insertedNode);
void compile(nextSource);
} catch (error) {
setState({
@@ -394,6 +400,53 @@ export const BrowserBundlerExample: React.FC = () => {
>
Add Solid
</button>
+ <button
+ type="button"
+ disabled={state.type === 'loading' || insertedSolid === null}
+ onClick={() => {
+ if (!insertedSolid) {
+ return;
+ }
+
+ setState({type: 'loading'});
+ void deleteJsxNode({
+ filePath: insertedSolid.filePath,
+ nodePath: insertedSolid.nodePath,
+ project: {
+ ...project,
+ files: {...project.files, 'src/Video.tsx': source},
+ rootDir: '/',
+ },
+ })
+ .then((result) => {
+ const nextSource = result.project.files['src/Video.tsx'];
+ if (!nextSource) {
+ throw new Error('The codemod did not return Video.tsx.');
+ }
+
+ setSource(nextSource);
+ setInsertedSolid(null);
+ void compile(nextSource);
+ })
+ .catch((error) => {
+ setState({
+ message: getCompilationErrorMessage(error),
+ type: 'error',
+ });
+ });
+ }}
+ style={{
+ backgroundColor: insertedSolid ? '#7f1d1d' : '#242933',
+ border: 0,
+ borderRadius: 5,
+ color: insertedSolid ? 'white' : '#6b7280',
+ fontSize: 12,
+ fontWeight: 600,
+ padding: '7px 11px',
+ }}
+ >
+ Remove Solid
+ </button>
<p
role="status"
aria-live="polite"
@@ -451,6 +504,7 @@ export const BrowserBundlerExample: React.FC = () => {
onChange={(event) => {
const nextSource = event.target.value;
setSource(nextSource);
+ setInsertedSolid(null);
void compile(nextSource);
}}
spellCheck={false}