File Viewer
Shows a file without leaving the page: images, PDF, text, JSON, Markdown, source code in any language, Google Docs links and shortcuts, plus spreadsheets and Office files through renderers you register. Use FileViewer for a full-screen dialog, ViewableFileContent inline, andFileContent when you load the bytes yourself.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/file-viewer.jsonCopies File Viewer and the components it uses (Button, Code Block, Dialog, Dropdown Menu, and Spinner) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/file-viewer. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @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, Code Block, Dialog, Dropdown Menu, and Spinner.
Copy and paste the following code into your project.
import { createContext, Suspense, useContext, useEffect, useId, useMemo, useRef, useState, type HTMLAttributes, type KeyboardEvent, type ReactNode, } from 'react'; import { ArrowUpRightIcon } from '@/lib/sprout/icons/arrow-up-right-icon'; 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 { DownloadIcon } from '@/lib/sprout/icons/download-icon'; import { MoreIcon } from '@/lib/sprout/icons/more-icon'; import { SidebarRightIcon } from '@/lib/sprout/icons/sidebar-right-icon'; import { cn } from '@/lib/sprout/classes'; import { fileKind, type FileKind } from '@/lib/sprout/file-kind'; import { Button } from '@/components/ui/button'; import { CodeBlock, languageForFilename } from '@/components/ui/code-block'; import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, type DialogContentProps, } from '@/components/ui/dialog'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { Spinner } from '@/components/ui/spinner'; import { StatePanel } from '@/lib/sprout/state-panel-core'; export type ViewableFileSource = { kind: 'local'; file: File } | { kind: 'remote'; url: string }; export interface ViewableFile { name: string; mediaType: string; source: ViewableFileSource; } export type ViewableFileKind = FileKind; export interface FileSheetRendererProps { name: string; bytes: ArrayBuffer; onRetry: () => void; } export interface FileOfficeRendererProps extends FileSheetRendererProps { kind: 'document' | 'slides'; } export interface FileMarkdownRendererProps { text: string; } export interface FileRenderers { markdown?: ((props: FileMarkdownRendererProps) => ReactNode) | undefined; sheet?: ((props: FileSheetRendererProps) => ReactNode) | undefined; office?: ((props: FileOfficeRendererProps) => ReactNode) | undefined; } const RenderersContext = createContext<FileRenderers>({}); export interface FileRenderersProviderProps { renderers: FileRenderers; children?: ReactNode; } export function FileRenderersProvider({ renderers, children }: FileRenderersProviderProps) { const parent = useContext(RenderersContext); const value = useMemo(() => ({ ...parent, ...renderers }), [parent, renderers]); return <RenderersContext value={value}>{children}</RenderersContext>; } function useRenderers(own: FileRenderers | undefined) { const shared = useContext(RenderersContext); return own ? { ...shared, ...own } : shared; } export const maxViewableFileBytes = 50 * 1024 * 1024; export function viewableFileKind(name: string, mediaType: string): ViewableFileKind { return fileKind(name, mediaType); } export interface GoogleDocumentLink { url: string; embedUrl: string; mediaType: string; } export function googleDocument(url: string): GoogleDocumentLink | null { let parsed: URL; try { parsed = new URL(url); } catch { return null; } if ( parsed.protocol !== 'https:' || parsed.hostname !== 'docs.google.com' || parsed.username || parsed.password || parsed.port ) return null; const match = /^\/(document|spreadsheets|presentation)\/d\/([a-zA-Z0-9_-]+)(?:\/|$)/.exec(parsed.pathname); if (!match) return null; const [, family, id] = match; const canonical = `https://docs.google.com/${family}/d/${id}`; const endpoint = family === 'presentation' ? 'embed' : 'preview'; return { url: `${canonical}/edit`, embedUrl: `${canonical}/${endpoint}${family === 'spreadsheets' ? '?widget=true&headers=false' : ''}`, mediaType: `application/vnd.google-apps.${family === 'spreadsheets' ? 'spreadsheet' : family}`, }; } export function googleShortcut(text: string): string { const value: unknown = JSON.parse(text); if (typeof value !== 'object' || value === null || !('url' in value) || typeof value.url !== 'string') throw new Error('This Google shortcut does not contain a document link.'); const document = googleDocument(value.url); if (!document) throw new Error('This shortcut does not contain a supported Google Docs, Sheets, or Slides link.'); return document.url; } const rasterTypes = new Set([ 'image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif', 'image/bmp', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/heic', 'image/heif', 'image/tiff', ]); export function renderableType(name: string, mediaType: string) { const kind = fileKind(name, mediaType); if (kind === 'pdf') return 'application/pdf'; const type = mediaType.trim().toLowerCase(); return kind === 'image' && rasterTypes.has(type) ? type : 'application/octet-stream'; } type LoadedFile = | { kind: 'loading' } | { kind: 'error'; message: string } | { kind: 'ready'; url: string; bytes: ArrayBuffer }; function useFileContent(file: ViewableFile, attempt = 0, enabled = true): LoadedFile { const [loaded, setLoaded] = useState<LoadedFile>({ kind: 'loading' }); const { source, name, mediaType } = file; useEffect(() => { if (!enabled) return; let cancelled = false; let objectUrl: string | undefined; const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 15000); setLoaded({ kind: 'loading' }); const load = async () => { let blob: Blob; if (source.kind === 'local') blob = source.file; else { const response = await fetch(source.url, { signal: controller.signal }); if (!response.ok) throw new Error('The file could not be loaded. Check the link and try again.'); blob = await response.blob(); } if (blob.size > maxViewableFileBytes) throw new Error('This file is larger than the 50 MB local viewing limit.'); const bytes = await blob.arrayBuffer(); if (cancelled) return; objectUrl = URL.createObjectURL( new Blob([bytes], { type: renderableType(name, blob.type || mediaType), }), ); setLoaded({ kind: 'ready', bytes, url: objectUrl }); }; void load() .catch((error: unknown) => { if (!cancelled) setLoaded({ kind: 'error', message: error instanceof Error && error.name !== 'AbortError' ? error.message : 'The file took too long to load. Try again.', }); }) .finally(() => clearTimeout(timeout)); return () => { cancelled = true; clearTimeout(timeout); controller.abort(); if (objectUrl) URL.revokeObjectURL(objectUrl); }; }, [source, name, mediaType, attempt, enabled]); return loaded; } interface FileViewerBaseProps { open: boolean; onOpenChange: (open: boolean) => void; renderers?: FileRenderers | undefined; finalFocus?: DialogContentProps['finalFocus']; actions?: ReactNode; menu?: ReactNode; panel?: ReactNode; panelLabel?: string; panelOpen?: boolean; defaultPanelOpen?: boolean; onPanelOpenChange?: (open: boolean) => void; } interface SingleFileProps { file: ViewableFile | null; files?: undefined; index?: undefined; onIndexChange?: undefined; } interface FileSetProps { file?: undefined; files: readonly ViewableFile[]; index: number; onIndexChange: (index: number) => void; } export type FileViewerProps = FileViewerBaseProps & (SingleFileProps | FileSetProps); const ownsArrowKeys = 'input, textarea, select, iframe, [contenteditable="true"], [role="region"], [role="slider"]'; export function FileViewer({ file, files, index = 0, onIndexChange, open, onOpenChange, renderers, finalFocus, actions, menu, panel, panelLabel = 'Details', panelOpen, defaultPanelOpen, onPanelOpenChange, }: FileViewerProps) { const panelId = useId(); const [ownPanelOpen, setOwnPanelOpen] = useState( () => defaultPanelOpen ?? (typeof window !== 'undefined' && !!window.matchMedia?.('(min-width: 1024px)').matches), ); const panelShown = !!panel && (panelOpen ?? ownPanelOpen); const togglePanel = () => { setOwnPanelOpen(!panelShown); onPanelOpenChange?.(!panelShown); }; const current = files ? (files[index] ?? null) : file; const count = files?.length ?? 0; const refocus = useRef<{ popup: Element; direction: string } | null>(null); const goTo = (target: number) => () => { const button = document.activeElement?.closest<HTMLElement>('[data-step]'); const popup = button?.closest('[data-file-viewer]'); refocus.current = button && popup ? { popup, direction: button.dataset.step ?? '' } : null; onIndexChange?.(target); }; const step = files && count > 1 ? { position: index + 1, count, previous: index > 0 ? goTo(index - 1) : undefined, next: index < count - 1 ? goTo(index + 1) : undefined, } : undefined; useEffect(() => { const pending = refocus.current; refocus.current = null; if (!pending) return; const enabled = ":not(:disabled):not([aria-disabled='true'])"; const target = pending.popup.querySelector<HTMLElement>(`[data-step="${pending.direction}"]${enabled}`) ?? pending.popup.querySelector<HTMLElement>(`[data-step]${enabled}`); target?.focus(); }, [index]); const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => { if (!step || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return; if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return; if ((event.target as Element).closest(ownsArrowKeys)) return; const move = event.key === 'ArrowLeft' ? step.previous : step.next; if (!move) return; event.preventDefault(); move(); }; return ( <Dialog open={open} onOpenChange={onOpenChange}> <DialogContent size="fullscreen" showCloseButton={false} data-file-viewer="" data-panel={panelShown ? 'open' : undefined} className="sprout-file-viewer" finalFocus={finalFocus} onKeyDown={handleKeyDown} > {current && open && ( <SelectedFile key={step ? index : undefined} file={current} renderers={renderers} step={step} actions={actions} menu={menu} panel={ panel ? { id: panelId, label: panelLabel, open: panelShown, toggle: togglePanel, } : undefined } /> )} {current && open && panel && ( <aside id={panelId} aria-label={panelLabel} hidden={!panelShown} data-slot="file-viewer-panel" className="sprout-file-viewer-panel" > {panel} </aside> )} </DialogContent> </Dialog> ); } interface FileStep { position: number; count: number; previous: (() => void) | undefined; next: (() => void) | undefined; } function sourceLabel(file: ViewableFile, google: boolean) { return google ? 'Google document' : file.source.kind === 'local' ? 'Local file · Not uploaded' : 'Linked file'; } interface PanelToggle { id: string; label: string; open: boolean; toggle: () => void; } function SelectedFile({ file, renderers, step, actions, menu, panel, }: { file: ViewableFile; renderers: FileRenderers | undefined; step: FileStep | undefined; actions: ReactNode; menu: ReactNode; panel: PanelToggle | undefined; }) { const [attempt, setAttempt] = useState(0); const retry = () => setAttempt(value => value + 1); const google = file.source.kind === 'remote' ? googleDocument(file.source.url) : null; const loaded = useFileContent(file, attempt, !google); return ( <> <header data-slot="file-viewer-header" className="sprout-file-viewer-header"> <div className="sprout-file-viewer-heading"> <DialogTitle> <span className="sprout-file-viewer-truncate" title={file.name}> {file.name} </span> </DialogTitle> <DialogDescription> <span className="sprout-file-viewer-truncate">{sourceLabel(file, !!google)}</span> </DialogDescription> </div> <div data-slot="file-viewer-controls" className="sprout-file-viewer-controls"> {step && ( <div data-slot="file-viewer-steps" className="sprout-file-viewer-steps"> <Button variant="ghost" size="icon-sm" aria-label="Previous file" data-step="previous" disabled={!step.previous} onClick={step.previous} > <ChevronLeftIcon size="md" aria-hidden="true" /> </Button> <span className="sprout-file-viewer-position" aria-hidden="true"> {step.position} of {step.count} </span> <Button variant="ghost" size="icon-sm" aria-label="Next file" data-step="next" disabled={!step.next} onClick={step.next} > <ChevronRightIcon size="md" aria-hidden="true" /> </Button> <span aria-live="polite" className="sprout-file-viewer-sr-only"> {file.name}, file {step.position} of {step.count} </span> </div> )} {actions && ( <div data-slot="file-viewer-actions" className="sprout-file-viewer-actions"> {actions} </div> )} {google ? ( <Button variant="outline" size="sm" nativeButton={false} render={<a href={google.url} target="_blank" rel="noopener noreferrer" />} > <ArrowUpRightIcon size="md" aria-hidden="true" /> Open in Google </Button> ) : loaded.kind === 'ready' ? ( <Button variant="outline" size="sm" aria-label="Download" nativeButton={false} render={<a href={loaded.url} download={file.name} />} > <DownloadIcon size="md" aria-hidden="true" /> <span className="sprout-file-viewer-label">Download</span> </Button> ) : ( <Button variant="outline" size="sm" aria-label="Download" disabled> <DownloadIcon size="md" aria-hidden="true" /> <span className="sprout-file-viewer-label">Download</span> </Button> )} <DropdownMenu> <DropdownMenuTrigger render={<Button variant="ghost" size="icon-sm" aria-label="More actions" />}> <MoreIcon size="md" aria-hidden="true" /> </DropdownMenuTrigger> <DropdownMenuContent align="end" size="menu"> <DropdownMenuItem onClick={retry}>{google ? 'Reload viewer' : 'Reload file'}</DropdownMenuItem> {menu && ( <> <DropdownMenuSeparator /> {menu} </> )} </DropdownMenuContent> </DropdownMenu> </div> <div data-slot="file-viewer-window" className="sprout-file-viewer-window"> {panel && ( <Button variant="ghost" size="icon-sm" aria-label={panel.label} aria-expanded={panel.open} aria-controls={panel.id} onClick={panel.toggle} > <SidebarRightIcon size="md" aria-hidden="true" /> </Button> )} <DialogClose render={<Button variant="ghost" size="icon-sm" aria-label="Close file viewer" />}> <CloseIcon size="lg" aria-hidden="true" /> </DialogClose> </div> </header> <div data-slot="viewable-file-content" className="sprout-file-viewer-surface"> {google ? ( <EmbeddedFile key={`${google.embedUrl}:${attempt}`} url={google.embedUrl} name={file.name} google onRetry={retry} /> ) : ( <FileBody loaded={loaded} file={file} renderers={renderers} onRetry={retry} /> )} </div> </> ); } export interface ViewableFileContentProps extends HTMLAttributes<HTMLDivElement> { file: ViewableFile; renderers?: FileRenderers | undefined; } export function ViewableFileContent({ file, renderers, className, ...props }: ViewableFileContentProps) { const [attempt, setAttempt] = useState(0); const retry = () => setAttempt(value => value + 1); const google = file.source.kind === 'remote' ? googleDocument(file.source.url) : null; return ( <div data-slot="viewable-file-content" {...props} className={cn('sprout-file-viewer-surface', className)}> {google ? ( <EmbeddedFile key={`${google.embedUrl}:${attempt}`} url={google.embedUrl} name={file.name} google onRetry={retry} /> ) : ( <LocalFile key={attempt} file={file} renderers={renderers} onRetry={retry} /> )} </div> ); } function LocalFile({ file, renderers, onRetry, }: { file: ViewableFile; renderers: FileRenderers | undefined; onRetry: () => void; }) { const loaded = useFileContent(file); return ( <> {loaded.kind === 'ready' && ( <div data-slot="file-viewer-toolbar" className="sprout-file-viewer-toolbar" data-align="end"> <Button variant="ghost" size="sm" onClick={onRetry}> Reload file </Button> <Button variant="outline" size="sm" nativeButton={false} render={<a href={loaded.url} download={file.name} />} > <DownloadIcon size="md" aria-hidden="true" /> Download </Button> </div> )} <FileBody loaded={loaded} file={file} renderers={renderers} onRetry={onRetry} /> </> ); } function FileBody({ loaded, file, renderers, onRetry, }: { loaded: LoadedFile; file: ViewableFile; renderers: FileRenderers | undefined; onRetry: () => void; }) { if (loaded.kind === 'loading') return <LoadingFile />; if (loaded.kind === 'error') return <FileError message={loaded.message} onRetry={onRetry} />; return ( <FileContent name={file.name} mediaType={file.mediaType} bytes={loaded.bytes} url={loaded.url} onRetry={onRetry} renderers={renderers} /> ); } const textKinds: readonly ViewableFileKind[] = ['text', 'code', 'json', 'markdown', 'google']; export interface FileContentProps { name: string; mediaType: string; bytes: ArrayBuffer; url: string; onRetry: () => void; renderers?: FileRenderers | undefined; } export function FileContent({ name, mediaType, bytes, url, onRetry, renderers: own }: FileContentProps) { const renderers = useRenderers(own); const kind = fileKind(name, mediaType); const text = useMemo(() => { if (!textKinds.includes(kind)) return null; try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { return undefined; } }, [bytes, kind]); if (text === undefined) return ( <FileError message="This file is not valid UTF-8 text. Download it to open in another application." onRetry={onRetry} /> ); const unavailable = ( <StatePanel kind="unavailable" title="This format cannot be displayed locally" description={ name.toLowerCase().endsWith('.ppt') ? 'Save this older PowerPoint file as .pptx to view the slides here. You can still download the original.' : 'Download the original file to open it in a compatible application.' } /> ); let body: ReactNode; if (bytes.byteLength === 0) body = <StatePanel kind="empty" title="This file is empty" description="The file contains no data to display." />; else if (kind === 'image') body = <ImageFile url={url} name={name} onRetry={onRetry} />; else if (kind === 'pdf') body = <EmbeddedFile url={url} name={name} onRetry={onRetry} />; else if (kind === 'google') body = <GoogleShortcut text={text ?? ''} name={name} onRetry={onRetry} />; else if (kind === 'sheet') body = renderers.sheet ? ( <Suspense fallback={<LoadingFile />}>{renderers.sheet({ name, bytes, onRetry })}</Suspense> ) : ( unavailable ); else if (kind === 'document' || kind === 'slides') body = renderers.office ? ( <Suspense fallback={<LoadingFile />}>{renderers.office({ name, bytes, kind, onRetry })}</Suspense> ) : ( unavailable ); else if (text !== null) body = <TextFile text={text} name={name} kind={kind} renderMarkdown={renderers.markdown} />; else body = unavailable; return ( <div data-slot="file-content" data-kind={kind} className="sprout-file-content"> {body} </div> ); } export type LoadingFileProps = HTMLAttributes<HTMLDivElement>; export function LoadingFile({ className, ...props }: LoadingFileProps) { return ( <StatePanel kind="loading" title="Opening file" description="Preparing the document viewer." data-file-state="loading" {...props} className={className} /> ); } export interface FileErrorProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> { message: ReactNode; onRetry: () => void; } export function FileError({ message, onRetry, className, ...props }: FileErrorProps) { return ( <StatePanel kind="error" title="Could not open this file" description={message} data-file-state="error" {...props} className={className} > <Button variant="outline" onClick={onRetry}> Try again </Button> </StatePanel> ); } function codeLanguageFor(name: string, kind: ViewableFileKind) { return kind === 'code' ? (languageForFilename(name) ?? 'text') : kind; } const previewTextKinds: readonly ViewableFileKind[] = ['text', 'code', 'json', 'markdown']; const previewBytes = 16 * 1024; const previewLines = 24; const previewRows = 8; const previewColumns = 6; function delimiterFor(file: ViewableFile) { const extension = file.name.split('.').pop()?.toLowerCase(); if (extension === 'csv' || file.mediaType === 'text/csv') return ','; if (extension === 'tsv' || file.mediaType === 'text/tab-separated-values') return '\t'; return null; } function parseDelimited(text: string, delimiter: string) { const rows: string[][] = []; let row: string[] = []; let cell = ''; let quoted = false; for (let index = 0; index < text.length && rows.length < previewRows; index++) { const char = text[index]!; if (quoted) { if (char === '"' && text[index + 1] === '"') { cell += '"'; index++; } else if (char === '"') quoted = false; else cell += char; } else if (char === '"' && !cell) quoted = true; else if (char === delimiter) { row.push(cell); cell = ''; } else if (char === '\n' || char === '\r') { if (char === '\r' && text[index + 1] === '\n') index++; row.push(cell); if (row.some(Boolean)) rows.push(row); row = []; cell = ''; } else cell += char; } if ((cell || row.length) && rows.length < previewRows) { row.push(cell); if (row.some(Boolean)) rows.push(row); } return rows; } export function isPreviewableFile(file: ViewableFile) { if (file.source.kind === 'remote' && googleDocument(file.source.url)) return false; const kind = fileKind(file.name, file.mediaType); return kind === 'image' || previewTextKinds.includes(kind) || delimiterFor(file) !== null; } export interface FilePreviewProps extends HTMLAttributes<HTMLDivElement> { file: ViewableFile; } export function FilePreview({ file, className, ...props }: FilePreviewProps) { if (!isPreviewableFile(file)) return null; const kind = fileKind(file.name, file.mediaType); return ( <div data-slot="file-preview" data-kind={kind} {...props} className={cn('sprout-file-preview', className)}> {kind === 'image' && file.source.kind === 'remote' ? ( <img src={file.source.url} alt={file.name} className="sprout-file-preview-image" /> ) : ( <LoadedPreview file={file} kind={kind} /> )} </div> ); } function LoadedPreview({ file, kind }: { file: ViewableFile; kind: ViewableFileKind }) { const loaded = useFileContent(file); const delimiter = delimiterFor(file); const head = useMemo( () => loaded.kind !== 'ready' || kind === 'image' ? null : new TextDecoder().decode(loaded.bytes.slice(0, previewBytes)), [loaded, kind], ); const table = useMemo(() => (head !== null && delimiter ? parseDelimited(head, delimiter) : null), [head, delimiter]); const text = head === null ? null : head.split('\n').slice(0, previewLines).join('\n'); if (loaded.kind === 'loading') return ( <span className="sprout-file-preview-state"> <Spinner size="sm" aria-hidden="true" /> Loading preview… </span> ); if (loaded.kind === 'error') return <span className="sprout-file-preview-state">Preview unavailable</span>; if (text === null) return <img src={loaded.url} alt={file.name} className="sprout-file-preview-image" />; if (!text.trim()) return <span className="sprout-file-preview-state">This file is empty</span>; if (table?.length) { const [header = [], ...rows] = table; const width = Math.min(previewColumns, Math.max(...table.map(row => row.length))); const cells = (row: string[]) => Array.from({ length: width }, (_, index) => row[index] ?? ''); return ( <table className="sprout-file-preview-table"> <thead> <tr> {cells(header).map((cell, index) => ( <th key={index}>{cell}</th> ))} </tr> </thead> <tbody> {rows.map((row, rowIndex) => ( <tr key={rowIndex}> {cells(row).map((cell, index) => ( <td key={index}>{cell}</td> ))} </tr> ))} </tbody> </table> ); } return ( <CodeBlock code={text} language={codeLanguageFor(file.name, kind)} variant="preview" lineNumbers={false} wrap={kind === 'text' || kind === 'markdown'} /> ); } function TextFile({ text, name, kind, renderMarkdown, }: { text: string; name: string; kind: ViewableFileKind; renderMarkdown: FileRenderers['markdown']; }) { const [source, setSource] = useState(false); const json = useMemo(() => { if (kind !== 'json') return null; try { return JSON.stringify(JSON.parse(text), null, 2); } catch { return undefined; } }, [kind, text]); const markdown = kind === 'markdown' && renderMarkdown; const prose = kind === 'text' || kind === 'markdown'; return ( <div className="sprout-file-text" data-format={markdown && !source ? 'formatted' : 'source'}> {markdown && ( <div className="sprout-file-text-bar"> <Button variant="outline" size="sm" aria-pressed={source} onClick={() => setSource(value => !value)}> {source ? 'Show formatted' : 'Show source'} </Button> </div> )} {json === undefined && ( <p role="alert" className="sprout-file-text-alert"> This file contains invalid JSON. The original text is shown below. </p> )} {markdown && !source ? ( <div className="sprout-file-text-scroll" tabIndex={0} role="region" aria-label={name}> <div className="sprout-file-text-page"> <Suspense fallback={<LoadingFile />}>{renderMarkdown({ text })}</Suspense> </div> </div> ) : ( <CodeBlock code={json ?? text} language={codeLanguageFor(name, kind)} variant="file" wrap={prose} /> )} </div> ); } function ImageFile({ url, name, onRetry }: { url: string; name: string; onRetry: () => void }) { const [state, setState] = useState<'loading' | 'ready' | 'error'>('loading'); const [zoom, setZoom] = useState(false); if (state === 'error') return ( <FileError message="Your browser could not decode this image. Try a PNG, JPEG, GIF, WebP, AVIF, or BMP version." onRetry={onRetry} /> ); return ( <> <div className="sprout-file-viewer-toolbar" data-align="center"> <Button variant="outline" size="sm" aria-pressed={zoom} onClick={() => setZoom(value => !value)}> {zoom ? 'Fit image' : 'Actual size'} </Button> </div> {state === 'loading' && <LoadingFile />} <div className="sprout-file-image-stage" data-zoom={zoom ? 'actual' : 'fit'} tabIndex={zoom ? 0 : undefined} role={zoom ? 'region' : undefined} aria-label={zoom ? `${name} at actual size` : undefined} > <img src={url} alt={name} onLoad={() => setState('ready')} onError={() => setState('error')} className="sprout-file-image" data-state={state} /> </div> </> ); } function GoogleShortcut({ text, name, onRetry }: { text: string; name: string; onRetry: () => void }) { let document: GoogleDocumentLink | null; try { document = googleDocument(googleShortcut(text)); } catch (error) { return ( <FileError message={error instanceof Error ? error.message : 'Invalid Google document shortcut.'} onRetry={onRetry} /> ); } if (!document) return null; return ( <> <div className="sprout-file-google-link"> <a href={document.url} target="_blank" rel="noopener noreferrer"> Open in Google </a> </div> <EmbeddedFile url={document.embedUrl} name={name} google onRetry={onRetry} /> </> ); } function EmbeddedFile({ url, name, google = false, onRetry, }: { url: string; name: string; google?: boolean; onRetry: () => void; }) { const [state, setState] = useState<'loading' | 'loaded' | 'slow'>('loading'); const timer = useRef<ReturnType<typeof setTimeout> | null>(null); useEffect(() => { timer.current = setTimeout(() => setState(value => (value === 'loading' ? 'slow' : value)), 12000); return () => { if (timer.current) clearTimeout(timer.current); }; }, []); return ( <div data-slot="file-embed" data-state={state} className="sprout-file-embed"> {google && ( <p className="sprout-file-embed-notice"> Google controls access to this document. If it cannot open here, use Open in Google to sign in or request access. </p> )} {state === 'loading' && ( <div className="sprout-file-embed-loading"> <LoadingFile /> </div> )} {state === 'slow' && ( <div className="sprout-file-embed-slow"> <p role="status">The embedded viewer is taking longer than expected.</p> <Button variant="outline" size="sm" onClick={onRetry}> Reload viewer </Button> </div> )} <iframe title={name} src={url} className="sprout-file-embed-frame" referrerPolicy="no-referrer" onLoad={() => { if (timer.current) clearTimeout(timer.current); setState('loaded'); }} onError={() => setState('slow')} allowFullScreen /> </div> ); }And the files it imports:
lib/sprout/icons/arrow-up-right-icon.tsxlib/sprout/icons/check-icon.tsxlib/sprout/icons/chevron-left-icon.tsxlib/sprout/icons/chevron-right-icon.tsxlib/sprout/icons/close-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/download-icon.tsxlib/sprout/icons/inbox-icon.tsxlib/sprout/icons/more-icon.tsxlib/sprout/icons/sidebar-right-icon.tsxlib/sprout/icons/warning-icon.tsxlib/sprout/file-kind.tslib/sprout/languages.tslib/sprout/state-panel-core.tsxlib/sprout/syntax.ts
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-file-viewer.sprout-dialog-fullscreen { grid-template-rows: auto minmax(0, 1fr); grid-template-columns: minmax(0, 1fr) auto; display: grid; } .sprout-file-viewer > .sprout-file-viewer-surface { grid-area: 2 / 1; } .sprout-file-viewer-header { border-bottom: 1px solid var(--sprout-line); background: var(--sprout-surface); grid-column: 1 / -1; grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "heading window" "controls controls"; align-items: center; gap: .5rem 1rem; padding: .625rem .75rem .625rem 1rem; display: grid; } .sprout-file-viewer-heading { grid-area: heading; gap: 2px; min-width: 0; display: grid; } .sprout-file-viewer-controls { flex-wrap: wrap; grid-area: controls; justify-content: flex-end; align-items: center; gap: .5rem; min-width: 0; display: flex; } .sprout-file-viewer-actions { align-items: center; gap: .5rem; display: flex; } .sprout-file-viewer-window { grid-area: window; align-items: center; gap: 2px; display: flex; } .sprout-file-viewer-window > [aria-expanded="true"] { background: var(--sprout-hover); color: var(--sprout-text); } @media (width <= 639.98px) { .sprout-file-viewer-controls .sprout-button-size-sm:has( > .sprout-file-viewer-label) { width: 28px; padding-inline: 0; } .sprout-file-viewer-label { display: none; } } @media (width >= 640px) { .sprout-file-viewer-header { grid-template-columns: minmax(0, 1fr) auto auto; grid-template-areas: "heading controls window"; min-height: 3.5rem; padding-inline: 1.5rem 1rem; } .sprout-file-viewer-controls { flex-wrap: nowrap; } .sprout-file-viewer-window:before { content: ""; background: var(--sprout-line); width: 1px; height: 1.25rem; margin-inline: .25rem .375rem; } .sprout-file-text-scroll, .sprout-file-text-page { padding: 2rem; } } .sprout-file-viewer-panel { z-index: 1; box-sizing: border-box; background: var(--sprout-surface); min-width: 0; min-height: 0; color: var(--sprout-text); font-family: var(--sprout-font); font-size: var(--sprout-text-sm); animation: sprout-file-viewer-panel-in var(--sprout-motion-normal, .18s) cubic-bezier(.16, 1, .3, 1) both; flex-direction: column; grid-area: 2 / 1 / auto / -1; display: flex; overflow: auto; } .sprout-file-viewer-panel[hidden] { display: none; } @media (width >= 768px) { .sprout-file-viewer-panel { border-inline-start: 1px solid var(--sprout-line); grid-column: 2; width: clamp(18rem, 28vw, 24rem); } } @keyframes sprout-file-viewer-panel-in { from { opacity: 0; translate: .75rem; } } .sprout-file-viewer-truncate { white-space: nowrap; text-overflow: ellipsis; display: block; overflow: hidden; } .sprout-file-viewer-surface { background: var(--sprout-canvas); min-height: 0; color: var(--sprout-text); font-family: var(--sprout-font); font-size: var(--sprout-text-sm); flex-direction: column; flex: 1; display: flex; overflow: hidden; } .sprout-file-viewer-toolbar { border-bottom: 1px solid var(--sprout-line); flex-wrap: wrap; flex-shrink: 0; justify-content: flex-end; align-items: center; gap: .5rem; padding: .5rem 1rem; display: flex; } .sprout-file-viewer-toolbar[data-align="center"] { justify-content: center; padding: .5rem; } .sprout-file-content { min-height: 0; color: var(--sprout-text); font-family: var(--sprout-font); font-size: var(--sprout-text-sm); flex-direction: column; flex: 1; display: flex; position: relative; overflow: auto; } .sprout-file-text { flex-direction: column; flex: 1; min-height: 0; display: flex; } .sprout-file-text > .sprout-code-block { flex: 1; } .sprout-file-text-bar { border-bottom: 1px solid var(--sprout-line); flex-shrink: 0; justify-content: flex-end; padding: .5rem 1rem; display: flex; } .sprout-file-text-alert { border-bottom: 1px solid var(--sprout-line); font-size: var(--sprout-text-sm); color: var(--sprout-danger); flex-shrink: 0; margin: 0; padding: .625rem 1rem; } .sprout-file-text-scroll { flex: 1; min-height: 0; padding: 1rem; overflow: auto; } .sprout-file-text-scroll:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: -1px; } .sprout-file-text-page { box-sizing: border-box; border: 1px solid var(--sprout-line); border-radius: var(--sprout-radius-panel); background: var(--sprout-surface); overflow-wrap: anywhere; min-width: 0; max-width: 56rem; margin-inline: auto; padding: 1.25rem; } .sprout-file-image-stage { flex: 1; min-height: 0; padding: 1rem; display: flex; overflow: auto; } .sprout-file-image-stage:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: -1px; } .sprout-file-image { object-fit: contain; max-width: 100%; max-height: 100%; transition: opacity var(--sprout-motion-normal, .18s) var(--sprout-motion-ease, ease); margin: auto; } .sprout-file-image[data-state="loading"] { opacity: 0; } .sprout-file-image-stage[data-zoom="actual"] .sprout-file-image { flex-shrink: 0; max-width: none; max-height: none; } .sprout-file-google-link { font-size: var(--sprout-text-sm); padding: .5rem 1rem; } .sprout-file-google-link a { color: var(--sprout-primary); text-underline-offset: 2px; border-radius: 2px; text-decoration: underline; } @media (hover: hover) { .sprout-file-google-link a:hover { color: var(--sprout-primary-hover); } } .sprout-file-google-link a:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 0; } .sprout-file-embed { flex-direction: column; flex: 1; min-height: 0; display: flex; position: relative; } .sprout-file-embed-notice { border-bottom: 1px solid var(--sprout-line); background: var(--sprout-surface); font-size: var(--sprout-text-xs); color: var(--sprout-muted); flex-shrink: 0; margin: 0; padding: .5rem 1rem; line-height: 1rem; } .sprout-file-embed-loading { inset-inline: 0; z-index: 10; pointer-events: none; position: absolute; top: 3rem; } .sprout-file-embed-slow { background: var(--sprout-surface); animation: sprout-file-viewer-in var(--sprout-motion-fast, .12s) var(--sprout-motion-ease, ease) both; flex-wrap: wrap; flex-shrink: 0; justify-content: center; align-items: center; gap: .75rem; padding: .75rem; display: flex; } .sprout-file-embed-slow p { font-size: var(--sprout-text-sm); margin: 0; } .sprout-file-embed-frame { background: var(--sprout-surface); border: 0; flex: 1; width: 100%; min-height: 0; } @keyframes sprout-file-viewer-in { from { opacity: 0; } } @media (prefers-reduced-motion: reduce) { .sprout-file-image, .sprout-file-embed-slow, .sprout-file-viewer-panel { transition: none; animation: none; } .sprout-state-panel { animation-name: sprout-state-panel-fade; } } .sprout-file-preview { box-sizing: border-box; min-height: 0; max-height: 14rem; color: var(--sprout-text); font-family: var(--sprout-font); flex-direction: column; display: flex; overflow: hidden; } .sprout-file-preview[data-kind="image"] { justify-content: center; align-items: center; } .sprout-file-preview-image { border-radius: calc(var(--sprout-radius-panel) - 4px); object-fit: contain; max-width: 100%; max-height: 14rem; display: block; } .sprout-file-preview-table { table-layout: fixed; border-collapse: collapse; width: 100%; font-size: var(--sprout-text-xs); font-variant-numeric: tabular-nums; line-height: 1.4; } .sprout-file-preview-table :is(th, td) { border-bottom: 1px solid var(--sprout-border); text-align: left; text-overflow: ellipsis; white-space: nowrap; padding: 4px 6px; overflow: hidden; } .sprout-file-preview-table th { color: var(--sprout-muted); font-weight: 500; } .sprout-file-preview-table tr:last-child td { border-bottom: 0; } .sprout-file-preview-state { min-height: 5rem; color: var(--sprout-muted); font-size: var(--sprout-text-xs); justify-content: center; align-items: center; gap: 8px; display: flex; } .sprout-file-viewer-steps { flex-shrink: 0; align-items: center; gap: 2px; display: flex; } .sprout-file-viewer-position { min-width: 3.5rem; color: var(--sprout-muted); font-size: var(--sprout-text-xs); font-variant-numeric: tabular-nums; text-align: center; } .sprout-file-viewer-sr-only { clip-path: inset(50%); white-space: nowrap; width: 1px; height: 1px; position: absolute; overflow: hidden; } .sprout-state-panel { font-family: var(--sprout-font); color: var(--sprout-text); overflow-wrap: anywhere; animation: sprout-state-panel-in var(--sprout-motion-normal, .18s) var(--sprout-motion-ease, ease) both; } .sprout-state-panel[data-layout="centered"] { text-align: center; flex-direction: column; align-items: center; gap: 1.5rem; width: 100%; max-width: 28rem; margin-inline: auto; padding: 3rem 1.5rem; display: flex; } .sprout-state-panel-media { border: 1px solid var(--sprout-line); background: var(--sprout-surface); width: 2.5rem; height: 2.5rem; color: var(--sprout-text); box-shadow: var(--sprout-shadow-control); border-radius: .5rem; flex-shrink: 0; justify-content: center; align-items: center; display: flex; } .sprout-state-panel-media > svg { flex-shrink: 0; } .sprout-state-panel-danger { color: var(--sprout-danger); } .sprout-state-panel-text { gap: .5rem; width: 100%; display: grid; } .sprout-state-panel-title { font-size: var(--sprout-text-base); letter-spacing: normal; color: var(--sprout-text); margin: 0; font-weight: 500; line-height: 1.5; } .sprout-state-panel-description { font-size: var(--sprout-text-sm); color: var(--sprout-muted); margin: 0; line-height: 1.5; } .sprout-state-panel-actions { width: 100%; font-size: var(--sprout-text-sm); color: var(--sprout-muted); flex-direction: column; align-items: center; gap: .75rem; display: flex; } .sprout-state-panel-actions:empty { display: none; } .sprout-state-panel[data-layout="sample"] { width: 100%; container-type: inline-size; } .sprout-state-panel-card { border: 1px solid var(--sprout-line); border-radius: var(--sprout-radius-panel); background: var(--sprout-surface); box-shadow: var(--sprout-shadow-control); display: grid; overflow: hidden; } .sprout-state-panel-copy { flex-direction: column; justify-content: center; align-items: flex-start; gap: 1.5rem; min-width: 0; padding: 1.5rem; display: flex; } [data-layout="sample"] .sprout-state-panel-text { max-width: 28rem; } [data-layout="sample"] .sprout-state-panel-title { font-size: 1.25rem; line-height: 1.4; } [data-layout="sample"] .sprout-state-panel-description { font-size: var(--sprout-text-base); } [data-layout="sample"] .sprout-state-panel-actions { align-items: stretch; gap: .5rem; } .sprout-state-panel-sample { border-top: 1px solid var(--sprout-line); background: var(--sprout-canvas); min-height: 15rem; display: none; position: relative; overflow: hidden; } .sprout-state-panel-sample-window { border-top: 1px solid var(--sprout-line); border-left: 1px solid var(--sprout-line); border-top-left-radius: var(--sprout-radius-panel); background: var(--sprout-surface); box-shadow: var(--sprout-shadow-panel); position: absolute; inset: 1.5rem 0 0 1.5rem; overflow: hidden; mask-image: linear-gradient(oklch(0% 0 0) 60%, #0000 100%); } @container (width >= 24rem) { [data-layout="sample"] .sprout-state-panel-actions { flex-flow: wrap; align-items: center; width: auto; } } @container (width >= 28rem) { .sprout-state-panel-sample { display: block; } } @container (width >= 32rem) { .sprout-state-panel-copy { padding: 2.5rem; } } @container (width >= 48rem) { .sprout-state-panel-card { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); } .sprout-state-panel-copy { padding-block: 3.5rem; } .sprout-state-panel-sample { border-top: 0; border-left: 1px solid var(--sprout-line); min-height: 22rem; } } @keyframes sprout-state-panel-fade { from { opacity: 0; } } @keyframes sprout-state-panel-in { from { opacity: 0; transform: translateY(4px); } } }Import it from
@/components/ui/file-viewer. 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/file-viewer.
Open a file
Attachments open the full-screen viewer. Local files stay in browser memory; linked files load from their URL; Google links embed Google’s own viewer.
Shared file with activity
Put people and Share in actions, extra commands in menu, and comments, activity, or access in the side panel. Selecting an avatar opens the People tab.
Empty, invalid, and unsupported files
Each file explains what went wrong and how to recover. Errors offer Try again; formats the browser can’t show suggest downloading.
Inline in a panel
ViewableFileContent fills any flex column, such as a chat canvas tab or a fixed-height preview.
Opening file
Preparing the document viewer.
Opening file
Preparing the document viewer.
Files you load yourself
A file page or canvas tab fetches bytes its own way, then shows LoadingFile, FileError, or FileContent.
Opening file
Preparing the document viewer.
Google file in a canvas
A Google Drive file downloaded as Office bytes and shown with the renderers registered by FileRenderersProvider.
Opening hours
Current Google file
Opening file
Preparing the document viewer.
Proposed upload
An approval card shows the exact file an action will upload before anyone approves it.
Opening file
Preparing the document viewer.
Without renderers
With no sheet or Office renderer registered, those formats ask people to download the original. Markdown falls back to plain text.
Opening file
Preparing the document viewer.
Slides in a canvas tab
A file attached in chat opens in the canvas with ViewableFileContent, here rendered by the registered Office renderer.
Opening file
Preparing the document viewer.
Dialog
import { FileAttachment } from "@tulipfarm/sprout/attachment";
import { FileViewer } from "@tulipfarm/sprout/file-viewer";
<FileAttachment file={attachment} preview viewable />
<FileViewer
file={{ name: "Returns policy.pdf", mediaType: "application/pdf", source: { kind: "local", file } }}
open={open}
onOpenChange={setOpen}
/>file.source is { kind: "local", file } for aFile in browser memory or { kind: "remote", url }for a link. The header shows the name and “Local file · Not uploaded”, “Linked file”, or “Google document”. Docs, Sheets, and Slides links on docs.google.com embed Google’s viewer and add Open in Google. Other files load up to 50 MB, time out after 15 seconds, and get Download in the header. Reload sits in the More actions menu.
Stepping through files
const [index, setIndex] = useState<number | null>(null);
<FileViewer
files={files}
index={index ?? 0}
onIndexChange={setIndex}
open={index !== null}
onOpenChange={(open) => !open && setIndex(null)}
finalFocus={() => buttons.current[index ?? 0]}
/>Pass files, index, andonIndexChange instead of file. With more than one file the header adds Previous file and Next file buttons and an “N of M” count. Left and Right arrows step too. The arrows stop at the first and last file. They are ignored while focus is in a text field, an embed, or a scrollable region, and when a modifier key is held.finalFocus picks where focus lands on close, usually the button for the file that was last on screen. AttachmentGroupwires this up for you.
Inline and your own bytes
import { FileContent, FileError, LoadingFile, renderableType } from "@tulipfarm/sprout/file-viewer";
const url = URL.createObjectURL(new Blob([bytes], { type: renderableType(name, mediaType) }));
<section aria-label="File content" className="flex h-160 flex-col overflow-hidden rounded-xl border">
{content.kind === "loading" ? <LoadingFile />
: content.kind === "failed" ? <FileError message="The file content couldn’t be loaded. Your file is unchanged." onRetry={retry} />
: <FileContent name={name} mediaType={mediaType} bytes={content.bytes} url={url} onRetry={retry} />}
</section>All three fill a flex column, so give the parent a height.renderableType picks a safe type for the blob URL: PDF and raster images keep theirs, and anything a browser could run, including SVG, becomesapplication/octet-stream.
- Images fit the frame; Actual size scrolls them at full resolution.
- Text, code, JSON, and Markdown source show in a
CodeBlockwith syntax colors and Copy. The language comes from the file name, such as.py,.rs, orDockerfile. Code keeps line numbers; notes and Markdown wrap. - JSON is pretty-printed. Invalid JSON shows its original text with a warning.
- Markdown is formatted, with a Show source toggle, when a Markdown renderer is registered.
FilePreviewshows a small, non-interactive peek: the image, or the first 24 lines of text and code.isPreviewableFilesays whether a file has one.- Empty files, text that isn’t UTF-8, legacy
.ppt, and other formats show a state that says what to do next. - An embed that hasn’t loaded after 12 seconds offers Reload viewer. It is also in the More actions menu.
Renderers
import { FileRenderersProvider } from "@tulipfarm/sprout/file-viewer";
const SpreadsheetFile = lazy(() => import("./spreadsheet-file"));
const OfficeFile = lazy(() => import("./office-file"));
<FileRenderersProvider
renderers={{
sheet: (props) => <SpreadsheetFile {...props} />, // { name, bytes, onRetry }
office: (props) => <OfficeFile {...props} />, // { name, bytes, kind: "document" | "slides", onRetry }
markdown: ({ text }) => <MessageResponse>{text}</MessageResponse>,
}}
>
<App />
</FileRenderersProvider>Spreadsheet and Office parsers are large, so Sprõut doesn’t bundle them. Each renderer runs inside Suspense with LoadingFile as the fallback, so lazy components work as they are. Renderers can useLoadingFile and FileError for their own states. Any viewer also takes a renderers prop that overrides the provider. The demo above uses small sample renderers.
People, menu, and side panel
<FileViewer
file={file}
open={open}
onOpenChange={setOpen}
actions={
<>
<AvatarGroup aria-label="People with access">…</AvatarGroup>
<Button size="sm">Share</Button>
</>
}
menu={<DropdownMenuItem>Copy link</DropdownMenuItem>}
panel={<Tabs>…</Tabs>}
panelLabel="Comments and activity"
/>actions sits in the header before Download. Put who is viewing and a Share button there. menu addsDropdownMenuItems to More actions after Reload.panel adds a side panel and a header toggle named bypanelLabel. The panel starts open on screens 1024px and wider. Set defaultPanelOpen, or control it withpanelOpen and onPanelOpenChange. The panel stays mounted while hidden and across file steps, so tabs and drafts inside it survive. On small screens it covers the file.
Accessibility
The dialog is titled by the file name and traps focus; Escape or “Close file viewer” closes it and returns focus to the button that opened it. Loading is announced as a status and errors as an alert, each with a Try again button. Actual size is a toggle button witharia-pressed, and the zoomed image is a scrollable, focusable region. Text and code scroll in a focusable region named after the language, such as “Python code”, and formatted Markdown in one named after the file. Show source is a toggle button witharia-pressed. When stepping, the new file’s name and position, such as “README.md, file 2 of 6”, are announced politely. Embedded frames are named after the file. Images fade in over 180ms and the slow-viewer notice over 120ms; with reduced motion both appear at once.
Theme tokens
The content area uses --sprout-canvas; pages, the header, and toolbars use --sprout-surface and--sprout-line. Warnings use --sprout-danger, links --sprout-primary, and focus rings--sprout-focus.