import type { AssetInfo, FieldValueInfo } from '@shumai/dtos' import { client } from '@/ui/api/client' import { m } from '@/ui/paraglide/messages.js' import { useQuery } from '@tanstack/react-query' import { useDraggable } from '@dnd-kit/react' import { AlertCircle, Archive, AudioLines, File, Folder, Loader2, MoreVertical } from 'lucide-react' import React, { useEffect, useMemo, useRef, useState } from 'react' import { cn } from '@/ui/lib/utils' import { formatSize } from '@/ui/lib/format' import { formatRemainingTimeSeconds } from '@/ui/lib/time' import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils' import type { DragState } from '../dnd-types' import FieldRenderer from '../field-renderer' import { Badge } from '@/ui/components/ui/badge' import { Checkbox } from '@/ui/components/ui/checkbox' import { EditableText } from '@/ui/components/ui/editable-text' import { useUploadStore } from '@/ui/stores/upload' import { ProgressCircle } from '@/ui/components/ui/progress-circle' import { handleCardClick } from '@/ui/lib/selection-utils' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' interface FileListItemProps { 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 onDragStart: (item: AssetInfo) => void onDrop: (target: AssetInfo) => void onRename: (newName: string) => void onFinishEditing: () => void onSaveField: (fieldId: string, value: unknown) => void dragState?: DragState disabled?: boolean fields: MetadataFieldInfo[] columnSizing?: Record canEdit?: boolean isRecents?: boolean isPublic?: boolean selectedCount?: number } export function FileListItem({ teamId, item, isSelected, isChecked, isEditing, 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, fields, columnSizing, canEdit = true, isRecents, isPublic = false, selectedCount, }: FileListItemProps) { const [name, setName] = useState(item.name) const inputRef = 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]) const isLocalUploader = Boolean(fileUploadState) const isUploadFailed = fileUploadState?.status === 'failed' const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100 const isUploading = displayItem.status === 'uploading' && !isUploadDone && !isUploadFailed let uploadingText: string | null = null if (isUploading) { if (isLocalUploader) { if (fileUploadState?.speed && fileUploadState?.eta != null) { uploadingText = m.upload_eta_speed({ eta: formatRemainingTimeSeconds(fileUploadState.eta), speed: `${formatSize(fileUploadState.speed)}/s`, }) } else { uploadingText = m.uploading() } } else { uploadingText = m.user_is_uploading({ user: displayItem.creator?.name || m.someone(), }) } } // 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 isBeingDragged = isDraggableDragging || (dragState?.draggedIds.has(displayItem.id!) ?? false) 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]) useEffect(() => { setName(displayItem.name) }, [displayItem.name]) const formatDate = (date?: string) => { if (!date) return '-' return new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', }) } 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() } } return (
onDoubleClick(displayItem)} onContextMenu={(e) => onContextMenu(e, displayItem)} onMouseDown={(e) => { if (e.shiftKey) { e.preventDefault() } }} data-testid="file-card" className="group cursor-pointer select-none transition-colors whitespace-nowrap flex w-full outline-none focus:outline-none focus-visible:outline-none" >
{}} onClick={(e) => { e.stopPropagation() onSelect(displayItem, e, { isCheckbox: true }) }} className="h-4 w-4 shrink-0 hover:border-primary transition-colors cursor-pointer data-[state=checked]:bg-primary data-[state=checked]:border-primary" />
{isUploading ? ( isLocalUploader ? ( ) : ( ) ) : displayItem.status === 'failed' && !displayItem.preview?.thumbnailUrl ? ( ) : displayItem.preview?.thumbnailUrl ? ( ) : displayItem.preview?.proxyType === 'audio' || displayItem.proxyType === 'audio' ? ( ) : displayItem.type === 'folder' ? ( ) : ( )}
setName(e.target.value)} onBlur={handleRename} onKeyDown={handleKeyDown} disabled={!isEditing} className="h-auto p-0 text-sm font-medium text-foreground truncate min-w-0 flex-1" /> {uploadingText && ( {uploadingText} )} {(displayItem.status === 'error' || isUploadFailed) && ( {m.failed_to_upload_parenthesized()} )} {displayItem.status === 'failed' && ( {m.processing_failed_parenthesized()} )} {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()} )}
{displayItem.type === 'folder' ? '-' : displayItem.sizeByte ? formatSize(displayItem.sizeByte) : '-'}
{formatDate(displayItem.updatedAt)} {!isRecents && ( )}
{displayItem.type === 'file' && fields.map((field) => (
e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()} className="px-4 py-2 truncate border-r shrink-0 flex items-center" style={{ width: columnSizing?.[field.id!] || 150, minWidth: columnSizing?.[field.id!] || 150, }} > onSaveField(field.id!, val) : undefined} readOnly={field.readOnly || !canEdit || !!isRecents} />
))}
) }