Skip to content

🎥 Make videos programmatically with React

add-drag-drop-feature

ChetanKarwabfb380a0762a
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index eeea41c711..2ffef192d3 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -200,7 +200,12 @@ const handleAddAsset = (
res: ServerResponse,
publicDir: string,
): void => {
- const form = formidable();
+ const TWO_GIGABYTES = 2 * 1024 * 1024 * 1024;
+ const form = formidable({
+ maxTotalFileSize: TWO_GIGABYTES,
+ maxFieldsSize: TWO_GIGABYTES,
+ maxFileSize: TWO_GIGABYTES,
+ });
form.parse(
req,
@@ -208,7 +213,10 @@ const handleAddAsset = (
if (err) {
res.writeHead(500, {'Content-Type': 'application/json'});
res.end(
- JSON.stringify({success: false, error: 'Error parsing form data'}),
+ JSON.stringify({
+ success: false,
+ error: err.message || 'Unknown error',
+ }),
);
return;
}
@@ -359,8 +367,6 @@ export const handleRoutes = ({
}
if (url.pathname === '/api/add-asset') {
- // eslint-disable-next-line no-console
- console.log('add-asset');
return handleAddAsset(request, response, publicDir);
}
diff --git a/packages/studio/src/components/AssetSelector.tsx b/packages/studio/src/components/AssetSelector.tsx
index 5eb4a8c482..7266ce56f5 100644
--- a/packages/studio/src/components/AssetSelector.tsx
+++ b/packages/studio/src/components/AssetSelector.tsx
@@ -1,4 +1,10 @@
-import React, {useCallback, useContext, useEffect, useMemo} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
import type {StaticFile} from 'remotion';
import {getStaticFiles} from 'remotion';
import {StudioServerConnectionCtx} from '../helpers/client-id';
@@ -10,6 +16,7 @@ import {FolderContext} from '../state/folders';
import {useZIndex} from '../state/z-index';
import {AssetFolderTree} from './AssetSelectorItem';
import {inlineCodeSnippet} from './Menu/styles';
+import {handleUploadFile} from './utils';
const container: React.CSSProperties = {
display: 'flex',
@@ -49,7 +56,7 @@ export const AssetSelector: React.FC = () => {
const {tabIndex} = useZIndex();
const {assetFoldersExpanded, setAssetFoldersExpanded} =
useContext(FolderContext);
-
+ const [dropLocation, setDropLocation] = useState<string | null>(null);
const {subscribeToEvent} = useContext(StudioServerConnectionCtx);
const [{publicFolderExists, staticFiles}, setState] = React.useState<State>(
@@ -97,7 +104,31 @@ export const AssetSelector: React.FC = () => {
);
return (
- <div style={container}>
+ <div
+ style={container}
+ onDragOver={(e) => e.preventDefault()}
+ onDrop={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleUploadFile(e.dataTransfer.files[0], dropLocation || '/');
+ setDropLocation(null);
+ }}
+ >
+ {true && (
+ <div
+ style={{
+ backgroundColor: 'white',
+ padding: 20,
+ borderRadius: 10,
+ boxShadow: '0 0 10px rgba(0, 0, 0, 0.2)',
+ position: 'fixed',
+ bottom: 20,
+ right: 20,
+ }}
+ >
+ Uploading file...
+ </div>
+ )}
{staticFiles.length === 0 ? (
publicFolderExists ? (
<div style={emptyState}>
@@ -125,6 +156,8 @@ export const AssetSelector: React.FC = () => {
name={null}
tabIndex={tabIndex}
toggleFolder={toggleFolder}
+ dropLocation={dropLocation}
+ setDropLocation={setDropLocation}
/>
</div>
)}
diff --git a/packages/studio/src/components/AssetSelectorItem.tsx b/packages/studio/src/components/AssetSelectorItem.tsx
index 60843d5a4f..f840ec6bbb 100644
--- a/packages/studio/src/components/AssetSelectorItem.tsx
+++ b/packages/studio/src/components/AssetSelectorItem.tsx
@@ -1,4 +1,11 @@
-import React, {useCallback, useContext, useMemo, useState} from 'react';
+import React, {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import {Internals, type StaticFile} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {
@@ -70,7 +77,17 @@ const AssetFolderItem: React.FC<{
level: number;
parentFolder: string;
toggleFolder: (folderName: string, parentName: string | null) => void;
-}> = ({tabIndex, item, level, parentFolder, toggleFolder}) => {
+ dropLocation: string | null;
+ setDropLocation: React.Dispatch<React.SetStateAction<string | null>>;
+}> = ({
+ tabIndex,
+ item,
+ level,
+ parentFolder,
+ toggleFolder,
+ dropLocation,
+ setDropLocation,
+}) => {
const [hovered, setHovered] = useState(false);
const onPointerEnter = useCallback(() => {
@@ -103,7 +120,7 @@ const AssetFolderItem: React.FC<{
const Icon = item.expanded ? ExpandedFolderIcon : CollapsedFolderIcon;
return (
- <>
+ <div>
<div
style={folderStyle}
onPointerEnter={onPointerEnter}
@@ -128,9 +145,11 @@ const AssetFolderItem: React.FC<{
parentFolder={parentFolder}
tabIndex={tabIndex}
toggleFolder={toggleFolder}
+ dropLocation={dropLocation}
+ setDropLocation={setDropLocation}
/>
) : null}
- </>
+ </div>
);
};
@@ -141,13 +160,53 @@ export const AssetFolderTree: React.FC<{
level: number;
tabIndex: number;
toggleFolder: (folderName: string, parentName: string | null) => void;
-}> = ({item, level, name, parentFolder, toggleFolder, tabIndex}) => {
+ dropLocation: string | null;
+ setDropLocation: React.Dispatch<React.SetStateAction<string | null>>;
+}> = ({
+ item,
+ level,
+ name,
+ parentFolder,
+ toggleFolder,
+ tabIndex,
+ dropLocation,
+ setDropLocation,
+}) => {
const combinedParents = useMemo(() => {
return [parentFolder, name].filter(NoReactInternals.truthy).join('/');
}, [name, parentFolder]);
-
+ const dragDepthRef = useRef(0);
+ const isDropDiv = useMemo(() => {
+ return dropLocation === combinedParents;
+ }, [combinedParents, dropLocation]);
+ useEffect(() => {
+ if (dropLocation === null) {
+ dragDepthRef.current = 0;
+ }
+ }, [dropLocation]);
return (
- <div>
+ <div
+ onDragEnter={() => {
+ if (dragDepthRef.current === 0) {
+ setDropLocation((currentDropLocation) =>
+ currentDropLocation?.includes(combinedParents)
+ ? currentDropLocation
+ : combinedParents,
+ );
+ }
+
+ dragDepthRef.current++;
+ }}
+ onDragLeave={() => {
+ dragDepthRef.current--;
+ if (dragDepthRef.current === 0) {
+ setDropLocation(() => parentFolder);
+ }
+ }}
+ style={{
+ backgroundColor: isDropDiv ? CLEAR_HOVER : BACKGROUND,
+ }}
+ >
{item.folders.map((folder) => {
return (
<AssetFolderItem
@@ -157,6 +216,8 @@ export const AssetFolderTree: React.FC<{
level={level + 1}
parentFolder={combinedParents}
toggleFolder={toggleFolder}
+ dropLocation={dropLocation}
+ setDropLocation={setDropLocation}
/>
);
})}
diff --git a/packages/studio/src/components/FileInput.tsx b/packages/studio/src/components/FileInput.tsx
deleted file mode 100644
index ef1c603322..0000000000
--- a/packages/studio/src/components/FileInput.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import {useState} from 'react';
-import {notificationCenter} from './Notifications/NotificationCenter';
-
-const FileUpload = () => {
- const [selectedFile, setSelectedFile] = useState<File | undefined | null>(
- null,
- );
-
- const handleFileChange: React.ChangeEventHandler<HTMLInputElement> = (
- event,
- ) => {
- setSelectedFile(event.target.files?.[0]);
- };
-
- const handleUpload = async () => {
- if (!selectedFile) {
- notificationCenter.current?.addNotification({
- content: `Please select a file first!`,
- created: Date.now(),
- duration: 1000,
- id: String(Math.random()),
- });
- return;
- }
-
- const formData = new FormData();
- formData.append('file', selectedFile);
- formData.append('assetPath', '/');
-
- try {
- const response = await fetch('/api/add-asset', {
- method: 'POST',
- body: formData,
- });
-
- if (response.ok) {
- const jsonResponse = await response.json();
- notificationCenter.current?.addNotification({
- content: `File uploaded successfully: ${jsonResponse}`,
- created: Date.now(),
- duration: 1000,
- id: String(Math.random()),
- });
- } else {
- const jsonResponse = await response.json();
- notificationCenter.current?.addNotification({
- content: `Upload failed: ${JSON.stringify(jsonResponse)}`,
- created: Date.now(),
- duration: 1000,
- id: String(Math.random()),
- });
- }
- } catch (error) {
- notificationCenter.current?.addNotification({
- content: `Error during upload: ${error}`,
- created: Date.now(),
- duration: 1000,
- id: String(Math.random()),
- });
- }
- };
-
- return (
- <div>
- <input type="file" onChange={handleFileChange} />
- <button onClick={handleUpload} type="button">
- Upload File
- </button>
- </div>
- );
-};
-
-export default FileUpload;
diff --git a/packages/studio/src/components/TopPanel.tsx b/packages/studio/src/components/TopPanel.tsx
index 9e51fc72f8..65494b239b 100644
--- a/packages/studio/src/components/TopPanel.tsx
+++ b/packages/studio/src/components/TopPanel.tsx
@@ -10,7 +10,6 @@ import {
} from './CurrentCompositionSideEffects';
import {useIsRulerVisible} from './EditorRuler/use-is-ruler-visible';
import {ExplorerPanel} from './ExplorerPanel';
-import FileUpload from './FileInput';
import {OptionsPanel} from './OptionsPanel';
import {PreviewToolbar} from './PreviewToolbar';
import {SplitterContainer} from './Splitter/SplitterContainer';
@@ -115,7 +114,6 @@ export const TopPanel: React.FC<{
{actualStateLeft === 'expanded' ? (
<SplitterElement sticky={null} type="flexer">
<ExplorerPanel />
- <FileUpload />
</SplitterElement>
) : null}
{actualStateLeft === 'expanded' ? (
diff --git a/packages/studio/src/components/utils.ts b/packages/studio/src/components/utils.ts
new file mode 100644
index 0000000000..7f61643766
--- /dev/null
+++ b/packages/studio/src/components/utils.ts
@@ -0,0 +1,48 @@
+import {notificationCenter} from './Notifications/NotificationCenter';
+
+export const handleUploadFile = async (file: File, assetPath: string) => {
+ if (!file) {
+ notificationCenter.current?.addNotification({
+ content: `Please select a file first!`,
+ created: Date.now(),
+ duration: 3000,
+ id: String(Math.random()),
+ });
+ return;
+ }
+
+ const formData = new FormData();
+ formData.append('file', file);
+ formData.append('assetPath', assetPath);
+
+ try {
+ const response = await fetch('/api/add-asset', {
+ method: 'POST',
+ body: formData,
+ });
+
+ if (response.ok) {
+ notificationCenter.current?.addNotification({
+ content: `File uploaded successfully`,
+ created: Date.now(),
+ duration: 3000,
+ id: String(Math.random()),
+ });
+ } else {
+ const jsonResponse = await response.json();
+ notificationCenter.current?.addNotification({
+ content: `Upload failed: ${jsonResponse.error}`,
+ created: Date.now(),
+ duration: 3000,
+ id: String(Math.random()),
+ });
+ }
+ } catch (error) {
+ notificationCenter.current?.addNotification({
+ content: `Error during upload: ${error}`,
+ created: Date.now(),
+ duration: 3000,
+ id: String(Math.random()),
+ });
+ }
+};