Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Select assets dropped on the canvas (#10342)

Jonny Burger4fc6f1773af2
diff --git a/packages/browser-studio/src/browser-studio-operations.ts b/packages/browser-studio/src/browser-studio-operations.ts
index 58d76f9264..e8978e58a1 100644
--- a/packages/browser-studio/src/browser-studio-operations.ts
+++ b/packages/browser-studio/src/browser-studio-operations.ts
@@ -236,7 +236,11 @@ export const createBrowserStudioOperations = ({
throw new Error('Could not insert <Solid>');
}
- return Promise.resolve({success: true, nodePathMutation});
+ return Promise.resolve({
+ success: true,
+ insertedNodePath: null,
+ nodePathMutation,
+ });
} catch (error) {
return Promise.resolve({
success: false,
diff --git a/packages/example/e2e/studio.test.mts b/packages/example/e2e/studio.test.mts
index 1560effdb7..1711fa1545 100644
--- a/packages/example/e2e/studio.test.mts
+++ b/packages/example/e2e/studio.test.mts
@@ -1162,13 +1162,16 @@ test.describe('visual mode', () => {
await expect(currentTime).not.toHaveAttribute('aria-label', '0');
});
- test('should place Canvas drops where they are visible at the playhead', async ({
+ test('should place and select Canvas drops at the playhead', async ({
page,
}) => {
await page.goto(`${STUDIO_URL}/effect-keyframe-e2e`);
await expect(
page.getByRole('button', {name: '0', exact: true}),
).toBeVisible({timeout: 15_000});
+ if (!(await page.getByRole('button', {name: 'Inspector'}).isVisible())) {
+ await page.locator('[data-sidebar-toggle="right"]').click();
+ }
await page.locator('[data-timeline-scrubber]').click();
await expect(
@@ -1183,6 +1186,9 @@ test.describe('visual mode', () => {
await expect
.poll(() => fs.readFileSync(effectKeyframeE2eFile, 'utf-8'))
.toContain('quick.mov');
+ await expect(
+ page.getByRole('group', {name: 'Inspector source location'}).first(),
+ ).toContainText('<Video>', {timeout: 15_000});
const longVideoTag = getVideoTag(
fs.readFileSync(effectKeyframeE2eFile, 'utf-8'),
'quick.mov',
diff --git a/packages/studio-server/src/codemods/delete-jsx-node.ts b/packages/studio-server/src/codemods/delete-jsx-node.ts
index 2311d323bb..2b05805b02 100644
--- a/packages/studio-server/src/codemods/delete-jsx-node.ts
+++ b/packages/studio-server/src/codemods/delete-jsx-node.ts
@@ -465,7 +465,7 @@ export const deleteJsxNodes = async ({
input: finalFile,
prettierConfigOverride,
});
- const nodePathRemappings = getNodePathRemappings({
+ const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
diff --git a/packages/studio-server/src/codemods/duplicate-jsx-node.ts b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
index 651b0e05f0..cc924e7ed4 100644
--- a/packages/studio-server/src/codemods/duplicate-jsx-node.ts
+++ b/packages/studio-server/src/codemods/duplicate-jsx-node.ts
@@ -459,7 +459,7 @@ export const duplicateJsxNode = async ({
input: finalFile,
prettierConfigOverride,
});
- const nodePathRemappings = getNodePathRemappings({
+ const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
diff --git a/packages/studio-server/src/codemods/get-node-path-remappings.ts b/packages/studio-server/src/codemods/get-node-path-remappings.ts
index fa2f39d7f5..84bed71bef 100644
--- a/packages/studio-server/src/codemods/get-node-path-remappings.ts
+++ b/packages/studio-server/src/codemods/get-node-path-remappings.ts
@@ -33,7 +33,10 @@ export const getNodePathRemappings = ({
ast: File;
captured: CapturedJsxNodePath[];
output: string;
-}): SequenceNodePathRemapping[] => {
+}): {
+ nodePathRemappings: SequenceNodePathRemapping[];
+ finalNodePathByNode: Map<JSXOpeningElement, SequenceNodePath>;
+} => {
const nodesAfterMutation: JSXOpeningElement[] = [];
recast.visit(ast, {
visitJSXOpeningElement(path) {
@@ -60,7 +63,7 @@ export const getNodePathRemappings = ({
finalNodePathByNode.set(nodesAfterMutation[i], finalNodePaths[i]);
}
- return captured.flatMap(({node, nodePath}) => {
+ const nodePathRemappings = captured.flatMap(({node, nodePath}) => {
const newNodePath = finalNodePathByNode.get(node) ?? null;
if (
newNodePath !== null &&
@@ -71,4 +74,6 @@ export const getNodePathRemappings = ({
return [{oldNodePath: nodePath, newNodePath}];
});
+
+ return {finalNodePathByNode, nodePathRemappings};
};
diff --git a/packages/studio-server/src/codemods/reorder-sequence.ts b/packages/studio-server/src/codemods/reorder-sequence.ts
index 8d50c59b56..6f686fb207 100644
--- a/packages/studio-server/src/codemods/reorder-sequence.ts
+++ b/packages/studio-server/src/codemods/reorder-sequence.ts
@@ -122,7 +122,7 @@ export const reorderSequence = async ({
input: finalFile,
prettierConfigOverride,
});
- const nodePathRemappings = getNodePathRemappings({
+ const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
diff --git a/packages/studio-server/src/codemods/split-jsx-sequence.ts b/packages/studio-server/src/codemods/split-jsx-sequence.ts
index 11f5e55af2..9e0d7830f6 100644
--- a/packages/studio-server/src/codemods/split-jsx-sequence.ts
+++ b/packages/studio-server/src/codemods/split-jsx-sequence.ts
@@ -461,7 +461,7 @@ export const splitJsxSequence = async ({
input: finalFile,
prettierConfigOverride,
});
- const nodePathRemappings = getNodePathRemappings({
+ const {nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
diff --git a/packages/studio-server/src/helpers/resolve-composition-component.ts b/packages/studio-server/src/helpers/resolve-composition-component.ts
index 5109d85d69..f1d95b59bf 100644
--- a/packages/studio-server/src/helpers/resolve-composition-component.ts
+++ b/packages/studio-server/src/helpers/resolve-composition-component.ts
@@ -12,6 +12,7 @@ import type {
ImportSpecifier,
JSXAttribute,
JSXElement,
+ JSXOpeningElement,
JSXSpreadAttribute,
ObjectProperty,
VariableDeclaration,
@@ -25,6 +26,7 @@ import {
} from '@remotion/studio-shared';
import type {namedTypes} from 'ast-types';
import * as recast from 'recast';
+import type {SequenceNodePath} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {formatFileContent} from '../codemods/format-file-content';
import {
@@ -2309,6 +2311,7 @@ export const insertJsxElementIntoComposition = async ({
formatted: boolean;
logLine: number;
nodePathRemappings: SequenceNodePathRemapping[];
+ insertedNodePath: SequenceNodePath | null;
}> => {
const location = await resolveCompositionComponentWithFile({
remotionRoot,
@@ -2385,11 +2388,15 @@ export const insertJsxElementIntoComposition = async ({
input: finalFile,
prettierConfigOverride,
});
- const nodePathRemappings = getNodePathRemappings({
+ const {finalNodePathByNode, nodePathRemappings} = getNodePathRemappings({
ast,
captured: capturedNodePaths,
output,
});
+ const insertedNodePath =
+ finalNodePathByNode.get(
+ finalElementToInsert.openingElement as JSXOpeningElement,
+ ) ?? null;
return {
fileName: location.fileName,
@@ -2397,6 +2404,7 @@ export const insertJsxElementIntoComposition = async ({
oldContents: input,
output,
formatted,
+ insertedNodePath,
logLine,
nodePathRemappings,
};
diff --git a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
index 8077f7e749..c30ae699d3 100644
--- a/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
+++ b/packages/studio-server/src/preview-server/routes/insert-jsx-element.ts
@@ -246,6 +246,7 @@ export const insertJsxElementHandler: ApiHandler<
oldContents,
output,
formatted,
+ insertedNodePath,
logLine,
nodePathRemappings,
} = await insertJsxElementIntoComposition({
@@ -263,6 +264,12 @@ export const insertJsxElementHandler: ApiHandler<
restoredNodePaths: [],
},
]);
+ if (insertedNodePath === null) {
+ RenderInternals.Log.warn(
+ {indent: false, logLevel},
+ 'Could not determine the inserted JSX element node path. Skipping automatic selection.',
+ );
+ }
pushToUndoStack({
filePath: fileName,
@@ -309,6 +316,10 @@ export const insertJsxElementHandler: ApiHandler<
return {
success: true,
+ insertedNodePath:
+ insertedNodePath === null
+ ? null
+ : {absolutePath: fileName, nodePath: insertedNodePath},
nodePathMutation,
};
} catch (err) {
diff --git a/packages/studio-shared/src/api-requests.ts b/packages/studio-shared/src/api-requests.ts
index 799f91fef6..cface76f1f 100644
--- a/packages/studio-shared/src/api-requests.ts
+++ b/packages/studio-shared/src/api-requests.ts
@@ -867,6 +867,10 @@ export type InsertJsxElementRequest = {
export type InsertJsxElementResponse =
| {
success: true;
+ insertedNodePath: Pick<
+ SequencePropsSubscriptionKey,
+ 'absolutePath' | 'nodePath'
+ > | null;
nodePathMutation: SequenceNodePathMutation;
}
| {
diff --git a/packages/studio/src/components/Timeline/Timeline.tsx b/packages/studio/src/components/Timeline/Timeline.tsx
index 8c7520f68a..1c90c86c3a 100644
--- a/packages/studio/src/components/Timeline/Timeline.tsx
+++ b/packages/studio/src/components/Timeline/Timeline.tsx
@@ -1,11 +1,25 @@
import type {InsertJsxElementRequest} from '@remotion/studio-shared';
-import React, {useCallback, useContext, useMemo, useState} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from 'react';
import {Internals} from 'remotion';
+import {FastRefreshContext} from '../../fast-refresh-context';
import {getBrowserStudioOperations} from '../../helpers/browser-studio-operations';
import {calculateTimeline} from '../../helpers/calculate-timeline';
import {StudioServerConnectionCtx} from '../../helpers/client-id';
import {BACKGROUND} from '../../helpers/colors';
import type {TimelineTrackData} from '../../helpers/get-timeline-sequence-sort-key';
+import {
+ clearInsertedElementSelection,
+ getInsertedElementSelection,
+ subscribeToInsertedElementSelection,
+} from '../../helpers/inserted-element-selection';
import {isStudioInteractivityEnabled} from '../../helpers/interactivity-enabled';
import {useIsStill} from '../../helpers/is-current-selected-still';
import {useCachedCompositionComponentInfo} from '../../helpers/open-in-editor';
@@ -38,6 +52,7 @@ import {TimelineScrollable} from './TimelineScrollable';
import {
TimelineSelectableItemsProvider,
TimelineSelectAllKeybindings,
+ useTimelineSelection,
} from './TimelineSelection';
import {TimelineSlider} from './TimelineSlider';
import {
@@ -244,7 +259,9 @@ const TimelineContextMenuArea: React.FC<{
const TimelineInner: React.FC = () => {
const {sequences} = useContext(Internals.SequenceManager);
- const {compositions} = useContext(Internals.CompositionManager);
+ const {canvasContent, compositions} = useContext(
+ Internals.CompositionManager,
+ );
const videoConfig = Internals.useUnsafeVideoConfig();
const isStill = useIsStill();
const {overrideIdToNodePathMappings} = useContext(
@@ -274,6 +291,83 @@ const TimelineInner: React.FC = () => {
overrideIdToNodePathMappings,
compositions,
]);
+ const pendingInsertedElementSelection = useSyncExternalStore(
+ subscribeToInsertedElementSelection,
+ getInsertedElementSelection,
+ getInsertedElementSelection,
+ );
+ const {fastRefreshes} = useContext(FastRefreshContext);
+ const pendingSelectionStart = useRef<{
+ selection: NonNullable<typeof pendingInsertedElementSelection>;
+ fastRefreshes: number;
+ existingSequenceIds: Set<string>;
+ } | null>(null);
+ const {selectItems} = useTimelineSelection();
+ useEffect(() => {
+ if (pendingInsertedElementSelection === null) {
+ pendingSelectionStart.current = null;
+ return;
+ }
+
+ const matchesInsertedNodePath = (track: TimelineTrackData) =>
+ track.nodePathInfo !== null &&
+ track.nodePathInfo.sequenceSubscriptionKey.absolutePath ===
+ pendingInsertedElementSelection.nodePath.absolutePath &&
+ JSON.stringify(track.nodePathInfo.sequenceSubscriptionKey.nodePath) ===
+ JSON.stringify(pendingInsertedElementSelection.nodePath.nodePath);
+
+ if (
+ pendingSelectionStart.current?.selection !==
+ pendingInsertedElementSelection
+ ) {
+ pendingSelectionStart.current = {
+ selection: pendingInsertedElementSelection,
+ fastRefreshes,
+ existingSequenceIds: new Set(
+ timeline
+ .filter(matchesInsertedNodePath)
+ .map((track) => track.sequence.id),
+ ),
+ };
+ return;
+ }
+
+ if (pendingSelectionStart.current.fastRefreshes === fastRefreshes) {
+ return;
+ }
+
+ if (
+ canvasContent?.type === 'composition' &&
+ canvasContent.compositionId !==
+ pendingInsertedElementSelection.compositionId
+ ) {
+ clearInsertedElementSelection(pendingInsertedElementSelection);
+ return;
+ }
+
+ const insertedTrack = timeline.find(
+ (track) =>
+ matchesInsertedNodePath(track) &&
+ !pendingSelectionStart.current?.existingSequenceIds.has(
+ track.sequence.id,
+ ),
+ );
+ if (!insertedTrack || insertedTrack.nodePathInfo === null) {
+ return;
+ }
+
+ selectItems(
+ [{type: 'sequence', nodePathInfo: insertedTrack.nodePathInfo}],
+ {reveal: true},
+ );
+ clearInsertedElementSelection(pendingInsertedElementSelection);
+ }, [
+ canvasContent,
+ fastRefreshes,
+ pendingInsertedElementSelection,
+ selectItems,
+ timeline,
+ ]);
const durationInFrames = videoConfig?.durationInFrames ?? 0;
diff --git a/packages/studio/src/components/import-assets.ts b/packages/studio/src/components/import-assets.ts
index 59df507a48..4402c608b6 100644
--- a/packages/studio/src/components/import-assets.ts
+++ b/packages/studio/src/components/import-assets.ts
@@ -19,6 +19,7 @@ import {NoReactInternals} from 'remotion/no-react';
import {getStaticFiles} from '../api/get-static-files';
import {writeStaticFile} from '../api/write-static-file';
import {formatFigmaClipboardErrorNotification} from '../helpers/clipboard-figma';
+import {requestInsertedElementSelection} from '../helpers/inserted-element-selection';
import {installRequiredPackages} from '../helpers/install-required-package';
import type {Dimensions} from '../helpers/is-current-selected-still';
import {getMediaMetadata} from '../helpers/use-media-metadata';
@@ -734,6 +735,13 @@ const insertCompositionElement = async ({
return false;
}
+ if (result.insertedNodePath !== null) {
+ requestInsertedElementSelection({
+ compositionId,
+ nodePath: result.insertedNodePath,
+ });
+ }
+
return true;
};
diff --git a/packages/studio/src/helpers/inserted-element-selection.ts b/packages/studio/src/helpers/inserted-element-selection.ts
new file mode 100644
index 0000000000..38144aace3
--- /dev/null
+++ b/packages/studio/src/helpers/inserted-element-selection.ts
@@ -0,0 +1,41 @@
+import type {SequenceNodePath} from 'remotion';
+
+export type PendingInsertedElementSelection = {
+ compositionId: string;
+ nodePath: {
+ absolutePath: string;
+ nodePath: SequenceNodePath;
+ };
+};
+
+let pendingSelection: PendingInsertedElementSelection | null = null;
+const listeners = new Set<() => void>();
+
+export const requestInsertedElementSelection = (
+ selection: PendingInsertedElementSelection,
+) => {
+ pendingSelection = selection;
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+export const clearInsertedElementSelection = (
+ selection: PendingInsertedElementSelection,
+) => {
+ if (pendingSelection !== selection) {
+ return;
+ }
+
+ pendingSelection = null;
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+export const subscribeToInsertedElementSelection = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+};
+
+export const getInsertedElementSelection = () => pendingSelection;