Attachment
Shows a file a person attached, uploaded, or referenced. UseFileAttachment for a ready-made row, card, mention, or chip, and the Attachment parts when you need your own layout.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/attachment.jsonCopies Attachment and the components it uses (Button, File Viewer, Hover Card, and Spinner) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/attachment. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @base-ui/react @hugeicons/core-free-icons @hugeicons/react shikiAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Add the components it uses: Button, File Viewer, Hover Card, and Spinner.
Copy and paste the following code into your project.
'use client'; import { Children, createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, type ComponentProps, type DragEvent, type KeyboardEvent, type ReactElement, type ReactNode, } from 'react'; import { mergeProps } from '@base-ui/react/merge-props'; import { useRender } from '@base-ui/react/use-render'; import { ChevronLeftIcon } from '@/lib/sprout/icons/chevron-left-icon'; import { ChevronRightIcon } from '@/lib/sprout/icons/chevron-right-icon'; import { CloseIcon } from '@/lib/sprout/icons/close-icon'; import { ImageIcon } from '@/lib/sprout/icons/image-icon'; import { UploadIcon } from '@/lib/sprout/icons/upload-icon'; import { cn } from '@/lib/sprout/classes'; import { defaultFileAccept, fileKind, formatFileSize, type FileKind } from '@/lib/sprout/file-kind'; import { Button, type ButtonProps } from '@/components/ui/button'; import { FilePreview, FileViewer, isPreviewableFile, type ViewableFile } from '@/components/ui/file-viewer'; import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card'; import { Spinner } from '@/components/ui/spinner'; export const attachmentStateNames = ['idle', 'uploading', 'processing', 'error', 'done'] as const; export const attachmentSizeNames = ['lg', 'md', 'sm'] as const; export const attachmentOrientationNames = ['horizontal', 'vertical'] as const; export const attachmentMediaVariantNames = ['icon', 'image'] as const; export const attachmentGroupVariantNames = ['carousel', 'grid', 'inline', 'list'] as const; export const fileAttachmentVariantNames = ['list', 'grid', 'inline', 'chip'] as const; export const fileAttachmentStateNames = ['ready', 'uploading', 'processing', 'error'] as const; export const fileTypeIconSizeNames = ['sm', 'lg'] as const; export type AttachmentState = (typeof attachmentStateNames)[number]; export type AttachmentSize = (typeof attachmentSizeNames)[number]; export type AttachmentOrientation = (typeof attachmentOrientationNames)[number]; export type AttachmentMediaVariant = (typeof attachmentMediaVariantNames)[number]; export type AttachmentGroupVariant = (typeof attachmentGroupVariantNames)[number]; export type FileAttachmentVariant = (typeof fileAttachmentVariantNames)[number]; export type FileAttachmentState = (typeof fileAttachmentStateNames)[number]; export type FileTypeIconSize = (typeof fileTypeIconSizeNames)[number]; export type { FileKind }; export interface AttachmentProps extends ComponentProps<'div'> { state?: AttachmentState | undefined; size?: AttachmentSize | undefined; orientation?: AttachmentOrientation | undefined; } export function Attachment({ className, state = 'done', size = 'lg', orientation = 'horizontal', ...props }: AttachmentProps) { return ( <div data-slot="attachment" data-state={state} data-size={size} data-orientation={orientation} className={cn( 'sprout-attachment', `sprout-attachment-size-${size}`, `sprout-attachment-${orientation}`, className, )} {...props} /> ); } export interface AttachmentMediaProps extends ComponentProps<'div'> { variant?: AttachmentMediaVariant | undefined; } export function AttachmentMedia({ className, variant = 'icon', ...props }: AttachmentMediaProps) { return ( <div data-slot="attachment-media" data-variant={variant} className={cn('sprout-attachment-media', className)} {...props} /> ); } export function AttachmentContent({ className, ...props }: ComponentProps<'div'>) { return <div data-slot="attachment-content" className={cn('sprout-attachment-content', className)} {...props} />; } export function AttachmentTitle({ className, ...props }: ComponentProps<'span'>) { return <span data-slot="attachment-title" className={cn('sprout-attachment-title', className)} {...props} />; } export function AttachmentDescription({ className, ...props }: ComponentProps<'span'>) { return ( <span data-slot="attachment-description" className={cn('sprout-attachment-description', className)} {...props} /> ); } export function AttachmentActions({ className, ...props }: ComponentProps<'div'>) { return <div data-slot="attachment-actions" className={cn('sprout-attachment-actions', className)} {...props} />; } export function AttachmentAction({ variant, size = 'icon-xs', ...props }: ButtonProps) { return <Button data-slot="attachment-action" variant={variant ?? 'ghost'} size={size} {...props} />; } export type AttachmentTriggerProps = useRender.ComponentProps<'button'>; export function AttachmentTrigger({ className, render, type, ...props }: AttachmentTriggerProps) { return useRender({ defaultTagName: 'button', render, props: mergeProps<'button'>( { type: render ? type : (type ?? 'button'), className: cn('sprout-attachment-trigger', className), }, { 'data-slot': 'attachment-trigger' } as ComponentProps<'button'>, props, ), }); } export interface AttachmentGroupProps extends ComponentProps<'div'> { variant?: AttachmentGroupVariant | undefined; } interface ViewerEntry { file: () => ViewableFile | null; node: () => HTMLElement | null; } interface SharedViewer { register: (id: string, entry: ViewerEntry) => () => void; open: (id: string) => void; } const SharedViewerContext = createContext<SharedViewer | null>(null); interface OpenSet { ids: string[]; files: ViewableFile[]; index: number; } const byDocumentOrder = (a: { node: HTMLElement | null }, b: { node: HTMLElement | null }) => a.node && b.node && a.node.compareDocumentPosition(b.node) & Node.DOCUMENT_POSITION_PRECEDING ? 1 : -1; function SharedFileViewer({ children }: { children: ReactNode }) { const entries = useRef(new Map<string, ViewerEntry>()); const [set, setSet] = useState<OpenSet | null>(null); const [open, setOpen] = useState(false); const shared = useMemo<SharedViewer>( () => ({ register(id, entry) { entries.current.set(id, entry); return () => entries.current.delete(id); }, open(id) { const ordered = [...entries.current] .map(([key, entry]) => ({ id: key, file: entry.file(), node: entry.node(), })) .filter((item): item is typeof item & { file: ViewableFile } => item.file !== null) .sort(byDocumentOrder); const index = ordered.findIndex(item => item.id === id); if (index < 0) return; setSet({ ids: ordered.map(item => item.id), files: ordered.map(item => item.file), index, }); setOpen(true); }, }), [], ); const current = set && entries.current.get(set.ids[set.index] ?? ''); return ( <SharedViewerContext.Provider value={shared}> {children} {set && ( <FileViewer files={set.files} index={set.index} onIndexChange={index => setSet({ ...set, index })} open={open} onOpenChange={setOpen} finalFocus={() => current?.node()?.querySelector<HTMLElement>('button.sprout-file-attachment-open') ?? true} /> )} </SharedViewerContext.Provider> ); } export function AttachmentGroup(props: AttachmentGroupProps) { return ( <SharedFileViewer> <AttachmentGroupFrame {...props} /> </SharedFileViewer> ); } function AttachmentGroupFrame({ className, variant = 'carousel', children, ...props }: AttachmentGroupProps) { if (variant === 'carousel') return ( <AttachmentCarousel className={className} {...props}> {children} </AttachmentCarousel> ); return ( <div data-slot="attachment-group" data-variant={variant} role={props['aria-label'] || props['aria-labelledby'] ? 'group' : undefined} className={cn('sprout-attachment-group', `sprout-attachment-group-${variant}`, className)} {...props} > {children} </div> ); } const typing = 'input, textarea, select, [contenteditable="true"]'; function AttachmentCarousel({ className, children, onKeyDownCapture, ...props }: ComponentProps<'div'>) { const viewport = useRef<HTMLDivElement>(null); const [edges, setEdges] = useState({ start: false, end: false }); const measure = useCallback(() => { const node = viewport.current; if (!node) return; const max = node.scrollWidth - node.clientWidth; const start = node.scrollLeft > 1; const end = node.scrollLeft < max - 1; setEdges(current => (current.start === start && current.end === end ? current : { start, end })); }, []); useEffect(() => { const node = viewport.current; if (!node) return; measure(); const observer = new ResizeObserver(measure); observer.observe(node); if (node.firstElementChild) observer.observe(node.firstElementChild); return () => observer.disconnect(); }, [measure]); const scroll = (direction: -1 | 1) => { const node = viewport.current; if (node) node.scrollBy({ left: direction * node.clientWidth * 0.8 }); }; const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { onKeyDownCapture?.(event); if (event.defaultPrevented) return; if ((event.target as Element).closest(typing)) return; if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { event.preventDefault(); scroll(event.key === 'ArrowLeft' ? -1 : 1); } }; return ( <div data-slot="attachment-group" data-variant="carousel" role="region" aria-roledescription="carousel" className={cn('sprout-attachment-group', 'sprout-attachment-group-carousel', className)} onKeyDownCapture={handleKeyDown} {...props} > <div ref={viewport} className="sprout-attachment-carousel-viewport" onScroll={measure}> <div className="sprout-attachment-carousel-track"> {Children.map(children, child => child == null || child === false ? null : ( <div role="group" aria-roledescription="slide" className="sprout-attachment-carousel-item"> {child} </div> ), )} </div> </div> {edges.start && ( <span className="sprout-attachment-carousel-edge" data-side="start"> <Button variant="outline" size="icon-xs" aria-label="Previous attachments" tabIndex={-1} className="sprout-attachment-carousel-arrow" onClick={() => scroll(-1)} > <ChevronLeftIcon aria-hidden="true" /> </Button> </span> )} {edges.end && ( <span className="sprout-attachment-carousel-edge" data-side="end"> <Button variant="outline" size="icon-xs" aria-label="Next attachments" tabIndex={-1} className="sprout-attachment-carousel-arrow" onClick={() => scroll(1)} > <ChevronRightIcon aria-hidden="true" /> </Button> </span> )} </div> ); } export interface FileTypeIconProps extends Omit<ComponentProps<'svg'>, 'children'> { name: string; mediaType: string; size?: FileTypeIconSize | undefined; } export function FileTypeIcon({ name, mediaType, size = 'sm', className, ...props }: FileTypeIconProps) { const label = name.includes('.') ? (name.split('.').at(-1) ?? '').toUpperCase().slice(0, 4) : ''; const badgeWidth = label.length > 3 ? 13 : 11; return ( <svg viewBox="0 0 20 24" aria-hidden="true" focusable="false" data-slot="file-type-icon" data-size={size} data-kind={fileKind(name, mediaType)} className={cn('sprout-file-type-icon', `sprout-file-type-icon-size-${size}`, className)} {...props} > <path d="M3.5 1.5h9l4.5 4.5v16a.5.5 0 0 1-.5.5h-13a.5.5 0 0 1-.5-.5v-20a.5.5 0 0 1 .5-.5Z" className="sprout-file-type-icon-paper" strokeLinejoin="round" /> <path d="M12.5 1.5v4a.5.5 0 0 0 .5.5h4" className="sprout-file-type-icon-fold" strokeLinejoin="round" /> <path d="M6 15h8M6 17.5h8M6 20h5" className="sprout-file-type-icon-lines" strokeLinecap="round" /> {label && ( <> <rect x="1" y="6" width={badgeWidth} height="6" rx="1.5" className="sprout-file-type-icon-badge" /> <text x={1 + badgeWidth / 2} y="10.4" textAnchor="middle" fontSize="4.2" fontWeight="700" className="sprout-file-type-icon-label" > {label} </text> </> )} </svg> ); } export type AttachmentFileSource = { kind: 'local'; file: File } | { kind: 'remote'; url: string }; export interface AttachmentFile { id: string; name: string; mediaType: string; size: string; url?: string | undefined; source?: AttachmentFileSource | undefined; state: FileAttachmentState; } export interface FileAttachmentProps { file: AttachmentFile; variant?: FileAttachmentVariant | undefined; onRemove?: (() => void) | undefined; onRetry?: (() => void) | undefined; onOpen?: (() => void) | undefined; viewable?: boolean | undefined; preview?: boolean | undefined; actionLabel?: 'Inspect' | 'Download' | undefined; className?: string | undefined; } function AttachmentImage({ src, name }: { src: string; name: string }) { const [failed, setFailed] = useState(false); return failed ? ( <span className="sprout-attachment-image-failed"> <ImageIcon size="md" aria-hidden="true" /> Image unavailable </span> ) : ( <img src={src} alt={name} onError={() => setFailed(true)} className="sprout-attachment-image" /> ); } function viewableFile(file: AttachmentFile): ViewableFile | null { const source = file.source ?? (file.url ? { kind: 'remote' as const, url: file.url } : null); return source && { name: file.name, mediaType: file.mediaType, source }; } function stateLabelFor(file: AttachmentFile) { return file.state === 'ready' ? file.size : file.state === 'error' ? 'Upload failed' : file.state === 'uploading' ? 'Uploading…' : 'Processing…'; } export function FileAttachment({ file, variant = 'list', onRemove, onRetry, onOpen, viewable = false, preview = false, actionLabel = 'Inspect', className, }: FileAttachmentProps) { const [open, setOpen] = useState(false); const shared = useContext(SharedViewerContext); const id = useId(); const root = useRef<HTMLDivElement>(null); const image = fileKind(file.name, file.mediaType) === 'image'; const busy = file.state === 'uploading' || file.state === 'processing'; const stateLabel = stateLabelFor(file); const target = viewable || preview ? viewableFile(file) : null; const inViewer = !onOpen && viewable && target !== null; const openable = !!onOpen || inViewer; const peek = preview && target !== null && file.state !== 'error' && isPreviewableFile(target); const latest = useRef(target); latest.current = inViewer ? target : null; useEffect( () => shared && inViewer ? shared.register(id, { file: () => latest.current, node: () => root.current, }) : undefined, [shared, inViewer, id], ); const withPreview = (trigger: ReactElement) => peek ? ( <HoverCard> <HoverCardTrigger delay={400} closeDelay={150} render={trigger} /> <HoverCardContent side="top" align="start" className="sprout-file-attachment-peek"> <FilePreview file={target} /> </HoverCardContent> </HoverCard> ) : ( trigger ); const openLabel = `${actionLabel} ${file.name}`; const openProps = { type: 'button' as const, disabled: !!onOpen && busy, onClick: () => (onOpen ? onOpen() : shared ? shared.open(id) : setOpen(true)), }; const retry = file.state === 'error' && onRetry && ( <Button variant="ghost" size="sm" onClick={onRetry} aria-label={`Retry ${file.name}`}> Retry </Button> ); const remove = (size: 'icon-xs' | 'icon-sm') => onRemove && ( <Button variant="ghost" size={size} aria-label={`Remove ${file.name}`} onClick={onRemove}> <CloseIcon size="sm" aria-hidden="true" /> </Button> ); const viewer = inViewer && !shared && <FileViewer file={target} open={open} onOpenChange={setOpen} />; if (variant === 'chip') { const inner = ( <> {image && file.url ? ( <span className="sprout-file-attachment-thumb"> <AttachmentImage key={file.url} src={file.url} name={file.name} /> </span> ) : ( <FileTypeIcon name={file.name} mediaType={file.mediaType} /> )} <span className="sprout-file-attachment-name">{file.name}</span> </> ); return ( <> <div ref={root} data-slot="file-attachment" data-variant="chip" data-state={file.state} data-removable={onRemove ? '' : undefined} className={cn('sprout-file-attachment', className)} title={openable ? undefined : `${file.name} · ${stateLabel}`} > {withPreview( openable ? ( <button {...openProps} aria-label={openLabel} title={peek ? undefined : `${file.name} · ${stateLabel}`} className="sprout-file-attachment-open" > {inner} </button> ) : ( <span className="sprout-file-attachment-open">{inner}</span> ), )} {busy && <Spinner aria-label={stateLabel} />} {retry} {remove('icon-xs')} </div> {viewer} </> ); } const name = ( <> <span className="sprout-file-attachment-name" title={file.name}> {file.name} </span> {variant !== 'inline' && ( <span className="sprout-file-attachment-status"> {busy && <Spinner size="sm" aria-hidden="true" />} {stateLabel} </span> )} </> ); const thumbnail = image && file.url ? ( <AttachmentImage key={file.url} src={file.url} name={file.name} /> ) : ( <FileTypeIcon name={file.name} mediaType={file.mediaType} size="lg" /> ); return ( <> <div ref={root} data-slot="file-attachment" data-variant={variant} data-state={file.state} className={cn('sprout-file-attachment', className)} > {variant === 'grid' && (openable ? ( <button {...openProps} tabIndex={-1} aria-hidden="true" className="sprout-file-attachment-preview"> {thumbnail} </button> ) : ( <span className="sprout-file-attachment-preview">{thumbnail}</span> ))} {variant !== 'grid' && ( <span className="sprout-file-attachment-media"> {image && file.url && variant === 'list' ? ( <AttachmentImage key={file.url} src={file.url} name={file.name} /> ) : ( <FileTypeIcon name={file.name} mediaType={file.mediaType} /> )} </span> )} {withPreview( openable ? ( <button {...openProps} aria-label={openLabel} className="sprout-file-attachment-open"> {name} </button> ) : ( <span className="sprout-file-attachment-open">{name}</span> ), )} {variant === 'inline' && busy && <Spinner aria-label={stateLabel} />} {variant === 'inline' && file.state === 'error' && ( <span className="sprout-file-attachment-failed">Failed</span> )} {(retry || onRemove) && ( <div className="sprout-file-attachment-actions"> {retry} {remove('icon-sm')} </div> )} </div> {viewer} </> ); } export interface AttachmentDropzoneProps { onFiles: (files: File[]) => void; disabled?: boolean | undefined; accept?: string | undefined; className?: string | undefined; } export function AttachmentDropzone({ onFiles, disabled = false, accept = defaultFileAccept, className, }: AttachmentDropzoneProps) { const [dragging, setDragging] = useState(false); const input = useRef<HTMLInputElement>(null); const over = (event: DragEvent<HTMLDivElement>) => { event.preventDefault(); event.dataTransfer.dropEffect = disabled ? 'none' : 'copy'; if (!disabled) setDragging(true); }; return ( <div data-slot="attachment-dropzone" data-dragging={dragging ? '' : undefined} data-disabled={disabled ? '' : undefined} className={cn('sprout-attachment-dropzone', className)} onDragEnter={over} onDragOver={over} onDragLeave={event => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false); }} onDrop={event => { event.preventDefault(); setDragging(false); if (!disabled) onFiles(Array.from(event.dataTransfer.files)); }} > <input ref={input} type="file" accept={accept} multiple hidden disabled={disabled} onChange={event => { onFiles(Array.from(event.target.files ?? [])); event.target.value = ''; }} /> <UploadIcon size="xl" aria-hidden="true" className="sprout-attachment-dropzone-icon" /> <p className="sprout-attachment-dropzone-text">Drop files here, or choose them from your device.</p> <Button variant="outline" disabled={disabled} onClick={() => input.current?.click()}> Choose files </Button> </div> ); } export interface LocalFileAttachmentProps { file: File; onRemove?: (() => void) | undefined; onOpen?: (() => void) | undefined; viewable?: boolean | undefined; preview?: boolean | undefined; } export function LocalFileAttachment({ file, onRemove, onOpen, viewable, preview }: LocalFileAttachmentProps) { const [url, setUrl] = useState<string>(); const source = useMemo<AttachmentFileSource>(() => ({ kind: 'local', file }), [file]); useEffect(() => { if (fileKind(file.name, file.type) !== 'image') return; const next = URL.createObjectURL(file); setUrl(next); return () => URL.revokeObjectURL(next); }, [file]); return ( <FileAttachment variant="chip" file={{ id: `${file.name}-${file.lastModified}`, name: file.name, mediaType: file.type, size: formatFileSize(file.size), state: 'ready', source, url, }} onRemove={onRemove} onOpen={onOpen} viewable={viewable} preview={preview} /> ); }And the files it imports:
lib/sprout/icons/chevron-left-icon.tsxlib/sprout/icons/chevron-right-icon.tsxlib/sprout/icons/close-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/image-icon.tsxlib/sprout/icons/upload-icon.tsxlib/sprout/file-kind.tslib/sprout/languages.tslib/sprout/syntax.ts
Add the styles to your global CSS, after
@import "tailwindcss".@layer base { :root, .light { --sprout-file-paper: oklch(100% 0 0); --sprout-file-edge: oklch(87.17% .0082 286.23); --sprout-file-generic: oklch(65.18% .0118 280.36); --sprout-file-pdf: oklch(61.65% .1939 27.02); --sprout-file-sheet: oklch(57.34% .1422 151.05); --sprout-file-document: oklch(53.55% .1755 260.83); --sprout-file-slides: oklch(63.49% .1638 42.8); --sprout-file-image: oklch(85.06% .0674 242.56); --sprout-file-label: oklch(100% 0 0); } .dark { --sprout-file-paper: oklch(29.01% .0092 276.8); --sprout-file-edge: oklch(41.45% .0116 279.39); --sprout-file-image: oklch(57.61% .0841 245.81); } @media (prefers-color-scheme: dark) { :root:not(.light):not(.dark) { --sprout-file-paper: oklch(29.01% .0092 276.8); --sprout-file-edge: oklch(41.45% .0116 279.39); --sprout-file-image: oklch(57.61% .0841 245.81); } } } @layer components { .sprout-attachment { box-sizing: border-box; border: 1px solid var(--sprout-line); background: var(--sprout-surface); width: fit-content; min-width: 0; max-width: 100%; color: var(--sprout-text); border-radius: 12px; flex-wrap: wrap; flex-shrink: 0; font-family: inherit; display: flex; position: relative; } @media (hover: hover) { .sprout-attachment:has( > a, > button):hover { background: color-mix(in oklab, var(--sprout-hover) 50%, var(--sprout-surface)); } .sprout-file-attachment:has(button.sprout-file-attachment-open:not(:disabled)):hover { background: color-mix(in oklab, var(--sprout-hover) 50%, var(--sprout-surface)); } } .sprout-attachment:has( > .sprout-attachment-trigger:focus-visible) { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-attachment[data-state="idle"] { border-style: dashed; } .sprout-attachment[data-state="error"] { border-color: color-mix(in oklab, var(--sprout-danger) 35%, transparent); } .sprout-attachment-size-lg { font-size: var(--sprout-text-sm); gap: 8px; } .sprout-attachment-size-lg:has([data-slot="attachment-content"]) { padding: 8px 10px; } .sprout-attachment-size-lg:has([data-slot="attachment-media"]) { padding: 8px; } .sprout-attachment-size-md { font-size: var(--sprout-text-xs); gap: 10px; } .sprout-attachment-size-md:has([data-slot="attachment-content"]) { padding: 6px 8px; } .sprout-attachment-size-md:has([data-slot="attachment-media"]) { padding: 6px; } .sprout-attachment-size-sm { font-size: var(--sprout-text-xs); border-radius: 8px; gap: 6px; } .sprout-attachment-size-sm:has([data-slot="attachment-content"]) { padding: 4px 6px; } .sprout-attachment-size-sm:has([data-slot="attachment-media"]) { padding: 4px; } .sprout-attachment-horizontal { align-items: center; min-width: 10rem; } .sprout-attachment-vertical { flex-direction: column; width: 6rem; } .sprout-attachment-vertical:has([data-slot="attachment-content"]) { width: 7.5rem; } .sprout-attachment-media { aspect-ratio: 1; background: var(--sprout-hover); width: 40px; color: var(--sprout-text); border-radius: 8px; flex-shrink: 0; justify-content: center; align-items: center; display: flex; position: relative; overflow: hidden; } .sprout-attachment-size-md .sprout-attachment-media { width: 32px; } .sprout-attachment-size-sm .sprout-attachment-media { border-radius: 6px; width: 28px; } .sprout-attachment-vertical .sprout-attachment-media { width: 100%; } .sprout-attachment[data-state="error"] .sprout-attachment-media { background: var(--sprout-danger-subtle); color: var(--sprout-danger); } .sprout-attachment-media svg { pointer-events: none; } .sprout-attachment-media svg:not([class*="size-"]) { width: 16px; height: 16px; } .sprout-attachment-vertical .sprout-attachment-media svg:not([class*="size-"]), .sprout-attachment-vertical .sprout-attachment-media > [data-slot="spinner"] { width: 24px; height: 24px; } .sprout-attachment-size-sm .sprout-attachment-media svg:not([class*="size-"]) { width: 14px; height: 14px; } .sprout-attachment-media[data-variant="image"] { opacity: .6; } .sprout-attachment:is([data-state="done"], [data-state="idle"]) .sprout-attachment-media[data-variant="image"] { opacity: 1; } .sprout-attachment-media[data-variant="image"] > img { aspect-ratio: 1; object-fit: cover; width: 100%; } .sprout-attachment-content { flex: 1; min-width: 0; max-width: 100%; line-height: 1.25; } .sprout-attachment-vertical .sprout-attachment-content { padding-inline: 4px; } .sprout-attachment-title { text-overflow: ellipsis; white-space: nowrap; min-width: 0; max-width: 100%; font-weight: 500; display: block; overflow: hidden; } .sprout-attachment-description { min-width: 0; max-width: 100%; color: var(--sprout-muted); font-size: var(--sprout-text-xs); text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; display: block; overflow: hidden; } .sprout-attachment[data-state="error"] .sprout-attachment-description { color: var(--sprout-danger); } .sprout-attachment-actions { z-index: 2; flex-shrink: 0; align-items: center; display: flex; position: relative; } .sprout-attachment-vertical .sprout-attachment-actions { gap: 4px; position: absolute; top: 12px; right: 12px; } .sprout-attachment-vertical .sprout-attachment-actions .sprout-button { background: color-mix(in oklab, var(--sprout-surface) 88%, transparent); } .sprout-attachment-size-sm.sprout-attachment-vertical .sprout-attachment-actions { top: 6px; right: 6px; } .sprout-attachment-trigger { z-index: 1; border-radius: inherit; cursor: pointer; background: none; border: 0; outline: none; margin: 0; padding: 0; position: absolute; inset: 0; } .sprout-attachment:is([data-state="uploading"], [data-state="processing"]) .sprout-attachment-title, .sprout-file-attachment:is([data-state="uploading"], [data-state="processing"]) .sprout-file-attachment-name { color: var(--sprout-muted); } .sprout-attachment-group { min-width: 0; } .sprout-attachment-group-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; display: grid; } @media (width >= 40rem) { .sprout-attachment-group-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); } } .sprout-attachment-group-list { flex-direction: column; gap: 8px; display: flex; } .sprout-attachment-group-inline { flex-wrap: wrap; gap: 8px; display: flex; } .sprout-attachment-group-carousel { --sprout-attachment-fade: var(--sprout-surface); position: relative; } .sprout-attachment-carousel-viewport { overscroll-behavior-x: contain; scrollbar-width: none; scroll-padding-inline: 32px; overflow: auto hidden; } .sprout-attachment-carousel-viewport::-webkit-scrollbar { display: none; } .sprout-attachment-carousel-track { gap: 8px; width: max-content; padding: 4px 3px; display: flex; } .sprout-attachment-carousel-item { flex-shrink: 0; min-width: 0; } .sprout-attachment-carousel-edge { pointer-events: none; align-items: center; display: flex; position: absolute; inset-block: 0; } .sprout-attachment-carousel-edge[data-side="start"] { background: linear-gradient(to right, var(--sprout-attachment-fade), transparent); padding-right: 32px; left: 0; } .sprout-attachment-carousel-edge[data-side="end"] { background: linear-gradient(to left, var(--sprout-attachment-fade), transparent); padding-left: 32px; right: 0; } .sprout-attachment-carousel-arrow { opacity: 0; pointer-events: auto; } .sprout-attachment-group-carousel:hover .sprout-attachment-carousel-arrow, .sprout-attachment-group-carousel:focus-within .sprout-attachment-carousel-arrow, .sprout-attachment-carousel-arrow:focus-visible { opacity: 1; } @media (pointer: coarse) { .sprout-attachment-carousel-arrow { opacity: 1; } } .sprout-file-type-icon { flex-shrink: 0; } .sprout-file-type-icon-size-sm { width: 20px; height: 24px; } .sprout-file-type-icon-size-lg { width: 30px; height: 36px; } .sprout-file-type-icon-paper { fill: var(--sprout-file-paper); stroke: var(--sprout-file-edge); } .sprout-file-type-icon-fold { fill: none; stroke: var(--sprout-file-edge); } .sprout-file-type-icon-lines { stroke: var(--sprout-file-edge); } .sprout-file-type-icon-badge { fill: var(--sprout-file-generic); } .sprout-file-type-icon[data-kind="pdf"] .sprout-file-type-icon-badge { fill: var(--sprout-file-pdf); } .sprout-file-type-icon[data-kind="sheet"] .sprout-file-type-icon-badge { fill: var(--sprout-file-sheet); } .sprout-file-type-icon:is([data-kind="document"], [data-kind="google"]) .sprout-file-type-icon-badge { fill: var(--sprout-file-document); } .sprout-file-type-icon[data-kind="slides"] .sprout-file-type-icon-badge { fill: var(--sprout-file-slides); } .sprout-file-type-icon[data-kind="image"] .sprout-file-type-icon-badge { fill: var(--sprout-file-image); } .sprout-file-type-icon-label { fill: var(--sprout-file-label); font-family: inherit; } .sprout-file-attachment { box-sizing: border-box; border: 1px solid var(--sprout-line); background: var(--sprout-surface); min-width: 0; color: var(--sprout-text); border-radius: 12px; font-family: inherit; position: relative; } .sprout-file-attachment[data-state="error"] { border-color: var(--sprout-danger); } .sprout-file-attachment[data-variant="list"] { align-items: center; gap: 8px; padding: 8px; display: flex; } .sprout-file-attachment[data-variant="inline"] { align-items: center; gap: 4px; max-width: 100%; padding-left: 8px; display: flex; } .sprout-file-attachment[data-variant="inline"]:not(:has(.sprout-file-attachment-actions)) { padding-right: 10px; } .sprout-file-attachment[data-variant="grid"] { flex-direction: column; display: flex; } .sprout-file-attachment[data-variant="chip"] { max-width: 12rem; height: 36px; box-shadow: var(--sprout-shadow-control); flex-shrink: 0; align-items: center; gap: 4px; padding: 0 12px 0 10px; display: flex; } .sprout-file-attachment[data-variant="chip"][data-removable] { padding-right: 4px; } .sprout-file-attachment-open { min-width: 0; color: inherit; font: inherit; text-align: left; background: none; border: 0; border-radius: 6px; flex: 1; margin: 0; padding: 4px 0; display: block; } button.sprout-file-attachment-open { cursor: pointer; } button.sprout-file-attachment-open:disabled { cursor: default; } .sprout-file-attachment[data-variant="grid"] .sprout-file-attachment-open { padding: 12px; } .sprout-file-attachment[data-variant="chip"] .sprout-file-attachment-open { align-items: center; gap: 8px; padding: 0; display: flex; } .sprout-hover-card-content.sprout-file-attachment-peek { width: 22rem; padding: 4px; } .sprout-file-attachment-open:focus-visible, .sprout-file-attachment-preview:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-file-attachment[data-variant="chip"] button.sprout-file-attachment-open:after { content: ""; border-radius: inherit; position: absolute; inset: 0; } .sprout-file-attachment[data-variant="chip"] > :not(.sprout-file-attachment-open) { z-index: 1; position: relative; } .sprout-file-attachment[data-variant="chip"] .sprout-file-attachment-open:focus-visible { outline: none; } .sprout-file-attachment[data-variant="chip"]:has( > .sprout-file-attachment-open:focus-visible) { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-file-attachment-name { min-width: 0; font-size: var(--sprout-text-sm); text-overflow: ellipsis; white-space: nowrap; font-weight: 500; line-height: 1.25rem; display: block; overflow: hidden; } .sprout-file-attachment[data-variant="chip"] .sprout-file-attachment-name { font-size: var(--sprout-text-xs); line-height: 1rem; } .sprout-file-attachment-status { color: var(--sprout-muted); font-size: var(--sprout-text-xs); align-items: center; gap: 4px; margin-top: 2px; line-height: 1rem; display: flex; } .sprout-file-attachment[data-state="error"] .sprout-file-attachment-status, .sprout-file-attachment-failed { color: var(--sprout-danger); } .sprout-file-attachment-failed { font-size: var(--sprout-text-xs); flex-shrink: 0; } .sprout-file-attachment-media { color: var(--sprout-muted); flex-shrink: 0; display: flex; } .sprout-file-attachment[data-variant="list"] .sprout-file-attachment-media { background: var(--sprout-hover); border-radius: 6px; justify-content: center; align-items: center; width: 40px; height: 40px; overflow: hidden; } .sprout-file-attachment-media > .sprout-attachment-image { object-fit: cover; width: 100%; height: 100%; } .sprout-file-attachment-preview { aspect-ratio: 16 / 9; background: var(--sprout-hover); width: 100%; color: var(--sprout-muted); font: inherit; border: 0; border-radius: 11px 11px 0 0; justify-content: center; align-items: center; margin: 0; padding: 0; display: flex; overflow: hidden; } button.sprout-file-attachment-preview { cursor: pointer; } .sprout-file-attachment-preview > .sprout-attachment-image { object-fit: cover; width: 100%; height: 100%; } .sprout-file-attachment-thumb { background: var(--sprout-file-image); border-radius: 6px; flex-shrink: 0; justify-content: center; align-items: center; width: 22px; height: 22px; display: flex; overflow: hidden; } .sprout-file-attachment-thumb > .sprout-attachment-image { object-fit: cover; width: 100%; height: 100%; } .sprout-file-attachment-thumb > .sprout-attachment-image-failed { padding: 0; font-size: 0; } .sprout-file-attachment-thumb > .sprout-attachment-image-failed svg { width: 12px; height: 12px; } .sprout-file-attachment-actions { flex-shrink: 0; align-items: center; display: flex; } .sprout-file-attachment[data-variant="grid"] .sprout-file-attachment-actions { background: var(--sprout-surface); border-radius: 6px; position: absolute; top: 4px; right: 4px; } .sprout-attachment-image-failed { color: var(--sprout-muted); font-size: var(--sprout-text-xs); align-items: center; gap: 8px; padding: 8px; display: flex; } .sprout-attachment-dropzone { box-sizing: border-box; border: 1px dashed var(--sprout-input); background: color-mix(in oklab, var(--sprout-hover) 30%, var(--sprout-surface)); color: var(--sprout-text); text-align: center; border-radius: 12px; padding: 20px; } .sprout-attachment-dropzone[data-dragging] { border-color: var(--sprout-focus); background: var(--sprout-hover); } .sprout-attachment-dropzone[data-disabled] { cursor: not-allowed; } .sprout-attachment-dropzone[data-disabled] .sprout-attachment-dropzone-icon { opacity: .5; } .sprout-attachment-dropzone-icon { color: var(--sprout-muted); margin: 0 auto 8px; display: block; } .sprout-attachment-dropzone-text { color: var(--sprout-muted); font-size: var(--sprout-text-sm); margin: 0 0 12px; line-height: 1.25rem; } @media (prefers-reduced-motion: no-preference) { .sprout-attachment, .sprout-file-attachment, .sprout-attachment-dropzone { transition: background-color var(--sprout-motion-normal) var(--sprout-motion-ease), border-color var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-attachment-media[data-variant="image"] { transition: opacity var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-attachment-carousel-arrow { transition: opacity var(--sprout-motion-fast) var(--sprout-motion-ease), background-color var(--sprout-motion-fast) var(--sprout-motion-ease), color var(--sprout-motion-fast) var(--sprout-motion-ease); } .sprout-attachment-carousel-viewport { scroll-behavior: smooth; } .sprout-attachment:is([data-state="uploading"], [data-state="processing"]) .sprout-attachment-title, .sprout-file-attachment:is([data-state="uploading"], [data-state="processing"]) .sprout-file-attachment-name { background: linear-gradient(90deg, var(--sprout-muted) 0%, var(--sprout-muted) 40%, var(--sprout-text) 50%, var(--sprout-muted) 60%, var(--sprout-muted) 100%) 0 0 / 250% 100%; -webkit-text-fill-color: transparent; -webkit-background-clip: text; background-clip: text; animation: 1.8s linear infinite sprout-attachment-shimmer; } } @media (forced-colors: active) { .sprout-attachment-title, .sprout-file-attachment-name { -webkit-text-fill-color: currentColor !important; background: none !important; } } @keyframes sprout-attachment-shimmer { from { background-position: 100% 0; } to { background-position: 0 0; } } }Import it from
@/components/ui/attachment. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/attachment.
File attachments
import { AttachmentGroup, FileAttachment } from "@tulipfarm/sprout/attachment";
<AttachmentGroup variant="carousel" aria-label="Attached files">
{uploads.map((item) => (
<FileAttachment
key={item.id}
variant="chip"
file={{
id: item.id,
name: item.file.name,
mediaType: item.file.type,
size: "48 KB",
state: item.kind, // "ready" | "uploading" | "processing" | "error"
source: { kind: "local", file: item.file },
}}
preview
viewable
onRemove={() => remove(item.id)}
onRetry={() => retry(item)}
/>
))}
</AttachmentGroup>variant picks the shape:
"list"(default): a row with icon, name, and status line."grid": a card with a large preview above the name."inline": a compact pill for text."chip": a 36px chip for composers and messages.
The status line shows file.size when ready, which can also be a short source such as “Google Drive” or “Saved in Files”. Busy files show a spinner, and "error" shows “Upload failed” with a Retry button when you pass onRetry. onRemoveadds a remove button. Images with a url show a thumbnail.
Opening: viewable opens the file in the full-screenFileViewer on click, with syntax colors for code and text. PassonOpen instead to open it your own way, such as a canvas or a download; it is disabled while the file is busy. With neither, the name is plain text.actionLabel="Download"names the button “Download …” instead of “Inspect …”.
preview peeks at the file in a card after hovering or focusing the name for 400ms: the image, or the first 24 lines of text, code, JSON, or Markdown. Other formats and failed uploads get no card. Both props need file.source or file.url. Wrap the app in FileRenderersProvider to view sheets, Office files, and formatted Markdown.
<FileAttachment
variant="chip"
file={{ id, name: "Supplier price sheet", mediaType, size: "Google Drive", state: "ready" }}
onOpen={openInCanvas}
/>
<FileAttachment
variant="chip"
file={{ id, name: "Loading file…", mediaType: "", size: "", state: "processing" }}
onOpen={() => undefined}
/>
<FileAttachment
variant="chip"
actionLabel="Download"
file={{ id, name: "Price comparison.xlsx", mediaType, size: "52 KB", state: saving ? "processing" : "ready" }}
onOpen={save}
/>Groups
AttachmentGroup lays out attachments. "carousel"(default) scrolls one row sideways with fading edge arrows;"grid" makes two columns, three from 640px;"inline" wraps; "list" stacks. Give a carousel anaria-label. Viewable attachments in a group share one viewer that steps through them in page order with Previous, Next, and the arrow keys. Closing it returns focus to the last file shown.
Parts
<Attachment state="uploading" size="sm" orientation="horizontal">
<AttachmentTrigger aria-label="Open Q3 launch deck.pptx" onClick={open} />
<AttachmentMedia>
<FileTypeIcon name="Q3 launch deck.pptx" mediaType={type} />
</AttachmentMedia>
<AttachmentContent>
<AttachmentTitle>Q3 launch deck.pptx</AttachmentTitle>
<AttachmentDescription>Uploading 1.2 MB of 2.8 MB</AttachmentDescription>
</AttachmentContent>
<AttachmentActions>
<AttachmentAction aria-label="Remove Q3 launch deck.pptx" onClick={remove}>
<X />
</AttachmentAction>
</AttachmentActions>
</Attachment>state:"idle"dashes the border,"uploading"and"processing"shimmer the title,"error"turns it red,"done"(default) is plain.size:"lg"(40px media, the default),"md"(32px),"sm"(28px).orientation:"horizontal"(default) or"vertical", which stacks the media above the text and floats actions over its corner.AttachmentMedia variant="image"crops animg; the default"icon"centers an icon or spinner.AttachmentTriggerstretches over the card so a click anywhere opens it. It acceptsrenderfor a link.
File type icons
<FileTypeIcon name="Returns policy.pdf" mediaType="application/pdf" />
<FileTypeIcon name="Price list 2026.xlsx" mediaType={type} size="lg" />A decorative paper glyph with the extension in a colored badge: red for PDF, green for sheets, blue for documents and Google files, orange for slides, light blue for images, and gray for everything else. "sm" (default) is 20 × 24px; "lg" is 30 × 36px. A name without an extension shows no badge.
Local files
<AttachmentDropzone accept=".txt,.md,.pdf,.docx" disabled={busy} onFiles={add} />
{files.map((file, index) => (
<LocalFileAttachment key={index} file={file} preview viewable onRemove={() => remove(index)} />
))}AttachmentDropzone takes drops or a “Choose files” button and hands the files to onFiles. It uploads nothing.accept defaults to documents, sheets, slides, PDF, text, JSON, Google shortcuts, images, and common source files.LocalFileAttachment shows a File as a chip with a live image thumbnail, and passes preview andviewable through.
Accessibility
Each open button is named “Inspect name” or “Download name”; remove and retry buttons are named “Remove name” and “Retry name”. Busy chips have a spinner named “Uploading…” or “Processing…”. File type icons are hidden from assistive tech because the name is always beside them.
The carousel is a labelled region. Each item is a group, focus scrolls it into view, and Left and Right scroll it when focus is inside. The edge arrows are for pointers, so Tab never lands on a button that vanishes at the end of the row. The drop zone's button opens the system file picker. Transitions take 120 to 180ms; with reduced motion the title shimmer and smooth scrolling stop.
Theme tokens
Cards use --sprout-surface, --sprout-line,--sprout-hover, and --sprout-danger. File type icons use --sprout-file-paper,--sprout-file-edge, --sprout-file-label, and one badge color per kind: --sprout-file-generic,-pdf, -sheet, -document,-slides, and -image. Each has a light and a dark value.
