Merge pull request #15 from shumaiOne/feat/file-context-menu-enhancements

feat(ui): file context menu enhancements and share manager breadcrumb migration
This commit is contained in:
Yiling-J
2026-05-24 19:46:58 +08:00
committed by GitHub
8 changed files with 409 additions and 67 deletions
+12 -8
View File
@@ -318,12 +318,16 @@ export class AssetService {
},
})
await tx.asset.update({
where: { id: oldParentId },
data: { fileCount: { decrement: 1 } },
})
await this.updateAncestorsSize(tx, oldParentId, -sourceAsset.sizeByte)
await this.updateAncestorsSize(tx, stackParentId, sourceAsset.sizeByte)
const isUploading = sourceAsset.status === 'uploading'
if (!isUploading) {
await tx.asset.update({
where: { id: oldParentId },
data: { fileCount: { decrement: 1 } },
})
await this.updateAncestorsSize(tx, oldParentId, -sourceAsset.sizeByte)
await this.updateAncestorsSize(tx, stackParentId, sourceAsset.sizeByte)
}
const firstIndex = generateKeyBetween(null, null)
const secondIndex = generateKeyBetween(firstIndex, null)
@@ -341,8 +345,8 @@ export class AssetService {
await tx.asset.update({
where: { id: stack.id },
data: {
fileCount: 2,
sizeByte: destFile.sizeByte + sourceAsset.sizeByte,
fileCount: isUploading ? 1 : 2,
sizeByte: isUploading ? destFile.sizeByte : destFile.sizeByte + sourceAsset.sizeByte,
},
})
+106
View File
@@ -2,6 +2,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { uploadService } from './upload'
import { s3Service } from '@/services/s3/s3'
import { AssetStatus, AssetType, WorkflowTaskType } from '@/generated/prisma/client'
vi.mock('@/services/s3/s3', () => ({
@@ -179,4 +180,109 @@ describe('UploadService', () => {
})
expect(workflowTask).toBeNull()
})
it('should create a version stack when parentId is a file', async () => {
// Create an existing file
const fileA = await prisma.asset.create({
data: {
name: 'fileA.txt',
type: AssetType.file,
projectId,
parentId,
status: AssetStatus.processed,
sizeByte: 1000,
},
})
const req = {
parentId: fileA.id,
files: [
{
name: 'fileA_v2.txt',
id: 'v2',
size: 2000,
type: 'file' as const,
mediaType: 'text/plain',
children: [],
},
],
}
const resp = await uploadService.createUploadTask(userId, req)
expect(resp.taskId).toBeDefined()
// Should have created a version stack
const stack = await prisma.asset.findFirst({
where: { type: AssetType.version_stack, parentId },
})
expect(stack).toBeDefined()
expect(stack?.fileCount).toBe(1) // Only fileA is "uploaded", the new one is still "uploading"
expect(stack?.sizeByte).toBe(1000)
// The new asset should be inside the stack
const newAsset = await prisma.asset.findFirst({
where: { taskId: resp.taskId, parentId: stack!.id },
})
expect(newAsset).toBeDefined()
expect(newAsset?.status).toBe(AssetStatus.uploading)
})
it('should correctly update counts when confirming a version in a stack', async () => {
// Create a stack with one existing file
const stack = await prisma.asset.create({
data: {
name: '',
type: AssetType.version_stack,
projectId,
parentId,
status: AssetStatus.uploaded,
fileCount: 1,
sizeByte: 1000,
},
})
await prisma.asset.create({
data: {
name: 'v1.txt',
type: AssetType.file,
projectId,
parentId: stack.id,
status: AssetStatus.processed,
sizeByte: 1000,
},
})
// Create an uploading asset in that stack
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const fileV2 = await prisma.asset.create({
data: {
name: 'v2.txt',
type: AssetType.file,
projectId,
parentId: stack.id,
status: AssetStatus.uploading,
key: 'v2-key',
sizeByte: 2000,
},
})
vi.spyOn(s3Service, 'getObjectSize').mockResolvedValue(2000)
// Manually set parent folder size to match initial stack size for realistic aggregation
await prisma.asset.update({
where: { id: parentId },
data: { sizeByte: 1000 },
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: fileV2.id })
const updatedStack = await prisma.asset.findUnique({ where: { id: stack.id } })
expect(updatedStack?.fileCount).toBe(2)
expect(updatedStack?.sizeByte).toBe(3000)
// Verify parent folder size (initially 1000 from stack)
const parentFolder = await prisma.asset.findUnique({ where: { id: parentId } })
expect(parentFolder?.sizeByte).toBe(3000)
})
})
+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,25 @@
import type { AssetInfo } from '@/dtos/asset'
import type { ShareLinkInfo } from '@/dtos/share'
import {
ContextMenuContent,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuPortal,
} 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 +31,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 +53,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 +165,33 @@ 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>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
)}
</ContextMenuContent>
) : (
<ContextMenuContent
@@ -162,6 +212,13 @@ export function FileBrowserContextMenu({
<span>Download</span>
</ContextMenuItem>
{(item.type === 'file' || item.type === 'version_stack') && (
<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 +231,33 @@ 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>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
onSelect={() => onAddToShareLink?.(share.id, itemsToModify)}
>
<span className="truncate">{share.name}</span>
</ContextMenuItem>
))}
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
)}
</ContextMenuContent>
)
+118 -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,93 @@ 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
const assetsRes = await client.api.teams[':teamId'].shares[':shareId'].assets.$post({
param: { teamId, shareId: share.id },
json: { assetIds: items.map((i) => i.id!) },
})
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
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 +267,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 +502,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 +550,7 @@ export function FileBrowser({
createUploadTaskMutation({
param: { teamId: teamId },
json: {
parentId: assetId,
parentId: overrideParentId || assetId,
files: root,
},
})
@@ -471,6 +562,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 +772,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 +801,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}>
+1 -1
View File
@@ -80,7 +80,7 @@ export function FileCard({
const inputRef = useRef<HTMLInputElement>(null)
const shouldPoll =
item.type === 'file' &&
(item.type === 'file' || item.type === 'version_stack') &&
!!teamId &&
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
@@ -59,7 +59,7 @@ export function FileListItem({
const inputRef = useRef<HTMLInputElement>(null)
const shouldPoll =
item.type === 'file' &&
(item.type === 'file' || item.type === 'version_stack') &&
!!teamId &&
(item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing')
+67 -50
View File
@@ -1,8 +1,7 @@
import type { AncestorFolder, AssetInfo, AssetInfoPaginatedList } from '@/dtos/asset'
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 { useEffect, useState, useMemo } from 'react'
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'
@@ -56,27 +56,42 @@ export default function ShareManager({
const [ancestorFolders, setAncestorFolders] = useState<AncestorFolder[]>([])
useEffect(() => {
if (shareRootId && !currentFolderId) {
if (shareRootId) {
setCurrentFolderId(shareRootId)
setAncestorFolders([])
setSelectedIds(new Set())
}
}, [shareRootId, currentFolderId])
}, [shareRootId, shareId])
const setProjectState = useTopNavStore((s) => s.setProjectState)
const clearProjectState = useTopNavStore((s) => s.clearProjectState)
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,
@@ -124,8 +139,48 @@ export default function ShareManager({
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
})
const folders = foldersData?.pages.flatMap((page) => page.data ?? []) ?? []
const files = filesData?.pages.flatMap((page) => page.data ?? []) ?? []
const folders = useMemo(
() => foldersData?.pages.flatMap((page) => page.data ?? []) ?? [],
[foldersData],
)
const files = useMemo(
() => filesData?.pages.flatMap((page) => page.data ?? []) ?? [],
[filesData],
)
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: false, // Ensure share link name or subfolder is always shown in TopNav
shareId,
onFolderClick: handleBreadcrumbClick,
})
}
return () => clearProjectState()
}, [
teamId,
projectId,
projectName,
ancestorFolders,
currentFolderId,
shareRootId,
shareLink,
shareId,
folders,
setProjectState,
clearProjectState,
])
const handleClearSelection = () => {
setSelectedIds(new Set())
@@ -170,22 +225,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 +240,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 && (
<>