import type { AssetInfo, FieldValueInfo } from '@shumai/dtos' import { client } from '@/ui/api/client' import { useQuery } from '@tanstack/react-query' import { useDraggable } from '@dnd-kit/react' import { File, Folder, MoreVertical, AudioLines } from 'lucide-react' import React, { useEffect, useMemo, useRef, useState } from 'react' import { cn } from '@/ui/lib/utils' import { formatSize } from '@/ui/lib/format' 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 { 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) => 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 } 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, }: 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 shouldPoll = (item.type === 'file' || item.type === 'version_stack') && !!teamId && (item.status === 'uploading' || item.status === 'uploaded' || item.status === 'processing') 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: shouldPoll, refetchInterval: (query: unknown) => { const data = (query as { state: { data: { status?: string } } }).state.data return data?.status === 'processed' ? false : 1000 }, }) const displayItem = useMemo(() => { if (item.status === 'processed' || item.status === 'error') { return item } if (polledItem?.status === 'processed' || polledItem?.status === 'error') { 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 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) => { onSelect(displayItem, e) } 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) }} className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary" />
{displayItem.status === 'uploading' ? ( ) : 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" /> {displayItem.status === 'error' && ( (Failed to upload) )} {displayItem.agent && ( AI )} {displayItem.versionStack && ( v {displayItem.versionStack.versions.find((v) => v.id === displayItem.id)?.version ?? displayItem.versionStack.versions.length} )}
{displayItem.type === 'folder' ? '-' : displayItem.sizeByte ? formatSize(displayItem.sizeByte) : '-'}
{formatDate(displayItem.updatedAt)} {!isRecents && ( )}
{displayItem.type === 'file' && fields.map((field) => (
onSaveField(field.id!, val) : undefined} readOnly={field.readOnly || !canEdit || !!isRecents} />
))}
) }