feat(ui): add file context menu enhancements and migrate share manager breadcrumb

This commit is contained in:
yiling
2026-05-24 16:20:20 +08:00
parent 6829922b95
commit 542d3895bd
4 changed files with 269 additions and 52 deletions
+19 -3
View File
@@ -68,15 +68,28 @@ export class UploadService {
if (!parentAsset.projectId) throw new Error('Parent asset has no project')
const presignedUrls: PresignedUrl[] = []
await this.createAssetsRecursively(
const isParentFile = parentAsset.type === AssetType.file
const targetParentId = isParentFile ? parentAsset.parentId! : parentAsset.id
const createdAssetIds = await this.createAssetsRecursively(
userId,
task.id,
parentAsset.projectId,
parentAsset.id,
targetParentId,
req.files,
presignedUrls,
)
if (isParentFile && createdAssetIds.length > 0) {
for (const assetId of createdAssetIds) {
await assetService.reparentAssets({
assetIds: [assetId],
newParentId: parentAsset.id,
creatorId: userId,
})
}
}
return {
taskId: task.id,
presignedUrls: presignedUrls,
@@ -90,12 +103,13 @@ export class UploadService {
parentId: string,
files: FileNode[],
presignedUrls: PresignedUrl[],
): Promise<void> {
): Promise<string[]> {
const firstFile = await this.prismaClient.asset.findFirst({
where: { parentId },
orderBy: { sortIndex: 'asc' },
})
let currentSortIndex = firstFile?.sortIndex || undefined
const createdIds: string[] = []
for (const file of files) {
if (file.name.startsWith('.')) continue
@@ -124,6 +138,7 @@ export class UploadService {
taskId,
},
})
createdIds.push(newAsset.id)
if (file.children && file.children.length > 0) {
await this.createAssetsRecursively(
@@ -143,6 +158,7 @@ export class UploadService {
})
}
}
return createdIds
}
async confirmFileUpload(
@@ -1,10 +1,24 @@
import type { AssetInfo } from '@/dtos/asset'
import type { ShareLinkInfo } from '@/dtos/share'
import {
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
} from '@/ui/components/ui/context-menu'
import { Download, Edit, FolderPlus, Trash2, UploadCloud, History, FileText } from 'lucide-react'
import {
Download,
Edit,
FolderPlus,
Trash2,
UploadCloud,
History,
FileText,
Link,
Plus,
} from 'lucide-react'
interface FileBrowserContextMenuProps {
item: AssetInfo | null
@@ -16,12 +30,16 @@ interface FileBrowserContextMenuProps {
onNewFolder: (name: string) => void
onUploadFile: () => void
onUploadFolder: () => void
onNewVersion: (item: AssetInfo) => void
folders: AssetInfo[]
files: AssetInfo[]
isRecentlyDeleted?: boolean
onOpenAgentsMd?: (item: AssetInfo | null) => void
isShareView?: boolean
onRemoveFromShare?: (items: AssetInfo[]) => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: (items: AssetInfo[]) => void
onAddToShareLink?: (shareId: string, items: AssetInfo[]) => void
}
export function FileBrowserContextMenu({
@@ -34,12 +52,16 @@ export function FileBrowserContextMenu({
onNewFolder,
onUploadFile,
onUploadFolder,
onNewVersion,
folders,
files,
isRecentlyDeleted,
onOpenAgentsMd,
isShareView,
onRemoveFromShare,
shareLinks = [],
onCreateShareLink,
onAddToShareLink,
}: FileBrowserContextMenuProps) {
const allItems = [...folders, ...files]
const selectedItems = allItems.filter((i) => selectedIds.has(i.id!))
@@ -142,6 +164,31 @@ export function FileBrowserContextMenu({
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
<Plus className="mr-2 h-4 w-4" />
<span>Create Share Link</span>
</ContextMenuItem>
{shareLinks.length > 0 && (
<ContextMenuSub>
<ContextMenuSubTrigger>
<Link className="mr-2 h-4 w-4" />
<span>Add to Share Links</span>
</ContextMenuSubTrigger>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuSub>
)}
</ContextMenuContent>
) : (
<ContextMenuContent
@@ -162,6 +209,13 @@ export function FileBrowserContextMenu({
<span>Download</span>
</ContextMenuItem>
{item.type === 'file' && (
<ContextMenuItem onSelect={() => onNewVersion(item)}>
<UploadCloud className="mr-2 h-4 w-4" />
<span>Create new version</span>
</ContextMenuItem>
)}
{item.type === 'folder' && onOpenAgentsMd && (
<ContextMenuItem onSelect={() => onOpenAgentsMd(item)}>
<FileText className="mr-2 h-4 w-4" />
@@ -174,6 +228,31 @@ export function FileBrowserContextMenu({
<Trash2 className="mr-2 h-4 w-4" />
<span>Delete</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={() => onCreateShareLink?.(itemsToModify)}>
<Plus className="mr-2 h-4 w-4" />
<span>Create Share Link</span>
</ContextMenuItem>
{shareLinks.length > 0 && (
<ContextMenuSub>
<ContextMenuSubTrigger>
<Link className="mr-2 h-4 w-4" />
<span>Add to Share Links</span>
</ContextMenuSubTrigger>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuSub>
)}
</ContextMenuContent>
)
+117 -3
View File
@@ -5,15 +5,17 @@ import type { InferRequestType, InferResponseType } from 'hono/client'
import type { AssetInfo } from '@/dtos/asset'
import type { SearchCondition, SearchSort } from '@/dtos/search'
import type { CreateUploadTaskRequest } from '@/dtos/upload'
import type { ShareLinkInfo } from '@/dtos/share'
import { useFieldStore } from '@/ui/stores/fields'
import { useUploadStore } from '@/ui/stores/upload'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Download } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useInView } from 'react-intersection-observer'
import { toast } from 'sonner'
import type { DragState } from '../dnd-types'
import { FileBrowserContextMenu } from './context-menu'
import { useNavigate } from '@tanstack/react-router'
import { FileBrowserGridView } from './grid-view'
import { FileBrowserListView } from './list-view'
@@ -109,6 +111,92 @@ export function FileBrowser({
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const queryClient = useQueryClient()
const navigate = useNavigate()
const { data: shareLinksData } = useQuery({
queryKey: ['shares', teamId, projectId],
queryFn: async () => {
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$get({
param: { teamId, projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
},
enabled: !!teamId && !!projectId && !isPublic,
})
const { mutate: createShareLink } = useMutation({
mutationFn: async (items: AssetInfo[]) => {
const name =
items.length === 1
? items[0].name
: new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})
const res = await client.api.teams[':teamId'].projects[':projectId'].shares.$post({
param: { teamId, projectId },
json: { name },
})
if (!res.ok) throw new Error('Failed to create share link')
const share = await res.json()
// Add assets to the new share link
await client.api.teams[':teamId'].shares[':shareId'].assets.$post({
param: { teamId, shareId: share.id },
json: { assetIds: items.map((i) => i.id!) },
})
return share
},
onSuccess: (share) => {
queryClient.invalidateQueries({ queryKey: ['shares', teamId, projectId] })
toast.success('Share link created', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: share.id },
}),
},
})
},
})
const { mutate: addToShareLink } = useMutation({
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
const res = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({
param: { teamId, shareId },
json: { assetIds: items.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to add assets')
return { shareId }
},
onSuccess: ({ shareId }) => {
toast.success('Added to share link', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId },
}),
},
})
},
})
const handleCreateShareLink = (items: AssetInfo[]) => {
createShareLink(items)
}
const handleAddToShareLink = (shareId: string, items: AssetInfo[]) => {
addToShareLink({ shareId, items })
}
const {
editingItemId,
@@ -178,6 +266,8 @@ export function FileBrowser({
const [filesExpanded, setFilesExpanded] = React.useState(true)
const fileInputRef = useRef<HTMLInputElement>(null)
const folderInputRef = useRef<HTMLInputElement>(null)
const newVersionInputRef = useRef<HTMLInputElement>(null)
const [targetVersionFileId, setTargetVersionFileId] = useState<string | null>(null)
const fileContextMenu = useRef(false)
const scrollContainerRef = useRef<HTMLDivElement>(null)
@@ -411,7 +501,7 @@ export function FileBrowser({
}
const processAndUploadFiles = useCallback(
(files: FileList | File[]) => {
(files: FileList | File[], overrideParentId?: string) => {
if (!files || files.length === 0) return
const fileWithIds: FileWithId[] = []
@@ -459,7 +549,7 @@ export function FileBrowser({
createUploadTaskMutation({
param: { teamId: teamId },
json: {
parentId: assetId,
parentId: overrideParentId || assetId,
files: root,
},
})
@@ -471,6 +561,20 @@ export function FileBrowser({
processAndUploadFiles(event.target.files!)
}
const handleNewVersionClick = (item: AssetInfo) => {
setTargetVersionFileId(item.id!)
newVersionInputRef.current?.click()
}
const handleNewVersionFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && targetVersionFileId) {
processAndUploadFiles(event.target.files, targetVersionFileId)
setTargetVersionFileId(null)
// Reset input
event.target.value = ''
}
}
const handlePaste = useCallback(
(e: React.ClipboardEvent | ClipboardEvent) => {
if (isShareView) return
@@ -667,8 +771,12 @@ export function FileBrowser({
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
onNewVersion={handleNewVersionClick}
onRestore={handleRestore}
isRecentlyDeleted={isRecentlyDeleted}
shareLinks={shareLinksData?.data ?? []}
onCreateShareLink={handleCreateShareLink}
onAddToShareLink={handleAddToShareLink}
/>
</ContextMenu>
)
@@ -692,6 +800,12 @@ export function FileBrowser({
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<input
type="file"
ref={newVersionInputRef}
style={{ display: 'none' }}
onChange={handleNewVersionFileChange}
/>
{renderContent()}
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
+53 -45
View File
@@ -2,7 +2,6 @@ import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@/dtos/a
import { client } from '@/ui/api/client'
import { useMutation, useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useState } from 'react'
import { BreadcrumbNav } from './breadcrumb-nav'
import { FileBrowser } from './file-browser/file-browser'
import { ShareSettingsSidebar } from './share-settings-sidebar'
import { FolderTree } from './folder-tree'
@@ -13,6 +12,7 @@ import { PointerActivationConstraints } from '@dnd-kit/dom'
import { SnapToPointer } from './dnd-modifiers'
import { useUiStore } from '@/ui/stores/ui'
import { useUserMetadataStore } from '@/ui/stores/user-metadata'
import { useTopNavStore } from '@/ui/stores/top-nav'
import type { ShareLinkInfo } from '@/dtos/share'
import { toast } from 'sonner'
@@ -61,22 +61,34 @@ export default function ShareManager({
}
}, [shareRootId, currentFolderId])
const { setProjectState, clearProjectState } = useTopNavStore()
const handleBreadcrumbClick = (folderId: string) => {
if (folderId === currentFolderId) return
if (folderId === shareRootId) {
setCurrentFolderId(shareRootId)
setAncestorFolders([])
} else {
const index = ancestorFolders.findIndex((f) => f.id === folderId)
if (index !== -1) {
setCurrentFolderId(folderId)
setAncestorFolders(ancestorFolders.slice(index + 1))
}
}
setSelectedIds(new Set())
}
const [leftSidebarWidth, setLeftSidebarWidth] = useState(240)
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const {
fileListLeftSidebarCollapsed: isLeftSidebarCollapsed,
setFileListLeftSidebarCollapsed: setIsLeftSidebarCollapsed,
fileListRightSidebarCollapsed: isRightSidebarCollapsed,
setFileListRightSidebarCollapsed: setIsRightSidebarCollapsed,
viewModes,
setViewMode,
} = useUiStore()
const displayStyle = viewModes[projectId] ?? 'card'
const setDisplayStyle = (style: 'card' | 'list') => {
setViewMode(projectId, style)
}
const {
data: foldersData,
@@ -127,6 +139,40 @@ export default function ShareManager({
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
useEffect(() => {
if (shareLink) {
setProjectState({
teamId,
projectId,
projectName,
ancestorFolders,
currentAsset: {
name:
currentFolderId === shareRootId
? shareLink.name
: folders.find((f) => f.id === currentFolderId)?.name || shareLink.name,
type: 'folder',
},
isRootFolder: currentFolderId === shareRootId,
shareId,
onFolderClick: handleBreadcrumbClick,
})
}
return () => clearProjectState()
}, [
teamId,
projectId,
projectName,
ancestorFolders,
currentFolderId,
shareRootId,
shareLink,
shareId,
folders,
setProjectState,
clearProjectState,
])
const handleClearSelection = () => {
setSelectedIds(new Set())
}
@@ -170,22 +216,6 @@ export default function ShareManager({
}
}
const handleBreadcrumbClick = (folderId: string) => {
if (folderId === currentFolderId) return
if (folderId === shareRootId) {
setCurrentFolderId(shareRootId)
setAncestorFolders([])
} else {
const index = ancestorFolders.findIndex((f) => f.id === folderId)
if (index !== -1) {
setCurrentFolderId(folderId)
setAncestorFolders(ancestorFolders.slice(index + 1))
}
}
setSelectedIds(new Set())
}
if (!shareLink) return <div>Loading...</div>
return (
@@ -201,28 +231,6 @@ export default function ShareManager({
onDragEnd={handleDragEnd}
>
<div className="flex h-screen flex-col bg-background">
<BreadcrumbNav
teamId={teamId}
projectId={projectId}
projectName={projectName}
ancestorFolders={ancestorFolders}
currentAsset={{
name:
currentFolderId === shareRootId
? shareLink.name
: folders.find((f) => f.id === currentFolderId)?.name || shareLink.name,
type: 'folder',
}}
isRootFolder={currentFolderId === shareRootId}
displayStyle={displayStyle}
onDisplayStyleChange={setDisplayStyle}
isLeftSidebarCollapsed={isLeftSidebarCollapsed}
onLeftSidebarToggle={() => setIsLeftSidebarCollapsed(!isLeftSidebarCollapsed)}
isRightSidebarCollapsed={isRightSidebarCollapsed}
onRightSidebarToggle={() => setIsRightSidebarCollapsed(!isRightSidebarCollapsed)}
onFolderClick={handleBreadcrumbClick}
/>
<div className="flex flex-1 overflow-hidden relative">
{!isLeftSidebarCollapsed && (
<>