Add shared file storage with folder tree, permissions, and file manager UI
New document hub for centralized file storage — replaces scattered drives and USB sticks for non-technical SMBs. Three new tables: storage_folder (nested hierarchy), storage_folder_permission (role and user-level access control), storage_file. Backend: folder CRUD with nested paths, file upload/download via signed URLs, permission checks (view/edit/admin with inheritance from parent folders), public/private toggle, breadcrumb navigation, file search. Frontend: two-panel file manager — collapsible folder tree on left, icon grid view on right. Folder icons by type, file size display, upload button, context menu for download/delete. Breadcrumb nav. Files sidebar link added.
This commit is contained in:
73
packages/admin/src/api/storage.ts
Normal file
73
packages/admin/src/api/storage.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { StorageFolder, StorageFolderPermission, StorageFile } from '@/types/storage'
|
||||
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||
|
||||
// --- Folders ---
|
||||
|
||||
export const storageFolderKeys = {
|
||||
all: ['storage-folders'] as const,
|
||||
tree: ['storage-folders', 'tree'] as const,
|
||||
children: (parentId: string | null) => ['storage-folders', 'children', parentId] as const,
|
||||
detail: (id: string) => ['storage-folders', 'detail', id] as const,
|
||||
permissions: (id: string) => ['storage-folders', id, 'permissions'] as const,
|
||||
}
|
||||
|
||||
export function storageFolderTreeOptions() {
|
||||
return queryOptions({
|
||||
queryKey: storageFolderKeys.tree,
|
||||
queryFn: () => api.get<{ data: StorageFolder[] }>('/v1/storage/folders/tree'),
|
||||
})
|
||||
}
|
||||
|
||||
export function storageFolderChildrenOptions(parentId: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: storageFolderKeys.children(parentId),
|
||||
queryFn: () => api.get<{ data: StorageFolder[] }>('/v1/storage/folders', parentId ? { parentId } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function storageFolderDetailOptions(id: string) {
|
||||
return queryOptions({
|
||||
queryKey: storageFolderKeys.detail(id),
|
||||
queryFn: () => api.get<StorageFolder & { breadcrumbs: { id: string; name: string }[] }>(`/v1/storage/folders/${id}`),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
export function storageFolderPermissionsOptions(id: string) {
|
||||
return queryOptions({
|
||||
queryKey: storageFolderKeys.permissions(id),
|
||||
queryFn: () => api.get<{ data: StorageFolderPermission[] }>(`/v1/storage/folders/${id}/permissions`),
|
||||
enabled: !!id,
|
||||
})
|
||||
}
|
||||
|
||||
export const storageFolderMutations = {
|
||||
create: (data: Record<string, unknown>) => api.post<StorageFolder>('/v1/storage/folders', data),
|
||||
update: (id: string, data: Record<string, unknown>) => api.patch<StorageFolder>(`/v1/storage/folders/${id}`, data),
|
||||
delete: (id: string) => api.del<StorageFolder>(`/v1/storage/folders/${id}`),
|
||||
addPermission: (folderId: string, data: Record<string, unknown>) => api.post<StorageFolderPermission>(`/v1/storage/folders/${folderId}/permissions`, data),
|
||||
removePermission: (permId: string) => api.del<StorageFolderPermission>(`/v1/storage/folder-permissions/${permId}`),
|
||||
}
|
||||
|
||||
// --- Files ---
|
||||
|
||||
export const storageFileKeys = {
|
||||
all: (folderId: string) => ['storage-files', folderId] as const,
|
||||
list: (folderId: string, params: PaginationInput) => ['storage-files', folderId, params] as const,
|
||||
search: (q: string) => ['storage-files', 'search', q] as const,
|
||||
}
|
||||
|
||||
export function storageFileListOptions(folderId: string, params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: storageFileKeys.list(folderId, params),
|
||||
queryFn: () => api.get<PaginatedResponse<StorageFile>>(`/v1/storage/folders/${folderId}/files`, params),
|
||||
enabled: !!folderId,
|
||||
})
|
||||
}
|
||||
|
||||
export const storageFileMutations = {
|
||||
delete: (id: string) => api.del<StorageFile>(`/v1/storage/files/${id}`),
|
||||
getSignedUrl: (id: string) => api.get<{ url: string }>(`/v1/storage/files/${id}/signed-url`),
|
||||
}
|
||||
29
packages/admin/src/components/storage/file-icons.tsx
Normal file
29
packages/admin/src/components/storage/file-icons.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { FileText, Image, FileSpreadsheet, File, FileType, Film } from 'lucide-react'
|
||||
|
||||
const ICON_MAP: Record<string, { icon: typeof FileText; color: string }> = {
|
||||
'application/pdf': { icon: FileText, color: 'text-red-500' },
|
||||
'image/jpeg': { icon: Image, color: 'text-blue-500' },
|
||||
'image/png': { icon: Image, color: 'text-blue-500' },
|
||||
'image/webp': { icon: Image, color: 'text-blue-500' },
|
||||
'image/gif': { icon: Image, color: 'text-blue-500' },
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': { icon: FileType, color: 'text-blue-600' },
|
||||
'application/msword': { icon: FileType, color: 'text-blue-600' },
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': { icon: FileSpreadsheet, color: 'text-green-600' },
|
||||
'application/vnd.ms-excel': { icon: FileSpreadsheet, color: 'text-green-600' },
|
||||
'text/csv': { icon: FileSpreadsheet, color: 'text-green-600' },
|
||||
'text/plain': { icon: FileText, color: 'text-muted-foreground' },
|
||||
'video/mp4': { icon: Film, color: 'text-purple-500' },
|
||||
}
|
||||
|
||||
export function FileIcon({ contentType, className = 'h-8 w-8' }: { contentType: string; className?: string }) {
|
||||
const match = ICON_MAP[contentType] ?? { icon: File, color: 'text-muted-foreground' }
|
||||
const Icon = match.icon
|
||||
return <Icon className={`${className} ${match.color}`} />
|
||||
}
|
||||
|
||||
export function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`
|
||||
}
|
||||
91
packages/admin/src/components/storage/folder-tree.tsx
Normal file
91
packages/admin/src/components/storage/folder-tree.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import { useState } from 'react'
|
||||
import { ChevronRight, ChevronDown, Folder, FolderOpen, Lock } from 'lucide-react'
|
||||
import type { StorageFolder } from '@/types/storage'
|
||||
|
||||
interface FolderTreeProps {
|
||||
folders: StorageFolder[]
|
||||
selectedFolderId: string | null
|
||||
onSelect: (folderId: string | null) => void
|
||||
}
|
||||
|
||||
interface TreeNode {
|
||||
folder: StorageFolder
|
||||
children: TreeNode[]
|
||||
}
|
||||
|
||||
function buildTree(folders: StorageFolder[]): TreeNode[] {
|
||||
const map = new Map<string, TreeNode>()
|
||||
const roots: TreeNode[] = []
|
||||
|
||||
for (const folder of folders) {
|
||||
map.set(folder.id, { folder, children: [] })
|
||||
}
|
||||
|
||||
for (const folder of folders) {
|
||||
const node = map.get(folder.id)!
|
||||
if (folder.parentId && map.has(folder.parentId)) {
|
||||
map.get(folder.parentId)!.children.push(node)
|
||||
} else {
|
||||
roots.push(node)
|
||||
}
|
||||
}
|
||||
|
||||
return roots
|
||||
}
|
||||
|
||||
export function FolderTree({ folders, selectedFolderId, onSelect }: FolderTreeProps) {
|
||||
const tree = buildTree(folders)
|
||||
|
||||
return (
|
||||
<div className="space-y-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(null)}
|
||||
className={`flex items-center gap-2 w-full text-left px-2 py-1.5 rounded-md text-sm transition-colors ${
|
||||
selectedFolderId === null ? 'bg-accent text-accent-foreground font-medium' : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
|
||||
}`}
|
||||
>
|
||||
<Folder className="h-4 w-4 shrink-0" />
|
||||
<span>All Files</span>
|
||||
</button>
|
||||
{tree.map((node) => (
|
||||
<TreeItem key={node.folder.id} node={node} depth={0} selectedFolderId={selectedFolderId} onSelect={onSelect} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TreeItem({ node, depth, selectedFolderId, onSelect }: { node: TreeNode; depth: number; selectedFolderId: string | null; onSelect: (id: string) => void }) {
|
||||
const [expanded, setExpanded] = useState(depth < 2)
|
||||
const hasChildren = node.children.length > 0
|
||||
const isSelected = selectedFolderId === node.folder.id
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { onSelect(node.folder.id); if (hasChildren) setExpanded(!expanded) }}
|
||||
className={`flex items-center gap-1 w-full text-left px-2 py-1.5 rounded-md text-sm transition-colors ${
|
||||
isSelected ? 'bg-accent text-accent-foreground font-medium' : 'text-muted-foreground hover:bg-accent hover:text-accent-foreground'
|
||||
}`}
|
||||
style={{ paddingLeft: `${8 + depth * 16}px` }}
|
||||
>
|
||||
{hasChildren ? (
|
||||
expanded ? <ChevronDown className="h-3 w-3 shrink-0" /> : <ChevronRight className="h-3 w-3 shrink-0" />
|
||||
) : (
|
||||
<span className="w-3 shrink-0" />
|
||||
)}
|
||||
{isSelected ? <FolderOpen className="h-4 w-4 shrink-0 text-primary" /> : <Folder className="h-4 w-4 shrink-0" />}
|
||||
<span className="truncate">{node.folder.name}</span>
|
||||
{!node.folder.isPublic && <Lock className="h-3 w-3 shrink-0 text-muted-foreground/50" />}
|
||||
</button>
|
||||
{expanded && hasChildren && (
|
||||
<div>
|
||||
{node.children.map((child) => (
|
||||
<TreeItem key={child.folder.id} node={child} depth={depth + 1} selectedFolderId={selectedFolderId} onSelect={onSelect} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { Route as AuthenticatedRolesIndexRouteImport } from './routes/_authentic
|
||||
import { Route as AuthenticatedRepairsIndexRouteImport } from './routes/_authenticated/repairs/index'
|
||||
import { Route as AuthenticatedRepairBatchesIndexRouteImport } from './routes/_authenticated/repair-batches/index'
|
||||
import { Route as AuthenticatedMembersIndexRouteImport } from './routes/_authenticated/members/index'
|
||||
import { Route as AuthenticatedFilesIndexRouteImport } from './routes/_authenticated/files/index'
|
||||
import { Route as AuthenticatedAccountsIndexRouteImport } from './routes/_authenticated/accounts/index'
|
||||
import { Route as AuthenticatedRolesNewRouteImport } from './routes/_authenticated/roles/new'
|
||||
import { Route as AuthenticatedRolesRoleIdRouteImport } from './routes/_authenticated/roles/$roleId'
|
||||
@@ -88,6 +89,11 @@ const AuthenticatedMembersIndexRoute =
|
||||
path: '/members/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedFilesIndexRoute = AuthenticatedFilesIndexRouteImport.update({
|
||||
id: '/files/',
|
||||
path: '/files/',
|
||||
getParentRoute: () => AuthenticatedRoute,
|
||||
} as any)
|
||||
const AuthenticatedAccountsIndexRoute =
|
||||
AuthenticatedAccountsIndexRouteImport.update({
|
||||
id: '/accounts/',
|
||||
@@ -200,6 +206,7 @@ export interface FileRoutesByFullPath {
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/files/': typeof AuthenticatedFilesIndexRoute
|
||||
'/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/repair-batches/': typeof AuthenticatedRepairBatchesIndexRoute
|
||||
'/repairs/': typeof AuthenticatedRepairsIndexRoute
|
||||
@@ -226,6 +233,7 @@ export interface FileRoutesByTo {
|
||||
'/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/accounts': typeof AuthenticatedAccountsIndexRoute
|
||||
'/files': typeof AuthenticatedFilesIndexRoute
|
||||
'/members': typeof AuthenticatedMembersIndexRoute
|
||||
'/repair-batches': typeof AuthenticatedRepairBatchesIndexRoute
|
||||
'/repairs': typeof AuthenticatedRepairsIndexRoute
|
||||
@@ -255,6 +263,7 @@ export interface FileRoutesById {
|
||||
'/_authenticated/roles/$roleId': typeof AuthenticatedRolesRoleIdRoute
|
||||
'/_authenticated/roles/new': typeof AuthenticatedRolesNewRoute
|
||||
'/_authenticated/accounts/': typeof AuthenticatedAccountsIndexRoute
|
||||
'/_authenticated/files/': typeof AuthenticatedFilesIndexRoute
|
||||
'/_authenticated/members/': typeof AuthenticatedMembersIndexRoute
|
||||
'/_authenticated/repair-batches/': typeof AuthenticatedRepairBatchesIndexRoute
|
||||
'/_authenticated/repairs/': typeof AuthenticatedRepairsIndexRoute
|
||||
@@ -284,6 +293,7 @@ export interface FileRouteTypes {
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts/'
|
||||
| '/files/'
|
||||
| '/members/'
|
||||
| '/repair-batches/'
|
||||
| '/repairs/'
|
||||
@@ -310,6 +320,7 @@ export interface FileRouteTypes {
|
||||
| '/roles/$roleId'
|
||||
| '/roles/new'
|
||||
| '/accounts'
|
||||
| '/files'
|
||||
| '/members'
|
||||
| '/repair-batches'
|
||||
| '/repairs'
|
||||
@@ -338,6 +349,7 @@ export interface FileRouteTypes {
|
||||
| '/_authenticated/roles/$roleId'
|
||||
| '/_authenticated/roles/new'
|
||||
| '/_authenticated/accounts/'
|
||||
| '/_authenticated/files/'
|
||||
| '/_authenticated/members/'
|
||||
| '/_authenticated/repair-batches/'
|
||||
| '/_authenticated/repairs/'
|
||||
@@ -426,6 +438,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof AuthenticatedMembersIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/files/': {
|
||||
id: '/_authenticated/files/'
|
||||
path: '/files'
|
||||
fullPath: '/files/'
|
||||
preLoaderRoute: typeof AuthenticatedFilesIndexRouteImport
|
||||
parentRoute: typeof AuthenticatedRoute
|
||||
}
|
||||
'/_authenticated/accounts/': {
|
||||
id: '/_authenticated/accounts/'
|
||||
path: '/accounts'
|
||||
@@ -584,6 +603,7 @@ interface AuthenticatedRouteChildren {
|
||||
AuthenticatedRolesRoleIdRoute: typeof AuthenticatedRolesRoleIdRoute
|
||||
AuthenticatedRolesNewRoute: typeof AuthenticatedRolesNewRoute
|
||||
AuthenticatedAccountsIndexRoute: typeof AuthenticatedAccountsIndexRoute
|
||||
AuthenticatedFilesIndexRoute: typeof AuthenticatedFilesIndexRoute
|
||||
AuthenticatedMembersIndexRoute: typeof AuthenticatedMembersIndexRoute
|
||||
AuthenticatedRepairBatchesIndexRoute: typeof AuthenticatedRepairBatchesIndexRoute
|
||||
AuthenticatedRepairsIndexRoute: typeof AuthenticatedRepairsIndexRoute
|
||||
@@ -608,6 +628,7 @@ const AuthenticatedRouteChildren: AuthenticatedRouteChildren = {
|
||||
AuthenticatedRolesRoleIdRoute: AuthenticatedRolesRoleIdRoute,
|
||||
AuthenticatedRolesNewRoute: AuthenticatedRolesNewRoute,
|
||||
AuthenticatedAccountsIndexRoute: AuthenticatedAccountsIndexRoute,
|
||||
AuthenticatedFilesIndexRoute: AuthenticatedFilesIndexRoute,
|
||||
AuthenticatedMembersIndexRoute: AuthenticatedMembersIndexRoute,
|
||||
AuthenticatedRepairBatchesIndexRoute: AuthenticatedRepairBatchesIndexRoute,
|
||||
AuthenticatedRepairsIndexRoute: AuthenticatedRepairsIndexRoute,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useAuthStore } from '@/stores/auth.store'
|
||||
import { myPermissionsOptions } from '@/api/rbac'
|
||||
import { Avatar } from '@/components/shared/avatar-upload'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList } from 'lucide-react'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User, Wrench, Package, ClipboardList, FolderOpen } from 'lucide-react'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated')({
|
||||
beforeLoad: () => {
|
||||
@@ -87,6 +87,7 @@ function AuthenticatedLayout() {
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<NavLink to="/files" icon={<FolderOpen className="h-4 w-4" />} label="Files" />
|
||||
{canViewUsers && (
|
||||
<div className="mt-4 mb-1 px-3">
|
||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||
|
||||
288
packages/admin/src/routes/_authenticated/files/index.tsx
Normal file
288
packages/admin/src/routes/_authenticated/files/index.tsx
Normal file
@@ -0,0 +1,288 @@
|
||||
import { useState, useRef } from 'react'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import {
|
||||
storageFolderTreeOptions, storageFolderDetailOptions, storageFolderMutations, storageFolderKeys,
|
||||
storageFileListOptions, storageFileMutations, storageFileKeys,
|
||||
} from '@/api/storage'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { FolderTree } from '@/components/storage/folder-tree'
|
||||
import { FileIcon, formatFileSize } from '@/components/storage/file-icons'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { FolderPlus, Upload, Search, Folder, ChevronRight, MoreVertical, Trash2, Download } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { StorageFolder, StorageFile } from '@/types/storage'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/files/')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 50,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: FileManagerPage,
|
||||
})
|
||||
|
||||
function FileManagerPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const token = useAuthStore((s) => s.token)
|
||||
const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null)
|
||||
const [newFolderOpen, setNewFolderOpen] = useState(false)
|
||||
const [newFolderName, setNewFolderName] = useState('')
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const { params } = usePagination()
|
||||
|
||||
const { data: treeData, isLoading: treeLoading } = useQuery(storageFolderTreeOptions())
|
||||
const { data: folderDetail } = useQuery(storageFolderDetailOptions(selectedFolderId ?? ''))
|
||||
const { data: filesData, isLoading: filesLoading } = useQuery(
|
||||
storageFileListOptions(selectedFolderId ?? '', { ...params, limit: 50 }),
|
||||
)
|
||||
const { data: subFoldersData } = useQuery({
|
||||
queryKey: storageFolderKeys.children(selectedFolderId),
|
||||
queryFn: () => {
|
||||
const allFolders = treeData?.data ?? []
|
||||
return { data: allFolders.filter((f) => f.parentId === selectedFolderId) }
|
||||
},
|
||||
enabled: !!treeData,
|
||||
})
|
||||
|
||||
const createFolderMutation = useMutation({
|
||||
mutationFn: storageFolderMutations.create,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: storageFolderKeys.all })
|
||||
toast.success('Folder created')
|
||||
setNewFolderOpen(false)
|
||||
setNewFolderName('')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const deleteFolderMutation = useMutation({
|
||||
mutationFn: storageFolderMutations.delete,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: storageFolderKeys.all })
|
||||
setSelectedFolderId(null)
|
||||
toast.success('Folder deleted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const deleteFileMutation = useMutation({
|
||||
mutationFn: storageFileMutations.delete,
|
||||
onSuccess: () => {
|
||||
if (selectedFolderId) queryClient.invalidateQueries({ queryKey: storageFileKeys.all(selectedFolderId) })
|
||||
toast.success('File deleted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
if (!selectedFolderId || !e.target.files?.length) return
|
||||
const files = Array.from(e.target.files)
|
||||
|
||||
for (const file of files) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
try {
|
||||
const res = await fetch(`/v1/storage/folders/${selectedFolderId}/files`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
toast.error(`Upload failed: ${(err as any).error?.message ?? file.name}`)
|
||||
}
|
||||
} catch {
|
||||
toast.error(`Upload failed: ${file.name}`)
|
||||
}
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: storageFileKeys.all(selectedFolderId) })
|
||||
toast.success(`${files.length} file(s) uploaded`)
|
||||
e.target.value = ''
|
||||
}
|
||||
|
||||
async function handleDownload(file: StorageFile) {
|
||||
try {
|
||||
const { url } = await storageFileMutations.getSignedUrl(file.id)
|
||||
window.open(url, '_blank')
|
||||
} catch {
|
||||
toast.error('Download failed')
|
||||
}
|
||||
}
|
||||
|
||||
function handleCreateFolder(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!newFolderName.trim()) return
|
||||
createFolderMutation.mutate({ name: newFolderName.trim(), parentId: selectedFolderId ?? undefined })
|
||||
}
|
||||
|
||||
const folders = treeData?.data ?? []
|
||||
const files = filesData?.data ?? []
|
||||
const subFolders = subFoldersData?.data ?? []
|
||||
const breadcrumbs = folderDetail?.breadcrumbs ?? []
|
||||
|
||||
return (
|
||||
<div className="flex gap-0 h-[calc(100vh-6rem)]">
|
||||
{/* Left Panel — Folder Tree */}
|
||||
<div className="w-60 shrink-0 border-r overflow-y-auto p-3">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="text-sm font-semibold">Folders</h2>
|
||||
<Dialog open={newFolderOpen} onOpenChange={setNewFolderOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-7 w-7 p-0">
|
||||
<FolderPlus className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>New Folder</DialogTitle></DialogHeader>
|
||||
<form onSubmit={handleCreateFolder} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Folder Name</Label>
|
||||
<Input value={newFolderName} onChange={(e) => setNewFolderName(e.target.value)} placeholder="e.g. HR Documents" autoFocus />
|
||||
</div>
|
||||
{selectedFolderId && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Creating inside: {breadcrumbs.map((b) => b.name).join(' / ') || 'Root'}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={createFolderMutation.isPending || !newFolderName.trim()}>
|
||||
{createFolderMutation.isPending ? 'Creating...' : 'Create Folder'}
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{treeLoading ? (
|
||||
<div className="space-y-2">{Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-7 w-full" />)}</div>
|
||||
) : (
|
||||
<FolderTree folders={folders} selectedFolderId={selectedFolderId} onSelect={setSelectedFolderId} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right Panel — Files */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{/* Toolbar */}
|
||||
<div className="flex items-center gap-2 p-3 border-b">
|
||||
{/* Breadcrumbs */}
|
||||
<div className="flex items-center gap-1 text-sm flex-1 min-w-0">
|
||||
<button type="button" onClick={() => setSelectedFolderId(null)} className="text-muted-foreground hover:text-foreground">
|
||||
Files
|
||||
</button>
|
||||
{breadcrumbs.map((crumb) => (
|
||||
<span key={crumb.id} className="flex items-center gap-1">
|
||||
<ChevronRight className="h-3 w-3 text-muted-foreground" />
|
||||
<button type="button" onClick={() => setSelectedFolderId(crumb.id)} className="text-muted-foreground hover:text-foreground truncate max-w-[120px]">
|
||||
{crumb.name}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{selectedFolderId && (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
|
||||
<Upload className="mr-2 h-4 w-4" />Upload
|
||||
</Button>
|
||||
<input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileUpload} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="p-4">
|
||||
{!selectedFolderId ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Folder className="h-12 w-12 mx-auto mb-3 opacity-30" />
|
||||
<p>Select a folder to view files</p>
|
||||
<p className="text-xs mt-1">Or create a new folder to get started</p>
|
||||
</div>
|
||||
) : filesLoading ? (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||
{Array.from({ length: 8 }).map((_, i) => <Skeleton key={i} className="h-28 w-full rounded-lg" />)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Sub-folders */}
|
||||
{subFolders.length > 0 && (
|
||||
<div className="mb-4">
|
||||
<p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Folders</p>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||
{subFolders.map((folder) => (
|
||||
<button
|
||||
key={folder.id}
|
||||
type="button"
|
||||
onClick={() => setSelectedFolderId(folder.id)}
|
||||
className="flex flex-col items-center gap-1.5 p-3 rounded-lg border hover:bg-accent transition-colors group"
|
||||
>
|
||||
<Folder className="h-8 w-8 text-amber-500" />
|
||||
<span className="text-xs font-medium text-center truncate w-full">{folder.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Files */}
|
||||
{files.length > 0 && (
|
||||
<div>
|
||||
{subFolders.length > 0 && <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Files</p>}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
|
||||
{files.map((file) => (
|
||||
<div
|
||||
key={file.id}
|
||||
className="flex flex-col items-center gap-1.5 p-3 rounded-lg border hover:bg-accent transition-colors group relative"
|
||||
>
|
||||
<button type="button" onClick={() => handleDownload(file)} className="flex flex-col items-center gap-1.5 w-full">
|
||||
<FileIcon contentType={file.contentType} />
|
||||
<span className="text-xs font-medium text-center truncate w-full">{file.filename}</span>
|
||||
<span className="text-[10px] text-muted-foreground">{formatFileSize(file.sizeBytes)}</span>
|
||||
</button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="absolute top-1 right-1 h-6 w-6 rounded-md flex items-center justify-center opacity-0 group-hover:opacity-100 hover:bg-muted transition-opacity">
|
||||
<MoreVertical className="h-3 w-3" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => handleDownload(file)}>
|
||||
<Download className="mr-2 h-4 w-4" />Download
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteFileMutation.mutate(file.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{files.length === 0 && subFolders.length === 0 && (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Upload className="h-10 w-10 mx-auto mb-3 opacity-30" />
|
||||
<p>This folder is empty</p>
|
||||
<p className="text-xs mt-1">Upload files or create sub-folders</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
31
packages/admin/src/types/storage.ts
Normal file
31
packages/admin/src/types/storage.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export interface StorageFolder {
|
||||
id: string
|
||||
parentId: string | null
|
||||
name: string
|
||||
path: string
|
||||
createdBy: string | null
|
||||
isPublic: boolean
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
breadcrumbs?: { id: string; name: string }[]
|
||||
}
|
||||
|
||||
export interface StorageFolderPermission {
|
||||
id: string
|
||||
folderId: string
|
||||
roleId: string | null
|
||||
userId: string | null
|
||||
accessLevel: 'view' | 'edit' | 'admin'
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface StorageFile {
|
||||
id: string
|
||||
folderId: string
|
||||
filename: string
|
||||
path: string
|
||||
contentType: string
|
||||
sizeBytes: number
|
||||
uploadedBy: string | null
|
||||
createdAt: string
|
||||
}
|
||||
Reference in New Issue
Block a user