import { useCallback, useContext, useLayoutEffect, useRef, useState } from 'react' import { AttachmentPrimitive, useAui, useAuiState, } from '@assistant-ui/react' import type { PendingAttachment } from '@assistant-ui/react' import type { KeyboardEventHandler, MouseEventHandler, MutableRefObject, PointerEventHandler, PointerEvent as ReactPointerEvent, } from 'react' import { ImagePreview } from '@/components/ImagePreview' import { Spinner } from '@/components/Spinner' import { RefreshIcon } from '@/components/icons' import { useComposerParking } from '@/components/AssistantChat/composerParkingContext' import { I18nContext } from '@/lib/i18n-context' type ComposerAttachmentWithPreview = PendingAttachment & { previewUrl?: string retryable?: boolean } const TRUNCATED_REMOVE_MARGIN_LEFT = '-7px' export type AttachmentDragHandleProps = { onPointerDown: PointerEventHandler onKeyDown: KeyboardEventHandler ariaLabel: string title: string onSurfacePointerDown?: PointerEventHandler onSurfaceContextMenu?: MouseEventHandler onSurfaceClick?: MouseEventHandler } export type AttachmentRetryHandler = ( originalId: string, retryId: string, originalIndex: number, ) => void const fallbackTranslations: Record = { 'attachment.retryUpload': 'Retry upload', 'attachment.uploadFailed': 'Upload failed', } function useAttachmentTranslation() { const context = useContext(I18nContext) return context?.t ?? ((key: string) => fallbackTranslations[key] ?? key) } function ErrorIcon() { return ( ) } function RemoveIcon() { return ( ) } function DragHandleIcon() { return ( ) } function DragHandle(props: AttachmentDragHandleProps & { isFile?: boolean }) { const isFile = props.isFile === true return ( ) } export function AttachmentItem(props: { dragHandleProps?: AttachmentDragHandleProps attachmentOrderRef?: MutableRefObject retryingAttachmentIdsRef?: MutableRefObject> onRetry?: AttachmentRetryHandler } = {}) { const { id, name, file, status, previewUrl, retryable } = useAuiState((s) => s.attachment) as ComposerAttachmentWithPreview const aui = useAui() const composer = aui.composer() const isParking = useComposerParking() const t = useAttachmentTranslation() const [isRetrying, setIsRetrying] = useState(false) const filenameRef = useRef(null) const [isFilenameTruncated, setIsFilenameTruncated] = useState(false) const isUploading = status.type === 'running' const isError = status.type === 'incomplete' const showRetry = isError && retryable !== false && !isParking const isRetryPending = isRetrying || props.retryingAttachmentIdsRef?.current.has(id) === true useLayoutEffect(() => { const element = filenameRef.current if (!element) return const updateTruncation = () => { const next = element.scrollWidth > element.clientWidth setIsFilenameTruncated((current) => current === next ? current : next) } updateTruncation() if (typeof ResizeObserver === 'undefined') return const observer = new ResizeObserver(updateTruncation) observer.observe(element) return () => observer.disconnect() }, [name, isError]) const surfacePointerDown = props.dragHandleProps?.onSurfacePointerDown ? (event: ReactPointerEvent) => { const target = event.target if (target instanceof Element && target.closest('button, a, input, textarea, select, [role="button"]')) { return } props.dragHandleProps?.onSurfacePointerDown?.(event) } : undefined const retryUpload = useCallback(async () => { if (isRetryPending || isParking) return props.retryingAttachmentIdsRef?.current.add(id) setIsRetrying(true) try { const originalIndex = props.attachmentOrderRef?.current.indexOf(id) ?? -1 const retryFile = new File([file], file.name, { type: file.type, lastModified: file.lastModified, }) let unsubscribe: (() => void) | undefined if (props.onRetry) { unsubscribe = aui.subscribe(() => { const retryAttachment = composer.getState().attachments.find( (attachment) => attachment.file === retryFile, ) if (!retryAttachment) return unsubscribe?.() unsubscribe = undefined if (!composer.getState().attachments.some((attachment) => attachment.id === id)) { void composer.attachment({ id: retryAttachment.id }).remove().catch((error) => { console.error('Failed to cancel replacement attachment', error) }) return } props.onRetry?.(id, retryAttachment.id, originalIndex) void composer.attachment({ id }).remove().catch((error) => { console.error('Failed to remove replaced attachment', error) }) }) } try { if (!props.onRetry) { await composer.attachment({ id }).remove() } await composer.addAttachment(retryFile) } finally { unsubscribe?.() } } catch (error) { console.error('Failed to retry attachment upload', error) } finally { props.retryingAttachmentIdsRef?.current.delete(id) setIsRetrying(false) } }, [aui, composer, file, id, isParking, isRetryPending, props.attachmentOrderRef, props.onRetry, props.retryingAttachmentIdsRef]) if (previewUrl && !isError) { return ( {name} )} /> {props.dragHandleProps ? ( ) : null} {isUploading ? (
) : null} {!isParking ? ( ) : null}
) } return ( {showRetry ? ( ) : props.dragHandleProps && !isError ? ( ) : null} {isUploading ? : null} {isError && (!showRetry || isParking) ? ( {t('attachment.uploadFailed')} ) : null} {name} {!isParking ? ( ) : null} ) }