import { client } from '@/ui/api/client' import { m } from '@/ui/paraglide/messages.js' import { CopyDropdownMenuSub } from './copy-submenu' import type { CopyKind } from './copy-options' import type { AssetInfo, FieldValueInfo } from '@shumai/dtos' import { useQuery } from '@tanstack/react-query' import { Badge } from '@/ui/components/ui/badge' import { Button } from '@/ui/components/ui/button' import { Checkbox } from '@/ui/components/ui/checkbox' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/ui/components/ui/dropdown-menu' import { EditableText } from '@/ui/components/ui/editable-text' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from '@/ui/components/ui/tooltip' import { ProgressCircle } from '@/ui/components/ui/progress-circle' import { formatRemainingTimeSeconds, formatTimeAgo, getTrashDaysLeft } from '@/ui/lib/time' import { formatSize } from '@/ui/lib/format' import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils' import { handleCardClick } from '@/ui/lib/selection-utils' import { cn } from '@/ui/lib/utils' import { useUploadStore } from '@/ui/stores/upload' import { useDraggable, useDroppable } from '@dnd-kit/react' import { AlertCircle, Archive, ArchiveRestore, Clock, Download, Edit, History, Layers, Loader2, MessageCircleMore, MoreHorizontal, Trash2, } from 'lucide-react' import React, { useEffect, useMemo, useRef, useState } from 'react' import type { DragState } from '../dnd-types' import FieldRenderer from '../field-renderer' import { FilePreview } from './file-preview' import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import { FIELD_TYPE_ICONS } from '../fields-manager' interface FileCardProps { teamId?: string item: AssetInfo isSelected?: boolean isChecked?: boolean isEditing?: boolean onSelect?: (item: AssetInfo, event: React.MouseEvent, meta?: { isCheckbox?: boolean }) => void onDoubleClick?: (item: AssetInfo) => void onContextMenu?: (e: React.MouseEvent, item: AssetInfo) => void // Deprecated manual drag handlers replaced by dnd-kit onDragStart?: (item: AssetInfo) => void onDrop?: (target: AssetInfo) => void onRename?: (newName: string) => void onFinishEditing?: () => void onSaveField?: (fieldId: string, value: unknown) => void dragState?: DragState disabled?: boolean onAction?: ( action: | 'rename' | 'delete' | 'download' | 'restore' | 'remove-from-share' | 'manage-versions' | 'archive' | 'restore-archive', item: AssetInfo, ) => void isRecentlyDeleted?: boolean isRecents?: boolean selectedCount?: number fields?: MetadataFieldInfo[] isShareView?: boolean isPublic?: boolean canEdit?: boolean archiveStorageEnabled?: boolean /** When false, hides the download action. Defaults to true. */ allowDownload?: boolean hideCheckbox?: boolean hideActions?: boolean isTeamOwner?: boolean onCopy?: (kind: CopyKind, items: AssetInfo[]) => void } export function FileCard({ teamId, item, isSelected = false, isChecked = false, isEditing = false, onSelect = () => {}, onDoubleClick = () => {}, onContextMenu = () => {}, // eslint-disable-next-line @typescript-eslint/no-unused-vars onDragStart: _onDragStart, // eslint-disable-next-line @typescript-eslint/no-unused-vars onDrop: _onDrop, onRename = () => {}, onFinishEditing = () => {}, onSaveField = () => {}, dragState, disabled, onAction, onCopy, isTeamOwner = false, isRecentlyDeleted, isRecents, selectedCount, fields = [], isShareView, isPublic = false, canEdit = true, archiveStorageEnabled = false, allowDownload = true, hideCheckbox = false, hideActions = false, }: FileCardProps) { const [name, setName] = useState(item.name) const inputRef = useRef(null) const [isCreatorTooltipOpen, setIsCreatorTooltipOpen] = useState(false) const creatorRef = useRef(null) const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || '']) const uploadPercent = fileUploadState ? fileUploadState.total > 0 ? (fileUploadState.loaded / fileUploadState.total) * 100 : 0 : 0 const { data: polledItem } = useQuery({ queryKey: ['file', teamId, item.id], queryFn: async () => { const res = await client.api.files[':fileId'].$get({ param: { fileId: item.id || '' }, }) if (!res.ok) throw new Error('failed to fetch file') return (await res.json()) as unknown as AssetInfo }, enabled: false, }) const displayItem = useMemo(() => { if ( item.status === 'processed' || item.status === 'archived' || item.status === 'error' || item.status === 'failed' ) { return item } if (item.status === 'archiving' && polledItem?.status === 'processed') { return item } if (item.status === 'restoring' && polledItem?.status === 'archived') { return item } if ( polledItem?.status === 'processed' || polledItem?.status === 'archived' || polledItem?.status === 'error' || polledItem?.status === 'failed' ) { return polledItem } return polledItem || item }, [item, polledItem]) // dnd-kit hooks const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({ id: `browser:${displayItem.id!}`, data: { type: displayItem.type, id: displayItem.id, item: displayItem, }, disabled: disabled, }) const { ref: setDroppableRef, isDropTarget: isOver } = useDroppable({ id: `browser:${displayItem.id!}`, data: { type: displayItem.type, id: displayItem.id, item: displayItem, }, disabled: disabled, }) // Combine refs const setNodeRef = (node: HTMLElement | null) => { if (disabled) return setDraggableRef(node) setDroppableRef(node) } // Determine if this item is being dragged (either directly or as part of selection) const isBeingDragged = isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false) // Determine if this is a valid drop target // File/version stack target is valid ONLY if dragging 1 single regular file // And strictly, we shouldn't drop on ourselves const isValidDropTarget = useMemo(() => { if (!dragState?.isActive) return false if (dragState.draggedIds.has(displayItem.id!)) return false // Can't drop on self return dragState.isSingleFile }, [dragState, displayItem.id]) const showDropFeedback = isOver && isValidDropTarget // We only gray out the original item, drag overlay will show the "ghost" const opacity = isBeingDragged ? 0.5 : 1 const itemFieldValueMap = useMemo(() => { return (displayItem.fieldValues || []).reduce( (acc: Record, val: FieldValueInfo) => { acc[val.fieldId!] = val return acc }, {} as Record, ) }, [displayItem.fieldValues]) useEffect(() => { if (isEditing) { // Use a longer timeout to ensure the context menu has closed and // the DOM has stabilized before focusing. Radix focus restoration // can sometimes conflict with immediate focus calls. const timeoutId = setTimeout(() => { if (inputRef.current) { selectFileNameWithoutExtension(inputRef.current) } }, 150) return () => clearTimeout(timeoutId) } }, [isEditing]) // Reset name if item changes useEffect(() => { setName(displayItem.name) }, [displayItem.name]) const handleClick = (e: React.MouseEvent) => { handleCardClick({ item: displayItem, event: e, isPublic, selectedCount, isSelected, isChecked, onSelect, onDoubleClick, }) } const handleRename = () => { if (name !== displayItem.name) { onRename(name || '') } onFinishEditing() } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { handleRename() } if (e.key === 'Escape') { setName(displayItem.name || '') onFinishEditing() } } const creatorText = useMemo(() => { if (!displayItem.createdAt) return '' return m.created_by_at({ time: formatTimeAgo(displayItem.createdAt), author: displayItem.agent ? m.user_via_agent({ user: displayItem.creator?.name || m.unknown_user(), agent: displayItem.agent.name, }) : displayItem.creator?.name || m.unknown_user(), }) }, [displayItem.createdAt, displayItem.agent, displayItem.creator?.name]) const daysLeft = isRecentlyDeleted ? getTrashDaysLeft(displayItem.deletedAt) : null const daysLeftTooltip = daysLeft === null ? '' : daysLeft === 1 ? m.n_days_left_singular({ count: daysLeft }) : m.n_days_left_plural({ count: daysLeft }) // A preview (poster thumbnail and/or sprite) can be available before transcoding finishes, // since the poster/sprite are generated and persisted ahead of the proxy transcodes. const hasPreview = Boolean( item.matchedSprite || displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl, ) const isFailed = displayItem.status === 'failed' const isLocalUploader = Boolean(fileUploadState) const isUploadFailed = fileUploadState?.status === 'failed' const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100 const isUploading = displayItem.status === 'uploading' && !isUploadDone && !isUploadFailed const isProcessing = displayItem.status === 'processing' || displayItem.status === 'uploaded' || (displayItem.status === 'uploading' && isUploadDone) // While uploading/transcoding/error, the creator row is replaced by a status label so the real // date/author only appears once the asset is ready or failed. let statusText: string | null = null if (isUploadFailed || displayItem.status === 'error') { statusText = m.failed_to_upload() } else if (isUploading) { if (isLocalUploader) { if (fileUploadState?.speed && fileUploadState?.eta != null) { statusText = m.upload_eta_speed({ eta: formatRemainingTimeSeconds(fileUploadState.eta), speed: `${formatSize(fileUploadState.speed)}/s`, }) } else { statusText = m.uploading() } } else { statusText = m.user_is_uploading({ user: displayItem.creator?.name || m.someone(), }) } } else if (isProcessing) { statusText = m.preparing() } const failedErrorMessage = displayItem.media?.error || m.processing_failed() const isOriginalUnavailable = displayItem.status === 'archived' || displayItem.status === 'archiving' || displayItem.status === 'restoring' const canArchiveItem = displayItem.type === 'version_stack' ? displayItem.status === 'processed' || (displayItem.versionStack?.versions.some((v) => !v.status || v.status === 'processed') ?? false) : displayItem.status === 'processed' const canRestoreArchiveItem = displayItem.type === 'version_stack' ? displayItem.status === 'archived' || (displayItem.versionStack?.versions.some((v) => v.status === 'archived') ?? false) : displayItem.status === 'archived' const previewBadges = daysLeft !== null || (typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0) ? (
{daysLeft !== null && ( {m.days_left_short({ count: daysLeft })} )} {typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0 && ( {displayItem.commentsCount} )}
) : null return (
onDoubleClick(displayItem)} onContextMenu={(e) => onContextMenu(e, displayItem)} onMouseDown={(e) => { if (e.shiftKey) { e.preventDefault() } }} data-testid="file-card" className={cn( 'group relative flex cursor-pointer select-none flex-col overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary h-full m-1 outline-none focus:outline-none focus-visible:outline-none', (isSelected || isChecked) && 'outline-1 outline-primary border-primary', showDropFeedback && 'border-primary outline-1 outline-primary', )} > {!hideCheckbox && (
{}} onClick={(e) => { e.stopPropagation() onSelect(displayItem, e, { isCheckbox: true }) }} className="h-4 w-4 bg-white/20 dark:bg-white/20 border-2 hover:border-primary transition-colors cursor-pointer data-[state=checked]:bg-primary data-[state=checked]:border-primary border-foreground/15" />
)}
{displayItem.agent && ( AI )} {displayItem.versionStack && ( v {displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ?? displayItem.versionStack.versions.length} )} {displayItem.status === 'archived' && ( {m.archived_status()} )} {displayItem.status === 'archiving' && ( {m.archiving_status()} )} {displayItem.status === 'restoring' && ( {m.restoring_status()} )} {isFailed && ( {m.transcoding_failed()} {failedErrorMessage} )}
{isUploading ? (
{isLocalUploader ? ( ) : ( )}
) : hasPreview ? ( <>
{previewBadges} ) : displayItem.status === 'error' || isUploadFailed ? (
{m.failed_to_upload()}
) : isFailed ? (
{m.processing_failed()}
) : isProcessing ? (
{/* Same geometry as the upload progress ring, but empty inside and no percentage. */}
) : ( <> {previewBadges} )}
setName(e.target.value)} onBlur={handleRename} onKeyDown={handleKeyDown} disabled={!isEditing} className="h-auto p-0 text-sm font-medium text-foreground truncate !bg-transparent" /> { if (nextOpen) { if ( creatorRef.current && (creatorRef.current.scrollHeight > creatorRef.current.clientHeight || creatorRef.current.scrollWidth > creatorRef.current.clientWidth) ) { setIsCreatorTooltipOpen(true) } else { setIsCreatorTooltipOpen(false) } } else { setIsCreatorTooltipOpen(false) } }} >

{statusText ?? creatorText}

{isCreatorTooltipOpen && ( {creatorText} )}
{!hideActions && !isRecents && ( {isShareView ? ( <> {allowDownload && ( { e.stopPropagation() onAction?.('download', item) }} > {m.download()} )} {canEdit && ( { e.stopPropagation() onAction?.('remove-from-share', item) }} className="text-destructive" > {m.remove_from_share()} )} ) : isRecentlyDeleted ? ( { e.stopPropagation() onAction?.('restore', item) }} > {m.restore()} ) : ( <> {canEdit && (!isChecked || (selectedCount || 0) <= 1) && ( { e.stopPropagation() onAction?.('rename', item) }} > {m.rename()} )} {canEdit && item.type === 'version_stack' && ( { e.stopPropagation() onAction?.('manage-versions', item) }} > {m.manage_versions()} )} {allowDownload && ( { e.stopPropagation() onAction?.('download', item) }} > {m.download()} )} {!isRecentlyDeleted && !isShareView && ( onCopy?.(kind, targetItems)} /> )} {canEdit && archiveStorageEnabled && canArchiveItem && ( { e.stopPropagation() onAction?.('archive', item) }} > {m.archive()} )} {canEdit && archiveStorageEnabled && canRestoreArchiveItem && ( { e.stopPropagation() onAction?.('restore-archive', item) }} > {m.restore_from_archive()} )} {canEdit && ( <> { e.stopPropagation() onAction?.('delete', item) }} className="text-destructive" > {m.delete()} )} )} )}
{fields && fields.length > 0 && (
e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()} > {fields.map((field) => { const Icon = field.config?.type ? FIELD_TYPE_ICONS[field.config.type as FieldType] : null return (
onSaveField(field.id!, val) : undefined } readOnly={field.readOnly || !canEdit || !!isRecents} />
) })}
)}
) }