mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 17:09:27 +00:00
feat(asset): add move to and copy to functionalities
This commit is contained in:
+28
-1
@@ -3,7 +3,7 @@ import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission } from '@/services/authz/authz'
|
||||
import { projectService } from '@/services/project/project'
|
||||
import { assetService } from '@/services/asset/asset'
|
||||
import { reparentAssetsRequestSchema } from '@/dtos/asset'
|
||||
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset'
|
||||
import {
|
||||
createProjectRequestSchema,
|
||||
updateProjectRequestSchema,
|
||||
@@ -208,5 +208,32 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.body(null, 204)
|
||||
},
|
||||
)
|
||||
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
// Check Edit permission on target folder/project
|
||||
await authzService.hasPermission({
|
||||
assetId: req.newParentId,
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
})
|
||||
|
||||
// Check Read permission on all source assets
|
||||
for (const assetId of req.assetIds) {
|
||||
await authzService.hasPermission({
|
||||
assetId,
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
})
|
||||
}
|
||||
|
||||
await assetService.copyAssets({
|
||||
...req,
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
return c.body(null, 204)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -220,6 +220,14 @@ export const reparentAssetsRequestSchema = z.object({
|
||||
})
|
||||
export type ReparentAssetsRequest = z.infer<typeof reparentAssetsRequestSchema>
|
||||
|
||||
export const copyAssetsRequestSchema = z.object({
|
||||
newParentId: z.string(),
|
||||
assetIds: z.array(z.string()),
|
||||
withComments: z.boolean().default(false),
|
||||
creatorId: z.string().optional(),
|
||||
})
|
||||
export type CopyAssetsRequest = z.infer<typeof copyAssetsRequestSchema>
|
||||
|
||||
export const updateFileRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
})
|
||||
|
||||
@@ -11,6 +11,7 @@ vi.mock('@/services/s3/s3', () => ({
|
||||
putObject: vi.fn().mockResolvedValue(undefined),
|
||||
deleteObject: vi.fn().mockResolvedValue(1),
|
||||
deletePrefix: vi.fn().mockResolvedValue(1),
|
||||
copyObject: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -355,6 +356,98 @@ describe('AssetService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('handles copying assets recursively', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
|
||||
await assetService.copyAssets({
|
||||
assetIds: [assets.folderA.id],
|
||||
newParentId: assets.root3.id,
|
||||
creatorId: user.id,
|
||||
withComments: false,
|
||||
})
|
||||
|
||||
// Verify root3 now has 1 more folder
|
||||
await verifyAsset(assets.root3.id, {
|
||||
type: AssetType.folder,
|
||||
fileCount: 1,
|
||||
size: 300,
|
||||
})
|
||||
|
||||
// Verify children of folderA were copied
|
||||
const copiedFolders = await prisma.asset.findMany({
|
||||
where: { parentId: assets.root3.id, name: 'folderA' },
|
||||
})
|
||||
expect(copiedFolders.length).toBe(1)
|
||||
const newFolderA = copiedFolders[0]
|
||||
|
||||
const children = await prisma.asset.findMany({
|
||||
where: { parentId: newFolderA.id },
|
||||
})
|
||||
expect(children.length).toBe(2)
|
||||
expect(children.map((c) => c.name)).toContain('fileA1')
|
||||
expect(children.map((c) => c.name)).toContain('fileA2')
|
||||
})
|
||||
|
||||
it('handles copying assets with comments and attachments', async () => {
|
||||
const { user, assets, project } = await setupBasicAssets()
|
||||
|
||||
// Create a comment with attachment on fileA1
|
||||
const attachmentAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'attach.png',
|
||||
type: AssetType.attachment,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
sizeByte: 50,
|
||||
},
|
||||
})
|
||||
|
||||
const comment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: assets.fileA1.id,
|
||||
creatorId: user.id,
|
||||
message: 'Original Comment',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: comment.id,
|
||||
assetId: attachmentAsset.id,
|
||||
},
|
||||
})
|
||||
|
||||
await assetService.copyAssets({
|
||||
assetIds: [assets.fileA1.id],
|
||||
newParentId: assets.root3.id,
|
||||
creatorId: user.id,
|
||||
withComments: true,
|
||||
})
|
||||
|
||||
// Find the copied file
|
||||
const copiedFiles = await prisma.asset.findMany({
|
||||
where: { parentId: assets.root3.id, name: 'fileA1' },
|
||||
})
|
||||
expect(copiedFiles.length).toBe(1)
|
||||
const newFileA1 = copiedFiles[0]
|
||||
|
||||
// Verify comments were copied
|
||||
const newComments = await prisma.assetComment.findMany({
|
||||
where: { assetId: newFileA1.id },
|
||||
include: { attachments: { include: { asset: true } } },
|
||||
})
|
||||
expect(newComments.length).toBe(1)
|
||||
expect(newComments[0].message).toBe('Original Comment')
|
||||
expect(newComments[0].attachments.length).toBe(1)
|
||||
|
||||
// Verify attachment asset was deep copied
|
||||
const newAttachmentAsset = newComments[0].attachments[0].asset
|
||||
expect(newAttachmentAsset.id).not.toBe(attachmentAsset.id)
|
||||
expect(newAttachmentAsset.name).toBe('attach.png')
|
||||
expect(newAttachmentAsset.type).toBe(AssetType.attachment)
|
||||
})
|
||||
|
||||
it('handles reparenting - Version Stack: move into stack', async () => {
|
||||
const { user, assets } = await setupBasicAssets()
|
||||
await assetService.reparentAssets({
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
AttachmentInfo,
|
||||
ChildPreview,
|
||||
CommentInfo,
|
||||
CopyAssetsRequest,
|
||||
CreateAssetRequest,
|
||||
CreateCommentRequest,
|
||||
FieldValueInfo,
|
||||
@@ -21,6 +22,8 @@ import { Asset, AssetType, Prisma } from '@/generated/prisma/client.ts'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@/services/pagination'
|
||||
import { s3Service } from '@/services/s3/s3'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
type AssetWithIncludes = Prisma.AssetGetPayload<{
|
||||
include: {
|
||||
@@ -266,6 +269,206 @@ export class AssetService {
|
||||
})
|
||||
}
|
||||
|
||||
async copyAssets(req: CopyAssetsRequest): Promise<void> {
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newParent = await tx.asset.findUnique({
|
||||
where: { id: req.newParentId },
|
||||
include: { project: { include: { team: true } } },
|
||||
})
|
||||
if (!newParent) throw new Error('New parent not found')
|
||||
if (!newParent.project) throw new Error('New parent folder is not associated with a project')
|
||||
|
||||
const assetsToCopy = await tx.asset.findMany({
|
||||
where: { id: { in: req.assetIds } },
|
||||
include: { project: { include: { team: true } } },
|
||||
})
|
||||
|
||||
if (assetsToCopy.length !== req.assetIds.length) {
|
||||
throw new Error('Not all assets to be copied were found')
|
||||
}
|
||||
|
||||
for (const a of assetsToCopy) {
|
||||
if (!a.project || !a.project.team) {
|
||||
throw new Error(`Asset ${a.id} is not associated with a team`)
|
||||
}
|
||||
if (!newParent.project.team) {
|
||||
throw new Error('New parent folder is not associated with a team')
|
||||
}
|
||||
if (a.project.team.id !== newParent.project.team.id) {
|
||||
throw new Error(`Cannot copy asset ${a.id} to a different team`)
|
||||
}
|
||||
}
|
||||
|
||||
const firstFile = await tx.asset.findFirst({
|
||||
where: { parentId: newParent.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
let firstSortIndex = firstFile?.sortIndex || null
|
||||
|
||||
let totalSize = 0
|
||||
for (let i = req.assetIds.length - 1; i >= 0; i--) {
|
||||
const assetId = req.assetIds[i]
|
||||
const asset = assetsToCopy.find((a) => a.id === assetId)!
|
||||
const newSortIndex = generateSortIndex(firstSortIndex)
|
||||
const copiedAsset = await this.copyAssetRecursive(
|
||||
tx,
|
||||
asset,
|
||||
newParent.id,
|
||||
newParent.projectId!,
|
||||
newSortIndex,
|
||||
req.creatorId,
|
||||
req.withComments,
|
||||
)
|
||||
totalSize += copiedAsset.sizeByte
|
||||
firstSortIndex = newSortIndex
|
||||
}
|
||||
|
||||
await tx.asset.update({
|
||||
where: { id: newParent.id },
|
||||
data: {
|
||||
fileCount: { increment: assetsToCopy.length },
|
||||
},
|
||||
})
|
||||
await this.updateAncestorsSize(tx, newParent.id, totalSize)
|
||||
})
|
||||
}
|
||||
|
||||
private async copyAssetRecursive(
|
||||
tx: Prisma.TransactionClient,
|
||||
asset: Asset,
|
||||
newParentId: string | null,
|
||||
projectId: string | null,
|
||||
sortIndex: string | null,
|
||||
creatorId?: string,
|
||||
withComments: boolean = false,
|
||||
): Promise<Asset> {
|
||||
let newKey = asset.key
|
||||
if (asset.type === AssetType.file && asset.key) {
|
||||
// Duplicate S3 object
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const ext = path.extname(asset.key)
|
||||
newKey = ulid() + ext
|
||||
await s3Service.copyObject(bucket, asset.key, bucket, newKey)
|
||||
}
|
||||
|
||||
const newAsset = await tx.asset.create({
|
||||
data: {
|
||||
name: asset.name,
|
||||
nameNgram: asset.nameNgram,
|
||||
key: newKey,
|
||||
type: asset.type,
|
||||
mediaType: asset.mediaType,
|
||||
fileCount: asset.fileCount,
|
||||
sizeByte: asset.sizeByte,
|
||||
status: asset.status,
|
||||
transcodeTaskId: asset.transcodeTaskId,
|
||||
media: (asset.media as any) || undefined,
|
||||
isDeleted: asset.isDeleted,
|
||||
deletedAt: asset.deletedAt,
|
||||
sortIndex: sortIndex,
|
||||
parentId: newParentId,
|
||||
projectId: projectId,
|
||||
creatorId: creatorId || asset.creatorId,
|
||||
taskId: asset.taskId,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
targetId: asset.targetId as any,
|
||||
},
|
||||
})
|
||||
|
||||
if (withComments) {
|
||||
await this.copyComments(tx, asset.id, newAsset.id, creatorId)
|
||||
}
|
||||
|
||||
if (asset.type === AssetType.folder) {
|
||||
const children = await tx.asset.findMany({
|
||||
where: { parentId: asset.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
for (const child of children) {
|
||||
await this.copyAssetRecursive(
|
||||
tx,
|
||||
child,
|
||||
newAsset.id,
|
||||
projectId,
|
||||
child.sortIndex,
|
||||
creatorId,
|
||||
withComments,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return newAsset
|
||||
}
|
||||
|
||||
private async copyComments(
|
||||
tx: Prisma.TransactionClient,
|
||||
oldAssetId: string,
|
||||
newAssetId: string,
|
||||
creatorId?: string,
|
||||
) {
|
||||
const comments = await tx.assetComment.findMany({
|
||||
where: { assetId: oldAssetId, replyToId: null },
|
||||
include: {
|
||||
attachments: { include: { asset: true } },
|
||||
replies: {
|
||||
include: {
|
||||
attachments: { include: { asset: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
for (const comment of comments) {
|
||||
await this.copyCommentRecursive(tx, comment, newAssetId, null, creatorId)
|
||||
}
|
||||
}
|
||||
|
||||
private async copyCommentRecursive(
|
||||
tx: Prisma.TransactionClient,
|
||||
comment: any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
newAssetId: string,
|
||||
newReplyToId: string | null,
|
||||
creatorId?: string,
|
||||
) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { id, createdAt, updatedAt, assetId, replyToId, attachments, replies, ...data } = comment
|
||||
const newComment = await tx.assetComment.create({
|
||||
data: {
|
||||
...data,
|
||||
assetId: newAssetId,
|
||||
replyToId: newReplyToId,
|
||||
creatorId: creatorId || comment.creatorId,
|
||||
},
|
||||
})
|
||||
|
||||
if (attachments) {
|
||||
for (const attachment of attachments) {
|
||||
// Deep copy attachment asset
|
||||
const copiedAttachmentAsset = await this.copyAssetRecursive(
|
||||
tx,
|
||||
attachment.asset,
|
||||
null, // attachment usually has no parent
|
||||
attachment.asset.projectId,
|
||||
attachment.asset.sortIndex,
|
||||
creatorId,
|
||||
false,
|
||||
)
|
||||
await tx.assetCommentAttachment.create({
|
||||
data: {
|
||||
commentId: newComment.id,
|
||||
assetId: copiedAttachmentAsset.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (replies) {
|
||||
for (const reply of replies) {
|
||||
await this.copyCommentRecursive(tx, reply, newAssetId, newComment.id, creatorId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async reparentFileToFile(
|
||||
tx: Prisma.TransactionClient,
|
||||
destFile: AssetWithProjectTeam,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ObjectInfo } from '@/dtos/s3'
|
||||
import {
|
||||
CopyObjectCommand,
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadObjectCommand,
|
||||
@@ -49,6 +50,12 @@ export interface S3Service {
|
||||
contentType?: string,
|
||||
): Promise<void>
|
||||
getObject(bucket: string, key: string): Promise<S3Object>
|
||||
copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void>
|
||||
downloadToFile(bucket: string, key: string, filePath: string): Promise<void>
|
||||
deleteObject(bucket: string, key: string): Promise<number>
|
||||
deletePrefix(bucket: string, prefix: string): Promise<number>
|
||||
@@ -131,6 +138,21 @@ export class S3StorageService implements S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
async copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void> {
|
||||
const command = new CopyObjectCommand({
|
||||
Bucket: destBucket,
|
||||
Key: destKey,
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
CopySource: `${sourceBucket}/${sourceKey}`,
|
||||
})
|
||||
await this.client.send(command)
|
||||
}
|
||||
|
||||
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
|
||||
const command = new GetObjectCommand({
|
||||
Bucket: bucket,
|
||||
@@ -331,6 +353,21 @@ export class LocalStorageService implements S3Service {
|
||||
}
|
||||
}
|
||||
|
||||
async copyObject(
|
||||
sourceBucket: string,
|
||||
sourceKey: string,
|
||||
destBucket: string,
|
||||
destKey: string,
|
||||
): Promise<void> {
|
||||
const srcPath = this.getFilePath(sourceBucket, sourceKey)
|
||||
const destPath = this.getFilePath(destBucket, destKey)
|
||||
const dir = path.dirname(destPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
await fs.promises.copyFile(srcPath, destPath)
|
||||
}
|
||||
|
||||
async downloadToFile(bucket: string, key: string, filePath: string): Promise<void> {
|
||||
const srcPath = this.getFilePath(bucket, key)
|
||||
await fs.promises.copyFile(srcPath, filePath)
|
||||
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
FileText,
|
||||
Link,
|
||||
Plus,
|
||||
ArrowRight,
|
||||
Copy,
|
||||
} from 'lucide-react'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
@@ -32,6 +34,8 @@ interface FileBrowserContextMenuProps {
|
||||
onUploadFile: () => void
|
||||
onUploadFolder: () => void
|
||||
onNewVersion: (item: AssetInfo) => void
|
||||
onMoveTo: (items: AssetInfo[]) => void
|
||||
onCopyTo: (items: AssetInfo[]) => void
|
||||
folders: AssetInfo[]
|
||||
files: AssetInfo[]
|
||||
isRecentlyDeleted?: boolean
|
||||
@@ -54,6 +58,8 @@ export function FileBrowserContextMenu({
|
||||
onUploadFile,
|
||||
onUploadFolder,
|
||||
onNewVersion,
|
||||
onMoveTo,
|
||||
onCopyTo,
|
||||
folders,
|
||||
files,
|
||||
isRecentlyDeleted,
|
||||
@@ -161,6 +167,14 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={handleDelete} className="text-destructive">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
<span>Delete</span>
|
||||
@@ -212,6 +226,15 @@ export function FileBrowserContextMenu({
|
||||
<span>Download</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
|
||||
<ArrowRight className="mr-2 h-4 w-4" />
|
||||
<span>Move to</span>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => onCopyTo(itemsToModify)}>
|
||||
<Copy className="mr-2 h-4 w-4" />
|
||||
<span>Copy to</span>
|
||||
</ContextMenuItem>
|
||||
|
||||
{(item.type === 'file' || item.type === 'version_stack') && (
|
||||
<ContextMenuItem onSelect={() => onNewVersion(item)}>
|
||||
<UploadCloud className="mr-2 h-4 w-4" />
|
||||
|
||||
@@ -16,6 +16,7 @@ import { toast } from 'sonner'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { MoveCopyDialog } from '../move-copy-dialog'
|
||||
|
||||
import { FileBrowserGridView } from './grid-view'
|
||||
import { FileBrowserListView } from './list-view'
|
||||
@@ -110,6 +111,8 @@ export function FileBrowser({
|
||||
fieldVisibility,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
|
||||
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
|
||||
const queryClient = useQueryClient()
|
||||
const navigate = useNavigate()
|
||||
|
||||
@@ -126,6 +129,97 @@ export function FileBrowser({
|
||||
enabled: !!teamId && !!projectId && !isPublic,
|
||||
})
|
||||
|
||||
const $reparent = client.api.projects[':projectId'].reparent.$post
|
||||
const { mutate: reparentAssets } = useMutation<
|
||||
InferResponseType<typeof $reparent, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $reparent>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $reparent(request)
|
||||
if (!res.ok) throw new Error('Failed to move assets')
|
||||
return null as unknown as InferResponseType<typeof $reparent, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const $copy = client.api.projects[':projectId'].copy.$post
|
||||
const { mutate: copyAssets } = useMutation<
|
||||
InferResponseType<typeof $copy, 204>,
|
||||
Error,
|
||||
InferRequestType<typeof $copy>
|
||||
>({
|
||||
mutationFn: async (request) => {
|
||||
const res = await $copy(request)
|
||||
if (!res.ok) throw new Error('Failed to copy assets')
|
||||
return null as unknown as InferResponseType<typeof $copy, 204>
|
||||
},
|
||||
})
|
||||
|
||||
const handleMoveCopyConfirm = async (targetFolderId: string, withComments: boolean) => {
|
||||
const assetIds = itemsToMoveCopy.map((i) => i.id!)
|
||||
if (moveCopyMode === 'move') {
|
||||
reparentAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully moved ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
} else {
|
||||
copyAssets(
|
||||
{
|
||||
param: { projectId },
|
||||
json: { newParentId: targetFolderId, assetIds, withComments },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
toast.success(`Successfully copied ${assetIds.length} item(s)`, {
|
||||
action: {
|
||||
label: 'Go to folder',
|
||||
onClick: () => {
|
||||
navigate({
|
||||
to: '/projects/$projectId/folders/$folderId',
|
||||
params: { projectId, folderId: targetFolderId },
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders', teamId] })
|
||||
setMoveCopyMode(null)
|
||||
setItemsToMoveCopy([])
|
||||
onClearSelection()
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(`Error: ${err.message}`)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const { mutate: createShareLink } = useMutation({
|
||||
mutationFn: async (items: AssetInfo[]) => {
|
||||
const name =
|
||||
@@ -773,6 +867,14 @@ export function FileBrowser({
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
onNewVersion={handleNewVersionClick}
|
||||
onMoveTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('move')
|
||||
}}
|
||||
onCopyTo={(items) => {
|
||||
setItemsToMoveCopy(items)
|
||||
setMoveCopyMode('copy')
|
||||
}}
|
||||
onRestore={handleRestore}
|
||||
isRecentlyDeleted={isRecentlyDeleted}
|
||||
shareLinks={shareLinksData?.data ?? []}
|
||||
@@ -809,6 +911,17 @@ export function FileBrowser({
|
||||
/>
|
||||
{renderContent()}
|
||||
|
||||
{moveCopyMode && (
|
||||
<MoveCopyDialog
|
||||
isOpen={!!moveCopyMode}
|
||||
onClose={() => setMoveCopyMode(null)}
|
||||
onConfirm={handleMoveCopyConfirm}
|
||||
mode={moveCopyMode}
|
||||
teamId={teamId}
|
||||
currentProjectId={projectId}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
|
||||
@@ -28,6 +28,8 @@ interface FolderTreeProps {
|
||||
projectName: string
|
||||
rootFolderId: string
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
}
|
||||
|
||||
export function FolderTree({
|
||||
@@ -36,6 +38,8 @@ export function FolderTree({
|
||||
projectName,
|
||||
rootFolderId,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
}: FolderTreeProps) {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
@@ -117,6 +121,8 @@ export function FolderTree({
|
||||
level={0}
|
||||
isRoot={true}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
@@ -247,6 +253,8 @@ interface FolderTreeItemProps {
|
||||
level: number
|
||||
isRoot?: boolean
|
||||
dragState?: DragState
|
||||
onSelect?: (folder: AssetInfo) => void
|
||||
selectedFolderId?: string
|
||||
}
|
||||
|
||||
function FolderTreeItem({
|
||||
@@ -256,6 +264,8 @@ function FolderTreeItem({
|
||||
level,
|
||||
isRoot,
|
||||
dragState,
|
||||
onSelect,
|
||||
selectedFolderId,
|
||||
}: FolderTreeItemProps) {
|
||||
const [isExpanded, setIsExpanded] = useState(isRoot || false)
|
||||
const navigate = useNavigate()
|
||||
@@ -321,6 +331,11 @@ function FolderTreeItem({
|
||||
}
|
||||
|
||||
const handleFolderClick = () => {
|
||||
if (onSelect) {
|
||||
onSelect(folder)
|
||||
return
|
||||
}
|
||||
|
||||
if (isRoot) {
|
||||
navigate({
|
||||
to: '/projects/$projectId',
|
||||
@@ -340,7 +355,7 @@ function FolderTreeItem({
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: !!isRoot,
|
||||
disabled: !!isRoot || !!onSelect,
|
||||
})
|
||||
|
||||
const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({
|
||||
@@ -349,7 +364,7 @@ function FolderTreeItem({
|
||||
type: 'folder',
|
||||
item: folder,
|
||||
},
|
||||
disabled: dragState?.draggedIds.has(folder.id!),
|
||||
disabled: dragState?.draggedIds.has(folder.id!) || !!onSelect,
|
||||
})
|
||||
|
||||
const setNodeRef = (node: HTMLDivElement | null) => {
|
||||
@@ -358,20 +373,24 @@ function FolderTreeItem({
|
||||
}
|
||||
|
||||
const isValidDropTarget = useMemo(() => {
|
||||
if (onSelect) return false
|
||||
if (!dragState?.isActive) return false
|
||||
if (dragState.draggedIds.has(folder.id!)) return false
|
||||
return true
|
||||
}, [dragState, folder.id])
|
||||
}, [dragState, folder.id, onSelect])
|
||||
|
||||
const showDropFeedback = isOver && isValidDropTarget
|
||||
|
||||
const isSelected = selectedFolderId === folder.id
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
ref={setNodeRef}
|
||||
className={cn(
|
||||
'group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
isActive && 'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
(isActive || isSelected) &&
|
||||
'bg-sidebar-accent text-sidebar-accent-foreground font-medium',
|
||||
isDragging && 'opacity-50',
|
||||
showDropFeedback && 'bg-sidebar-accent ring-2 ring-primary ring-inset',
|
||||
)}
|
||||
@@ -415,6 +434,8 @@ function FolderTreeItem({
|
||||
folder={child}
|
||||
level={level + 1}
|
||||
dragState={dragState}
|
||||
onSelect={onSelect}
|
||||
selectedFolderId={selectedFolderId}
|
||||
/>
|
||||
))}
|
||||
{hasNextPage && (
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/ui/components/ui/select'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { FolderTree } from './folder-tree'
|
||||
import { AssetInfo } from '@/dtos/asset'
|
||||
import { ProjectInfo } from '@/dtos/project'
|
||||
import { ScrollArea } from './ui/scroll-area'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
|
||||
interface MoveCopyDialogProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onConfirm: (targetFolderId: string, withComments: boolean) => void
|
||||
mode: 'move' | 'copy'
|
||||
teamId: string
|
||||
currentProjectId: string
|
||||
}
|
||||
|
||||
export function MoveCopyDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onConfirm,
|
||||
mode,
|
||||
teamId,
|
||||
currentProjectId,
|
||||
}: MoveCopyDialogProps) {
|
||||
const [selectedProjectId, setSelectedProjectId] = useState(currentProjectId)
|
||||
const [selectedFolder, setSelectedFolder] = useState<AssetInfo | null>(null)
|
||||
const [withComments, setWithComments] = useState(false)
|
||||
|
||||
const { data: projectsData, isLoading: isLoadingProjects } = useQuery({
|
||||
queryKey: ['projects', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].projects.$get({
|
||||
param: { teamId },
|
||||
query: { first: '100' },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch projects')
|
||||
return (await res.json()) as unknown as { data: ProjectInfo[] }
|
||||
},
|
||||
enabled: !!teamId && isOpen,
|
||||
})
|
||||
|
||||
const projects = projectsData?.data ?? []
|
||||
const selectedProject = projects.find((p) => p.id === selectedProjectId)
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (selectedFolder) {
|
||||
onConfirm(selectedFolder.id, withComments)
|
||||
} else if (selectedProject?.rootFolder) {
|
||||
onConfirm(selectedProject.rootFolder, withComments)
|
||||
}
|
||||
}
|
||||
|
||||
const title = mode === 'move' ? 'Move to' : 'Copy to'
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="sm:max-w-[425px] flex flex-col h-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-4 flex-1 overflow-hidden">
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="text-sm font-medium">Select Project</label>
|
||||
<Select
|
||||
value={selectedProjectId}
|
||||
onValueChange={(val) => {
|
||||
setSelectedProjectId(val)
|
||||
setSelectedFolder(null)
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a project" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2 flex-1 overflow-hidden">
|
||||
<label className="text-sm font-medium">Select Folder</label>
|
||||
<div className="border rounded-md flex-1 overflow-hidden">
|
||||
<ScrollArea className="h-full">
|
||||
{selectedProject && selectedProject.rootFolder ? (
|
||||
<FolderTree
|
||||
teamId={teamId}
|
||||
projectId={selectedProject.id}
|
||||
projectName={selectedProject.name}
|
||||
rootFolderId={selectedProject.rootFolder}
|
||||
onSelect={setSelectedFolder}
|
||||
selectedFolderId={selectedFolder?.id || selectedProject.rootFolder}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full p-4">
|
||||
{isLoadingProjects ? (
|
||||
<Loader2 className="animate-spin h-6 w-6" />
|
||||
) : (
|
||||
'Select a project first'
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{mode === 'copy' && (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="copy-comments"
|
||||
checked={withComments}
|
||||
onCheckedChange={(checked) => setWithComments(!!checked)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="copy-comments"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Copy comments
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!selectedProject}>
|
||||
Confirm
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user