Skip to content

🎥 Make videos programmatically with React

Add sequence inspector Wrap codemod

Jonny Burger9cbaf718b0ab
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index e075470586..7291c9552f 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -12,6 +12,8 @@ import {
duplicateComposition as duplicateCompositionCodemod,
duplicateEffects as duplicateEffectsCodemod,
duplicateJsxNodes as duplicateJsxNodesCodemod,
+ canWrapJsxNode,
+ wrapJsxNode as wrapJsxNodeCodemod,
getJsxNodeProps,
moveComposition,
moveFolder,
@@ -1438,6 +1440,52 @@ export const createBrowserStudioOperations = ({
}
};
+ const wrapJsxNode: NonNullable<BrowserStudioOperations['wrapJsxNode']> = ({
+ fileName,
+ nodePath,
+ wrapper,
+ width,
+ height,
+ }) => {
+ try {
+ const project = getProject();
+ const filePath = findProjectFile({project, filePath: fileName});
+ const eligibility = canWrapJsxNode({
+ input: project.files[filePath],
+ nodePath,
+ });
+ if (wrapper === null) {
+ return Promise.resolve({
+ success: true,
+ ...eligibility,
+ nodePathMutation: null,
+ });
+ }
+
+ const result = wrapJsxNodeCodemod({
+ project,
+ node: {filePath, nodePath},
+ wrapper,
+ width: width ?? 0,
+ height: height ?? 0,
+ });
+ const nodePathMutation = controller.applyMutation({
+ undoRedoNavigation: null,
+ timelineSelection: null,
+ fileName,
+ mutate: () => result.project,
+ nodePathMutationFiles: getNodePathMutationFiles(result),
+ });
+ if (nodePathMutation === null) {
+ throw new Error('Could not wrap JSX node');
+ }
+
+ return Promise.resolve({success: true, ...eligibility, nodePathMutation});
+ } catch (error) {
+ return Promise.resolve(getStructuredError(error));
+ }
+ };
+
const splitJsxSequence: BrowserStudioOperations['splitJsxSequence'] = async ({
sequences,
}) => {
@@ -2162,6 +2210,7 @@ export const createBrowserStudioOperations = ({
}),
duplicateComposition,
duplicateJsxNode,
+ wrapJsxNode,
effects: effectOperations,
emitEvent: controller.emitEvent,
findInFile: controller.findInFile,
diff --git a/packages/codemods/src/index.ts b/packages/codemods/src/index.ts
index b59a60b3b2..e3ee3b4a4c 100644
--- a/packages/codemods/src/index.ts
+++ b/packages/codemods/src/index.ts
@@ -129,6 +129,7 @@ export type {
CodemodResult,
} from './codemod-project';
export {deleteJsxNodes, type DeleteJsxNodesOptions} from './delete-jsx-nodes';
+export {canWrapJsxNode, wrapJsxNode} from './wrap-jsx-node';
export type {
EffectArrayElement,
EffectDeletionTarget,
diff --git a/packages/codemods/src/wrap-jsx-node.ts b/packages/codemods/src/wrap-jsx-node.ts
new file mode 100644
index 0000000000..342aea7e4f
--- /dev/null
+++ b/packages/codemods/src/wrap-jsx-node.ts
@@ -0,0 +1,179 @@
+import type {JSXElement, 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 JsxNodeReference} from './node-references';
+import {ensureNamedImport, getImportedName} from './sequence-props/imports';
+import {parseAst, serializeAst} from './sequence-props/parse-ast';
+import {stripParenthesizedExtra} from './strip-parenthesized-extra';
+
+type JsxWrapper = 'AbsoluteFill' | 'Sequence' | 'HtmlInCanvas';
+
+export const canWrapJsxNode = ({
+ input,
+ nodePath,
+}: {
+ input: string;
+ nodePath: SequenceNodePath;
+}): {canWrap: boolean; canWrapHtmlInCanvas: boolean} => {
+ const ast = parseAst(input);
+ const path = findJsxElementPathForDeletion(ast, nodePath);
+ if (!path || !(path.node as JSXElement).loc) {
+ return {canWrap: false, canWrapHtmlInCanvas: false};
+ }
+
+ const htmlInCanvasNames = new Set(['HtmlInCanvas']);
+ for (const statement of ast.program.body) {
+ if (
+ statement.type !== 'ImportDeclaration' ||
+ statement.source.value !== 'remotion'
+ ) {
+ continue;
+ }
+
+ for (const specifier of statement.specifiers ?? []) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ getImportedName(specifier) === 'HtmlInCanvas'
+ ) {
+ htmlInCanvasNames.add(specifier.local?.name ?? 'HtmlInCanvas');
+ }
+ }
+ }
+
+ const isHtmlInCanvasElement = (element: JSXElement) => {
+ const {name} = element.openingElement;
+ return (
+ (name.type === 'JSXIdentifier' && htmlInCanvasNames.has(name.name)) ||
+ (name.type === 'JSXMemberExpression' &&
+ name.property.name === 'HtmlInCanvas')
+ );
+ };
+
+ let current = path;
+ while (current) {
+ const node = current.node as Node;
+ if (node.type === 'JSXElement' && isHtmlInCanvasElement(node)) {
+ return {canWrap: true, canWrapHtmlInCanvas: false};
+ }
+
+ current = current.parentPath;
+ }
+
+ let containsHtmlInCanvas = false;
+ recast.types.visit(path.node as Parameters<typeof recast.types.visit>[0], {
+ visitJSXElement(elementPath) {
+ if (isHtmlInCanvasElement(elementPath.node as JSXElement)) {
+ containsHtmlInCanvas = true;
+ }
+
+ this.traverse(elementPath);
+ },
+ });
+
+ return {canWrap: true, canWrapHtmlInCanvas: !containsHtmlInCanvas};
+};
+
+export const wrapJsxNode = <Project extends CodemodProject>({
+ project,
+ node,
+ wrapper,
+ width,
+ height,
+}: {
+ project: Project;
+ node: JsxNodeReference;
+ wrapper: JsxWrapper;
+ width: number;
+ height: number;
+}) => {
+ const filePath = findProjectFile({project, filePath: node.filePath});
+ const input = project.files[filePath];
+ const eligibility = canWrapJsxNode({input, nodePath: node.nodePath});
+ if (
+ !eligibility.canWrap ||
+ (wrapper === 'HtmlInCanvas' && !eligibility.canWrapHtmlInCanvas)
+ ) {
+ throw new Error('This JSX element cannot be wrapped');
+ }
+
+ if (
+ wrapper === 'HtmlInCanvas' &&
+ (!Number.isInteger(width) ||
+ width <= 0 ||
+ !Number.isInteger(height) ||
+ height <= 0)
+ ) {
+ throw new Error('HtmlInCanvas requires positive integer dimensions');
+ }
+
+ const ast = parseAst(input);
+ const captured = captureJsxNodePaths(ast);
+ const path = findJsxElementPathForDeletion(ast, node.nodePath);
+ if (!path) {
+ throw new Error('Could not find the JSX element to wrap');
+ }
+
+ const original = path.node as JSXElement;
+ const logLine = original.openingElement.loc?.start.line ?? 1;
+ const occupiedNames = new Set<string>();
+ recast.types.visit(ast, {
+ visitIdentifier(identifierPath) {
+ occupiedNames.add(identifierPath.node.name);
+ this.traverse(identifierPath);
+ },
+ visitJSXIdentifier(identifierPath) {
+ occupiedNames.add(identifierPath.node.name);
+ this.traverse(identifierPath);
+ },
+ });
+ let suggestedName: string = wrapper;
+ for (let suffix = 1; occupiedNames.has(suggestedName); suffix++) {
+ suggestedName = `${wrapper}FromRemotion${suffix}`;
+ }
+
+ const localName = ensureNamedImport({
+ ast,
+ importedName: wrapper,
+ localName: suggestedName,
+ sourcePath: 'remotion',
+ });
+ const b = recast.types.builders;
+ const name = b.jsxIdentifier(localName);
+ const attributes =
+ wrapper === 'HtmlInCanvas'
+ ? [
+ b.jsxAttribute(
+ b.jsxIdentifier('width'),
+ b.jsxExpressionContainer(b.numericLiteral(width)),
+ ),
+ b.jsxAttribute(
+ b.jsxIdentifier('height'),
+ b.jsxExpressionContainer(b.numericLiteral(height)),
+ ),
+ ]
+ : [];
+ path.replace(
+ b.jsxElement(
+ b.jsxOpeningElement(name, attributes, false),
+ b.jsxClosingElement(b.jsxIdentifier(localName)),
+ [stripParenthesizedExtra(original) as never],
+ ) as never,
+ );
+
+ const output = serializeAst(ast);
+ const {nodePathRemappings} = getNodePathRemappings({ast, captured, output});
+ return {
+ ...getNodeEditResult({
+ project,
+ edits: [{filePath, output, nodePathRemappings}],
+ }),
+ logLine,
+ };
+};
diff --git a/packages/studio-server/src/preview-server/api-routes.ts b/packages/studio-server/src/preview-server/api-routes.ts
index 2e544e1161..7d9e489946 100644
--- a/packages/studio-server/src/preview-server/api-routes.ts
+++ b/packages/studio-server/src/preview-server/api-routes.ts
@@ -72,6 +72,7 @@ import {updateEffectKeyframeSettingsHandler} from './routes/update-effect-keyfra
import {updateElementInstallTargetHandler} from './routes/update-element-install-target';
import {updateSequenceKeyframeSettingsHandler} from './routes/update-sequence-keyframe-settings';
import {handleUpgradeRemotion} from './routes/upgrade-remotion';
+import {wrapJsxNodeHandler} from './routes/wrap-jsx-node';
type StandardApiRoute = Exclude<
keyof ApiRoutes,
@@ -128,6 +129,7 @@ export const allApiRoutes: {
'/api/paste-effects': pasteEffectsHandler,
'/api/delete-jsx-nodes': deleteJsxNodesHandler,
'/api/duplicate-jsx-node': duplicateJsxNodeHandler,
+ '/api/wrap-jsx-node': wrapJsxNodeHandler,
'/api/split-jsx-sequence': splitJsxSequenceHandler,
'/api/split-video-from-audio': splitVideoFromAudioHandler,
'/api/insert-basic-captions': insertBasicCaptionsHandler,
diff --git a/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts b/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts
new file mode 100644
index 0000000000..16b21387e9
--- /dev/null
+++ b/packages/studio-server/src/preview-server/routes/wrap-jsx-node.ts
@@ -0,0 +1,121 @@
+import {readFileSync} from 'node:fs';
+import {canWrapJsxNode, wrapJsxNode} from '@remotion/codemods';
+import {RenderInternals} from '@remotion/renderer';
+import type {
+ WrapJsxNodeRequest,
+ WrapJsxNodeResponse,
+} 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 wrapJsxNodeHandler: ApiHandler<
+ WrapJsxNodeRequest,
+ WrapJsxNodeResponse
+> = ({
+ input: {fileName, nodePath, wrapper, width, height},
+ remotionRoot,
+ logLevel,
+}) => {
+ return withSourceFileWriteQueue((): Promise<WrapJsxNodeResponse> => {
+ try {
+ const {absolutePath, fileRelativeToRoot} = resolveFileInsideProject({
+ remotionRoot,
+ fileName,
+ action: 'modify',
+ });
+ const fileContents = readFileSync(absolutePath, 'utf-8');
+ const eligibility = canWrapJsxNode({input: fileContents, nodePath});
+ if (wrapper === null) {
+ return Promise.resolve({
+ success: true,
+ ...eligibility,
+ nodePathMutation: null,
+ });
+ }
+
+ if (
+ !eligibility.canWrap ||
+ (wrapper === 'HtmlInCanvas' && !eligibility.canWrapHtmlInCanvas)
+ ) {
+ throw new Error('This JSX element cannot be wrapped');
+ }
+
+ const result = wrapJsxNode({
+ project: {files: {[absolutePath]: fileContents}, rootDir: remotionRoot},
+ node: {filePath: absolutePath, nodePath},
+ wrapper,
+ width: width ?? 0,
+ height: height ?? 0,
+ });
+ const output = result.project.files[absolutePath];
+ const remappings = result.nodePathRemappings.map(
+ ({oldNodePath, newNodePath}) => ({oldNodePath, newNodePath}),
+ );
+ const nodePathMutation = broadcastSequenceNodePathMutation(
+ [{absolutePath, remappings}],
+ null,
+ );
+ const line = result.logLine;
+ pushTransactionToUndoStack({
+ snapshots: [
+ {
+ filePath: absolutePath,
+ oldContents: fileContents,
+ newContents: null,
+ logLine: line,
+ nodePathRemappings: remappings,
+ },
+ ],
+ logLevel,
+ remotionRoot,
+ description: {
+ undoMessage: `↩️ Wrapping in ${wrapper}`,
+ redoMessage: `↪️ Wrapping in ${wrapper}`,
+ },
+ entryType: 'wrap-jsx-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)} Wrapped JSX in <${wrapper}>`,
+ );
+ RenderInternals.Log.verbose(
+ {indent: false, logLevel},
+ `[wrap-jsx-node] Wrote ${fileRelativeToRoot}`,
+ );
+ printUndoHint(logLevel);
+ return Promise.resolve({success: true, ...eligibility, 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.ts
index 915003e550..8571fadb24 100644
--- a/packages/studio-server/src/preview-server/undo-stack.ts
+++ b/packages/studio-server/src/preview-server/undo-stack.ts
@@ -40,6 +40,7 @@ type UndoEntryType =
| 'reorder-sequence'
| 'delete-jsx-nodes'
| 'duplicate-jsx-node'
+ | 'wrap-jsx-node'
| 'split-jsx-sequence'
| 'split-video-from-audio'
| 'insert-basic-captions'
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index c946b851cc..1237854327 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -884,6 +884,25 @@ export type DuplicateJsxNodeResponse =
stack: string;
};
+export type JsxWrapper = 'AbsoluteFill' | 'Sequence' | 'HtmlInCanvas';
+
+export type WrapJsxNodeRequest = {
+ fileName: string;
+ nodePath: SequenceNodePath;
+ wrapper: JsxWrapper | null;
+ width: number | null;
+ height: number | null;
+};
+
+export type WrapJsxNodeResponse =
+ | {
+ success: true;
+ canWrap: boolean;
+ canWrapHtmlInCanvas: boolean;
+ nodePathMutation: SequenceNodePathMutation | null;
+ }
+ | {success: false; reason: string; stack: string};
+
export type SplitJsxSequenceRequestItem = {
fileName: string;
nodePath: SequenceNodePath;
@@ -1437,6 +1456,7 @@ export type ApiRoutes = {
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse
>;
+ '/api/wrap-jsx-node': ReqAndRes<WrapJsxNodeRequest, WrapJsxNodeResponse>;
'/api/split-jsx-sequence': ReqAndRes<
SplitJsxSequenceRequest,
SplitJsxSequenceResponse
diff --git a/packages/studio-shared/src/browser-studio-operations.ts b/packages/studio-shared/src/browser-studio-operations.ts
index 9ee6a767ef..3b6bf037ee 100644
--- a/packages/studio-shared/src/browser-studio-operations.ts
+++ b/packages/studio-shared/src/browser-studio-operations.ts
@@ -29,6 +29,8 @@ import type {
DuplicateEffectResponse,
DuplicateJsxNodeRequest,
DuplicateJsxNodeResponse,
+ WrapJsxNodeRequest,
+ WrapJsxNodeResponse,
InsertJsxElementRequest,
InsertJsxElementResponse,
InsertElementRequest,
@@ -189,6 +191,7 @@ export type BrowserStudioOperations = {
duplicateJsxNode: (
request: DuplicateJsxNodeRequest,
) => Promise<DuplicateJsxNodeResponse>;
+ wrapJsxNode?: (request: WrapJsxNodeRequest) => Promise<WrapJsxNodeResponse>;
effects: BrowserStudioEffectOperations;
findInFile: (request: FindInFileRequest) => Promise<FindInFileResponse>;
getFileSource: (fileName: string) => Promise<string | null>;
diff --git a/packages/studio-shared/src/index.ts b/packages/studio-shared/src/index.ts
index d55adce154..06990bddf1 100644
--- a/packages/studio-shared/src/index.ts
+++ b/packages/studio-shared/src/index.ts
@@ -53,6 +53,9 @@ export {
DuplicateJsxNodeRequest,
DuplicateJsxNodeRequestItem,
DuplicateJsxNodeResponse,
+ JsxWrapper,
+ WrapJsxNodeRequest,
+ WrapJsxNodeResponse,
EditorPickerId,
EffectDefinition,
ElementInstallDestination,
diff --git a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
index 0ba62155fe..b743c7cdd5 100644
--- a/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/SequenceSelectionInspector.tsx
@@ -50,6 +50,7 @@ import {
SequenceInspectorHeader,
useSequenceInspectorSourceLocation,
} from './SequenceInspectorHeader';
+import {SequenceWrapAction} from './SequenceWrapAction';
import {selectedContainer} from './styles';
import {useTrackForSelection} from './use-track-for-selection';
@@ -332,6 +333,11 @@ const SequenceSourceQuickActions: React.FC<{
>
Duplicate
</InspectorQuickAction>
+ <SequenceWrapAction
+ nodePathInfo={selection.nodePathInfo}
+ sequence={track.sequence}
+ sourceActionsDisabled={sourceActionsDisabled}
+ />
<InspectorQuickAction
disabled={sourceActionsDisabled}
onClick={onDelete}
diff --git a/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx b/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx
new file mode 100644
index 0000000000..0013b386b8
--- /dev/null
+++ b/packages/studio/src/components/InspectorPanel/SequenceWrapAction.tsx
@@ -0,0 +1,164 @@
+import type {JsxWrapper} from '@remotion/studio-shared';
+import React, {useCallback, useEffect, useMemo, useState} from 'react';
+import {isHtmlInCanvasSupported, useVideoConfig} from 'remotion';
+import {LIGHT_TEXT} from '../../helpers/colors';
+import type {SequenceNodePathInfo} from '../../helpers/get-timeline-sequence-sort-key';
+import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
+import {CaretDown} from '../../icons/caret';
+import {INSPECTOR_PANEL_HORIZONTAL_PADDING} from '../InspectorPanelLayout';
+import type {ComboboxValue} from '../NewComposition/ComboBox';
+import {showNotification} from '../Notifications/NotificationCenter';
+import {SegmentedButton, type SegmentedButtonSegment} from '../SegmentedButton';
+import {wrapJsxNode} from '../wrap-jsx-node-api';
+
+const wrapperNames: JsxWrapper[] = ['AbsoluteFill', 'Sequence', 'HtmlInCanvas'];
+
+const buttonStyle: React.CSSProperties = {
+ borderRadius: 4,
+ height: 28,
+ margin: '0 4px',
+ width: 'calc(100% - 8px)',
+};
+
+const segmentStyle: React.CSSProperties = {
+ fontSize: 13,
+ gap: 8,
+ justifyContent: 'flex-start',
+ padding: `0 ${INSPECTOR_PANEL_HORIZONTAL_PADDING - 4}px`,
+ width: '100%',
+};
+
+const labelStyle: React.CSSProperties = {flex: 1, textAlign: 'left'};
+
+export const SequenceWrapAction: React.FC<{
+ readonly nodePathInfo: SequenceNodePathInfo;
+ readonly sequence: TimelineTrackData['sequence'];
+ readonly sourceActionsDisabled: boolean;
+}> = ({nodePathInfo, sequence, sourceActionsDisabled}) => {
+ const {width, height} = useVideoConfig();
+ const nodePathKey = JSON.stringify(nodePathInfo.sequenceSubscriptionKey);
+ const [eligibility, setEligibility] = useState<{
+ canWrap: boolean;
+ canWrapHtmlInCanvas: boolean;
+ } | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ setEligibility(null);
+ if (sourceActionsDisabled) {
+ return;
+ }
+
+ let cancelled = false;
+ const nodePath = JSON.parse(
+ nodePathKey,
+ ) as SequenceNodePathInfo['sequenceSubscriptionKey'];
+ wrapJsxNode({
+ fileName: nodePath.absolutePath,
+ nodePath: nodePath.nodePath,
+ wrapper: null,
+ width: null,
+ height: null,
+ })
+ .then((result) => {
+ if (!cancelled && result.success) {
+ setEligibility({
+ canWrap: result.canWrap,
+ canWrapHtmlInCanvas: result.canWrapHtmlInCanvas,
+ });
+ }
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [nodePathKey, sequence, sourceActionsDisabled]);
+
+ const onWrap = useCallback(
+ (wrapper: JsxWrapper) => {
+ if (busy || sourceActionsDisabled || !eligibility?.canWrap) {
+ return;
+ }
+
+ setBusy(true);
+ const nodePath = JSON.parse(
+ nodePathKey,
+ ) as SequenceNodePathInfo['sequenceSubscriptionKey'];
+ wrapJsxNode({
+ fileName: nodePath.absolutePath,
+ nodePath: nodePath.nodePath,
+ wrapper,
+ width,
+ height,
+ })
+ .then((result) => {
+ if (!result.success) {
+ showNotification(result.reason, 4000);
+ }
+ })
+ .catch((error) => {
+ showNotification((error as Error).message, 4000);
+ })
+ .finally(() => setBusy(false));
+ },
+ [busy, eligibility, height, nodePathKey, sourceActionsDisabled, width],
+ );
+
+ const values = useMemo<ComboboxValue[]>(
+ () =>
+ wrapperNames.map((wrapper) => ({
+ type: 'item',
+ id: wrapper,
+ label: wrapper,
+ value: wrapper,
+ onClick: () => onWrap(wrapper),
+ keyHint: null,
+ leftItem: null,
+ subMenu: null,
+ quickSwitcherLabel: null,
+ disabled:
+ busy ||
+ (wrapper === 'HtmlInCanvas' &&
+ (!eligibility?.canWrapHtmlInCanvas || !isHtmlInCanvasSupported())),
+ })),
+ [busy, eligibility, onWrap],
+ );
+
+ const segments = useMemo<SegmentedButtonSegment[]>(
+ () => [
+ {
+ ariaLabel: 'Wrap',
+ buttonId: null,
+ disabled: busy,
+ idleColor: LIGHT_TEXT,
+ leaveLeftSpace: false,
+ onOpenChange: null,
+ renderContent: (color) => (
+ <>
+ <span style={labelStyle}>Wrap</span>
+ <CaretDown color={color} />
+ </>
+ ),
+ segmentId: 'wrap',
+ selectedId: null,
+ style: segmentStyle,
+ title:
+ nodePathInfo.numberOfSequencesWithThisNodePath > 1
+ ? `Wrap all ${nodePathInfo.numberOfSequencesWithThisNodePath} instances of this JSX element`
+ : 'Wrap this JSX element',
+ tooltipLabel: null,
+ type: 'menu',
+ values,
+ },
+ ],
+ [busy, nodePathInfo.numberOfSequencesWithThisNodePath, values],
+ );
+
+ if (!eligibility?.canWrap || sourceActionsDisabled) {
+ return null;
+ }
+
+ return (
+ <SegmentedButton segments={segments} style={buttonStyle} title={null} />
+ );
+};
diff --git a/packages/studio/src/components/wrap-jsx-node-api.ts b/packages/studio/src/components/wrap-jsx-node-api.ts
new file mode 100644
index 0000000000..e41cacee77
--- /dev/null
+++ b/packages/studio/src/components/wrap-jsx-node-api.ts
@@ -0,0 +1,25 @@
+import type {
+ WrapJsxNodeRequest,
+ WrapJsxNodeResponse,
+} from '@remotion/studio-shared';
+import {getBrowserStudioOperations} from '../helpers/browser-studio-operations';
+import {callApi} from './call-api';
+
+export const wrapJsxNode = (
+ request: WrapJsxNodeRequest,
+): Promise<WrapJsxNodeResponse> => {
+ const browserStudioOperations = getBrowserStudioOperations();
+ if (browserStudioOperations) {
+ if (!browserStudioOperations.wrapJsxNode) {
+ return Promise.resolve({
+ success: false,
+ reason: 'Wrapping JSX is unavailable in this Browser Studio',
+ stack: '',
+ });
+ }
+
+ return browserStudioOperations.wrapJsxNode(request);
+ }
+
+ return callApi('/api/wrap-jsx-node', request);
+};