mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 21:04:59 +00:00
Merge pull request #126 from shumaiOne/feat/external-drag-drop
feat(webui): add external drag-and-drop file and folder upload support
This commit is contained in:
@@ -2,21 +2,25 @@
|
|||||||
import { client } from '@/ui/api/client'
|
import { client } from '@/ui/api/client'
|
||||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||||
|
|
||||||
import type { AssetInfo } from '@shumai/dtos'
|
|
||||||
import type { CollectionInfo } from '@shumai/dtos'
|
|
||||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
|
||||||
import type { ShareLinkInfo } from '@shumai/dtos'
|
|
||||||
import type { CreateUploadTaskRequest } from '@shumai/dtos'
|
|
||||||
import { formatSize } from '@/ui/lib/format'
|
|
||||||
import { ulid } from 'ulid'
|
|
||||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||||
|
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||||
|
import { formatSize } from '@/ui/lib/format'
|
||||||
import { useFieldStore } from '@/ui/stores/fields'
|
import { useFieldStore } from '@/ui/stores/fields'
|
||||||
import { useUploadStore } from '@/ui/stores/upload'
|
import { useUploadStore } from '@/ui/stores/upload'
|
||||||
|
import type {
|
||||||
|
AssetInfo,
|
||||||
|
CollectionInfo,
|
||||||
|
CreateUploadTaskRequest,
|
||||||
|
SearchCondition,
|
||||||
|
SearchSort,
|
||||||
|
ShareLinkInfo,
|
||||||
|
} from '@shumai/dtos'
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useNavigate } from '@tanstack/react-router'
|
import { useNavigate } from '@tanstack/react-router'
|
||||||
import { Download, AlertTriangle, Loader2 } from 'lucide-react'
|
import { AlertTriangle, Download, Loader2 } from 'lucide-react'
|
||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { ulid } from 'ulid'
|
||||||
import type { DragState } from '../dnd-types'
|
import type { DragState } from '../dnd-types'
|
||||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||||
import { FileBrowserContextMenu } from './context-menu'
|
import { FileBrowserContextMenu } from './context-menu'
|
||||||
@@ -31,6 +35,8 @@ import {
|
|||||||
AlertDialogHeader,
|
AlertDialogHeader,
|
||||||
AlertDialogTitle,
|
AlertDialogTitle,
|
||||||
} from '../ui/alert-dialog'
|
} from '../ui/alert-dialog'
|
||||||
|
import { Button } from '../ui/button'
|
||||||
|
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
@@ -39,8 +45,6 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from '../ui/dialog'
|
} from '../ui/dialog'
|
||||||
import { Button } from '../ui/button'
|
|
||||||
import { ContextMenu, ContextMenuTrigger } from '../ui/context-menu'
|
|
||||||
import { FileCard } from './file-card'
|
import { FileCard } from './file-card'
|
||||||
import { FileListItem } from './file-list-item'
|
import { FileListItem } from './file-list-item'
|
||||||
import { FolderCard } from './folder-card'
|
import { FolderCard } from './folder-card'
|
||||||
@@ -138,6 +142,70 @@ export function FileBrowser({
|
|||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const [isExternalDragging, setIsExternalDragging] = useState(false)
|
||||||
|
const [externalOverFolderId, setExternalOverFolderId] = useState<string | null>(null)
|
||||||
|
const dragCounter = useRef(0)
|
||||||
|
|
||||||
|
const resetExternalDragState = useCallback(() => {
|
||||||
|
setIsExternalDragging(false)
|
||||||
|
setExternalOverFolderId(null)
|
||||||
|
dragCounter.current = 0
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
// Prevent default window behavior to avoid browser replacing page on accidental drops
|
||||||
|
useEffect(() => {
|
||||||
|
const preventDefault = (e: DragEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
window.addEventListener('dragover', preventDefault)
|
||||||
|
window.addEventListener('drop', preventDefault)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('dragover', preventDefault)
|
||||||
|
window.removeEventListener('drop', preventDefault)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleGlobalDragEnter = (e: React.DragEvent) => {
|
||||||
|
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||||
|
e.preventDefault()
|
||||||
|
if (e.dataTransfer.types.includes('Files')) {
|
||||||
|
dragCounter.current++
|
||||||
|
setIsExternalDragging(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleGlobalDragLeave = (e: React.DragEvent) => {
|
||||||
|
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||||
|
e.preventDefault()
|
||||||
|
if (e.dataTransfer.types.includes('Files')) {
|
||||||
|
dragCounter.current--
|
||||||
|
if (dragCounter.current <= 0) {
|
||||||
|
dragCounter.current = 0
|
||||||
|
setIsExternalDragging(false)
|
||||||
|
setExternalOverFolderId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleGlobalDragOver = (e: React.DragEvent) => {
|
||||||
|
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleGlobalDrop = async (e: React.DragEvent) => {
|
||||||
|
if (!canEdit || isRecentlyDeleted || isShareView || isPublic || !!collection) return
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
|
||||||
|
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||||
|
|
||||||
|
resetExternalDragState()
|
||||||
|
|
||||||
|
if (files.length > 0) {
|
||||||
|
processAndUploadFiles(files)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
|
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
|
||||||
|
|
||||||
const displayedFiles = useMemo(() => {
|
const displayedFiles = useMemo(() => {
|
||||||
@@ -550,6 +618,13 @@ export function FileBrowser({
|
|||||||
isShareView,
|
isShareView,
|
||||||
fields: displayedFields,
|
fields: displayedFields,
|
||||||
canEdit,
|
canEdit,
|
||||||
|
isExternalDragging,
|
||||||
|
externalOverFolderId,
|
||||||
|
setExternalOverFolderId,
|
||||||
|
resetExternalDragState,
|
||||||
|
onExternalDrop: (files: File[], folderId: string) => {
|
||||||
|
processAndUploadFiles(files, folderId)
|
||||||
|
},
|
||||||
}
|
}
|
||||||
if (displayStyle === 'card') {
|
if (displayStyle === 'card') {
|
||||||
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
|
if (effectiveType === 'folder') return <FolderCard key={item.id} {...props} />
|
||||||
@@ -812,6 +887,10 @@ export function FileBrowser({
|
|||||||
<div
|
<div
|
||||||
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
|
className="flex-1 bg-background relative flex flex-col min-h-0 overflow-hidden"
|
||||||
onContextMenu={(e) => onContextMenu(e)}
|
onContextMenu={(e) => onContextMenu(e)}
|
||||||
|
onDragEnter={handleGlobalDragEnter}
|
||||||
|
onDragLeave={handleGlobalDragLeave}
|
||||||
|
onDragOver={handleGlobalDragOver}
|
||||||
|
onDrop={handleGlobalDrop}
|
||||||
>
|
>
|
||||||
{!isShareView && !isPublic && onFilterChange && onSortChange && (
|
{!isShareView && !isPublic && onFilterChange && onSortChange && (
|
||||||
<FileBrowserToolbar
|
<FileBrowserToolbar
|
||||||
@@ -886,6 +965,11 @@ export function FileBrowser({
|
|||||||
handleEmptyAreaClick={handleEmptyAreaClick}
|
handleEmptyAreaClick={handleEmptyAreaClick}
|
||||||
dragState={dragState}
|
dragState={dragState}
|
||||||
sort={sort}
|
sort={sort}
|
||||||
|
isExternalDragging={isExternalDragging}
|
||||||
|
externalOverFolderId={externalOverFolderId}
|
||||||
|
setExternalOverFolderId={setExternalOverFolderId}
|
||||||
|
resetExternalDragState={resetExternalDragState}
|
||||||
|
onExternalDrop={(files, folderId) => processAndUploadFiles(files, folderId)}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<FileBrowserGridView
|
<FileBrowserGridView
|
||||||
@@ -970,6 +1054,13 @@ export function FileBrowser({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{isExternalDragging && !externalOverFolderId && (
|
||||||
|
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-50 pointer-events-none animate-in fade-in slide-in-from-bottom-4 duration-300">
|
||||||
|
<div className="flex items-center gap-3 px-6 py-3 rounded-full bg-primary/80 text-primary-foreground shadow-lg shadow-primary/20 border border-primary/20 backdrop-blur-md">
|
||||||
|
<span className="font-medium text-sm">Drop files here to upload</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</ContextMenuTrigger>
|
</ContextMenuTrigger>
|
||||||
<FileBrowserContextMenu
|
<FileBrowserContextMenu
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { Download, Edit, History, MoreHorizontal, Trash2 } from 'lucide-react'
|
|||||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import type { DragState } from '../dnd-types'
|
import type { DragState } from '../dnd-types'
|
||||||
import { FilePreview } from './file-preview'
|
import { FilePreview } from './file-preview'
|
||||||
|
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||||
|
|
||||||
interface FolderCardProps {
|
interface FolderCardProps {
|
||||||
item: AssetInfo
|
item: AssetInfo
|
||||||
@@ -38,6 +39,11 @@ interface FolderCardProps {
|
|||||||
selectedCount?: number
|
selectedCount?: number
|
||||||
canEdit?: boolean
|
canEdit?: boolean
|
||||||
isShareView?: boolean
|
isShareView?: boolean
|
||||||
|
isExternalDragging?: boolean
|
||||||
|
externalOverFolderId?: string | null
|
||||||
|
setExternalOverFolderId?: (id: string | null) => void
|
||||||
|
resetExternalDragState?: () => void
|
||||||
|
onExternalDrop?: (files: File[], folderId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
|
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
|
||||||
@@ -114,6 +120,11 @@ export function FolderCard({
|
|||||||
selectedCount,
|
selectedCount,
|
||||||
canEdit = true,
|
canEdit = true,
|
||||||
isShareView,
|
isShareView,
|
||||||
|
isExternalDragging,
|
||||||
|
externalOverFolderId,
|
||||||
|
setExternalOverFolderId,
|
||||||
|
resetExternalDragState,
|
||||||
|
onExternalDrop,
|
||||||
}: FolderCardProps) {
|
}: FolderCardProps) {
|
||||||
const [name, setName] = useState(item.name || '')
|
const [name, setName] = useState(item.name || '')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
@@ -153,7 +164,8 @@ export function FolderCard({
|
|||||||
return true
|
return true
|
||||||
}, [dragState, item.id])
|
}, [dragState, item.id])
|
||||||
|
|
||||||
const showDropFeedback = isOver && isValidDropTarget
|
const isExternalOver = isExternalDragging && externalOverFolderId === item.id
|
||||||
|
const showDropFeedback = (isOver && isValidDropTarget) || isExternalOver
|
||||||
const opacity = isBeingDragged ? 0.5 : 1
|
const opacity = isBeingDragged ? 0.5 : 1
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -224,6 +236,40 @@ export function FolderCard({
|
|||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
onDragEnter={
|
||||||
|
isExternalDragging
|
||||||
|
? () => {
|
||||||
|
setExternalOverFolderId?.(item.id!)
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDragLeave={
|
||||||
|
isExternalDragging
|
||||||
|
? (e) => {
|
||||||
|
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||||
|
setExternalOverFolderId?.(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDragOver={
|
||||||
|
isExternalDragging
|
||||||
|
? (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDrop={
|
||||||
|
isExternalDragging
|
||||||
|
? async (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
resetExternalDragState?.()
|
||||||
|
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||||
|
onExternalDrop?.(files, item.id!)
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
className={cn(
|
className={cn(
|
||||||
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
|
'group relative w-full max-w-[340px] select-none cursor-pointer isolate flex flex-col items-center h-full',
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import React, { useMemo, useState, useEffect } from 'react'
|
|||||||
import { cn } from '../../lib/utils'
|
import { cn } from '../../lib/utils'
|
||||||
import type { DragState } from '../dnd-types'
|
import type { DragState } from '../dnd-types'
|
||||||
import { Checkbox } from '../ui/checkbox'
|
import { Checkbox } from '../ui/checkbox'
|
||||||
|
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
|
||||||
|
|
||||||
interface ListRowProps {
|
interface ListRowProps {
|
||||||
item: AssetInfo
|
item: AssetInfo
|
||||||
@@ -23,6 +24,11 @@ interface ListRowProps {
|
|||||||
columnSizing?: Record<string, number>
|
columnSizing?: Record<string, number>
|
||||||
virtualRow: { start: number; index: number }
|
virtualRow: { start: number; index: number }
|
||||||
measureElement: (el: HTMLElement | null) => void
|
measureElement: (el: HTMLElement | null) => void
|
||||||
|
isExternalDragging?: boolean
|
||||||
|
externalOverFolderId?: string | null
|
||||||
|
setExternalOverFolderId?: (id: string | null) => void
|
||||||
|
resetExternalDragState?: () => void
|
||||||
|
onExternalDrop?: (files: File[], folderId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
function ListRow({
|
function ListRow({
|
||||||
@@ -34,6 +40,11 @@ function ListRow({
|
|||||||
columnSizing,
|
columnSizing,
|
||||||
virtualRow,
|
virtualRow,
|
||||||
measureElement,
|
measureElement,
|
||||||
|
isExternalDragging,
|
||||||
|
externalOverFolderId,
|
||||||
|
setExternalOverFolderId,
|
||||||
|
resetExternalDragState,
|
||||||
|
onExternalDrop,
|
||||||
}: ListRowProps) {
|
}: ListRowProps) {
|
||||||
const isDraggingItem = dragState?.draggedIds.has(item.id!)
|
const isDraggingItem = dragState?.draggedIds.has(item.id!)
|
||||||
const isDraggingAny = dragState?.isActive
|
const isDraggingAny = dragState?.isActive
|
||||||
@@ -83,7 +94,8 @@ function ListRow({
|
|||||||
return false
|
return false
|
||||||
}, [dragState, item.id, item.type])
|
}, [dragState, item.id, item.type])
|
||||||
|
|
||||||
const showDropFeedback = isRowOver && isValidDropTarget
|
const isExternalOver = isExternalDragging && externalOverFolderId === item.id
|
||||||
|
const showDropFeedback = (isRowOver && isValidDropTarget) || isExternalOver
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -92,6 +104,40 @@ function ListRow({
|
|||||||
measureElement(node)
|
measureElement(node)
|
||||||
}}
|
}}
|
||||||
data-index={virtualRow.index}
|
data-index={virtualRow.index}
|
||||||
|
onDragEnter={
|
||||||
|
isExternalDragging && item.type === 'folder'
|
||||||
|
? () => {
|
||||||
|
setExternalOverFolderId?.(item.id!)
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDragLeave={
|
||||||
|
isExternalDragging && item.type === 'folder'
|
||||||
|
? (e) => {
|
||||||
|
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||||
|
setExternalOverFolderId?.(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDragOver={
|
||||||
|
isExternalDragging && item.type === 'folder'
|
||||||
|
? (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
onDrop={
|
||||||
|
isExternalDragging && item.type === 'folder'
|
||||||
|
? async (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
e.stopPropagation()
|
||||||
|
resetExternalDragState?.()
|
||||||
|
const files = await getAllFilesFromEntries(e.dataTransfer)
|
||||||
|
onExternalDrop?.(files, item.id!)
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
className={cn(
|
className={cn(
|
||||||
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col',
|
'group border-b border-border transition-colors hover:bg-primary/20 absolute top-0 left-0 w-full flex flex-col',
|
||||||
isSelected && 'bg-primary/10',
|
isSelected && 'bg-primary/10',
|
||||||
@@ -146,6 +192,11 @@ interface FileBrowserListViewProps {
|
|||||||
handleEmptyAreaClick: (e: React.MouseEvent) => void
|
handleEmptyAreaClick: (e: React.MouseEvent) => void
|
||||||
dragState?: DragState
|
dragState?: DragState
|
||||||
sort?: SearchSort
|
sort?: SearchSort
|
||||||
|
isExternalDragging?: boolean
|
||||||
|
externalOverFolderId?: string | null
|
||||||
|
setExternalOverFolderId?: (id: string | null) => void
|
||||||
|
resetExternalDragState?: () => void
|
||||||
|
onExternalDrop?: (files: File[], folderId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function FileBrowserListView({
|
export function FileBrowserListView({
|
||||||
@@ -174,6 +225,11 @@ export function FileBrowserListView({
|
|||||||
handleEmptyAreaClick,
|
handleEmptyAreaClick,
|
||||||
dragState,
|
dragState,
|
||||||
sort,
|
sort,
|
||||||
|
isExternalDragging,
|
||||||
|
externalOverFolderId,
|
||||||
|
setExternalOverFolderId,
|
||||||
|
resetExternalDragState,
|
||||||
|
onExternalDrop,
|
||||||
}: FileBrowserListViewProps) {
|
}: FileBrowserListViewProps) {
|
||||||
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
|
const [columnSizing, setColumnSizing] = useState<Record<string, number>>({})
|
||||||
|
|
||||||
@@ -459,6 +515,11 @@ export function FileBrowserListView({
|
|||||||
columnSizing={columnSizing}
|
columnSizing={columnSizing}
|
||||||
virtualRow={virtualRow}
|
virtualRow={virtualRow}
|
||||||
measureElement={rowVirtualizer.measureElement}
|
measureElement={rowVirtualizer.measureElement}
|
||||||
|
isExternalDragging={isExternalDragging}
|
||||||
|
externalOverFolderId={externalOverFolderId}
|
||||||
|
setExternalOverFolderId={setExternalOverFolderId}
|
||||||
|
resetExternalDragState={resetExternalDragState}
|
||||||
|
onExternalDrop={onExternalDrop}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -3,3 +3,114 @@ export function arrayMove<T>(array: T[], from: number, to: number): T[] {
|
|||||||
newArray.splice(to, 0, newArray.splice(from, 1)[0])
|
newArray.splice(to, 0, newArray.splice(from, 1)[0])
|
||||||
return newArray
|
return newArray
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface SafeFileSystemEntry {
|
||||||
|
name: string
|
||||||
|
isFile: boolean
|
||||||
|
isDirectory: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SafeFileSystemFileEntry extends SafeFileSystemEntry {
|
||||||
|
file(successCallback: (file: File) => void, errorCallback?: (err: unknown) => void): void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SafeFileSystemDirectoryEntry extends SafeFileSystemEntry {
|
||||||
|
createReader(): SafeFileSystemDirectoryReader
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SafeFileSystemDirectoryReader {
|
||||||
|
readEntries(
|
||||||
|
successCallback: (entries: SafeFileSystemEntry[]) => void,
|
||||||
|
errorCallback?: (err: unknown) => void,
|
||||||
|
): void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recursively retrieves all files from a DataTransfer object, traversing directories.
|
||||||
|
* Preserves the directory structure using the non-standard `webkitRelativePath` property on File objects.
|
||||||
|
*/
|
||||||
|
export async function getAllFilesFromEntries(dataTransfer: DataTransfer): Promise<File[]> {
|
||||||
|
const files: File[] = []
|
||||||
|
|
||||||
|
interface QueueItem {
|
||||||
|
entry: SafeFileSystemEntry
|
||||||
|
path: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const queue: QueueItem[] = []
|
||||||
|
const items = dataTransfer.items
|
||||||
|
|
||||||
|
if (items) {
|
||||||
|
for (let i = 0; i < items.length; i++) {
|
||||||
|
const item = items[i]
|
||||||
|
if (item.kind === 'file') {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const entry = (item as any).webkitGetAsEntry?.() as SafeFileSystemEntry | null
|
||||||
|
if (entry) {
|
||||||
|
queue.push({ entry, path: '' })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback if dataTransfer.items is not supported (only dataTransfer.files is available)
|
||||||
|
return Array.from(dataTransfer.files)
|
||||||
|
}
|
||||||
|
|
||||||
|
const readEntries = (
|
||||||
|
dirReader: SafeFileSystemDirectoryReader,
|
||||||
|
): Promise<SafeFileSystemEntry[]> => {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
dirReader.readEntries(
|
||||||
|
(entries) => resolve(entries),
|
||||||
|
() => resolve([]),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const getFile = (fileEntry: SafeFileSystemFileEntry): Promise<File> => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
fileEntry.file(
|
||||||
|
(file) => resolve(file),
|
||||||
|
(err) => reject(err),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const next = queue.shift()
|
||||||
|
if (!next) continue
|
||||||
|
const { entry, path } = next
|
||||||
|
|
||||||
|
if (entry.isFile) {
|
||||||
|
try {
|
||||||
|
const file = await getFile(entry as SafeFileSystemFileEntry)
|
||||||
|
const relativePath = path ? `${path}/${file.name}` : file.name
|
||||||
|
|
||||||
|
// Define webkitRelativePath dynamically so processAndUploadFiles can read the structure
|
||||||
|
Object.defineProperty(file, 'webkitRelativePath', {
|
||||||
|
value: relativePath,
|
||||||
|
writable: false,
|
||||||
|
configurable: true,
|
||||||
|
})
|
||||||
|
files.push(file)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Error reading file entry:', e)
|
||||||
|
}
|
||||||
|
} else if (entry.isDirectory) {
|
||||||
|
const dirReader = (entry as SafeFileSystemDirectoryEntry).createReader()
|
||||||
|
let entries: SafeFileSystemEntry[] = []
|
||||||
|
let readBatch = await readEntries(dirReader)
|
||||||
|
while (readBatch.length > 0) {
|
||||||
|
entries = entries.concat(readBatch)
|
||||||
|
readBatch = await readEntries(dirReader)
|
||||||
|
}
|
||||||
|
|
||||||
|
const newPath = path ? `${path}/${entry.name}` : entry.name
|
||||||
|
for (const childEntry of entries) {
|
||||||
|
queue.push({ entry: childEntry, path: newPath })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return files
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user