🎥 Make videos programmatically with React
`@remotion/codemods`: Add `unwrapNode()` to remove wrappers and keep children
JonnyBurger0ba5c23bdbd0
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.tsindex ae4ec1e2d0..18753bf5ad 100644--- a/packages/browser-studio/src/browser-studio-operations.ts+++ b/packages/browser-studio/src/browser-studio-operations.ts@@ -14,6 +14,8 @@ import {duplicateComposition as duplicateCompositionCodemod,duplicateEffects as duplicateEffectsCodemod,duplicateNodes as duplicateNodesCodemod,+ canUnwrapNode,+ unwrapNode as unwrapNodeCodemod,canWrapNode,wrapNode as wrapNodeCodemod,getNodeProps,@@ -1434,6 +1436,49 @@ export const createBrowserStudioOperations = ({}};+ const unwrapNode: BrowserStudioOperations['unwrapNode'] = ({+ fileName,+ compositionId,+ nodePath,+ dryRun,+ }) => {+ try {+ const project = getProject();+ const filePath = findProjectFile({project, filePath: fileName});+ const canUnwrap = canUnwrapNode({+ input: project.files[filePath],+ nodePath,+ });+ if (dryRun) {+ return Promise.resolve({+ success: true,+ canUnwrap,+ nodePathMutation: null,+ });+ }++ const result = unwrapNodeCodemod({project, node: {filePath, nodePath}});+ const {childNodePath} = result;+ const nodePathMutation = controller.applyMutation({+ undoRedoNavigation: null,+ timelineSelection:+ childNodePath === null+ ? null+ : {compositionId, absolutePath: filePath, nodePath: childNodePath},+ fileName,+ mutate: (current) => applyCodemodChanges(current, result.changes),+ nodePathMutationFiles: getNodePathMutationFiles(result),+ });+ if (nodePathMutation === null) {+ throw new Error('Could not unwrap JSX node');+ }++ return Promise.resolve({success: true, canUnwrap, nodePathMutation});+ } catch (error) {+ return Promise.resolve(getStructuredError(error));+ }+ };+const wrapNode: BrowserStudioOperations['wrapNode'] = ({fileName,compositionId,@@ -2487,6 +2532,7 @@ export const createBrowserStudioOperations = ({deleteComposition: deleteCompositionOperation,precomposeJsxNodes,duplicateNodes,+ unwrapNode,wrapNode,effects: effectOperations,clearPendingHmrEvent: controller.clearPendingHmrEvent,diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.tsindex 0c85e3d6cf..329cbf736f 100644--- a/packages/codemods/src/index.ts+++ b/packages/codemods/src/index.ts@@ -136,6 +136,7 @@ export type {} from './codemod-project';export {applyCodemodChanges} from './codemod-project';export {deleteNodes, type DeleteNodesOptions} from './delete-nodes';+export {canUnwrapNode, unwrapNode, type UnwrapNodeOptions} from './unwrap-node';export {canWrapNode, wrapNode, type WrapNodeOptions} from './wrap-node';export {canPrecomposeJsxNodes,diff --git a/packages/codemods/src/unwrap-node.ts b/packages/codemods/src/unwrap-node.tsnew file mode 100644index 0000000000..6a6c390b27--- /dev/null+++ b/packages/codemods/src/unwrap-node.ts@@ -0,0 +1,187 @@+import type {JSXElement, JSXOpeningElement, Node} from '@babel/types';+import * as recast from 'recast';+import type {SequenceNodePath} from 'remotion';+import type {CodemodProject} from './codemod-project';+import {findJsxElementPathForDeletion} from './delete-jsx-nodes-internal';+import {+ captureJsxNodePaths,+ getNodePathRemappings,+} from './get-node-path-remappings';+import {findProjectFile} from './internals';+import {getNodeEditResult, type NodeReference} from './node-references';+import {recastLocToOffset} from './recast-loc-to-offset';+import {parseAst} from './sequence-props/parse-ast';+import {applySourceEdits} from './source-edits';+import {getLineIndent} from './source-style';++export type UnwrapNodeOptions<Project extends CodemodProject> = {+ project: Project;+ node: NodeReference;+};++export const canUnwrapNode = ({+ input,+ nodePath,+}: {+ input: string;+ nodePath: SequenceNodePath;+}): boolean => {+ const path = findJsxElementPathForDeletion(parseAst(input), nodePath);+ const element = path?.node as JSXElement | undefined;+ return Boolean(element?.loc && element.closingElement?.loc);+};++export const unwrapNode = <Project extends CodemodProject>({+ project,+ node,+}: UnwrapNodeOptions<Project>) => {+ const filePath = findProjectFile({project, filePath: node.filePath});+ const input = project.files[filePath];+ const ast = parseAst(input);+ const captured = captureJsxNodePaths(ast);+ const path = findJsxElementPathForDeletion(ast, node.nodePath);+ const element = path?.node as JSXElement | undefined;+ if (+ !path ||+ !element?.loc ||+ !element.openingElement.loc ||+ !element.closingElement?.loc+ ) {+ throw new Error('This JSX element cannot be unwrapped');+ }++ const start = recastLocToOffset(input, element.loc.start);+ const end = recastLocToOffset(input, element.loc.end);+ const openingEnd = recastLocToOffset(input, element.openingElement.loc.end);+ const closingStart = recastLocToOffset(+ input,+ element.closingElement.loc.start,+ );+ let firstChild: JSXOpeningElement | null = null;+ for (const child of element.children) {+ recast.types.visit(child, {+ visitJSXOpeningElement(childPath) {+ firstChild ??= childPath.node as JSXOpeningElement;+ return false;+ },+ });+ if (firstChild !== null) break;+ }++ const parent = path.parentPath?.node as Node | undefined;+ const isJsxChild =+ parent?.type === 'JSXElement' || parent?.type === 'JSXFragment';+ const meaningfulChildren = element.children.filter(+ (child) => child.type !== 'JSXText' || child.value.trim() !== '',+ );+ const singleChild =+ meaningfulChildren.length === 1 &&+ (meaningfulChildren[0].type === 'JSXElement' ||+ meaningfulChildren[0].type === 'JSXFragment')+ ? meaningfulChildren[0]+ : null;+ const needsFragment = !isJsxChild && singleChild === null;++ // Preserve text, comments and expressions exactly. A fragment keeps JSX+ // children valid in expression positions without introducing a component.+ let replacement = input.slice(openingEnd, closingStart);+ if (needsFragment) {+ path.replace(+ recast.types.builders.jsxFragment(+ recast.types.builders.jsxOpeningFragment(),+ recast.types.builders.jsxClosingFragment(),+ element.children as never,+ ),+ );+ replacement = `<>${replacement}</>`;+ } else {+ if (isJsxChild) {+ path.replace(...element.children);+ } else {+ path.replace(singleChild!);+ }++ // Dedent code, but never change whitespace inside literal content.+ const preservedRanges: {+ start: number;+ end: number;+ preserveWhitespace: boolean;+ }[] = [];+ recast.types.visit(element, {+ visitNode(literalPath) {+ const literal = literalPath.node as Node;+ if (+ literal.loc &&+ (literal.type === 'TemplateLiteral' ||+ literal.type === 'StringLiteral' ||+ (literal.type === 'JSXText' && literal.value.trim() !== ''))+ ) {+ preservedRanges.push({+ preserveWhitespace: literal.type !== 'JSXText',+ start: recastLocToOffset(input, literal.loc.start),+ end: recastLocToOffset(input, literal.loc.end),+ });+ }++ this.traverse(literalPath);+ },+ });+ const indent = getLineIndent({input, offset: start});+ const firstContent = replacement.search(/\S/);+ const childIndent =+ firstContent === -1+ ? indent+ : getLineIndent({input, offset: openingEnd + firstContent});+ let offset = openingEnd;+ replacement = replacement+ .split(/(?<=\n)/)+ .map((line) => {+ const lineOffset = offset;+ offset += line.length;+ if (+ lineOffset === openingEnd ||+ preservedRanges.some(+ (range) =>+ lineOffset >= range.start &&+ lineOffset < range.end &&+ (range.preserveWhitespace ||+ input+ .slice(+ lineOffset,+ Math.min(range.end, lineOffset + line.length),+ )+ .trim().length > 0),+ )+ ) {+ return line;+ }++ return childIndent.startsWith(indent) && line.startsWith(childIndent)+ ? `${indent}${line.slice(childIndent.length)}`+ : line;+ })+ .join('');+ // Whitespace-only boundary lines belonged to the wrapper's layout.+ replacement = replacement+ .replace(/^[\t ]*\r?\n[\t ]*/, '')+ .replace(/\r?\n[\t ]*$/, '');+ }++ const output = applySourceEdits({input, edits: [{start, end, replacement}]});+ const {nodePathRemappings, finalNodePathByNode} = getNodePathRemappings({+ ast,+ captured,+ output,+ });+ return {+ ...getNodeEditResult({+ project,+ edits: [{filePath, output, nodePathRemappings}],+ }),+ childNodePath:+ firstChild === null+ ? null+ : (finalNodePathByNode.get(firstChild) ?? null),+ logLine: element.openingElement.loc.start.line,+ };+};diff --git a/packages/docs/docs/codemods/table-of-contents.tsx b/packages/docs/docs/codemods/table-of-contents.tsxindex 6c69515272..291f817732 100644--- a/packages/docs/docs/codemods/table-of-contents.tsx+++ b/packages/docs/docs/codemods/table-of-contents.tsx@@ -144,6 +144,10 @@ export const TableOfContents: React.FC = () => {same position.</div></TOCItem>+ <TOCItem link="/docs/codemods/unwrap-node">+ <strong>unwrapNode()</strong>+ <div>Removes a wrapper and keeps its children.</div>+ </TOCItem><TOCItem link="/docs/codemods/update-composition-metadata"><strong>updateCompositionMetadata()</strong><div>diff --git a/packages/docs/docs/codemods/unwrap-node.mdx b/packages/docs/docs/codemods/unwrap-node.mdxnew file mode 100644index 0000000000..6589629b26--- /dev/null+++ b/packages/docs/docs/codemods/unwrap-node.mdx@@ -0,0 +1,76 @@+---+image: /generated/articles-docs-codemods-unwrap-node.png+title: 'unwrapNode()'+crumb: '@remotion/codemods'+---++# unwrapNode()<AvailableFrom v="4.0.537" />++Removes a JSX element while keeping its children. Use it to unwrap components such as [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas), [`<HtmlInCanvasMotionBlur>`](/docs/motion-blur/html-in-canvas-motion-blur), or [`<Track>`](/docs/track).++The wrapper's props and behavior, including timing, layout, and effects, are removed. Its children keep their own props. Imports are left unchanged.++:::warning++_Draft API_: This API is experimental and may change.++:::++```ts twoslash title="unwrap-node.ts"+import {getNodes, unwrapNode, type CodemodProject} from '@remotion/codemods';++declare const project: CodemodProject;++const node = getNodes({project, filePath: 'src/Video.tsx'}).find(+ (candidate) => candidate.tagName === 'HtmlInCanvas',+);++if (node) {+ const result = unwrapNode({project, node});+ console.log(result.changes);+}+```++Children become siblings in the wrapper's parent. When the wrapper is an expression, such as a component's return value, a single JSX child replaces it directly. Multiple children, text, or expression children are enclosed in a fragment to keep the source valid.++## Options++### project++An in-memory [`CodemodProject`](/docs/codemods#project-model). The input project is not mutated.++### node++The reference of the element to unwrap. See [node references](/docs/codemods#node-references). The element must have a closing tag.++## Return value++### changes++An array of `{filePath, previousContents, nextContents}` file changes.++### nodePathRemappings++Mappings for removed and moved JSX nodes. The wrapper has a `null` new path, and its children receive updated paths where needed. See [node references](/docs/codemods#node-references).++### childNodePath++The new path of the first JSX element inside the wrapper's children, or `null` if there is none.++### logLine++The one-based line of the wrapper's opening tag in the input source.++## Errors++Throws when the node cannot be found or has no closing tag. Failed edits leave the input project unchanged.++## Compatibility++<CompatibilityTable chrome firefox safari nodejs bun serverlessFunctions clientSideRendering serverSideRendering player studio />++## See also++- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/unwrap-node.ts)+- [`wrapNode()`](/docs/codemods/wrap-node)+- [`deleteNodes()`](/docs/codemods/delete-nodes)diff --git a/packages/docs/docs/codemods/wrap-node.mdx b/packages/docs/docs/codemods/wrap-node.mdxindex 459160563a..46651bd479 100644--- a/packages/docs/docs/codemods/wrap-node.mdx+++ b/packages/docs/docs/codemods/wrap-node.mdx@@ -80,3 +80,4 @@ Throws when the node cannot be found, cannot be wrapped, or the wrapper is inval- [Source code for this function](https://github.com/remotion-dev/remotion/blob/main/packages/codemods/src/wrap-node.ts)- [`createElement()`](/docs/codemods/create-element)- [`addElement()`](/docs/codemods/add-element)+- [`unwrapNode()`](/docs/codemods/unwrap-node)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex d49c152831..d1cfed9e0d 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -2149,6 +2149,7 @@ const sidebars: SidebarsConfig = {'codemods/split-sequences','codemods/static-file-value','codemods/unwrap-folder',+ 'codemods/unwrap-node','codemods/update-composition-metadata','codemods/update-effect-keyframes','codemods/update-effect-props',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex ad009ab339..6e536850a1 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2772,6 +2772,15 @@ export const articles = [noAi: false,slug: 'codemods/unwrap-folder',},+ {+ id: 'codemods/unwrap-node',+ title: 'unwrapNode()',+ relativePath: 'docs/codemods/unwrap-node.mdx',+ compId: 'articles-docs-codemods-unwrap-node',+ crumb: '@remotion/codemods',+ noAi: false,+ slug: 'codemods/unwrap-node',+ },{id: 'codemods/update-composition-metadata',title: 'updateCompositionMetadata()',diff --git a/packages/docs/static/generated/articles-docs-codemods-unwrap-node.png b/packages/docs/static/generated/articles-docs-codemods-unwrap-node.pngnew file mode 100644index 0000000000..8b5de03d41Binary files /dev/null and b/packages/docs/static/generated/articles-docs-codemods-unwrap-node.png differdiff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.tsindex ff8a7c38ad..4bc56a270b 100644--- a/packages/studio-server/src/preview-server/api-routes.ts+++ b/packages/studio-server/src/preview-server/api-routes.ts@@ -77,6 +77,7 @@ import {unsubscribeFromDefaultProps} from './routes/unsubscribe-from-default-proimport {unsubscribeFromFileExistence} from './routes/unsubscribe-from-file-existence';import {unsubscribeFromSequenceProps} from './routes/unsubscribe-from-sequence-props';import {unwrapFolderHandler} from './routes/unwrap-folder';+import {unwrapNodeHandler} from './routes/unwrap-node';import {handleUpdate} from './routes/update-available';import {updateCompositionMetadataHandler} from './routes/update-composition-metadata';import {updateDefaultPropsHandler} from './routes/update-default-props';@@ -151,6 +152,7 @@ export const allApiRoutes: {'/api/paste-effects': pasteEffectsHandler,'/api/delete-nodes': deleteNodesHandler,'/api/duplicate-nodes': duplicateNodesHandler,+ '/api/unwrap-node': unwrapNodeHandler,'/api/wrap-node': wrapNodeHandler,'/api/precompose-jsx-nodes': precomposeJsxNodesHandler,'/api/split-sequences': splitSequencesHandler,diff --git a/packages/studio-server/src/preview-server/routes/unwrap-node.ts b/packages/studio-server/src/preview-server/routes/unwrap-node.tsnew file mode 100644index 0000000000..42a7dd1467--- /dev/null+++ b/packages/studio-server/src/preview-server/routes/unwrap-node.ts@@ -0,0 +1,129 @@+import {readFileSync} from 'node:fs';+import {canUnwrapNode, unwrapNode} from '@remotion/codemods';+import {RenderInternals} from '@remotion/renderer';+import type {+ UnwrapNodeRequest,+ UnwrapNodeResponse,+} from '@remotion/studio-shared';+import {writeFileAndNotifyFileWatchers} from '../../file-watcher';+import {resolveFileInsideProject} from '../../helpers/resolve-file-inside-project';+import type {ApiHandler} from '../api-types';+import {formatLogFileLocation} from '../format-log-file-location';+import {broadcastSequenceNodePathMutation} from '../sequence-node-path-mutation';+import {+ printUndoHint,+ pushTransactionToUndoStack,+ suppressUndoStackInvalidation,+} from '../undo-stack';+import {+ getCodemodTimingPrefix,+ withSourceFileWriteQueue,+} from './source-file-write-queue';++export const unwrapNodeHandler: ApiHandler<+ UnwrapNodeRequest,+ UnwrapNodeResponse+> = ({+ input: {fileName, compositionId, nodePath, dryRun},+ remotionRoot,+ logLevel,+}) => {+ return withSourceFileWriteQueue((): Promise<UnwrapNodeResponse> => {+ try {+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({+ remotionRoot,+ fileName,+ action: 'modify',+ });+ const fileContents = readFileSync(absolutePath, 'utf-8');+ const canUnwrap = canUnwrapNode({input: fileContents, nodePath});+ if (dryRun) {+ return Promise.resolve({+ success: true,+ canUnwrap,+ nodePathMutation: null,+ });+ }++ const result = unwrapNode({+ project: {files: {[absolutePath]: fileContents}, rootDir: remotionRoot},+ node: {filePath: absolutePath, nodePath},+ });+ const change = result.changes.find(+ ({filePath}) => filePath === absolutePath,+ );+ if (+ change?.previousContents !== fileContents ||+ change.nextContents === null+ ) {+ throw new Error('Could not unwrap JSX node');+ }++ const output = change.nextContents;+ const remappings = result.nodePathRemappings.map(+ ({oldNodePath, newNodePath, oldJsxName, newJsxName}) => ({+ oldNodePath,+ newNodePath,+ oldJsxName,+ newJsxName,+ }),+ );+ const {childNodePath} = result;+ const nodePathMutation = broadcastSequenceNodePathMutation(+ [{absolutePath, remappings}],+ childNodePath !== null+ ? {compositionId, absolutePath, nodePath: childNodePath}+ : null,+ );+ const line = result.logLine;+ pushTransactionToUndoStack({+ snapshots: [+ {+ filePath: absolutePath,+ oldContents: fileContents,+ newContents: null,+ logLine: line,+ nodePathRemappings: remappings,+ },+ ],+ logLevel,+ remotionRoot,+ description: {+ undoMessage: '↩️ Unwrapping JSX',+ redoMessage: '↪️ Unwrapping JSX',+ },+ entryType: 'unwrap-node',+ suppressHmrOnFileRestore: false,+ undoRedoNavigation: null,+ });+ suppressUndoStackInvalidation(absolutePath);+ writeFileAndNotifyFileWatchers({+ file: absolutePath,+ content: output,+ originatorClientId: undefined,+ metadata: {skipSequencePropsUpdate: true},+ });+ const locationLabel = formatLogFileLocation({+ remotionRoot,+ absolutePath,+ line,+ });+ RenderInternals.Log.info(+ {indent: false, logLevel},+ `${getCodemodTimingPrefix(logLevel)}${RenderInternals.chalk.blueBright(locationLabel)} Unwrapped JSX`,+ );+ RenderInternals.Log.verbose(+ {indent: false, logLevel},+ `[unwrap-node] Wrote ${fileRelativeToRoot}`,+ );+ printUndoHint(logLevel);+ return Promise.resolve({success: true, canUnwrap, nodePathMutation});+ } catch (err) {+ return Promise.resolve({+ success: false,+ reason: (err as Error).message,+ stack: (err as Error).stack ?? '',+ });+ }+ });+};diff --git a/packages/studio-server/src/preview-server/undo-stack.ts b/packages/studio-server/src/preview-server/undo-stack.tsindex 49d8273612..8839485fb1 100644--- a/packages/studio-server/src/preview-server/undo-stack.ts+++ b/packages/studio-server/src/preview-server/undo-stack.ts@@ -44,6 +44,7 @@ type UndoEntryType =| 'delete-nodes'| 'duplicate-nodes'| 'wrap-node'+ | 'unwrap-node'| 'precompose-jsx-nodes'| 'split-sequences'| 'split-video-from-audio'diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.tsindex 064e224f20..427d2f75ad 100644--- a/packages/studio-shared/src/api-requests.ts+++ b/packages/studio-shared/src/api-requests.ts@@ -995,6 +995,21 @@ export type WrapNodeResponse =}| {success: false; reason: string; stack: string};+export type UnwrapNodeRequest = {+ fileName: string;+ compositionId: string;+ nodePath: SequenceNodePath;+ dryRun: boolean;+};++export type UnwrapNodeResponse =+ | {+ success: true;+ canUnwrap: boolean;+ nodePathMutation: SequenceNodePathMutation | null;+ }+ | {success: false; reason: string; stack: string};+export type PrecomposeJsxNodesRequestItem = {fileName: string;nodePath: SequenceNodePath;@@ -1684,6 +1699,10 @@ export const studioOperations = {PrecomposeJsxNodesRequest,PrecomposeJsxNodesResponse>({mutatesSource: true}),+ '/api/unwrap-node': new StudioOperation<+ UnwrapNodeRequest,+ UnwrapNodeResponse+ >({mutatesSource: true}),'/api/wrap-node': new StudioOperation<WrapNodeRequest, WrapNodeResponse>({mutatesSource: true,}),diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.tsindex 68e5fef24e..ef13330f44 100644--- a/packages/studio-shared/src/browser-studio-operations.ts+++ b/packages/studio-shared/src/browser-studio-operations.ts@@ -34,6 +34,8 @@ import type {PrecomposeJsxNodesResponse,DuplicateNodesRequest,DuplicateNodesResponse,+ UnwrapNodeRequest,+ UnwrapNodeResponse,WrapNodeRequest,WrapNodeResponse,InsertCompositionElementRequest,@@ -189,6 +191,7 @@ export type BrowserStudioOperations = {duplicateNodes: (request: DuplicateNodesRequest,) => Promise<DuplicateNodesResponse>;+ unwrapNode: (request: UnwrapNodeRequest) => Promise<UnwrapNodeResponse>;wrapNode: (request: WrapNodeRequest) => Promise<WrapNodeResponse>;effects: BrowserStudioEffectOperations;findInFile: (request: FindInFileRequest) => Promise<FindInFileResponse>;diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.tsindex 14b6f636fb..55dfea492d 100644--- a/packages/studio-shared/src/index.ts+++ b/packages/studio-shared/src/index.ts@@ -61,6 +61,8 @@ export {DuplicateNodesRequestItem,DuplicateNodesResponse,NodeWrapper,+ UnwrapNodeRequest,+ UnwrapNodeResponse,WrapNodeRequest,WrapNodeResponse,EditorPickerId,diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsxindex c38d084796..1dde0d5dce 100644--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx@@ -49,6 +49,7 @@ import {useSequenceInspectorSourceLocation,} from './SequenceInspectorHeader';import {SequencePrecomposeAction} from './SequencePrecomposeAction';+import {SequenceUnwrapAction} from './SequenceUnwrapAction';import {SequenceWrapAction} from './SequenceWrapAction';import {selectedContainer} from './styles';import {useTrackForSelection} from './use-track-for-selection';@@ -367,6 +368,10 @@ const SequenceSourceQuickActions: React.FC<{sourceActionsDisabled={sourceActionsDisabled}sourceLocation={validatedLocation}/>+ <SequenceUnwrapAction+ nodePathInfo={selection.nodePathInfo}+ sourceActionsDisabled={sourceActionsDisabled || isTransition}+ /><SequencePrecomposeActiontargets={[{diff --git a/packages/studio/src/components/InspectorPanel/SequenceUnwrapAction.tsx b/packages/studio/src/components/InspectorPanel/SequenceUnwrapAction.tsxnew file mode 100644index 0000000000..1241dc0221--- /dev/null+++ b/packages/studio/src/components/InspectorPanel/SequenceUnwrapAction.tsx@@ -0,0 +1,88 @@+import React, {useCallback, useContext, useEffect, useState} from 'react';+import {Internals} from 'remotion';+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';+import {showNotification} from '../Notifications/NotificationCenter';+import {unwrapNode} from '../unwrap-node-api';+import {+ InspectorQuickAction,+ largeInspectorActionIconContainerStyle,+ largeInspectorActionIconStyle,+} from './common';++export const SequenceUnwrapAction: React.FC<{+ readonly nodePathInfo: SequenceNodePathInfo;+ readonly sourceActionsDisabled: boolean;+}> = ({nodePathInfo, sourceActionsDisabled}) => {+ const {canvasContent} = useContext(Internals.CompositionManager);+ const [canUnwrap, setCanUnwrap] = useState(false);+ const [busy, setBusy] = useState(false);+ const {absolutePath, nodePath} = nodePathInfo.sequenceSubscriptionKey;+ const compositionId =+ canvasContent?.type === 'composition' ? canvasContent.compositionId : null;++ useEffect(() => {+ let cancelled = false;+ setCanUnwrap(false);+ if (sourceActionsDisabled || compositionId === null) return;+ unwrapNode({fileName: absolutePath, nodePath, compositionId, dryRun: true})+ .then((result) => {+ if (!cancelled) setCanUnwrap(result.success && result.canUnwrap);+ })+ .catch(() => undefined);+ return () => {+ cancelled = true;+ };+ }, [absolutePath, nodePath, compositionId, sourceActionsDisabled]);++ const onUnwrap = useCallback(async () => {+ if (busy || !canUnwrap || sourceActionsDisabled || compositionId === null)+ return;+ setBusy(true);+ try {+ const result = await unwrapNode({+ fileName: absolutePath,+ nodePath,+ compositionId,+ dryRun: false,+ });+ if (!result.success) showNotification(result.reason, 4000);+ } catch (error) {+ showNotification((error as Error).message, 4000);+ } finally {+ setBusy(false);+ }+ }, [+ absolutePath,+ nodePath,+ compositionId,+ busy,+ canUnwrap,+ sourceActionsDisabled,+ ]);++ if (!canUnwrap || sourceActionsDisabled || compositionId === null)+ return null;+ return (+ <InspectorQuickAction+ disabled={busy}+ onClick={onUnwrap}+ iconContainerStyle={largeInspectorActionIconContainerStyle}+ aria-label="Unwrap: remove this element and keep its children"+ renderIcon={(color) => (+ <svg+ viewBox="0 0 24 24"+ style={largeInspectorActionIconStyle}+ fill="none"+ stroke={color}+ strokeWidth={1.5}+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5M9 9h6v6H9z" />+ </svg>+ )}+ >+ Unwrap+ </InspectorQuickAction>+ );+};diff --git a/packages/studio/src/components/unwrap-node-api.ts b/packages/studio/src/components/unwrap-node-api.tsnew file mode 100644index 0000000000..2bba0fb128--- /dev/null+++ b/packages/studio/src/components/unwrap-node-api.ts@@ -0,0 +1,17 @@+import type {+ UnwrapNodeRequest,+ UnwrapNodeResponse,+} from '@remotion/studio-shared';+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';+import {callApi} from './call-api';++export const unwrapNode = (+ request: UnwrapNodeRequest,+): Promise<UnwrapNodeResponse> => {+ const browserStudioOperations = getBrowserStudioOperations();+ if (browserStudioOperations) {+ return browserStudioOperations.unwrapNode(request);+ }++ return callApi('/api/unwrap-node', request);+};diff --git a/packages/studio/src/test/make-browser-studio-operations.ts b/packages/studio/src/test/make-browser-studio-operations.tsindex 2fe196abbd..4e456a5ff9 100644--- a/packages/studio/src/test/make-browser-studio-operations.ts+++ b/packages/studio/src/test/make-browser-studio-operations.ts@@ -19,6 +19,7 @@ export const makeBrowserStudioOperations = (duplicateComposition: () => unusedOperation('duplicateComposition'),duplicateNodes: () => unusedOperation('duplicateNodes'),precomposeJsxNodes: () => unusedOperation('precomposeJsxNodes'),+ unwrapNode: () => unusedOperation('unwrapNode'),wrapNode: () => unusedOperation('wrapNode'),effects: {addEffect: () => unusedOperation('effects'),