Skip to content

🎥 Make videos programmatically with React

`@remotion/studio`: Add inspector asset rename (#8837)

Jonny Burgerd45a4d8cce4e
diff --git a/packages/studio/src/components/CurrentAsset.tsx b/packages/studio/src/components/CurrentAsset.tsx
index f8570491e6..3a1b4a5237 100644
--- a/packages/studio/src/components/CurrentAsset.tsx
+++ b/packages/studio/src/components/CurrentAsset.tsx
@@ -1,6 +1,7 @@
import {formatBytes} from '@remotion/studio-shared';
-import React, {useContext, useMemo} from 'react';
+import React, {useCallback, useContext, useMemo} from 'react';
import {Internals, staticFile} from 'remotion';
+import {StudioServerConnectionCtx} from '../helpers/client-id';
import {formatMediaDuration} from '../helpers/format-media-duration';
import {getPreviewFileType} from '../helpers/get-preview-file-type';
import {
@@ -9,12 +10,16 @@ import {
} from '../helpers/render-codec-label';
import type {MediaMetadata} from '../helpers/use-media-metadata';
import {useMediaMetadata} from '../helpers/use-media-metadata';
+import {InlineEditableTitle} from './InlineEditableTitle';
import {
INSPECTOR_INFO_HEADER_MIN_HEIGHT,
InspectorInfoHeader,
InspectorInfoSubtitle,
- InspectorInfoTitle,
} from './InspectorInfoHeader';
+import {
+ getStaticFileRenameSelection,
+ useRenameStaticFile,
+} from './NewComposition/use-rename-static-file';
import {useStaticFiles} from './use-static-files';
export const CURRENT_ASSET_HEIGHT = INSPECTOR_INFO_HEADER_MIN_HEIGHT;
@@ -70,13 +75,21 @@ export const getCurrentAssetMediaDetailLines = (
return detailLines;
};
-export const CurrentAsset: React.FC = () => {
+export const CurrentAsset: React.FC<{
+ readonly readOnlyStudio: boolean;
+}> = ({readOnlyStudio}) => {
const {canvasContent} = useContext(Internals.CompositionManager);
+ const connectionStatus = useContext(StudioServerConnectionCtx)
+ .previewServerState.type;
const assetName =
canvasContent?.type === 'asset' ? canvasContent.asset : null;
const staticFiles = useStaticFiles();
+ const renameFile = useRenameStaticFile({
+ relativePath: assetName ?? '',
+ staticFiles,
+ });
const sizeInBytes = useMemo(() => {
if (!assetName) {
@@ -89,6 +102,13 @@ export const CurrentAsset: React.FC = () => {
const src = getCurrentAssetMetadataSource(assetName);
const mediaMetadata = useMediaMetadata(src);
+ const canRename = connectionStatus === 'connected' && !readOnlyStudio;
+ const onRename = useCallback(
+ (newName: string) => {
+ renameFile(newName).catch(() => undefined);
+ },
+ [renameFile],
+ );
if (!assetName) {
return <InspectorInfoHeader />;
@@ -117,7 +137,13 @@ export const CurrentAsset: React.FC = () => {
return (
<InspectorInfoHeader>
- <InspectorInfoTitle>{fileName}</InspectorInfoTitle>
+ <InlineEditableTitle
+ value={fileName}
+ canRename={canRename}
+ getInitialSelection={getStaticFileRenameSelection}
+ onCommit={onRename}
+ title={assetName}
+ />
{subtitleParts.length > 0 ? (
<InspectorInfoSubtitle>
{subtitleParts.join(' · ')}
diff --git a/packages/studio/src/components/InlineEditableTitle.tsx b/packages/studio/src/components/InlineEditableTitle.tsx
index d4cfe7ec80..ae53b38957 100644
--- a/packages/studio/src/components/InlineEditableTitle.tsx
+++ b/packages/studio/src/components/InlineEditableTitle.tsx
@@ -68,9 +68,10 @@ const titleInput: React.CSSProperties = {
export const InlineEditableTitle: React.FC<{
readonly value: string;
readonly canRename: boolean;
+ readonly getInitialSelection?: (value: string) => [number, number];
readonly onCommit: (newValue: string) => void;
readonly title?: string;
-}> = ({value, canRename, onCommit, title}) => {
+}> = ({value, canRename, getInitialSelection, onCommit, title}) => {
const [isEditing, setIsEditing] = useState(false);
const [isHovered, setIsHovered] = useState(false);
const [draftValue, setDraftValue] = useState(value);
@@ -83,16 +84,25 @@ export const InlineEditableTitle: React.FC<{
}
}, [isEditing, value]);
- const focusInput = useCallback((input: HTMLInputElement | null) => {
- inputRef.current = input;
+ const focusInput = useCallback(
+ (input: HTMLInputElement | null) => {
+ inputRef.current = input;
- if (!input) {
- return;
- }
+ if (!input) {
+ return;
+ }
- input.focus();
- input.select();
- }, []);
+ input.focus();
+ if (getInitialSelection) {
+ const [start, end] = getInitialSelection(value);
+ input.setSelectionRange(start, end);
+ return;
+ }
+
+ input.select();
+ },
+ [getInitialSelection, value],
+ );
const commit = useCallback(
(newValue: string) => {
diff --git a/packages/studio/src/components/InspectorPanel.tsx b/packages/studio/src/components/InspectorPanel.tsx
index f17e52a989..a5a28bc955 100644
--- a/packages/studio/src/components/InspectorPanel.tsx
+++ b/packages/studio/src/components/InspectorPanel.tsx
@@ -11,8 +11,9 @@ import {useTimelineSelection} from './Timeline/TimelineSelection';
export const InspectorPanel: React.FC<{
readonly composition: _InternalTypes['AnyComposition'] | null;
readonly currentDefaultProps: Record<string, unknown>;
+ readonly readOnlyStudio: boolean;
readonly setDefaultProps: UpdaterFunction<Record<string, unknown>>;
-}> = ({composition, currentDefaultProps, setDefaultProps}) => {
+}> = ({composition, currentDefaultProps, readOnlyStudio, setDefaultProps}) => {
const {selectedItems} = useTimelineSelection();
const sameSequenceInspectorSelection = useMemo(
() => getSameSequenceInspectorSelection(selectedItems),
@@ -24,6 +25,7 @@ export const InspectorPanel: React.FC<{
<DefaultInspector
composition={composition}
currentDefaultProps={currentDefaultProps}
+ readOnlyStudio={readOnlyStudio}
setDefaultProps={setDefaultProps}
/>
);
diff --git a/packages/studio/src/components/InspectorPanel/DefaultInspector.tsx b/packages/studio/src/components/InspectorPanel/DefaultInspector.tsx
index 7eb03e1b79..478d3070c6 100644
--- a/packages/studio/src/components/InspectorPanel/DefaultInspector.tsx
+++ b/packages/studio/src/components/InspectorPanel/DefaultInspector.tsx
@@ -38,8 +38,9 @@ import {
export const DefaultInspector: React.FC<{
readonly composition: _InternalTypes['AnyComposition'] | null;
readonly currentDefaultProps: Record<string, unknown>;
+ readonly readOnlyStudio: boolean;
readonly setDefaultProps: UpdaterFunction<Record<string, unknown>>;
-}> = ({composition, currentDefaultProps, setDefaultProps}) => {
+}> = ({composition, currentDefaultProps, readOnlyStudio, setDefaultProps}) => {
const {canvasContent} = useContext(Internals.CompositionManager);
const hasSelectedAsset = canvasContent?.type === 'asset';
const z = useZodIfPossible();
@@ -104,7 +105,7 @@ export const DefaultInspector: React.FC<{
return (
<div style={scrollableContainer} className={VERTICAL_SCROLLBAR_CLASSNAME}>
<div style={compositionSection}>
- <CurrentAsset />
+ <CurrentAsset readOnlyStudio={readOnlyStudio} />
</div>
</div>
);
diff --git a/packages/studio/src/components/NewComposition/RenameStaticFile.tsx b/packages/studio/src/components/NewComposition/RenameStaticFile.tsx
index 83798b0a35..45b8dff319 100644
--- a/packages/studio/src/components/NewComposition/RenameStaticFile.tsx
+++ b/packages/studio/src/components/NewComposition/RenameStaticFile.tsx
@@ -7,20 +7,23 @@ import React, {
useRef,
useState,
} from 'react';
-import {Internals} from 'remotion';
-import {renameStaticFile} from '../../api/rename-static-file';
-import {pushUrl} from '../../helpers/url-state';
import {ModalsContext} from '../../state/modals';
import {Button} from '../Button';
import {Row, Spacing} from '../layout';
import {ModalFooterContainer} from '../ModalFooter';
import {ModalHeader} from '../ModalHeader';
-import {showNotification} from '../Notifications/NotificationCenter';
import {label, optionRow, rightRow} from '../RenderModal/layout';
import {useStaticFiles} from '../use-static-files';
import {DismissableModal} from './DismissableModal';
import {InputAndValidationContainer} from './InputAndValidationContainer';
import {RemotionInput} from './RemInput';
+import {
+ getRenamedStaticFilePath,
+ getStaticFileBaseName,
+ getStaticFileRenameSelection,
+ validateStaticFileRename,
+ useRenameStaticFile,
+} from './use-rename-static-file';
import {ValidationMessage} from './ValidationMessage';
const content: React.CSSProperties = {
@@ -31,65 +34,38 @@ const content: React.CSSProperties = {
minWidth: 500,
};
-const getParent = (relativePath: string) => {
- const slashIndex = relativePath.lastIndexOf('/');
- return slashIndex === -1 ? '' : relativePath.slice(0, slashIndex);
-};
-
-const getBaseName = (relativePath: string) => {
- const slashIndex = relativePath.lastIndexOf('/');
- return slashIndex === -1 ? relativePath : relativePath.slice(slashIndex + 1);
-};
-
export const RenameStaticFileModal: React.FC<{
readonly relativePath: string;
}> = ({relativePath}) => {
const {setSelectedModal} = useContext(ModalsContext);
- const {canvasContent} = useContext(Internals.CompositionManager);
- const {setCanvasContent} = useContext(Internals.CompositionSetters);
const staticFiles = useStaticFiles();
- const [newName, setNewName] = useState(() => getBaseName(relativePath));
+ const [newName, setNewName] = useState(() =>
+ getStaticFileBaseName(relativePath),
+ );
const [submitting, setSubmitting] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
+ const renameFile = useRenameStaticFile({relativePath, staticFiles});
useEffect(() => {
const input = inputRef.current;
if (!input) return;
- const dotIndex = newName.lastIndexOf('.');
- const stemEnd = dotIndex === -1 ? newName.length : dotIndex;
- input.setSelectionRange(0, stemEnd);
+ const [start, end] = getStaticFileRenameSelection(newName);
+ input.setSelectionRange(start, end);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- const parent = useMemo(() => getParent(relativePath), [relativePath]);
const newRelativePath = useMemo(() => {
- return [parent, newName].filter(Boolean).join('/');
- }, [newName, parent]);
+ return getRenamedStaticFilePath({newName, relativePath});
+ }, [newName, relativePath]);
const changed = newRelativePath !== relativePath;
const validationMessage = useMemo(() => {
- const trimmedName = newName.trim();
- if (trimmedName.length === 0) {
- return 'Name cannot be empty';
- }
-
- if (trimmedName !== newName) {
- return 'Name cannot start or end with whitespace';
- }
-
- if (newName.includes('/') || newName.includes('\\')) {
- return 'Name cannot include slashes';
- }
-
- const existingFile = staticFiles.find((file) => {
- return file.name === newRelativePath && file.name !== relativePath;
+ return validateStaticFileRename({
+ newName,
+ newRelativePath,
+ relativePath,
+ staticFiles,
});
-
- if (existingFile) {
- return 'An asset with this name already exists';
- }
-
- return null;
}, [newName, newRelativePath, relativePath, staticFiles]);
const valid = changed && validationMessage === null;
@@ -107,39 +83,19 @@ export const RenameStaticFileModal: React.FC<{
}
setSubmitting(true);
- const notification = showNotification(`Renaming ${relativePath}...`, null);
-
- renameStaticFile({
- oldRelativePath: relativePath,
- newRelativePath,
- })
- .then(() => {
- setSelectedModal(null);
- if (
- canvasContent?.type === 'asset' &&
- canvasContent.asset === relativePath
- ) {
- setCanvasContent({type: 'asset', asset: newRelativePath});
- pushUrl(`/assets/${newRelativePath}`);
+ renameFile(newName)
+ .then((renamed) => {
+ if (!renamed) {
+ setSubmitting(false);
+ return;
}
- notification.replaceContent(`Renamed to ${newRelativePath}`, 2000);
+ setSelectedModal(null);
})
- .catch((err) => {
+ .catch(() => {
setSubmitting(false);
- notification.replaceContent(
- `Could not rename ${relativePath}: ${(err as Error).message}`,
- 3000,
- );
});
- }, [
- canvasContent,
- newRelativePath,
- relativePath,
- setCanvasContent,
- setSelectedModal,
- valid,
- ]);
+ }, [newName, renameFile, setSelectedModal, valid]);
const onSubmit: React.FormEventHandler<HTMLFormElement> = useCallback(
(e) => {
diff --git a/packages/studio/src/components/NewComposition/use-rename-static-file.ts b/packages/studio/src/components/NewComposition/use-rename-static-file.ts
new file mode 100644
index 0000000000..8513a1f0a2
--- /dev/null
+++ b/packages/studio/src/components/NewComposition/use-rename-static-file.ts
@@ -0,0 +1,134 @@
+import {useCallback, useContext} from 'react';
+import {Internals, type StaticFile} from 'remotion';
+import {renameStaticFile} from '../../api/rename-static-file';
+import {pushUrl} from '../../helpers/url-state';
+import {showNotification} from '../Notifications/NotificationCenter';
+
+export const getStaticFileParent = (relativePath: string) => {
+ const slashIndex = relativePath.lastIndexOf('/');
+ return slashIndex === -1 ? '' : relativePath.slice(0, slashIndex);
+};
+
+export const getStaticFileBaseName = (relativePath: string) => {
+ const slashIndex = relativePath.lastIndexOf('/');
+ return slashIndex === -1 ? relativePath : relativePath.slice(slashIndex + 1);
+};
+
+export const getStaticFileRenameSelection = (
+ fileName: string,
+): [number, number] => {
+ const dotIndex = fileName.lastIndexOf('.');
+ return [0, dotIndex > 0 ? dotIndex : fileName.length];
+};
+
+export const getRenamedStaticFilePath = ({
+ newName,
+ relativePath,
+}: {
+ readonly newName: string;
+ readonly relativePath: string;
+}) => {
+ const parent = getStaticFileParent(relativePath);
+ return [parent, newName].filter(Boolean).join('/');
+};
+
+export const validateStaticFileRename = ({
+ newName,
+ newRelativePath,
+ relativePath,
+ staticFiles,
+}: {
+ readonly newName: string;
+ readonly newRelativePath: string;
+ readonly relativePath: string;
+ readonly staticFiles: StaticFile[];
+}) => {
+ const trimmedName = newName.trim();
+ if (trimmedName.length === 0) {
+ return 'Name cannot be empty';
+ }
+
+ if (trimmedName !== newName) {
+ return 'Name cannot start or end with whitespace';
+ }
+
+ if (newName.includes('/') || newName.includes('\\')) {
+ return 'Name cannot include slashes';
+ }
+
+ const existingFile = staticFiles.find((file) => {
+ return file.name === newRelativePath && file.name !== relativePath;
+ });
+
+ if (existingFile) {
+ return 'An asset with this name already exists';
+ }
+
+ return null;
+};
+
+export const useRenameStaticFile = ({
+ relativePath,
+ staticFiles,
+}: {
+ readonly relativePath: string;
+ readonly staticFiles: StaticFile[];
+}) => {
+ const {canvasContent} = useContext(Internals.CompositionManager);
+ const {setCanvasContent} = useContext(Internals.CompositionSetters);
+
+ return useCallback(
+ async (newName: string) => {
+ const newRelativePath = getRenamedStaticFilePath({
+ newName,
+ relativePath,
+ });
+
+ if (newRelativePath === relativePath) {
+ return true;
+ }
+
+ const validationMessage = validateStaticFileRename({
+ newName,
+ newRelativePath,
+ relativePath,
+ staticFiles,
+ });
+
+ if (validationMessage) {
+ showNotification(validationMessage, 2000);
+ return false;
+ }
+
+ const notification = showNotification(
+ `Renaming ${relativePath}...`,
+ null,
+ );
+
+ try {
+ await renameStaticFile({
+ oldRelativePath: relativePath,
+ newRelativePath,
+ });
+
+ if (
+ canvasContent?.type === 'asset' &&
+ canvasContent.asset === relativePath
+ ) {
+ setCanvasContent({type: 'asset', asset: newRelativePath});
+ pushUrl(`/assets/${newRelativePath}`);
+ }
+
+ notification.replaceContent(`Renamed to ${newRelativePath}`, 2000);
+ return true;
+ } catch (err) {
+ notification.replaceContent(
+ `Could not rename ${relativePath}: ${(err as Error).message}`,
+ 3000,
+ );
+ return false;
+ }
+ },
+ [canvasContent, relativePath, setCanvasContent, staticFiles],
+ );
+};
diff --git a/packages/studio/src/components/OptionsPanel.tsx b/packages/studio/src/components/OptionsPanel.tsx
index ce153843e9..1841a5eb84 100644
--- a/packages/studio/src/components/OptionsPanel.tsx
+++ b/packages/studio/src/components/OptionsPanel.tsx
@@ -281,6 +281,7 @@ export const OptionsPanel: React.FC<{
<InspectorPanel
composition={composition}
currentDefaultProps={currentDefaultProps}
+ readOnlyStudio={readOnlyStudio}
setDefaultProps={setDefaultProps}
/>
) : !renderingAvailable ? null : (
diff --git a/packages/studio/src/test/current-asset.test.ts b/packages/studio/src/test/current-asset.test.ts
index 365a874027..48078eb87e 100644
--- a/packages/studio/src/test/current-asset.test.ts
+++ b/packages/studio/src/test/current-asset.test.ts
@@ -3,6 +3,11 @@ import {
getCurrentAssetMediaDetailLines,
getCurrentAssetMetadataSource,
} from '../components/CurrentAsset';
+import {
+ getRenamedStaticFilePath,
+ getStaticFileRenameSelection,
+ validateStaticFileRename,
+} from '../components/NewComposition/use-rename-static-file';
test('does not request media metadata for image assets', () => {
expect(getCurrentAssetMetadataSource('1.jpg')).toBe(null);
@@ -52,3 +57,59 @@ test('formats missing audio for current asset videos', () => {
}),
).toEqual(['Video: H.264 · 30.00 FPS · HDR: Yes', 'Audio: No audio']);
});
+
+test('keeps renamed assets in their current folder', () => {
+ expect(
+ getRenamedStaticFilePath({
+ relativePath: 'nested/clip.mp4',
+ newName: 'renamed.mp4',
+ }),
+ ).toBe('nested/renamed.mp4');
+ expect(
+ getRenamedStaticFilePath({
+ relativePath: 'clip.mp4',
+ newName: 'renamed.mp4',
+ }),
+ ).toBe('renamed.mp4');
+});
+
+test('validates renamed asset names', () => {
+ const staticFiles = [
+ {
+ name: 'nested/clip.mp4',
+ src: '/nested/clip.mp4',
+ sizeInBytes: 10,
+ lastModified: 0,
+ },
+ {
+ name: 'nested/existing.mp4',
+ src: '/nested/existing.mp4',
+ sizeInBytes: 10,
+ lastModified: 0,
+ },
+ ];
+
+ expect(
+ validateStaticFileRename({
+ newName: 'existing.mp4',
+ newRelativePath: 'nested/existing.mp4',
+ relativePath: 'nested/clip.mp4',
+ staticFiles,
+ }),
+ ).toBe('An asset with this name already exists');
+ expect(
+ validateStaticFileRename({
+ newName: 'renamed.mp4',
+ newRelativePath: 'nested/renamed.mp4',
+ relativePath: 'nested/clip.mp4',
+ staticFiles,
+ }),
+ ).toBe(null);
+});
+
+test('selects asset names without their extension for renaming', () => {
+ expect(getStaticFileRenameSelection('clip.mp4')).toEqual([0, 4]);
+ expect(getStaticFileRenameSelection('clip.final.mp4')).toEqual([0, 10]);
+ expect(getStaticFileRenameSelection('README')).toEqual([0, 6]);
+ expect(getStaticFileRenameSelection('.env')).toEqual([0, 4]);
+});