@swisper.ai/web-file-preview 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/file-preview/components/renderer-types.d.ts +4 -1
- package/dist/components/file-preview/components/renderer-types.d.ts.map +1 -1
- package/dist/components/file-preview/components/viewer/viewer-components.stories.d.ts.map +1 -1
- package/dist/components/file-preview/file-preview.d.ts.map +1 -1
- package/dist/components/file-preview/file-preview.stories.d.ts +49 -2
- package/dist/components/file-preview/file-preview.stories.d.ts.map +1 -1
- package/dist/components/file-thumbnail/components/previews/html-preview.d.ts.map +1 -1
- package/dist/components/file-thumbnail/components/previews/image-preview.d.ts.map +1 -1
- package/dist/components/file-thumbnail/components/previews/markdown-preview.d.ts.map +1 -1
- package/dist/components/file-thumbnail/components/previews/reveal-class-name.d.ts +4 -2
- package/dist/components/file-thumbnail/components/previews/reveal-class-name.d.ts.map +1 -1
- package/dist/components/file-thumbnail/components/previews/scaled-page.d.ts +4 -1
- package/dist/components/file-thumbnail/components/previews/scaled-page.d.ts.map +1 -1
- package/dist/components/file-thumbnail/file-thumbnail.d.ts +2 -0
- package/dist/components/file-thumbnail/file-thumbnail.d.ts.map +1 -1
- package/dist/components/file-thumbnail/file-thumbnail.stories.d.ts +76 -10
- package/dist/components/file-thumbnail/file-thumbnail.stories.d.ts.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.es.js +50 -33
- package/dist/index.es.js.map +1 -1
- package/package.json +14 -6
- package/src/__storybook__/parent-block.tsx +21 -0
- package/src/components/file-preview/__stories__/fixtures.ts +66 -0
- package/src/components/file-preview/components/renderer-types.ts +4 -1
- package/src/components/file-preview/components/viewer/viewer-components.stories.tsx +2 -8
- package/src/components/file-preview/file-preview.json +15 -0
- package/src/components/file-preview/file-preview.stories.tsx +378 -38
- package/src/components/file-preview/file-preview.tsx +7 -2
- package/src/components/file-thumbnail/__stories__/fixtures.ts +99 -0
- package/src/components/file-thumbnail/__stories__/types.ts +26 -0
- package/src/components/file-thumbnail/components/previews/html-preview.tsx +5 -1
- package/src/components/file-thumbnail/components/previews/image-preview.tsx +3 -1
- package/src/components/file-thumbnail/components/previews/markdown-preview.tsx +5 -1
- package/src/components/file-thumbnail/components/previews/reveal-class-name.ts +8 -8
- package/src/components/file-thumbnail/components/previews/scaled-page.tsx +6 -1
- package/src/components/file-thumbnail/file-thumbnail.json +17 -1
- package/src/components/file-thumbnail/file-thumbnail.stories.tsx +551 -84
- package/src/components/file-thumbnail/file-thumbnail.tsx +24 -7
- /package/src/components/file-thumbnail/components/shared/__tests__/{generation-queue.spec.ts → generation-queue.test.ts} +0 -0
- /package/src/components/file-thumbnail/hooks/__tests__/{use-object-url.spec.ts → use-object-url.test.ts} +0 -0
- /package/src/lib/__tests__/{file-kinds.spec.ts → file-kinds.test.ts} +0 -0
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":["useIntersectionObserver","useEventCallback","useTimeout","FILE_EXTENSIONS_BY_KIND","KIND_BY_EXTENSION","kind","extension","getFileExtension","dotIndex","fileName","getFileKind","isFilePreviewSupported","isFileThumbnailSupported","loadFileBlob","fileBlob","src","getFileName","response","cause","signal","HtmlRenderer","rootRef","cn","className","objectUrl","lazyRenderer","createLazy","Lazy","lazy","load","Loaded","createFailedRenderer","current","useState","props","useEffect","onUnmount","onError","ImageRenderer","VideoRenderer","onLoad","TextRenderer","text","setText","handleLoad","reportReadError","isCancelled","blob","nextText","RendererBoundary","Component","configured","setFilePreviewPdfWasmSource","url","setFilePreviewSpreadsheetWasmSource","source","setFilePreviewPresentationWasmSource","setFilePreviewDocxWasmSource","getConfiguredWasmSources","FilePreviewThemeContext","createContext","FilePreviewThemeProvider","theme","useFilePreviewTheme","useContext","CsvRenderer","module","DocxRenderer","SpreadsheetRenderer","PdfRenderer","MarkdownRenderer","RENDERERS","FilePreviewContext","useFilePreviewContext","context","component","createUnsupportedFileError","type","FilePreview","isSupported","loadStatus","setStatus","loadError","setError","loaded","setLoaded","prev","setPrev","unsupportedError","useMemo","status","error","handleError","nextError","reportUnsupported","createdUrl","show","controller","contextValue","FilePreviewFile","forwardRef","ref","Renderer","Suspense","FilePreviewError","asChild","Slot","children","SKELETON_DELAY_MS","SLOW_LOAD_DELAY_MS","LINE_WIDTHS","LINE_COUNT","useElapsed","elapsed","setElapsed","delayMs","FilePreviewLoaderSkeleton","isShown","isSlow","VisuallyHidden","Skeleton","index","Typography","FilePreviewLoader","HtmlThumbnail","reportSource","onSource","reportError","EMPTY","useObjectUrl","state","setState","isEnabled","useImageUrlSource","ImageThumbnail","revealClassName","useScaleToFit","size","setSize","element","observer","entry","scale","designWidth","ScaledPage","useRef","designHeight","PAGE_DESIGN_WIDTH","escapeAttribute","value","frameDocument","page","HtmlPreview","FIT_CLASS","hasPixels","image","ImagePreview","imageRef","setImage","useCallback","settle","event","fit","DESIGN_WIDTH","MarkdownPage","MarkdownPreview","revealedKeys","initialLoadedKey","key","usePreviewReveal","revealFrameRef","loadedKey","setLoadedKey","failedKey","setFailedKey","prevKey","setPrevKey","cancelReveal","markLoaded","markFailed","SURFACE_STYLE","THUMBNAIL_WIDTH","MAX_PIXEL_RATIO","canObserveVisibility","THUMBNAILS","GENERATED_KINDS","sourcesBySrc","sourcesByBlob","blobIdCounter","blobIds","fileIdentity","id","readCachedSource","writeCachedSource","FileThumbnailContext","useFileThumbnailContext","FileThumbnail","pendingFileBlob","hasFile","Thumbnail","previewImageUrl","identity","observeRef","isVisible","node","produced","setProduced","failedIdentity","setFailedIdentity","prevIdentity","setPrevIdentity","seenIdentity","setSeenIdentity","availableKey","reportedAvailableRef","reportLoadAvailable","onLoadAvailable","cached","hasProduced","revealStatus","hasFailed","isUndrawable","isLoading","handleSource","next","data","onLoadFailed","handlePreviewFailed","loadBlob","shouldProduce","pixelRatio","isDrawing","reportLoadStarted","onLoadStarted","reportUndrawable","isLoaded","reportLoaded","onLoaded","FileThumbnailPreview","previewProps","FileThumbnailLoader","FileNameLabel","extensionLength","stem","FileThumbnailFallback"],"sources":["../src/lib/file-kinds.ts","../src/lib/load-file-blob.ts","../src/components/file-preview/components/html/html-renderer.tsx","../src/components/file-preview/components/lazy-renderer.tsx","../src/components/file-preview/components/media/media-renderers.tsx","../src/components/file-preview/components/renderer-boundary.tsx","../src/components/file-preview/components/wasm-sources.ts","../src/components/file-preview/hooks/use-file-preview-theme.tsx","../src/components/file-preview/file-preview.tsx","../src/components/file-thumbnail/components/html/html-thumbnail.tsx","../src/components/file-thumbnail/hooks/use-object-url.ts","../src/components/file-thumbnail/hooks/use-url-source.ts","../src/components/file-thumbnail/components/image/image-thumbnail.tsx","../src/components/file-thumbnail/components/previews/reveal-class-name.ts","../src/components/file-thumbnail/hooks/use-scale-to-fit.ts","../src/components/file-thumbnail/components/previews/scaled-page.tsx","../src/components/file-thumbnail/components/previews/html-preview.tsx","../src/components/file-thumbnail/components/previews/image-preview.tsx","../src/components/file-thumbnail/components/previews/markdown-preview.tsx","../src/components/file-thumbnail/hooks/use-preview-reveal.ts","../src/components/file-thumbnail/file-thumbnail.tsx"],"sourcesContent":["/**\n * Extensions this package can show, grouped by the renderer that draws them. `FilePreview`\n * and `FileThumbnail` both read this one table, as do `isFilePreviewSupported` and\n * `isFileThumbnailSupported`, so a type cannot be reported as supported and then shown as\n * unsupported.\n *\n * It is an allowlist on purpose: new types are added once they have been checked in their\n * renderer, rather than everything being attempted and failing as a blank page or a\n * surprise download.\n *\n * A file's `blob:` URL inherits this app's origin, so a document that can carry script is\n * only listed with a renderer that cannot run it. `html` is drawn exclusively in\n * `sandbox=\"\"` iframes: no `allow-scripts`, and an opaque origin that cannot reach the host's\n * cookies or storage. `svg` stays absent - it is drawn as an image or inline, and inline SVG\n * runs its script.\n *\n * Exported for file pickers and `accept` attributes.\n */\nexport const FILE_EXTENSIONS_BY_KIND = {\n /** Rendered by the Extend `PDFViewer` (PDFium in WASM), not the browser's own viewer. */\n pdf: ['pdf'],\n image: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'avif'],\n /** Only containers every evergreen browser plays; `mov` and `ogv` are not in that set. */\n video: ['mp4', 'webm'],\n text: ['txt'],\n /** Parsed and drawn as a table; a browser would download a framed CSV instead. */\n csv: ['csv'],\n /**\n * Rendered by `@extend-ai/react-xlsx`. Its WASM parser detects the format from the bytes,\n * and reads legacy BIFF8 `xls` as well as OOXML, so both are listed. `xlsb` is detected\n * too but has not been checked in the preview, so it waits.\n */\n spreadsheet: ['xlsx', 'xlsm', 'xls'],\n /**\n * Rendered by `docx-preview`. Legacy `doc` is a binary format no browser library renders\n * faithfully; it needs server-side conversion (e.g. to PDF) before it can be previewed.\n */\n docx: ['docx'],\n /**\n * Rendered by `@extend-ai/react-pptx`. Its WASM parser reads OOXML `pptx` and legacy binary\n * `ppt`, so both are listed. `ppsx`/`pptm` have not been checked in the preview, so they wait.\n */\n presentation: ['pptx', 'ppt'],\n /** Parsed with GitHub-flavoured Markdown and sanitised; raw HTML in the file is dropped. */\n markdown: ['md', 'markdown'],\n /** Only ever framed with `sandbox=\"\"` (see above), so its script never runs. */\n html: ['html', 'htm'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** Which renderer draws a file: a key of `FILE_EXTENSIONS_BY_KIND`. */\nexport type FileKind = keyof typeof FILE_EXTENSIONS_BY_KIND;\n\nconst KIND_BY_EXTENSION = new Map<string, FileKind>(\n (Object.keys(FILE_EXTENSIONS_BY_KIND) as FileKind[]).flatMap((kind) =>\n FILE_EXTENSIONS_BY_KIND[kind].map((extension) => [extension, kind] as const),\n ),\n);\n\n/** Lower-cased extension after the last dot, or `''` for `README` and `.env`-style names. */\nexport function getFileExtension(fileName: string): string {\n const dotIndex = fileName.lastIndexOf('.');\n\n return dotIndex > 0 ? fileName.slice(dotIndex + 1).toLowerCase() : '';\n}\n\n/**\n * The kind of `fileName`, matched case-insensitively on its last extension, or `null` when\n * this package cannot show it.\n *\n * Takes the file name rather than a URL because storage URLs are often opaque\n * (`/files/8f3a…?sig=…`) and carry no extension.\n */\nexport function getFileKind(fileName: string): FileKind | null {\n return KIND_BY_EXTENSION.get(getFileExtension(fileName)) ?? null;\n}\n\n/**\n * Whether `FilePreview` can show a file, decided from its name alone.\n *\n * Lets consumers choose before rendering - for example, offering a download link instead of\n * opening a preview panel. `FilePreview` runs the same check itself and renders\n * `FilePreviewError` for unsupported files without fetching them, so calling this first is\n * optional.\n */\nexport function isFilePreviewSupported(fileName: string): boolean {\n return getFileKind(fileName) !== null;\n}\n\n/**\n * Whether `FileThumbnail` supports a file: the same types as `FilePreview`, decided from its\n * name alone.\n *\n * Supported is not quite the same as drawn: the thumbnail draws every kind itself (a PDF's\n * first page, a workbook's first sheet, rendered Markdown, …) except video and plain text,\n * which get `FileThumbnailFallback` - as does an unsupported file, never an error.\n */\nexport function isFileThumbnailSupported(fileName: string): boolean {\n return getFileKind(fileName) !== null;\n}\n","export interface LoadFileBlobOptions {\n src?: string;\n fileBlob?: Blob;\n /** Called at failure time, so the message names the file as it is called by then. */\n getFileName: () => string;\n signal: AbortSignal;\n}\n\n/**\n * The file's bytes: `fileBlob` as is, or `src` downloaded.\n *\n * Fetched rather than handed to an engine as a URL, so a 404, a CORS refusal or a network\n * failure becomes one real error before any engine runs, and every engine reads the same\n * in-memory file. The cost is that `src` must allow CORS.\n *\n * Rejects with a `[web-file-preview]` error naming the file, or with the abort reason once\n * `signal` aborts - callers check `signal.aborted` and ignore those.\n */\nexport async function loadFileBlob({\n src,\n fileBlob,\n getFileName,\n signal,\n}: LoadFileBlobOptions): Promise<Blob> {\n if (fileBlob) {\n return fileBlob;\n }\n\n if (src === undefined) {\n throw new Error(`[web-file-preview] \"${getFileName()}\" has neither \"src\" nor \"fileBlob\".`);\n }\n\n let response: Response;\n\n try {\n response = await fetch(src, { signal });\n } catch (cause) {\n if (signal.aborted) {\n throw cause;\n }\n\n throw new Error(\n `[web-file-preview] Could not fetch \"${getFileName()}\". The server is ` +\n 'unreachable or does not allow cross-origin requests (CORS) from this origin.',\n { cause },\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `[web-file-preview] Failed to load \"${getFileName()}\": ` +\n `HTTP ${response.status} ${response.statusText}`.trim(),\n );\n }\n\n try {\n // The blob keeps the response Content-Type, which some engines rely on.\n return await response.blob();\n } catch (cause) {\n if (signal.aborted) {\n throw cause;\n }\n\n throw new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, { cause });\n }\n}\n","import type { Ref } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { FilePreviewRendererProps } from '../renderer-types';\n\n/**\n * An HTML page, framed with `sandbox=\"\"` and nothing allowed.\n *\n * The `blob:` URL carries this app's origin, so an unsandboxed frame would run the file's\n * script with the host's cookies and storage. The empty sandbox turns off script, forms,\n * popups and top navigation, and gives the page an opaque origin: it renders, and can do\n * nothing else. Do not add `allow-scripts` or `allow-same-origin` - together they let the\n * page remove its own sandbox.\n *\n * The page keeps its own colours; like PDF and Word pages, it is never re-themed.\n */\nexport function HtmlRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('bg-white', className)}\n >\n <iframe\n src={objectUrl}\n title={fileName}\n sandbox=\"\"\n referrerPolicy=\"no-referrer\"\n className=\"block size-full border-0\"\n // A sandboxed frame reports no load failure: a broken page still shows as a page.\n onLoad={onLoad}\n />\n </div>\n );\n}\n","import { lazy, useEffect, useState, type ComponentType } from 'react';\n\n/** What the lazy wrapper itself reads; the rest of the props pass through untouched. */\ninterface LazyRendererProps {\n fileName: string;\n onError: (error: Error) => void;\n}\n\n/**\n * `React.lazy` for a renderer, so the spreadsheet engine (~25 MB with its WASM) and the\n * docx parser are only downloaded by consumers that actually preview those files.\n *\n * A failed chunk load (offline, a deploy that removed the old chunk) would otherwise be\n * thrown by `lazy` into the host's error boundary. It resolves to a renderer that reports\n * it through the preview's error slot instead.\n *\n * `lazy` caches its result for good, failures included, so once the failed renderer\n * unmounts (the preview moved on to another file) a fresh `lazy` replaces it and the next\n * mount retries. Swapping any earlier would make the failing mount itself retry: a\n * component that suspends before its first commit loses its state, so it would pick up\n * the fresh `lazy` on its next render.\n */\nexport function lazyRenderer<P extends LazyRendererProps>(load: () => Promise<ComponentType<P>>) {\n type Renderer = ComponentType<P>;\n\n const createLazy = (): Renderer => {\n // `lazy` types its result against `P`'s ref variant, which a generic `P` cannot satisfy;\n // it renders the loaded component with exactly the props it is given.\n const Lazy = lazy(() =>\n load().then(\n (Loaded) => ({ default: Loaded }),\n (cause: unknown) => ({\n default: createFailedRenderer<P>(cause, () => {\n if (current === Lazy) {\n current = createLazy();\n }\n }),\n }),\n ),\n ) as unknown as Renderer;\n\n return Lazy;\n };\n let current = createLazy();\n\n return function LazyRenderer(props: P) {\n // Held per mount, so a swap while mounted cannot switch this instance to a new chunk.\n const [Loaded] = useState(() => current);\n\n return <Loaded {...props} />;\n };\n}\n\nfunction createFailedRenderer<P extends LazyRendererProps>(\n cause: unknown,\n onUnmount: () => void,\n): ComponentType<P> {\n return function FailedRenderer({ fileName, onError }: P) {\n useEffect(() => onUnmount, []);\n\n useEffect(() => {\n onError(\n new Error(\n `[web-file-preview] Could not load the viewer for \"${fileName}\". Its code chunk failed ` +\n 'to download; check the network, or reload after a deploy.',\n { cause },\n ),\n );\n }, [fileName, onError]);\n\n return null;\n };\n}\n","import { useEffect, useState, type Ref } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { FilePreviewRendererProps } from '../renderer-types';\n\n/**\n * Images, video and plain text as native elements. They replace the iframe, which gave\n * each type the browser's own page chrome and could not report a decode failure.\n */\n\nexport function ImageRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('flex items-center justify-center overflow-auto', className)}\n >\n <img\n src={objectUrl}\n alt={fileName}\n className=\"max-h-full max-w-full object-contain\"\n onLoad={onLoad}\n onError={() =>\n onError(new Error(`[web-file-preview] Could not decode \"${fileName}\" as an image.`))\n }\n />\n </div>\n );\n}\n\nexport function VideoRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('flex items-center justify-center bg-black', className)}\n >\n <video\n src={objectUrl}\n aria-label={fileName}\n controls\n className=\"max-h-full max-w-full\"\n // `loadeddata` means the first frame can be shown; `load` never fires on video.\n onLoadedData={onLoad}\n onError={() =>\n onError(\n new Error(\n `[web-file-preview] Could not play \"${fileName}\". The browser does not support its codec.`,\n ),\n )\n }\n />\n </div>\n );\n}\n\nexport function TextRenderer({\n blob,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n const [text, setText] = useState<string | null>(null);\n // Read at call time, so a renamed file or a new handler does not re-read the file.\n const handleLoad = useEventCallback(onLoad);\n const reportReadError = useEventCallback((cause: unknown) =>\n onError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`, { cause })),\n );\n\n useEffect(() => {\n let isCancelled = false;\n setText(null);\n\n // Wrapped so a synchronous throw reaches the error slot as a rejection.\n Promise.resolve()\n .then(() => blob.text())\n .then(\n (nextText) => {\n if (!isCancelled) {\n setText(nextText);\n }\n },\n (cause: unknown) => {\n if (!isCancelled) {\n reportReadError(cause);\n }\n },\n );\n\n return () => {\n isCancelled = true;\n };\n }, [blob, reportReadError]);\n\n useEffect(() => {\n if (text !== null) {\n handleLoad();\n }\n }, [text, handleLoad]);\n\n if (text === null) {\n return null;\n }\n\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('overflow-auto bg-paper-elevation-1', className)}\n >\n <pre\n aria-label={fileName}\n className=\"whitespace-pre-wrap break-words p-16 font-mono text-sm text-text-primary\"\n >\n {text}\n </pre>\n </div>\n );\n}\n","import { Component, type ReactNode } from 'react';\n\ninterface RendererBoundaryProps {\n fileName: string;\n onError: (error: Error) => void;\n children: ReactNode;\n}\n\ninterface RendererBoundaryState {\n hasFailed: boolean;\n}\n\n/**\n * Keeps a renderer that throws while rendering (a malformed workbook tripping the\n * spreadsheet engine, say) inside the preview. Without it the throw unmounts the host's\n * page; with it the preview's own error slot shows instead.\n *\n * Remount it with a `key` per file so a new file gets a fresh attempt.\n */\nexport class RendererBoundary extends Component<RendererBoundaryProps, RendererBoundaryState> {\n override state: RendererBoundaryState = { hasFailed: false };\n\n static getDerivedStateFromError(): RendererBoundaryState {\n return { hasFailed: true };\n }\n\n override componentDidCatch(cause: unknown) {\n this.props.onError(\n new Error(`[web-file-preview] Failed to render \"${this.props.fileName}\".`, { cause }),\n );\n }\n\n override render() {\n return this.state.hasFailed ? null : this.props.children;\n }\n}\n","/**\n * Where the preview's WASM engines load from, as configured by the host.\n *\n * Stored here rather than forwarded to the engines directly: importing an engine eagerly\n * would put it in every host's main bundle, instead of the lazy chunk that only loads when\n * that file type is previewed. The lazy loaders in `file-preview.tsx` read these and\n * hand them over before the engine's first use - the only point at which it accepts one.\n */\n\n/**\n * Where an engine's WASM can be fetched from. Mirrors `@extend-ai/react-xlsx`'s\n * `XlsxWasmSource` structurally so this package's public types do not import the engine.\n */\nexport type FilePreviewWasmSource =\n string | URL | Request | Response | BufferSource | WebAssembly.Module;\n\nconst configured: {\n pdf?: string;\n spreadsheet?: FilePreviewWasmSource;\n presentation?: FilePreviewWasmSource;\n docx?: FilePreviewWasmSource;\n} = {};\n\n/**\n * Tells the PDF preview where to load PDFium's WASM from. By default it comes from\n * cdn.jsdelivr.net, pinned to the engine's version. Call this once at startup, before\n * the first preview, when the host has a strict CSP or no internet access - for example\n * with `'/static/pdfium.wasm'` copied from `@embedpdf/pdfium/dist/pdfium.wasm`.\n */\nexport function setFilePreviewPdfWasmSource(url: string) {\n configured.pdf = url;\n}\n\n/**\n * Tells the `.xlsx` preview where to load its parser's WASM from. Most hosts do not need\n * this: Vite and webpack 5 copy the file automatically, because the engine references it\n * with `new URL(..., import.meta.url)`. Call it once at startup, before the first preview,\n * when that does not work - Turbopack, a CDN-hosted copy, or a strict CSP - for example\n * with `'/static/duke_sheets_wasm_bg.wasm'` copied from\n * `@extend-ai/react-xlsx/duke_sheets_wasm_bg.wasm`.\n */\nexport function setFilePreviewSpreadsheetWasmSource(source: FilePreviewWasmSource) {\n configured.spreadsheet = source;\n}\n\n/**\n * Tells the `.pptx`/`.ppt` preview where to load its parser's WASM from. Same defaults and\n * reasons as `setFilePreviewSpreadsheetWasmSource`, with\n * `@extend-ai/react-pptx/pptx_wasm_bg.wasm` as the file to copy. Prefer a URL: the parser\n * runs in a worker, and a `Response` cannot be handed to it.\n */\nexport function setFilePreviewPresentationWasmSource(source: FilePreviewWasmSource) {\n configured.presentation = source;\n}\n\n/**\n * Tells the `.docx` thumbnail where to load its parser's WASM from. Same defaults and\n * reasons as `setFilePreviewSpreadsheetWasmSource`, with\n * `@extend-ai/react-docx/docx_wasm_bg.wasm` as the file to copy. Only `FileThumbnail` uses\n * this engine; `FilePreview` lays Word pages out with `docx-preview`, which needs no WASM.\n */\nexport function setFilePreviewDocxWasmSource(source: FilePreviewWasmSource) {\n configured.docx = source;\n}\n\nexport function getConfiguredWasmSources(): Readonly<typeof configured> {\n return configured;\n}\n","import { createContext, useContext, type ReactNode } from 'react';\n\nexport type FilePreviewTheme = 'dark' | 'light';\n\n/**\n * `dark` because the design tokens only define a dark palette today; a preview with no\n * provider above it matches the chrome it sits in.\n */\nconst FilePreviewThemeContext = createContext<FilePreviewTheme>('dark');\n\nexport interface FilePreviewThemeProviderProps {\n theme: FilePreviewTheme;\n children: ReactNode;\n}\n\n/**\n * Sets the theme of every `FilePreview` below it. Mount it once near the root, next to\n * wherever the host decides its own color scheme.\n *\n * A context rather than a `FilePreview` prop: the theme belongs to the host page, not to\n * one file, and a prop would have to be threaded to every preview the host opens.\n *\n * Tokened chrome follows the `data-theme` the preview root carries. The theme is also handed\n * to engines that draw their own colors and cannot read CSS tokens - today the spreadsheet\n * grid. File content itself is never recolored: PDF, Word and slide pages stay as authored.\n */\nexport function FilePreviewThemeProvider({ theme, children }: FilePreviewThemeProviderProps) {\n return (\n <FilePreviewThemeContext.Provider value={theme}>{children}</FilePreviewThemeContext.Provider>\n );\n}\n\nexport function useFilePreviewTheme(): FilePreviewTheme {\n return useContext(FilePreviewThemeContext);\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n forwardRef,\n Suspense,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ComponentType,\n type ReactNode,\n} from 'react';\nimport { useEventCallback, useTimeout } from 'usehooks-ts';\n\nimport { getFileExtension, getFileKind, type FileKind } from '@/lib/file-kinds';\nimport { loadFileBlob } from '@/lib/load-file-blob';\nimport { Skeleton, Typography, VisuallyHidden } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { HtmlRenderer } from './components/html/html-renderer';\nimport { lazyRenderer } from './components/lazy-renderer';\nimport { ImageRenderer, TextRenderer, VideoRenderer } from './components/media/media-renderers';\nimport { RendererBoundary } from './components/renderer-boundary';\nimport type { FilePreviewRendererProps } from './components/renderer-types';\nimport { getConfiguredWasmSources } from './components/wasm-sources';\nimport { useFilePreviewTheme } from './hooks/use-file-preview-theme';\n\n// CSV is lazy too: papaparse is small, but a host previewing only PDFs should not pay for it.\nconst CsvRenderer = lazyRenderer(() =>\n import('./components/csv/csv-renderer').then((module) => module.CsvRenderer),\n);\nconst DocxRenderer = lazyRenderer(() =>\n import('./components/docx/docx-renderer').then((module) => module.DocxRenderer),\n);\n// The WASM engines each get the host's configured source as their chunk loads, which is\n// before their first use - the only point at which they accept one.\nconst SpreadsheetRenderer = lazyRenderer(() =>\n import('./components/spreadsheet/spreadsheet-renderer').then((module) => {\n module.applySpreadsheetWasmSource(getConfiguredWasmSources().spreadsheet);\n return module.SpreadsheetRenderer;\n }),\n);\n// PDFium alone is several MB of WASM, so PDF is lazy like the other engines.\nconst PdfRenderer = lazyRenderer(() =>\n import('./components/pdf/pdf-renderer').then((module) => {\n module.applyPdfiumWasmUrl(getConfiguredWasmSources().pdf);\n return module.PdfRenderer;\n }),\n);\n// react-markdown and its plugins are only downloaded by hosts that preview Markdown.\nconst MarkdownRenderer = lazyRenderer(() =>\n import('./components/markdown/markdown-renderer').then((module) => module.MarkdownRenderer),\n);\nconst PresentationRenderer = lazyRenderer(() =>\n import('./components/presentation/presentation-renderer').then((module) => {\n module.applyPresentationWasmSource(getConfiguredWasmSources().presentation);\n return module.PresentationRenderer;\n }),\n);\n\nconst RENDERERS: Record<FileKind, ComponentType<FilePreviewRendererProps>> = {\n pdf: PdfRenderer,\n image: ImageRenderer,\n video: VideoRenderer,\n text: TextRenderer,\n csv: CsvRenderer,\n spreadsheet: SpreadsheetRenderer,\n docx: DocxRenderer,\n presentation: PresentationRenderer,\n markdown: MarkdownRenderer,\n html: HtmlRenderer,\n};\n\nexport type FilePreviewStatus = 'loading' | 'loaded' | 'error';\n\ninterface FilePreviewContextValue {\n fileName: string;\n /** `blob:` URL of the downloaded file, `null` until the download finishes. */\n objectUrl: string | null;\n /** The downloaded file itself, set together with `objectUrl`. Parsing renderers read it. */\n blob: Blob | null;\n status: FilePreviewStatus;\n /** Set when `status` is `'error'`, `null` otherwise. */\n error: Error | null;\n handleLoad: () => void;\n handleError: (error: Error) => void;\n}\n\nconst FilePreviewContext = createContext<FilePreviewContextValue>(null!);\n\nfunction useFilePreviewContext(component: string) {\n const context = useContext(FilePreviewContext);\n\n if (!context) {\n throw new Error(\n `[web-file-preview] <${component}> must be used within <FilePreview>. ` +\n 'Render it as a child of the FilePreview that owns the file.',\n );\n }\n\n return context;\n}\n\ninterface FilePreviewBaseProps {\n /**\n * The original file name. Its extension decides whether the file can be previewed at\n * all (see `isFilePreviewSupported`); an unsupported one is never fetched.\n */\n fileName: string;\n /**\n * Additional CSS classes to apply\n */\n className?: string;\n /** Inner content to render inside the file preview. */\n children: ReactNode;\n /**\n * Called when the file is loaded successfully.\n */\n onLoad?: () => void;\n /**\n * Called when the file fails to load, or once when `fileName` is not a supported type.\n */\n onError?: (error: Error) => void;\n}\n\ninterface FilePreviewSrcProps {\n /**\n * URL of the file to preview. Must be same-origin or served with CORS headers that\n * allow this origin, because the file is fetched rather than framed directly.\n * Pass either `src` or `fileBlob`, never both.\n */\n src: string;\n fileBlob?: never;\n}\n\ninterface FilePreviewBlobProps {\n /**\n * The file itself, already in memory. Framed through `URL.createObjectURL`, so no\n * request is made. Its `type` should be set (a `File` from an input already has it),\n * otherwise the browser may download it instead of rendering it.\n * Pass either `src` or `fileBlob`, never both.\n */\n fileBlob: Blob;\n src?: never;\n}\n\nexport type FilePreviewProps = FilePreviewBaseProps & (FilePreviewSrcProps | FilePreviewBlobProps);\n\nfunction createUnsupportedFileError(fileName: string) {\n const extension = getFileExtension(fileName);\n const type = extension ? `\".${extension}\" files` : 'Files without an extension';\n\n return new Error(\n `[web-file-preview] Cannot preview \"${fileName}\": ${type} are not supported. ` +\n 'Check isFilePreviewSupported(fileName) before rendering FilePreview ' +\n 'to offer a download instead.',\n );\n}\n\n/**\n * Owns the load status of a file preview and shares it with `FilePreviewFile`,\n * `FilePreviewLoader` and `FilePreviewError`, so consumers compose their own\n * loading and error UI.\n *\n * The file comes from exactly one of `src` or `fileBlob`. Either way renderers get the\n * `Blob` and a `blob:` URL of it, never `src` itself. Fetching `src` up front turns a 404,\n * a CORS refusal or a network failure into a real error before any renderer runs, and\n * every renderer reads the same in-memory file. The cost is that `src` must allow CORS and\n * the whole file downloads before it shows. A `fileBlob` skips the request entirely.\n */\nexport function FilePreview({\n src,\n fileBlob,\n fileName,\n className,\n children,\n onLoad,\n onError,\n}: FilePreviewProps) {\n if (src !== undefined && fileBlob !== undefined) {\n throw new Error(\n '[web-file-preview] <FilePreview> received both \"src\" and \"fileBlob\". ' +\n 'Pass exactly one: \"src\" for a URL to fetch, or \"fileBlob\" for a file already in memory.',\n );\n }\n\n if (src === undefined && fileBlob === undefined) {\n throw new Error(\n '[web-file-preview] <FilePreview> needs a file. ' +\n 'Pass \"src\" for a URL to fetch, or \"fileBlob\" for a file already in memory.',\n );\n }\n\n const source = src ?? fileBlob;\n const isSupported = getFileKind(fileName) !== null;\n const [loadStatus, setStatus] = useState<FilePreviewStatus>('loading');\n const [loadError, setError] = useState<Error | null>(null);\n const [loaded, setLoaded] = useState<{ objectUrl: string; blob: Blob } | null>(null);\n const [prev, setPrev] = useState({ source, isSupported });\n\n // Reset during render rather than in an effect, so a new file never paints one frame\n // with the previous file's status.\n if (source !== prev.source || isSupported !== prev.isSupported) {\n setPrev({ source, isSupported });\n setStatus('loading');\n setError(null);\n setLoaded(null);\n }\n\n // Derived rather than set from the effect, so an unsupported file shows its error on\n // the first paint instead of flashing the loader.\n const unsupportedError = useMemo(\n () => (isSupported ? null : createUnsupportedFileError(fileName)),\n [isSupported, fileName],\n );\n const status: FilePreviewStatus = unsupportedError ? 'error' : loadStatus;\n const error = unsupportedError ?? loadError;\n\n // Stable, and read the latest props when called, so an inline `onLoad`/`onError` or a\n // renamed file neither refetches nor re-runs a renderer's parse, both of which key their\n // effects on these handlers.\n const handleLoad = useEventCallback(() => {\n setStatus('loaded');\n setError(null);\n onLoad?.();\n });\n\n const handleError = useEventCallback((nextError: Error) => {\n setStatus('error');\n setError(nextError);\n onError?.(nextError);\n });\n\n const reportUnsupported = useEventCallback((nextError: Error) => onError?.(nextError));\n\n /** Read at failure time, so the message names the file as it is called now. */\n const getFileName = useEventCallback(() => fileName);\n\n useEffect(() => {\n if (unsupportedError) {\n reportUnsupported(unsupportedError);\n return;\n }\n\n let createdUrl: string | null = null;\n\n const show = (blob: Blob) => {\n try {\n createdUrl = URL.createObjectURL(blob);\n setLoaded({ objectUrl: createdUrl, blob });\n } catch (cause) {\n handleError(new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, { cause }));\n }\n };\n\n // Synchronous for a blob in memory, so it shows without waiting a tick.\n if (fileBlob) {\n show(fileBlob);\n\n return () => {\n if (createdUrl) {\n URL.revokeObjectURL(createdUrl);\n }\n };\n }\n\n const controller = new AbortController();\n\n loadFileBlob({ src, getFileName, signal: controller.signal }).then(\n (blob) => {\n if (!controller.signal.aborted) {\n show(blob);\n }\n },\n (error: unknown) => {\n if (!controller.signal.aborted) {\n handleError(\n error instanceof Error\n ? error\n : new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, {\n cause: error,\n }),\n );\n }\n },\n );\n\n return () => {\n controller.abort();\n\n if (createdUrl) {\n URL.revokeObjectURL(createdUrl);\n }\n };\n }, [src, fileBlob, unsupportedError, getFileName, handleError, reportUnsupported]);\n\n const theme = useFilePreviewTheme();\n\n const contextValue = useMemo(\n () => ({\n fileName,\n objectUrl: loaded?.objectUrl ?? null,\n blob: loaded?.blob ?? null,\n status,\n error,\n handleLoad,\n handleError,\n }),\n [fileName, loaded, status, error, handleLoad, handleError],\n );\n\n return (\n <FilePreviewContext.Provider value={contextValue}>\n <div\n data-testid=\"file-preview\"\n data-status={status}\n // Scopes the design system's `theme-light:` variant to this preview.\n data-theme={theme}\n className={cn('relative size-full', className)}\n >\n {children}\n </div>\n </FilePreviewContext.Provider>\n );\n}\n\nexport interface FilePreviewFileProps {\n className?: string;\n}\n\n/**\n * The file itself, drawn by the renderer its extension calls for: the Extend PDF viewer\n * for PDF; native `<img>`, `<video>` and `<pre>` for images, video and text; a table for\n * CSV; a spreadsheet grid for Excel; laid-out pages for `.docx`; the Extend\n * `PptxViewerPreview` for PowerPoint; sanitised Markdown; and HTML in a `sandbox=\"\"` frame,\n * the only type ever framed.\n *\n * The ref is the renderer's root `HTMLDivElement`.\n */\nexport const FilePreviewFile = forwardRef<HTMLElement, FilePreviewFileProps>(\n ({ className }, ref) => {\n const { objectUrl, blob, fileName, status, handleLoad, handleError } =\n useFilePreviewContext('FilePreviewFile');\n const theme = useFilePreviewTheme();\n const kind = getFileKind(fileName);\n\n if (!objectUrl || !blob || !kind || status === 'error') {\n return null;\n }\n\n const props: FilePreviewRendererProps = {\n blob,\n objectUrl,\n fileName,\n theme,\n className: cn('size-full', status !== 'loaded' && 'invisible', className),\n onLoad: handleLoad,\n onError: handleError,\n rootRef: ref,\n };\n\n const Renderer = RENDERERS[kind];\n\n return (\n // Keyed by the URL so a new file gets a fresh boundary after a render failure.\n <RendererBoundary key={objectUrl} fileName={fileName} onError={handleError}>\n {/* `null`: the preview is still `loading`, so FilePreviewLoader already shows. */}\n <Suspense fallback={null}>\n <Renderer {...props} />\n </Suspense>\n </RendererBoundary>\n );\n },\n);\n\nFilePreviewFile.displayName = 'FilePreviewFile';\n\nexport interface FilePreviewErrorRenderProps {\n error: Error;\n}\n\nexport interface FilePreviewErrorProps {\n asChild?: boolean;\n /**\n * A render function rather than a node, so the message can depend on the error without\n * the consumer mirroring it into their own state from `onError`.\n */\n children: (props: FilePreviewErrorRenderProps) => ReactNode;\n className?: string;\n}\n\nexport const FilePreviewError = forwardRef<HTMLDivElement, FilePreviewErrorProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status, error } = useFilePreviewContext('FilePreviewError');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'error' || !error) {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n role=\"alert\"\n data-testid=\"file-preview-error\"\n className={cn('absolute inset-0', className)}\n >\n {children({ error })}\n </Component>\n );\n },\n);\n\nFilePreviewError.displayName = 'FilePreviewError';\n\n/** How long a load runs before the skeleton shows, so fast loads never flash it. */\nconst SKELETON_DELAY_MS = 300;\n/** How long a load runs before the skeleton says it is taking longer than expected. */\nconst SLOW_LOAD_DELAY_MS = 5000;\n\n// Paragraph widths alternate, so the placeholder reads as text rather than boxes.\nconst LINE_WIDTHS = ['w-11/12', 'w-full', 'w-4/5', 'w-full', 'w-2/3'] as const;\nconst LINE_COUNT = 30;\n\nfunction useElapsed(delayMs: number) {\n const [elapsed, setElapsed] = useState(false);\n useTimeout(() => setElapsed(true), delayMs);\n\n return elapsed;\n}\n\n/**\n * The loader's default content: document lines built from `Skeleton`, shown once the load\n * has run 300ms. It mounts with the loader, so every load restarts both delays.\n */\nfunction FilePreviewLoaderSkeleton({ fileName }: { fileName: string }) {\n const isShown = useElapsed(SKELETON_DELAY_MS);\n const isSlow = useElapsed(SLOW_LOAD_DELAY_MS);\n\n if (!isShown) {\n return null;\n }\n\n return (\n <div className=\"flex size-full flex-col gap-16 p-24\">\n <VisuallyHidden>Loading {fileName}</VisuallyHidden>\n <div className=\"flex min-h-0 flex-1 flex-col gap-12 overflow-hidden\">\n <Skeleton className=\"h-20 w-1/3 shrink-0\" />\n {Array.from({ length: LINE_COUNT }, (_, index) => (\n <Skeleton\n key={index}\n className={cn('h-12 shrink-0', LINE_WIDTHS[index % LINE_WIDTHS.length])}\n />\n ))}\n </div>\n {isSlow && (\n <Typography variant=\"caption-md\" className=\"text-typography-text-secondary\">\n This is taking longer than expected…\n </Typography>\n )}\n </div>\n );\n}\n\nexport interface FilePreviewLoaderProps {\n asChild?: boolean;\n /** Your own loading UI. Leave it out to get the default `Skeleton` document lines. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * Shown while the file downloads and renders, over the space the file will fill. A\n * `role=\"status\"` region; without `children` it shows `Skeleton` lines after 300ms, names\n * the file for screen readers, and adds \"This is taking longer than expected…\" after 5s.\n */\nexport const FilePreviewLoader = forwardRef<HTMLDivElement, FilePreviewLoaderProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status, fileName } = useFilePreviewContext('FilePreviewLoader');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'loading') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n role=\"status\"\n aria-live=\"polite\"\n aria-busy=\"true\"\n data-testid=\"file-preview-loader\"\n className={cn('absolute inset-0', className)}\n >\n {children ?? <FilePreviewLoaderSkeleton fileName={fileName} />}\n </Component>\n );\n },\n);\n\nFilePreviewLoader.displayName = 'FilePreviewLoader';\n","import { useEffect } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport type { FileThumbnailProducerProps } from '../thumbnail-types';\n\n/**\n * An HTML page, drawn by `HtmlPreview`'s sandboxed frames.\n *\n * From `src`, the inner frame loads the page by URL: never fetched here, so no CORS. From\n * `fileBlob`, the page's markup goes into the inner frame's `srcdoc` instead. A `blob:` URL\n * cannot work there: it belongs to the host's origin, and the outer frame - sandboxed, with\n * an opaque origin - is refused it, leaving the tile blank.\n */\nexport function HtmlThumbnail({\n src,\n fileBlob,\n fileName,\n onSource,\n onError,\n}: FileThumbnailProducerProps) {\n const reportSource = useEventCallback(onSource);\n const reportError = useEventCallback(onError);\n\n useEffect(() => {\n if (src !== undefined) {\n reportSource({ type: 'html', url: src });\n return;\n }\n\n if (!fileBlob) {\n return;\n }\n\n let isCancelled = false;\n\n // Wrapped so a synchronous throw arrives as a rejection.\n Promise.resolve()\n .then(() => fileBlob.text())\n .then(\n (html) => {\n if (!isCancelled) {\n reportSource({ type: 'html', html });\n }\n },\n (cause: unknown) => {\n if (!isCancelled) {\n reportError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`, { cause }));\n }\n },\n );\n\n return () => {\n isCancelled = true;\n };\n }, [src, fileBlob, fileName, reportSource, reportError]);\n\n return null;\n}\n","import { useEffect, useState } from 'react';\n\ninterface ObjectUrlState {\n /** `blob:` URL of the blob, `null` until the effect has created it. */\n url: string | null;\n /** `URL.createObjectURL` threw, so there is nothing to draw. */\n failed: boolean;\n}\n\nconst EMPTY: ObjectUrlState = { url: null, failed: false };\n\ninterface UseObjectUrlOptions {\n /**\n * Creates the URL only while `true`. Switching it off revokes the current URL and returns\n * to `{ url: null, failed: false }`, as a missing blob does. Defaults to `true`.\n */\n isEnabled?: boolean;\n}\n\n/**\n * A `blob:` URL for `blob`, revoked when the blob changes, `isEnabled` turns off, or the\n * component unmounts.\n *\n * Created in an effect rather than a `useMemo`: StrictMode runs the memo twice and would leak\n * the first URL, and a memo has no cleanup to revoke it in.\n */\nexport function useObjectUrl(\n blob: Blob | undefined,\n { isEnabled = true }: UseObjectUrlOptions = {},\n): ObjectUrlState {\n const [state, setState] = useState<ObjectUrlState>(EMPTY);\n\n useEffect(() => {\n if (!blob || !isEnabled) {\n setState(EMPTY);\n return;\n }\n\n let url: string;\n\n try {\n url = URL.createObjectURL(blob);\n } catch {\n setState({ url: null, failed: true });\n return;\n }\n\n setState({ url, failed: false });\n\n return () => {\n URL.revokeObjectURL(url);\n };\n }, [blob, isEnabled]);\n\n return state;\n}\n","import { useEffect } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport type { FileThumbnailProducerProps } from '../components/thumbnail-types';\n\nimport { useObjectUrl } from './use-object-url';\n\n/**\n * An image file's own URL: `src`, or a `blob:` URL of `fileBlob` that lives as long as the\n * subcomponent - which `FileThumbnail` keeps mounted for as long as it shows this file.\n *\n * Never fetches: the `<img>` loads the URL itself, so no CORS is needed.\n */\nexport function useImageUrlSource({\n src,\n fileBlob,\n fileName,\n onSource,\n onError,\n}: FileThumbnailProducerProps) {\n const objectUrl = useObjectUrl(fileBlob, { isEnabled: src === undefined });\n const url = src ?? objectUrl.url;\n const reportSource = useEventCallback(onSource);\n const reportError = useEventCallback(onError);\n\n useEffect(() => {\n if (url) {\n reportSource({ type: 'image', url });\n }\n }, [url, reportSource]);\n\n useEffect(() => {\n if (objectUrl.failed) {\n reportError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`));\n }\n }, [objectUrl.failed, fileName, reportError]);\n}\n","import { useImageUrlSource } from '../../hooks/use-url-source';\nimport type { FileThumbnailProducerProps } from '../thumbnail-types';\n\n/** An image file draws as itself. */\nexport function ImageThumbnail(props: FileThumbnailProducerProps) {\n useImageUrlSource(props);\n\n return null;\n}\n","import { cn } from '@swisper.ai/web-core';\n\nimport type { PreviewRevealStatus } from '../../hooks/use-preview-reveal';\n\n/**\n * Extend's reveal: every preview stays mounted while it loads, hidden and blurred, then\n * fades and sharpens in once drawn. Shared so image, Markdown and HTML reveal alike.\n */\nexport function revealClassName(status: PreviewRevealStatus) {\n return cn(\n 'transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none',\n status === 'loaded' ? 'opacity-100 blur-none' : 'opacity-0 blur-sm',\n );\n}\n","import { useEffect, useState, type RefObject } from 'react';\n\ninterface ScaleToFit {\n /** `0` until the container has been measured, so nothing paints at the wrong size. */\n scale: number;\n /** The container's height in design pixels: how much of the page is visible. */\n designHeight: number;\n}\n\n/**\n * How much to shrink content laid out at `designWidth` so it spans the container's width.\n *\n * Documents are laid out at a readable page width and scaled down, rather than laid out at\n * the tile's width: a 120px-wide page would wrap every line and look nothing like the file.\n */\nexport function useScaleToFit(ref: RefObject<HTMLElement | null>, designWidth: number): ScaleToFit {\n const [size, setSize] = useState({ width: 0, height: 0 });\n\n useEffect(() => {\n const element = ref.current;\n\n // jsdom has no ResizeObserver; the preview then stays unscaled, which tests don't see.\n if (!element || typeof ResizeObserver === 'undefined') {\n return;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n if (entry) {\n setSize({ width: entry.contentRect.width, height: entry.contentRect.height });\n }\n });\n\n observer.observe(element);\n\n return () => observer.disconnect();\n }, [ref]);\n\n const scale = size.width > 0 ? size.width / designWidth : 0;\n\n return { scale, designHeight: scale > 0 ? size.height / scale : 0 };\n}\n","import { useRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useScaleToFit } from '../../hooks/use-scale-to-fit';\n\ninterface ScaledPageProps {\n /** The width the content is laid out at, in CSS pixels, before it is scaled to the tile. */\n designWidth: number;\n className?: string;\n children: ReactNode;\n}\n\n/**\n * A white page laid out at `designWidth` and scaled down to the tile's width, top-left\n * anchored, cropped at the tile's bottom - the first screen of the document in miniature.\n */\nexport function ScaledPage({ designWidth, className, children }: ScaledPageProps) {\n const ref = useRef<HTMLDivElement>(null);\n const { scale, designHeight } = useScaleToFit(ref, designWidth);\n\n return (\n <div\n ref={ref}\n aria-hidden\n className={cn('pointer-events-none absolute inset-0 overflow-hidden bg-white', className)}\n >\n <div\n className=\"origin-top-left\"\n style={{\n width: designWidth,\n height: designHeight || undefined,\n transform: scale ? `scale(${scale})` : undefined,\n // Unmeasured, the page would flash at full size for a frame.\n visibility: scale ? undefined : 'hidden',\n }}\n >\n {children}\n </div>\n </div>\n );\n}\n","import { cn } from '@swisper.ai/web-core';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\nimport { ScaledPage } from './scaled-page';\n\n/** A desktop-width layout viewport: pages are designed for one, and wrap badly narrower. */\nconst PAGE_DESIGN_WIDTH = 1024;\n\nexport interface HtmlPreviewProps extends PreviewProps {\n /** The page, by URL (an `.html` file), or its markup (a table built from CSV). */\n page: { url: string } | { html: string };\n /**\n * The width the page is laid out at before it is scaled to the tile. Defaults to a desktop\n * viewport, which suits web pages; generated markup can ask for less so it stays legible.\n */\n designWidth?: number;\n}\n\nfunction escapeAttribute(value: string) {\n return value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\n/**\n * The outer frame's document: nothing but the inner frame, filling it. Built as a string for\n * `srcdoc`, so the outer frame needs no URL of its own.\n */\nfunction frameDocument(page: HtmlPreviewProps['page']) {\n const source =\n 'url' in page ? `src=\"${escapeAttribute(page.url)}\"` : `srcdoc=\"${escapeAttribute(page.html)}\"`;\n\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><style>' +\n 'html,body{margin:0;height:100%;overflow:hidden;background:#fff}' +\n 'iframe{display:block;width:100%;height:100%;border:0}' +\n '</style></head><body>' +\n `<iframe sandbox=\"\" referrerpolicy=\"no-referrer\" ${source}></iframe>` +\n '</body></html>'\n );\n}\n\n/**\n * An HTML page in miniature, through two frames, both `sandbox=\"\"`:\n *\n * - The outer frame is the tile's fixed-width \"screen\". It is laid out at `designWidth` and\n * scaled down, and its `load` fires only once the inner frame has loaded, which is the\n * reveal signal - a cross-origin inner page would report nothing to this document.\n * - The inner frame takes the file itself as `src`, so the file is never fetched or parsed\n * here; the browser loads it like any page, minus script, forms, popups and navigation,\n * and with an opaque origin that cannot reach the host's cookies or storage.\n *\n * A sandboxed frame reports no load failure: a broken URL shows the browser's error page.\n */\nexport function HtmlPreview({\n page,\n designWidth = PAGE_DESIGN_WIDTH,\n status,\n onLoad,\n className,\n}: HtmlPreviewProps) {\n return (\n <ScaledPage designWidth={designWidth} className={cn(revealClassName(status), className)}>\n <iframe\n title=\"Page preview\"\n tabIndex={-1}\n sandbox=\"\"\n srcDoc={frameDocument(page)}\n data-testid=\"file-thumbnail-preview\"\n onLoad={onLoad}\n className=\"block size-full border-0\"\n />\n </ScaledPage>\n );\n}\n","import { forwardRef, useCallback, useEffect, useRef, type SyntheticEvent } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { ImageFit } from '../thumbnail-types';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\n\nexport interface ImagePreviewProps extends PreviewProps {\n url: string;\n fit?: ImageFit;\n}\n\nconst FIT_CLASS: Record<ImageFit, string> = {\n photo: 'object-cover object-center',\n page: 'object-cover object-top',\n sheet: 'object-contain object-left-top',\n slide: 'object-contain object-center',\n};\n\n/** A `load` with no pixels (a zero-size or undecodable image) is a failure to draw. */\nfunction hasPixels(image: HTMLImageElement) {\n return image.naturalWidth > 0 && image.naturalHeight > 0;\n}\n\n/**\n * A picture, cropped to fill the tile: an image file, a `previewImageUrl`, or the page,\n * sheet or slide an engine rasterised. The ref is the `<img>`.\n */\nexport const ImagePreview = forwardRef<HTMLImageElement, ImagePreviewProps>(\n ({ url, fit = 'photo', status, onLoad, onError, className }, ref) => {\n const imageRef = useRef<HTMLImageElement | null>(null);\n\n const setImage = useCallback(\n (image: HTMLImageElement | null) => {\n imageRef.current = image;\n\n if (typeof ref === 'function') {\n ref(image);\n } else if (ref) {\n ref.current = image;\n }\n },\n [ref],\n );\n\n const settle = useCallback(\n (image: HTMLImageElement) => (hasPixels(image) ? onLoad() : onError()),\n [onLoad, onError],\n );\n\n // An image that finished loading before React attached `onLoad` (from the browser cache,\n // say) never fires the event, so check once it is mounted.\n useEffect(() => {\n const image = imageRef.current;\n\n if (image?.complete && image.currentSrc) {\n settle(image);\n }\n }, [settle, url]);\n\n return (\n <img\n ref={setImage}\n src={url}\n // The root carries the file name; the picture adds nothing to announce.\n alt=\"\"\n draggable={false}\n loading=\"lazy\"\n decoding=\"async\"\n data-testid=\"file-thumbnail-preview\"\n onLoad={(event: SyntheticEvent<HTMLImageElement>) => settle(event.currentTarget)}\n onError={onError}\n className={cn(\n 'absolute inset-0 block size-full bg-white',\n FIT_CLASS[fit],\n revealClassName(status),\n className,\n )}\n />\n );\n },\n);\n\nImagePreview.displayName = 'ImagePreview';\n","import { Suspense } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { lazyRenderer } from '../../../file-preview/components/lazy-renderer';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\nimport { ScaledPage } from './scaled-page';\n\n/** Roughly a rendered README's text column: wide enough that lines wrap as they would. */\nconst DESIGN_WIDTH = 640;\n\nconst MarkdownPage = lazyRenderer(() =>\n import('./markdown-page').then((module) => module.MarkdownPage),\n);\n\nexport interface MarkdownPreviewProps extends PreviewProps {\n markdown: string;\n fileName: string;\n}\n\n/** Rendered Markdown in miniature: the top of the document, laid out as a page. */\nexport function MarkdownPreview({\n markdown,\n fileName,\n status,\n onLoad,\n onError,\n className,\n}: MarkdownPreviewProps) {\n return (\n <ScaledPage designWidth={DESIGN_WIDTH} className={cn(revealClassName(status), className)}>\n <div data-testid=\"file-thumbnail-preview\">\n <Suspense fallback={null}>\n <MarkdownPage\n markdown={markdown}\n fileName={fileName}\n onLoad={onLoad}\n onError={() => onError()}\n />\n </Suspense>\n </div>\n </ScaledPage>\n );\n}\n","/**\n * The reveal logic of the Extend UI registry's `file-thumbnail.tsx`, adapted to report a\n * status for any preview (image, Markdown, HTML) instead of taking `isLoading` / `hasError`\n * from the caller.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type PreviewRevealStatus = 'loading' | 'loaded' | 'error';\n\n/**\n * Preview keys that have finished their reveal this session. Switching views or tabs\n * remounts thumbnails; a key in here shows at once instead of replaying the blur-in, so only\n * a picture's first load animates. Module scope because it has to outlive the component.\n */\nconst revealedKeys = new Set<string>();\n\nfunction initialLoadedKey(key: string | null) {\n return key && revealedKeys.has(key) ? key : null;\n}\n\n/**\n * Load status of the preview drawn for `key`: `loading` until the preview calls\n * `markLoaded`, then `loaded` two frames later (so the hidden state paints first and the\n * reveal has something to transition from), or `error` after `markFailed`.\n */\nexport function usePreviewReveal(key: string | null) {\n const revealFrameRef = useRef<number | null>(null);\n const [loadedKey, setLoadedKey] = useState(() => initialLoadedKey(key));\n const [failedKey, setFailedKey] = useState<string | null>(null);\n const [prevKey, setPrevKey] = useState(key);\n\n // Reset during render rather than in an effect, so a new picture never paints one frame\n // with the previous one's status.\n if (key !== prevKey) {\n setPrevKey(key);\n setLoadedKey(initialLoadedKey(key));\n }\n\n const cancelReveal = useCallback(() => {\n if (revealFrameRef.current !== null) {\n window.cancelAnimationFrame(revealFrameRef.current);\n revealFrameRef.current = null;\n }\n }, []);\n\n // A pending reveal belongs to the key it was scheduled for.\n useEffect(() => cancelReveal, [cancelReveal, key]);\n\n const markLoaded = useCallback(() => {\n if (!key || revealedKeys.has(key)) {\n if (key) {\n setLoadedKey(key);\n }\n return;\n }\n\n setFailedKey(null);\n revealedKeys.add(key);\n cancelReveal();\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = null;\n setLoadedKey(key);\n });\n });\n }, [cancelReveal, key]);\n\n const markFailed = useCallback(() => {\n if (!key) {\n return;\n }\n\n revealedKeys.delete(key);\n cancelReveal();\n setFailedKey(key);\n setLoadedKey((current) => (current === key ? null : current));\n }, [cancelReveal, key]);\n\n let status: PreviewRevealStatus = 'loading';\n\n if (key && failedKey === key) {\n status = 'error';\n } else if (key && loadedKey === key) {\n status = 'loaded';\n }\n\n return { status, markLoaded, markFailed };\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n forwardRef,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n} from 'react';\nimport { useEventCallback, useIntersectionObserver } from 'usehooks-ts';\n\nimport { getFileExtension, getFileKind, type FileKind } from '@/lib/file-kinds';\nimport { loadFileBlob } from '@/lib/load-file-blob';\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { lazyRenderer } from '../file-preview/components/lazy-renderer';\nimport { RendererBoundary } from '../file-preview/components/renderer-boundary';\nimport { getConfiguredWasmSources } from '../file-preview/components/wasm-sources';\nimport { useFilePreviewTheme } from '../file-preview/hooks/use-file-preview-theme';\n\nimport { HtmlThumbnail } from './components/html/html-thumbnail';\nimport { ImageThumbnail } from './components/image/image-thumbnail';\nimport { HtmlPreview } from './components/previews/html-preview';\nimport { ImagePreview } from './components/previews/image-preview';\nimport { MarkdownPreview } from './components/previews/markdown-preview';\nimport type {\n FileThumbnailProducerProps,\n ThumbnailSource,\n ThumbnailSourceData,\n} from './components/thumbnail-types';\nimport { usePreviewReveal, type PreviewRevealStatus } from './hooks/use-preview-reveal';\n\nexport type FileThumbnailStatus = PreviewRevealStatus;\n\n/** Checkerboard tile behind the picture, so transparent areas of an image read as transparent. */\nconst CHECKER_BG =\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAMIElEQVR4AezbS25b2RJEUYMTqPmPsVrVrc57FYANGIJkkYz7OZ9lOCGLZGRk7jQC7NzHv//++7+m/v777/811XhH23hHmx5NpUdTjXe0jXe06dFUejTVeEfbeEebHk2lR1ONd7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4qTyT3FTjHW3jHW16NJUeTTXe0Tbe0aZHU+nRVOMdbeMdbXo0lR5NNd7RNt7R+gawWqTbB4EXCAiAF2D5KAKrERAAq13UPqcRWLGxAFjxqnZC4EkCAuBJUD6GwIoEBMCKV7UTAk8SEABPgvKxvQmsur0AWPWy9kLgCQIC4AlIPoLAqgQEwKqXtRcCTxAQAE9A8pG9Cay8vQBY+bp2Q+AbAgLgG0DeRmBlAgJg5evaDYFvCAiAbwB5e28Cq2//yDPBTeWZ5KYa72gb72jTo6n0aKrxjrbxjjY9mkqPphrvaBvvaNOjqfRoqvGOtvGO1jeA1SPefgj8gYAA+AMcbyGwOgEBsPqF7fc2gR2EAmCHK9sRgS8ICIAvwHgZgR0ICIAdrmxHBL4gIAC+AOPlvQnssr0A2OXS9kTgEwIC4BMoXkJgFwICYJdL2xOBTwgIgE+geGlvAjttLwB2urZdEfhAQAB8AOJXBHYiIAB2urZdEfhAQAB8AOLXvQnstv0jzwQ3lWeSm2q8o228o02PptKjqcY72sY72vRoKj2aaryjbbyjTY+m0qOpxjvaxjta3wB2i3z7IvAbAQHwGwz/RGA3AgJgt4vb90sCO74hAHa8up0R+ElAAPwE4QcCOxIQADte3c4I/CQgAH6C8GNvArtuLwB2vby9EfiPgAD4D4K/COxKQADsenl7I/AfAQHwHwR/9yaw8/YCYOfr2317AgJg+/8CAOxMQADsfH27b09AAGz/X2BvALtv/38AAAD//xLPItAAAAAGSURBVAMAOitaB8Pc+tcAAAAASUVORK5CYII=';\n\n/** The loader's and the fallback's shared surface, so a load that fails only stops pulsing. */\nconst SURFACE_STYLE = { backgroundImage: `url(${CHECKER_BG})` };\n\n/**\n * Rasterised thumbnails are drawn this wide, in CSS pixels: sharp in tiles up to about this\n * size, and small enough that a gallery of data URLs stays cheap.\n */\nconst THUMBNAIL_WIDTH = 320;\n\n/** Past 2x the extra pixels are invisible at tile size, and cost memory per cached tile. */\nconst MAX_PIXEL_RATIO = 2;\n\n/**\n * Without `IntersectionObserver` (jsdom, very old browsers) there is no way to tell, so every\n * tile counts as on screen and loads when it mounts.\n */\nfunction canObserveVisibility() {\n return typeof window !== 'undefined' && 'IntersectionObserver' in window;\n}\n\n// Each engine arrives in its own chunk, only for hosts that show that type. The WASM engines\n// get the host's configured source as their chunk loads, before first use - the only point\n// at which they accept one (see `file-preview.tsx`).\nconst PdfThumbnail = lazyRenderer(() =>\n import('./components/pdf/pdf-thumbnail').then((module) => {\n module.applyPdfiumWasmUrl(getConfiguredWasmSources().pdf);\n return module.PdfThumbnail;\n }),\n);\nconst SpreadsheetThumbnail = lazyRenderer(() =>\n import('./components/spreadsheet/spreadsheet-thumbnail').then((module) => {\n module.applySpreadsheetThumbnailWasmSource(getConfiguredWasmSources().spreadsheet);\n return module.SpreadsheetThumbnail;\n }),\n);\nconst PresentationThumbnail = lazyRenderer(() =>\n import('./components/presentation/presentation-thumbnail').then((module) => {\n module.applyPresentationThumbnailWasmSource(getConfiguredWasmSources().presentation);\n return module.PresentationThumbnail;\n }),\n);\nconst DocxThumbnail = lazyRenderer(() =>\n import('./components/docx/docx-thumbnail').then((module) => {\n module.applyDocxThumbnailWasmSource(getConfiguredWasmSources().docx);\n return module.DocxThumbnail;\n }),\n);\nconst MarkdownThumbnail = lazyRenderer(() =>\n import('./components/markdown/markdown-thumbnail').then((module) => module.MarkdownThumbnail),\n);\nconst CsvThumbnail = lazyRenderer(() =>\n import('./components/csv/csv-thumbnail').then((module) => module.CsvThumbnail),\n);\n\n/**\n * The subcomponent that turns each kind into a picture, like `RENDERERS` in\n * `file-preview.tsx`. `null` kinds get the fallback: a video's first frame would need the\n * whole file seeked and decoded per tile, and plain text reads no better small than the name.\n */\nconst THUMBNAILS: Record<FileKind, ComponentType<FileThumbnailProducerProps> | null> = {\n image: ImageThumbnail,\n html: HtmlThumbnail,\n pdf: PdfThumbnail,\n spreadsheet: SpreadsheetThumbnail,\n presentation: PresentationThumbnail,\n docx: DocxThumbnail,\n markdown: MarkdownThumbnail,\n csv: CsvThumbnail,\n video: null,\n text: null,\n};\n\n/**\n * Kinds whose picture is generated from the file's bytes, and so worth keeping: a remounted\n * tile (a view or tab switch) shows the cached picture instead of parsing the file again.\n * Images and HTML are not cached here; the browser caches their URLs itself.\n */\nconst GENERATED_KINDS = new Set<FileKind>([\n 'pdf',\n 'spreadsheet',\n 'presentation',\n 'docx',\n 'markdown',\n 'csv',\n]);\n\n// Session caches of generated pictures, by URL and by in-memory file. The `WeakMap` lets a\n// `Blob` and its picture be collected together; `src` entries live for the session, one\n// small data URL each.\nconst sourcesBySrc = new Map<string, ThumbnailSource>();\nconst sourcesByBlob = new WeakMap<Blob, ThumbnailSource>();\n\nlet blobIdCounter = 0;\nconst blobIds = new WeakMap<Blob, number>();\n\n/** A stable string for a file, for keys: the URL, or an id per in-memory `Blob`. */\nfunction fileIdentity(src: string | undefined, fileBlob: Blob | undefined) {\n if (src !== undefined) {\n return `src:${src}`;\n }\n\n if (!fileBlob) {\n return 'none';\n }\n\n let id = blobIds.get(fileBlob);\n\n if (id === undefined) {\n blobIdCounter += 1;\n id = blobIdCounter;\n blobIds.set(fileBlob, id);\n }\n\n return `blob:${id}`;\n}\n\nfunction readCachedSource(src: string | undefined, fileBlob: Blob | undefined) {\n return src !== undefined ? sourcesBySrc.get(src) : fileBlob && sourcesByBlob.get(fileBlob);\n}\n\nfunction writeCachedSource(\n src: string | undefined,\n fileBlob: Blob | undefined,\n source: ThumbnailSource,\n) {\n if (src !== undefined) {\n sourcesBySrc.set(src, source);\n } else if (fileBlob) {\n sourcesByBlob.set(fileBlob, source);\n }\n}\n\ninterface FileThumbnailContextValue {\n fileName: string;\n /** What `FileThumbnailPreview` draws, `null` until there is a picture. */\n source: ThumbnailSource | null;\n status: FileThumbnailStatus;\n markLoaded: () => void;\n markFailed: () => void;\n}\n\nconst FileThumbnailContext = createContext<FileThumbnailContextValue>(null!);\n\nfunction useFileThumbnailContext(component: string) {\n const context = useContext(FileThumbnailContext);\n\n if (!context) {\n throw new Error(\n `[web-file-preview] <${component}> must be used within <FileThumbnail>. ` +\n 'Render it as a child of the FileThumbnail that owns the file.',\n );\n }\n\n return context;\n}\n\ninterface FileThumbnailBaseProps {\n /**\n * The original file name. Its extension picks how the file is drawn (see\n * `isFileThumbnailSupported`), and labels the fallback.\n */\n fileName: string;\n /**\n * A picture of the file rendered elsewhere - a first page from your server, say. Drawn\n * instead of the file for any kind, and nothing is fetched or parsed: use it when you\n * already have one, or to spare the browser the engines in a long list.\n */\n previewImageUrl?: string;\n /**\n * Shows `FileThumbnailLoader` whatever the file, and holds off drawing it, while your own\n * pipeline is still producing `previewImageUrl`. Without it the thumbnail would start\n * drawing the file itself, then jump to your picture.\n */\n isLoading?: boolean;\n /**\n * Additional CSS classes to apply\n */\n className?: string;\n /** `FileThumbnailPreview`, `FileThumbnailLoader` and `FileThumbnailFallback`. */\n children: ReactNode;\n /**\n * Called the first time the tile is on screen for this `fileName` and `src`, whatever the\n * file, `fileBlob` or `isLoading`: the moment to start getting a file you pass as\n * `fileBlob={null}` until it arrives. Not called again when it scrolls away and returns.\n */\n onLoadAvailable?: () => void;\n /**\n * Called when the tile starts drawing the file: once it is on screen, has the file and\n * `isLoading` is off. Called again if it scrolls away before the picture is drawn and\n * returns, since the work restarts. A picture generated earlier this session (a PDF page,\n * say) shows at once and never calls it.\n */\n onLoadStarted?: () => void;\n /**\n * Called once the picture has drawn and the tile shows it, including a picture generated\n * earlier this session, which shows at once without `onLoadStarted`.\n */\n onLoaded?: () => void;\n /**\n * Called whenever the fallback takes over, and only then: the file failed to load or draw,\n * or it is a kind the tile never draws (video, plain text, an unsupported type), reported\n * once as the tile first paints. A `null` `fileBlob` is a file still on its way, never a\n * failure.\n */\n onLoadFailed?: (error: Error) => void;\n}\n\ninterface FileThumbnailSrcProps {\n /**\n * URL of the file. Images and HTML pages load from it directly (no CORS needed). Every other\n * kind is fetched and parsed in the browser, so like `FilePreview`'s `src` it must be\n * same-origin or allow this origin through CORS - otherwise the tile falls back.\n * Pass either `src` or `fileBlob`, never both.\n */\n src: string;\n fileBlob?: never;\n}\n\ninterface FileThumbnailBlobProps {\n /**\n * The file itself, already in memory. Nothing is fetched. `null` while your app is still\n * getting it: the tile shows `FileThumbnailLoader`, and draws the file once it arrives.\n * Pass either `src` or `fileBlob`, never both.\n */\n fileBlob: Blob | null | undefined;\n src?: never;\n}\n\nexport type FileThumbnailProps = FileThumbnailBaseProps &\n (FileThumbnailSrcProps | FileThumbnailBlobProps);\n\n/**\n * A small tile standing for a file. Owns the picture and its load status and shares them\n * with `FileThumbnailPreview`, `FileThumbnailLoader` and `FileThumbnailFallback`, which\n * each render only in their state, so consumers compose their own loading and fallback UI:\n *\n * @example ```tsx\n * <FileThumbnail fileName={name} src={url}>\n * <FileThumbnailLoader />\n * <FileThumbnailPreview />\n * <FileThumbnailFallback />\n * </FileThumbnail>\n * ```\n *\n * The picture is `previewImageUrl` when given. Otherwise a per-type subcomponent draws the\n * file: an image as itself, a PDF's first page, a workbook's first sheet, a deck's first\n * slide, a Word document's first page, rendered Markdown, an HTML page in a sandboxed frame,\n * or a CSV's first rows. Anything else - video, plain text, an unsupported type, a file that\n * fails to load or parse - is the fallback, never an error: a grid of tiles should not break\n * on one odd file.\n *\n * A `fileBlob` of `null` is a file still on its way: the tile shows the loader, not the\n * fallback, until it arrives.\n *\n * Nothing loads until the tile is on screen (in the viewport, not clipped by a scrolling\n * ancestor). Work that has not produced a picture stops when the tile scrolls away and\n * restarts when it returns; a picture already drawn stays.\n */\nexport const FileThumbnail = forwardRef<HTMLDivElement, FileThumbnailProps>(\n (\n {\n fileName,\n src,\n fileBlob: pendingFileBlob,\n previewImageUrl,\n isLoading = false,\n className,\n children,\n onLoadAvailable,\n onLoadStarted,\n onLoaded,\n onLoadFailed,\n },\n ref,\n ) => {\n // A `null` blob is on its way: nothing to draw yet, but nothing has failed either.\n const fileBlob = pendingFileBlob ?? undefined;\n const hasFile = src !== undefined || fileBlob !== undefined;\n const theme = useFilePreviewTheme();\n const kind = getFileKind(fileName);\n const Thumbnail = previewImageUrl || !kind ? null : THUMBNAILS[kind];\n const identity = `${kind ?? 'unsupported'}|${fileIdentity(src, fileBlob)}`;\n\n // Relative to the viewport, which also counts a tile clipped by a scrolling ancestor as\n // off screen. Not frozen once visible: work that has not produced a picture yet stops when\n // the tile scrolls away, so a fast scroll does not queue every tile it passed.\n const { ref: observeRef, isIntersecting: isVisible } = useIntersectionObserver({\n initialIsIntersecting: !canObserveVisibility(),\n });\n\n const rootRef = useCallback(\n (node: HTMLDivElement | null) => {\n observeRef(node);\n\n if (typeof ref === 'function') {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n },\n [observeRef, ref],\n );\n\n // What the subcomponent produced, and whether it failed, for this file only. Reset during\n // render rather than in an effect, so a new file never paints the previous one's picture.\n const [produced, setProduced] = useState<ThumbnailSource | null>(null);\n const [failedIdentity, setFailedIdentity] = useState<string | null>(null);\n const [prevIdentity, setPrevIdentity] = useState(identity);\n // The file whose tile has been on screen, so `previewImageUrl` stays up once it scrolls away.\n const [seenIdentity, setSeenIdentity] = useState<string | null>(null);\n\n if (identity !== prevIdentity) {\n setPrevIdentity(identity);\n setProduced(null);\n }\n\n if (isVisible && seenIdentity !== identity) {\n setSeenIdentity(identity);\n }\n\n // Not the blob: its arrival is what `onLoadAvailable` asks for, so it must not call it again.\n const availableKey = `${fileName}|${src ?? ''}`;\n const reportedAvailableRef = useRef<string | null>(null);\n const reportLoadAvailable = useEventCallback(() => onLoadAvailable?.());\n\n useEffect(() => {\n if (isVisible && reportedAvailableRef.current !== availableKey) {\n reportedAvailableRef.current = availableKey;\n reportLoadAvailable();\n }\n }, [isVisible, availableKey, reportLoadAvailable]);\n\n const cached = kind && GENERATED_KINDS.has(kind) ? readCachedSource(src, fileBlob) : undefined;\n const hasProduced = Boolean(produced?.key.startsWith(`${identity}|`));\n let source: ThumbnailSource | null = null;\n\n if (previewImageUrl) {\n if (isVisible || seenIdentity === identity) {\n source = { type: 'image', url: previewImageUrl, key: `preview:${previewImageUrl}` };\n }\n } else if (cached) {\n // A data URL made earlier this session: nothing to load, so it shows even off screen.\n source = cached;\n } else if (hasProduced) {\n source = produced;\n }\n\n const { status: revealStatus, markLoaded, markFailed } = usePreviewReveal(source?.key ?? null);\n const hasFailed = failedIdentity === identity;\n\n // Nothing to draw it with, whatever the file: the extension alone decides.\n const isUndrawable = !previewImageUrl && !Thumbnail;\n let status: FileThumbnailStatus;\n\n if (isLoading) {\n status = 'loading';\n } else if (isUndrawable || hasFailed) {\n // Decided here rather than after a failed load, so the fallback is the first paint.\n status = 'error';\n } else if (!source) {\n status = 'loading';\n } else {\n status = revealStatus;\n }\n\n const handleSource = useEventCallback((data: ThumbnailSourceData) => {\n const next = { ...data, key: `${identity}|${data.type}` };\n\n if (kind && GENERATED_KINDS.has(kind)) {\n writeCachedSource(src, fileBlob, next);\n }\n\n setProduced(next);\n });\n\n const handleError = useEventCallback((error: Error) => {\n setFailedIdentity(identity);\n // Surfaced for developers only; the tile itself shows the fallback, not the message.\n console.warn(error);\n onLoadFailed?.(error);\n });\n\n // The preview found it cannot draw the picture (an `<img>` error, say): same fallback,\n // same report.\n const handlePreviewFailed = useEventCallback(() => {\n markFailed();\n onLoadFailed?.(new Error(`[web-file-preview] Could not draw a thumbnail of \"${fileName}\".`));\n });\n\n /** The entry's download, handed to the lazy chunks as a prop (see `thumbnail-types.ts`). */\n const loadBlob = useCallback(\n (signal: AbortSignal) => loadFileBlob({ src, fileBlob, getFileName: () => fileName, signal }),\n // `fileName` only names errors; a rename must not restart the work.\n\n [src, fileBlob],\n );\n\n // Unmounting the subcomponent aborts its download and frees its generation slot. Once it has\n // produced, it stays: an image's blob URL lives only as long as it does.\n const shouldProduce =\n Boolean(Thumbnail) &&\n hasFile &&\n !cached &&\n !isLoading &&\n !hasFailed &&\n (isVisible || hasProduced);\n const pixelRatio = Math.min(\n typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1,\n MAX_PIXEL_RATIO,\n );\n\n // Loading with work under way, as opposed to waiting for the file, for `isLoading` or to\n // scroll on screen.\n const isDrawing = status === 'loading' && (shouldProduce || source !== null);\n const reportLoadStarted = useEventCallback(() => onLoadStarted?.());\n\n useEffect(() => {\n if (isDrawing) {\n reportLoadStarted();\n }\n }, [isDrawing, identity, reportLoadStarted]);\n\n // The fallback shows for an undrawable kind without anything failing, so report it here:\n // every fallback comes with an `onLoadFailed`.\n const reportUndrawable = useEventCallback(() =>\n onLoadFailed?.(\n new Error(\n `[web-file-preview] No thumbnail for \"${fileName}\": its type is not drawn. ` +\n 'Check isFileThumbnailSupported(fileName) to show your own tile instead.',\n ),\n ),\n );\n\n useEffect(() => {\n if (isUndrawable && !isLoading) {\n reportUndrawable();\n }\n }, [isUndrawable, isLoading, identity, reportUndrawable]);\n\n const isLoaded = status === 'loaded';\n const reportLoaded = useEventCallback(() => onLoaded?.());\n\n useEffect(() => {\n if (isLoaded) {\n reportLoaded();\n }\n }, [isLoaded, source?.key, reportLoaded]);\n\n const contextValue = useMemo(\n () => ({ fileName, source, status, markLoaded, markFailed: handlePreviewFailed }),\n [fileName, source, status, markLoaded, handlePreviewFailed],\n );\n\n return (\n <FileThumbnailContext.Provider value={contextValue}>\n <div\n ref={rootRef}\n role=\"img\"\n aria-label={fileName}\n aria-busy={status === 'loading' || undefined}\n title={fileName}\n data-testid=\"file-thumbnail\"\n data-kind={kind ?? 'unsupported'}\n data-status={status}\n // Scopes the design system's `theme-light:` variant to this thumbnail.\n data-theme={theme}\n className={cn(\n 'relative size-full overflow-hidden',\n 'user-select-no',\n 'rounded-[8px]',\n 'bg-white',\n '[contain:layout_paint]',\n className,\n )}\n >\n {shouldProduce && Thumbnail && (\n // Keyed by file, so each file gets a fresh subcomponent - and a fresh boundary\n // after an engine throws.\n <RendererBoundary key={identity} fileName={fileName} onError={handleError}>\n <Suspense fallback={null}>\n <Thumbnail\n fileName={fileName}\n src={src}\n fileBlob={fileBlob}\n loadBlob={loadBlob}\n width={THUMBNAIL_WIDTH}\n pixelRatio={pixelRatio}\n onSource={handleSource}\n onError={handleError}\n />\n </Suspense>\n </RendererBoundary>\n )}\n {children}\n </div>\n </FileThumbnailContext.Provider>\n );\n },\n);\n\nFileThumbnail.displayName = 'FileThumbnail';\n\nexport interface FileThumbnailPreviewProps {\n className?: string;\n}\n\n/**\n * The picture, filling the tile: an image cropped to cover, or a Markdown or HTML page laid\n * out at page width and scaled down. Mounted while loading too, hidden and blurred, because\n * it is what loads: without this part the tile never leaves `loading`. It fades in once\n * drawn; a picture that has already done so this session shows at once.\n *\n * The ref is the `<img>` when the picture is an image, and unset otherwise.\n */\nexport const FileThumbnailPreview = forwardRef<HTMLImageElement, FileThumbnailPreviewProps>(\n ({ className }, ref) => {\n const { fileName, source, status, markLoaded, markFailed } =\n useFileThumbnailContext('FileThumbnailPreview');\n\n if (!source || status === 'error') {\n return null;\n }\n\n const previewProps = { status, onLoad: markLoaded, onError: markFailed, className };\n\n switch (source.type) {\n case 'image':\n return (\n <ImagePreview\n key={source.key}\n ref={ref}\n url={source.url}\n fit={source.fit}\n {...previewProps}\n />\n );\n case 'markdown':\n return (\n <MarkdownPreview\n key={source.key}\n markdown={source.markdown}\n fileName={fileName}\n {...previewProps}\n />\n );\n case 'html':\n return (\n <HtmlPreview\n key={source.key}\n page={'url' in source ? { url: source.url } : { html: source.html }}\n designWidth={'html' in source ? source.designWidth : undefined}\n {...previewProps}\n />\n );\n }\n },\n);\n\nFileThumbnailPreview.displayName = 'FileThumbnailPreview';\n\nexport interface FileThumbnailLoaderProps {\n asChild?: boolean;\n /** Replaces the default pulsing surface. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * Shown while the tile waits to scroll on screen, while `fileBlob` is `null`, while the\n * picture is produced and loads, or while `isLoading` is set. It starts\n * transparent and fades in slowly, so a picture that is quick to draw never flashes it. It is\n * mounted only while loading, so each load starts its own fade.\n */\nexport const FileThumbnailLoader = forwardRef<HTMLDivElement, FileThumbnailLoaderProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status } = useFileThumbnailContext('FileThumbnailLoader');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'loading') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n // The root's `aria-busy` already announces the loading.\n aria-hidden\n data-testid=\"file-thumbnail-loader\"\n style={SURFACE_STYLE}\n className={cn(\n 'absolute inset-0',\n // The pulse animates `opacity` too, so it waits for the fade to finish.\n children === undefined &&\n 'animate-pulse [animation-delay:1300ms] motion-reduce:animate-none',\n className,\n )}\n >\n {children}\n </Component>\n );\n },\n);\n\nFileThumbnailLoader.displayName = 'FileThumbnailLoader';\n\nexport interface FileThumbnailFallbackProps {\n asChild?: boolean;\n /** Replaces the default file-name label. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * The file name, truncated in the middle so the extension stays visible: `longfilena…pdf`.\n * The stem keeps its trailing dot and takes the ellipsis; the extension never shrinks.\n */\nfunction FileNameLabel({ fileName }: { fileName: string }) {\n const extensionLength = getFileExtension(fileName).length;\n const stem = extensionLength ? fileName.slice(0, -extensionLength) : fileName;\n const extension = extensionLength ? fileName.slice(-extensionLength) : '';\n\n return (\n <Typography variant=\"body-small-low\" className={cn('flex min-w-0', 'text-black')}>\n <span className=\"truncate\">{stem}</span>\n {extension && <span className=\"shrink-0\">{extension}</span>}\n </Typography>\n );\n}\n\n/**\n * Shown when there is no picture: video, plain text, an unsupported type, or a file that\n * failed to load or draw. By default it is the loader's surface, still, labelled with the file\n * name, truncated in the middle so the extension stays visible (`longfilena…pdf`).\n */\nexport const FileThumbnailFallback = forwardRef<HTMLDivElement, FileThumbnailFallbackProps>(\n ({ asChild = false, children, className }, ref) => {\n const { fileName, status } = useFileThumbnailContext('FileThumbnailFallback');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'error') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n data-testid=\"file-thumbnail-fallback\"\n // By default the loader's surface, still, with the name on it.\n style={children === undefined ? SURFACE_STYLE : undefined}\n className={cn('absolute inset-0 flex items-center justify-center p-8', className)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,cAAW+F,GAAwB,uBAAuB;CAO5E,OAJIzG,MAAW,UAKb,kBAPgBe,IAAUC,IAAO,OAOjC;EACO;EACL,eAAY;EAEZ,OAAOC,MAAa,KAAA,IAAYyE,KAAgB,KAAA;EAChD,WAAW9J,EAAG,yDAAyDC,CAAS;EAE/E,UAAAoF,KAAY,kBAACsI,IAAD,EAAyB,YAAW,CAAA;CACxC,CAAA,IAZJ;AAcX,CACF;AAEA,GAAsB,cAAc"}
|
|
1
|
+
{"version":3,"file":"index.es.js","names":["useIntersectionObserver","useEventCallback","useTimeout","FILE_EXTENSIONS_BY_KIND","KIND_BY_EXTENSION","kind","extension","getFileExtension","dotIndex","fileName","getFileKind","isFilePreviewSupported","isFileThumbnailSupported","loadFileBlob","fileBlob","src","getFileName","response","cause","signal","HtmlRenderer","rootRef","cn","className","objectUrl","lazyRenderer","createLazy","Lazy","lazy","load","Loaded","createFailedRenderer","current","useState","props","useEffect","onUnmount","onError","ImageRenderer","VideoRenderer","onLoad","TextRenderer","text","setText","handleLoad","reportReadError","isCancelled","blob","nextText","RendererBoundary","Component","configured","setFilePreviewPdfWasmSource","url","setFilePreviewSpreadsheetWasmSource","source","setFilePreviewPresentationWasmSource","setFilePreviewDocxWasmSource","getConfiguredWasmSources","FilePreviewThemeContext","createContext","FilePreviewThemeProvider","theme","useFilePreviewTheme","useContext","CsvRenderer","module","DocxRenderer","SpreadsheetRenderer","PdfRenderer","MarkdownRenderer","RENDERERS","FilePreviewContext","useFilePreviewContext","context","component","createUnsupportedFileError","type","FilePreview","isSupported","loadStatus","setStatus","loadError","setError","loaded","setLoaded","prev","setPrev","unsupportedError","useMemo","status","error","handleError","nextError","reportUnsupported","createdUrl","show","controller","contextValue","FilePreviewFile","forwardRef","ref","Renderer","Suspense","FilePreviewError","asChild","Slot","children","SKELETON_DELAY_MS","SLOW_LOAD_DELAY_MS","LINE_WIDTHS","LINE_COUNT","useElapsed","elapsed","setElapsed","delayMs","FilePreviewLoaderSkeleton","isShown","isSlow","VisuallyHidden","Skeleton","index","Typography","FilePreviewLoader","HtmlThumbnail","reportSource","onSource","reportError","EMPTY","useObjectUrl","state","setState","isEnabled","useImageUrlSource","ImageThumbnail","revealClassName","useScaleToFit","size","setSize","element","observer","entry","scale","designWidth","ScaledPage","useRef","designHeight","PAGE_DESIGN_WIDTH","escapeAttribute","value","frameDocument","page","HtmlPreview","FIT_CLASS","hasPixels","image","ImagePreview","imageRef","setImage","useCallback","settle","event","fit","DESIGN_WIDTH","MarkdownPage","MarkdownPreview","revealedKeys","initialLoadedKey","key","usePreviewReveal","revealFrameRef","loadedKey","setLoadedKey","failedKey","setFailedKey","prevKey","setPrevKey","cancelReveal","markLoaded","markFailed","SURFACE_STYLE","THUMBNAIL_WIDTH","MAX_PIXEL_RATIO","canObserveVisibility","THUMBNAILS","GENERATED_KINDS","sourcesBySrc","sourcesByBlob","blobIdCounter","blobIds","fileIdentity","id","readCachedSource","writeCachedSource","FileThumbnailContext","useFileThumbnailContext","FileThumbnail","pendingFileBlob","hasFile","Thumbnail","previewImageUrl","identity","observeRef","isVisible","node","produced","setProduced","failedIdentity","setFailedIdentity","prevIdentity","setPrevIdentity","seenIdentity","setSeenIdentity","availableKey","reportedAvailableRef","reportLoadAvailable","onLoadAvailable","cached","hasProduced","revealStatus","hasFailed","isUndrawable","isLoading","handleSource","next","data","onLoadFailed","handlePreviewFailed","loadBlob","shouldProduce","pixelRatio","isDrawing","reportLoadStarted","onLoadStarted","reportUndrawable","isLoaded","reportLoaded","onLoaded","FileThumbnailPreview","previewProps","FileThumbnailLoader","FileNameLabel","extensionLength","stem","FileThumbnailFallback","labelClassName"],"sources":["../src/lib/file-kinds.ts","../src/lib/load-file-blob.ts","../src/components/file-preview/components/html/html-renderer.tsx","../src/components/file-preview/components/lazy-renderer.tsx","../src/components/file-preview/components/media/media-renderers.tsx","../src/components/file-preview/components/renderer-boundary.tsx","../src/components/file-preview/components/wasm-sources.ts","../src/components/file-preview/hooks/use-file-preview-theme.tsx","../src/components/file-preview/file-preview.tsx","../src/components/file-thumbnail/components/html/html-thumbnail.tsx","../src/components/file-thumbnail/hooks/use-object-url.ts","../src/components/file-thumbnail/hooks/use-url-source.ts","../src/components/file-thumbnail/components/image/image-thumbnail.tsx","../src/components/file-thumbnail/components/previews/reveal-class-name.ts","../src/components/file-thumbnail/hooks/use-scale-to-fit.ts","../src/components/file-thumbnail/components/previews/scaled-page.tsx","../src/components/file-thumbnail/components/previews/html-preview.tsx","../src/components/file-thumbnail/components/previews/image-preview.tsx","../src/components/file-thumbnail/components/previews/markdown-preview.tsx","../src/components/file-thumbnail/hooks/use-preview-reveal.ts","../src/components/file-thumbnail/file-thumbnail.tsx"],"sourcesContent":["/**\n * Extensions this package can show, grouped by the renderer that draws them. `FilePreview`\n * and `FileThumbnail` both read this one table, as do `isFilePreviewSupported` and\n * `isFileThumbnailSupported`, so a type cannot be reported as supported and then shown as\n * unsupported.\n *\n * It is an allowlist on purpose: new types are added once they have been checked in their\n * renderer, rather than everything being attempted and failing as a blank page or a\n * surprise download.\n *\n * A file's `blob:` URL inherits this app's origin, so a document that can carry script is\n * only listed with a renderer that cannot run it. `html` is drawn exclusively in\n * `sandbox=\"\"` iframes: no `allow-scripts`, and an opaque origin that cannot reach the host's\n * cookies or storage. `svg` stays absent - it is drawn as an image or inline, and inline SVG\n * runs its script.\n *\n * Exported for file pickers and `accept` attributes.\n */\nexport const FILE_EXTENSIONS_BY_KIND = {\n /** Rendered by the Extend `PDFViewer` (PDFium in WASM), not the browser's own viewer. */\n pdf: ['pdf'],\n image: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'avif'],\n /** Only containers every evergreen browser plays; `mov` and `ogv` are not in that set. */\n video: ['mp4', 'webm'],\n text: ['txt'],\n /** Parsed and drawn as a table; a browser would download a framed CSV instead. */\n csv: ['csv'],\n /**\n * Rendered by `@extend-ai/react-xlsx`. Its WASM parser detects the format from the bytes,\n * and reads legacy BIFF8 `xls` as well as OOXML, so both are listed. `xlsb` is detected\n * too but has not been checked in the preview, so it waits.\n */\n spreadsheet: ['xlsx', 'xlsm', 'xls'],\n /**\n * Rendered by `docx-preview`. Legacy `doc` is a binary format no browser library renders\n * faithfully; it needs server-side conversion (e.g. to PDF) before it can be previewed.\n */\n docx: ['docx'],\n /**\n * Rendered by `@extend-ai/react-pptx`. Its WASM parser reads OOXML `pptx` and legacy binary\n * `ppt`, so both are listed. `ppsx`/`pptm` have not been checked in the preview, so they wait.\n */\n presentation: ['pptx', 'ppt'],\n /** Parsed with GitHub-flavoured Markdown and sanitised; raw HTML in the file is dropped. */\n markdown: ['md', 'markdown'],\n /** Only ever framed with `sandbox=\"\"` (see above), so its script never runs. */\n html: ['html', 'htm'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** Which renderer draws a file: a key of `FILE_EXTENSIONS_BY_KIND`. */\nexport type FileKind = keyof typeof FILE_EXTENSIONS_BY_KIND;\n\nconst KIND_BY_EXTENSION = new Map<string, FileKind>(\n (Object.keys(FILE_EXTENSIONS_BY_KIND) as FileKind[]).flatMap((kind) =>\n FILE_EXTENSIONS_BY_KIND[kind].map((extension) => [extension, kind] as const),\n ),\n);\n\n/** Lower-cased extension after the last dot, or `''` for `README` and `.env`-style names. */\nexport function getFileExtension(fileName: string): string {\n const dotIndex = fileName.lastIndexOf('.');\n\n return dotIndex > 0 ? fileName.slice(dotIndex + 1).toLowerCase() : '';\n}\n\n/**\n * The kind of `fileName`, matched case-insensitively on its last extension, or `null` when\n * this package cannot show it.\n *\n * Takes the file name rather than a URL because storage URLs are often opaque\n * (`/files/8f3a…?sig=…`) and carry no extension.\n */\nexport function getFileKind(fileName: string): FileKind | null {\n return KIND_BY_EXTENSION.get(getFileExtension(fileName)) ?? null;\n}\n\n/**\n * Whether `FilePreview` can show a file, decided from its name alone.\n *\n * Lets consumers choose before rendering - for example, offering a download link instead of\n * opening a preview panel. `FilePreview` runs the same check itself and renders\n * `FilePreviewError` for unsupported files without fetching them, so calling this first is\n * optional.\n */\nexport function isFilePreviewSupported(fileName: string): boolean {\n return getFileKind(fileName) !== null;\n}\n\n/**\n * Whether `FileThumbnail` supports a file: the same types as `FilePreview`, decided from its\n * name alone.\n *\n * Supported is not quite the same as drawn: the thumbnail draws every kind itself (a PDF's\n * first page, a workbook's first sheet, rendered Markdown, …) except video and plain text,\n * which get `FileThumbnailFallback` - as does an unsupported file, never an error.\n */\nexport function isFileThumbnailSupported(fileName: string): boolean {\n return getFileKind(fileName) !== null;\n}\n","export interface LoadFileBlobOptions {\n src?: string;\n fileBlob?: Blob;\n /** Called at failure time, so the message names the file as it is called by then. */\n getFileName: () => string;\n signal: AbortSignal;\n}\n\n/**\n * The file's bytes: `fileBlob` as is, or `src` downloaded.\n *\n * Fetched rather than handed to an engine as a URL, so a 404, a CORS refusal or a network\n * failure becomes one real error before any engine runs, and every engine reads the same\n * in-memory file. The cost is that `src` must allow CORS.\n *\n * Rejects with a `[web-file-preview]` error naming the file, or with the abort reason once\n * `signal` aborts - callers check `signal.aborted` and ignore those.\n */\nexport async function loadFileBlob({\n src,\n fileBlob,\n getFileName,\n signal,\n}: LoadFileBlobOptions): Promise<Blob> {\n if (fileBlob) {\n return fileBlob;\n }\n\n if (src === undefined) {\n throw new Error(`[web-file-preview] \"${getFileName()}\" has neither \"src\" nor \"fileBlob\".`);\n }\n\n let response: Response;\n\n try {\n response = await fetch(src, { signal });\n } catch (cause) {\n if (signal.aborted) {\n throw cause;\n }\n\n throw new Error(\n `[web-file-preview] Could not fetch \"${getFileName()}\". The server is ` +\n 'unreachable or does not allow cross-origin requests (CORS) from this origin.',\n { cause },\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `[web-file-preview] Failed to load \"${getFileName()}\": ` +\n `HTTP ${response.status} ${response.statusText}`.trim(),\n );\n }\n\n try {\n // The blob keeps the response Content-Type, which some engines rely on.\n return await response.blob();\n } catch (cause) {\n if (signal.aborted) {\n throw cause;\n }\n\n throw new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, { cause });\n }\n}\n","import type { Ref } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { FilePreviewRendererProps } from '../renderer-types';\n\n/**\n * An HTML page, framed with `sandbox=\"\"` and nothing allowed.\n *\n * The `blob:` URL carries this app's origin, so an unsandboxed frame would run the file's\n * script with the host's cookies and storage. The empty sandbox turns off script, forms,\n * popups and top navigation, and gives the page an opaque origin: it renders, and can do\n * nothing else. Do not add `allow-scripts` or `allow-same-origin` - together they let the\n * page remove its own sandbox.\n *\n * The page keeps its own colours; like PDF and Word pages, it is never re-themed.\n */\nexport function HtmlRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('bg-white', className)}\n >\n <iframe\n src={objectUrl}\n title={fileName}\n sandbox=\"\"\n referrerPolicy=\"no-referrer\"\n className=\"block size-full border-0\"\n // A sandboxed frame reports no load failure: a broken page still shows as a page.\n onLoad={onLoad}\n />\n </div>\n );\n}\n","import { lazy, useEffect, useState, type ComponentType } from 'react';\n\n/** What the lazy wrapper itself reads; the rest of the props pass through untouched. */\ninterface LazyRendererProps {\n fileName: string;\n onError: (error: Error) => void;\n}\n\n/**\n * `React.lazy` for a renderer, so the spreadsheet engine (~25 MB with its WASM) and the\n * docx parser are only downloaded by consumers that actually preview those files.\n *\n * A failed chunk load (offline, a deploy that removed the old chunk) would otherwise be\n * thrown by `lazy` into the host's error boundary. It resolves to a renderer that reports\n * it through the preview's error slot instead.\n *\n * `lazy` caches its result for good, failures included, so once the failed renderer\n * unmounts (the preview moved on to another file) a fresh `lazy` replaces it and the next\n * mount retries. Swapping any earlier would make the failing mount itself retry: a\n * component that suspends before its first commit loses its state, so it would pick up\n * the fresh `lazy` on its next render.\n */\nexport function lazyRenderer<P extends LazyRendererProps>(load: () => Promise<ComponentType<P>>) {\n type Renderer = ComponentType<P>;\n\n const createLazy = (): Renderer => {\n // `lazy` types its result against `P`'s ref variant, which a generic `P` cannot satisfy;\n // it renders the loaded component with exactly the props it is given.\n const Lazy = lazy(() =>\n load().then(\n (Loaded) => ({ default: Loaded }),\n (cause: unknown) => ({\n default: createFailedRenderer<P>(cause, () => {\n if (current === Lazy) {\n current = createLazy();\n }\n }),\n }),\n ),\n ) as unknown as Renderer;\n\n return Lazy;\n };\n let current = createLazy();\n\n return function LazyRenderer(props: P) {\n // Held per mount, so a swap while mounted cannot switch this instance to a new chunk.\n const [Loaded] = useState(() => current);\n\n return <Loaded {...props} />;\n };\n}\n\nfunction createFailedRenderer<P extends LazyRendererProps>(\n cause: unknown,\n onUnmount: () => void,\n): ComponentType<P> {\n return function FailedRenderer({ fileName, onError }: P) {\n useEffect(() => onUnmount, []);\n\n useEffect(() => {\n onError(\n new Error(\n `[web-file-preview] Could not load the viewer for \"${fileName}\". Its code chunk failed ` +\n 'to download; check the network, or reload after a deploy.',\n { cause },\n ),\n );\n }, [fileName, onError]);\n\n return null;\n };\n}\n","import { useEffect, useState, type Ref } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { FilePreviewRendererProps } from '../renderer-types';\n\n/**\n * Images, video and plain text as native elements. They replace the iframe, which gave\n * each type the browser's own page chrome and could not report a decode failure.\n */\n\nexport function ImageRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('flex items-center justify-center overflow-auto', className)}\n >\n <img\n src={objectUrl}\n alt={fileName}\n className=\"max-h-full max-w-full object-contain\"\n onLoad={onLoad}\n onError={() =>\n onError(new Error(`[web-file-preview] Could not decode \"${fileName}\" as an image.`))\n }\n />\n </div>\n );\n}\n\nexport function VideoRenderer({\n objectUrl,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('flex items-center justify-center bg-black', className)}\n >\n <video\n src={objectUrl}\n aria-label={fileName}\n controls\n className=\"max-h-full max-w-full\"\n // `loadeddata` means the first frame can be shown; `load` never fires on video.\n onLoadedData={onLoad}\n onError={() =>\n onError(\n new Error(\n `[web-file-preview] Could not play \"${fileName}\". The browser does not support its codec.`,\n ),\n )\n }\n />\n </div>\n );\n}\n\nexport function TextRenderer({\n blob,\n fileName,\n className,\n onLoad,\n onError,\n rootRef,\n}: FilePreviewRendererProps) {\n const [text, setText] = useState<string | null>(null);\n // Read at call time, so a renamed file or a new handler does not re-read the file.\n const handleLoad = useEventCallback(onLoad);\n const reportReadError = useEventCallback((cause: unknown) =>\n onError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`, { cause })),\n );\n\n useEffect(() => {\n let isCancelled = false;\n setText(null);\n\n // Wrapped so a synchronous throw reaches the error slot as a rejection.\n Promise.resolve()\n .then(() => blob.text())\n .then(\n (nextText) => {\n if (!isCancelled) {\n setText(nextText);\n }\n },\n (cause: unknown) => {\n if (!isCancelled) {\n reportReadError(cause);\n }\n },\n );\n\n return () => {\n isCancelled = true;\n };\n }, [blob, reportReadError]);\n\n useEffect(() => {\n if (text !== null) {\n handleLoad();\n }\n }, [text, handleLoad]);\n\n if (text === null) {\n return null;\n }\n\n return (\n <div\n ref={rootRef as Ref<HTMLDivElement>}\n data-testid=\"file-preview-file\"\n className={cn('overflow-auto bg-paper-elevation-1', className)}\n >\n <pre\n aria-label={fileName}\n className=\"whitespace-pre-wrap break-words p-16 font-mono text-sm text-text-primary\"\n >\n {text}\n </pre>\n </div>\n );\n}\n","import { Component, type ReactNode } from 'react';\n\ninterface RendererBoundaryProps {\n fileName: string;\n onError: (error: Error) => void;\n children: ReactNode;\n}\n\ninterface RendererBoundaryState {\n hasFailed: boolean;\n}\n\n/**\n * Keeps a renderer that throws while rendering (a malformed workbook tripping the\n * spreadsheet engine, say) inside the preview. Without it the throw unmounts the host's\n * page; with it the preview's own error slot shows instead.\n *\n * Remount it with a `key` per file so a new file gets a fresh attempt.\n */\nexport class RendererBoundary extends Component<RendererBoundaryProps, RendererBoundaryState> {\n override state: RendererBoundaryState = { hasFailed: false };\n\n static getDerivedStateFromError(): RendererBoundaryState {\n return { hasFailed: true };\n }\n\n override componentDidCatch(cause: unknown) {\n this.props.onError(\n new Error(`[web-file-preview] Failed to render \"${this.props.fileName}\".`, { cause }),\n );\n }\n\n override render() {\n return this.state.hasFailed ? null : this.props.children;\n }\n}\n","/**\n * Where the preview's WASM engines load from, as configured by the host.\n *\n * Stored here rather than forwarded to the engines directly: importing an engine eagerly\n * would put it in every host's main bundle, instead of the lazy chunk that only loads when\n * that file type is previewed. The lazy loaders in `file-preview.tsx` read these and\n * hand them over before the engine's first use - the only point at which it accepts one.\n */\n\n/**\n * Where an engine's WASM can be fetched from. Mirrors `@extend-ai/react-xlsx`'s\n * `XlsxWasmSource` structurally so this package's public types do not import the engine.\n */\nexport type FilePreviewWasmSource =\n string | URL | Request | Response | BufferSource | WebAssembly.Module;\n\nconst configured: {\n pdf?: string;\n spreadsheet?: FilePreviewWasmSource;\n presentation?: FilePreviewWasmSource;\n docx?: FilePreviewWasmSource;\n} = {};\n\n/**\n * Tells the PDF preview where to load PDFium's WASM from. By default it comes from\n * cdn.jsdelivr.net, pinned to the engine's version. Call this once at startup, before\n * the first preview, when the host has a strict CSP or no internet access - for example\n * with `'/static/pdfium.wasm'` copied from `@embedpdf/pdfium/dist/pdfium.wasm`.\n */\nexport function setFilePreviewPdfWasmSource(url: string) {\n configured.pdf = url;\n}\n\n/**\n * Tells the `.xlsx` preview where to load its parser's WASM from. Most hosts do not need\n * this: Vite and webpack 5 copy the file automatically, because the engine references it\n * with `new URL(..., import.meta.url)`. Call it once at startup, before the first preview,\n * when that does not work - Turbopack, a CDN-hosted copy, or a strict CSP - for example\n * with `'/static/duke_sheets_wasm_bg.wasm'` copied from\n * `@extend-ai/react-xlsx/duke_sheets_wasm_bg.wasm`.\n */\nexport function setFilePreviewSpreadsheetWasmSource(source: FilePreviewWasmSource) {\n configured.spreadsheet = source;\n}\n\n/**\n * Tells the `.pptx`/`.ppt` preview where to load its parser's WASM from. Same defaults and\n * reasons as `setFilePreviewSpreadsheetWasmSource`, with\n * `@extend-ai/react-pptx/pptx_wasm_bg.wasm` as the file to copy. Prefer a URL: the parser\n * runs in a worker, and a `Response` cannot be handed to it.\n */\nexport function setFilePreviewPresentationWasmSource(source: FilePreviewWasmSource) {\n configured.presentation = source;\n}\n\n/**\n * Tells the `.docx` thumbnail where to load its parser's WASM from. Same defaults and\n * reasons as `setFilePreviewSpreadsheetWasmSource`, with\n * `@extend-ai/react-docx/docx_wasm_bg.wasm` as the file to copy. Only `FileThumbnail` uses\n * this engine; `FilePreview` lays Word pages out with `docx-preview`, which needs no WASM.\n */\nexport function setFilePreviewDocxWasmSource(source: FilePreviewWasmSource) {\n configured.docx = source;\n}\n\nexport function getConfiguredWasmSources(): Readonly<typeof configured> {\n return configured;\n}\n","import { createContext, useContext, type ReactNode } from 'react';\n\nexport type FilePreviewTheme = 'dark' | 'light';\n\n/**\n * `dark` because the design tokens only define a dark palette today; a preview with no\n * provider above it matches the chrome it sits in.\n */\nconst FilePreviewThemeContext = createContext<FilePreviewTheme>('dark');\n\nexport interface FilePreviewThemeProviderProps {\n theme: FilePreviewTheme;\n children: ReactNode;\n}\n\n/**\n * Sets the theme of every `FilePreview` below it. Mount it once near the root, next to\n * wherever the host decides its own color scheme.\n *\n * A context rather than a `FilePreview` prop: the theme belongs to the host page, not to\n * one file, and a prop would have to be threaded to every preview the host opens.\n *\n * Tokened chrome follows the `data-theme` the preview root carries. The theme is also handed\n * to engines that draw their own colors and cannot read CSS tokens - today the spreadsheet\n * grid. File content itself is never recolored: PDF, Word and slide pages stay as authored.\n */\nexport function FilePreviewThemeProvider({ theme, children }: FilePreviewThemeProviderProps) {\n return (\n <FilePreviewThemeContext.Provider value={theme}>{children}</FilePreviewThemeContext.Provider>\n );\n}\n\nexport function useFilePreviewTheme(): FilePreviewTheme {\n return useContext(FilePreviewThemeContext);\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n forwardRef,\n Suspense,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ComponentType,\n type ReactNode,\n} from 'react';\nimport { useEventCallback, useTimeout } from 'usehooks-ts';\n\nimport { getFileExtension, getFileKind, type FileKind } from '@/lib/file-kinds';\nimport { loadFileBlob } from '@/lib/load-file-blob';\nimport { Skeleton, Typography, VisuallyHidden } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { HtmlRenderer } from './components/html/html-renderer';\nimport { lazyRenderer } from './components/lazy-renderer';\nimport { ImageRenderer, TextRenderer, VideoRenderer } from './components/media/media-renderers';\nimport { RendererBoundary } from './components/renderer-boundary';\nimport type { FilePreviewRendererProps } from './components/renderer-types';\nimport { getConfiguredWasmSources } from './components/wasm-sources';\nimport { useFilePreviewTheme } from './hooks/use-file-preview-theme';\n\n// CSV is lazy too: papaparse is small, but a host previewing only PDFs should not pay for it.\nconst CsvRenderer = lazyRenderer(() =>\n import('./components/csv/csv-renderer').then((module) => module.CsvRenderer),\n);\nconst DocxRenderer = lazyRenderer(() =>\n import('./components/docx/docx-renderer').then((module) => module.DocxRenderer),\n);\n// The WASM engines each get the host's configured source as their chunk loads, which is\n// before their first use - the only point at which they accept one.\nconst SpreadsheetRenderer = lazyRenderer(() =>\n import('./components/spreadsheet/spreadsheet-renderer').then((module) => {\n module.applySpreadsheetWasmSource(getConfiguredWasmSources().spreadsheet);\n return module.SpreadsheetRenderer;\n }),\n);\n// PDFium alone is several MB of WASM, so PDF is lazy like the other engines.\nconst PdfRenderer = lazyRenderer(() =>\n import('./components/pdf/pdf-renderer').then((module) => {\n module.applyPdfiumWasmUrl(getConfiguredWasmSources().pdf);\n return module.PdfRenderer;\n }),\n);\n// react-markdown and its plugins are only downloaded by hosts that preview Markdown.\nconst MarkdownRenderer = lazyRenderer(() =>\n import('./components/markdown/markdown-renderer').then((module) => module.MarkdownRenderer),\n);\nconst PresentationRenderer = lazyRenderer(() =>\n import('./components/presentation/presentation-renderer').then((module) => {\n module.applyPresentationWasmSource(getConfiguredWasmSources().presentation);\n return module.PresentationRenderer;\n }),\n);\n\nconst RENDERERS: Record<FileKind, ComponentType<FilePreviewRendererProps>> = {\n pdf: PdfRenderer,\n image: ImageRenderer,\n video: VideoRenderer,\n text: TextRenderer,\n csv: CsvRenderer,\n spreadsheet: SpreadsheetRenderer,\n docx: DocxRenderer,\n presentation: PresentationRenderer,\n markdown: MarkdownRenderer,\n html: HtmlRenderer,\n};\n\nexport type FilePreviewStatus = 'loading' | 'loaded' | 'error';\n\ninterface FilePreviewContextValue {\n fileName: string;\n /** `blob:` URL of the downloaded file, `null` until the download finishes. */\n objectUrl: string | null;\n /** The downloaded file itself, set together with `objectUrl`. Parsing renderers read it. */\n blob: Blob | null;\n status: FilePreviewStatus;\n /** Set when `status` is `'error'`, `null` otherwise. */\n error: Error | null;\n handleLoad: () => void;\n handleError: (error: Error) => void;\n}\n\nconst FilePreviewContext = createContext<FilePreviewContextValue>(null!);\n\nfunction useFilePreviewContext(component: string) {\n const context = useContext(FilePreviewContext);\n\n if (!context) {\n throw new Error(\n `[web-file-preview] <${component}> must be used within <FilePreview>. ` +\n 'Render it as a child of the FilePreview that owns the file.',\n );\n }\n\n return context;\n}\n\ninterface FilePreviewBaseProps {\n /**\n * The original file name. Its extension decides whether the file can be previewed at\n * all (see `isFilePreviewSupported`); an unsupported one is never fetched.\n */\n fileName: string;\n /**\n * Additional CSS classes to apply\n */\n className?: string;\n /** Inner content to render inside the file preview. */\n children: ReactNode;\n /**\n * Called when the file is loaded successfully.\n */\n onLoad?: () => void;\n /**\n * Called when the file fails to load, or once when `fileName` is not a supported type.\n */\n onError?: (error: Error) => void;\n}\n\ninterface FilePreviewSrcProps {\n /**\n * URL of the file to preview. Must be same-origin or served with CORS headers that\n * allow this origin, because the file is fetched rather than framed directly.\n * Pass either `src` or `fileBlob`, never both.\n */\n src: string;\n fileBlob?: never;\n}\n\ninterface FilePreviewBlobProps {\n /**\n * The file itself, already in memory. Framed through `URL.createObjectURL`, so no\n * request is made. Its `type` should be set (a `File` from an input already has it),\n * otherwise the browser may download it instead of rendering it.\n * Pass either `src` or `fileBlob`, never both.\n */\n fileBlob: Blob;\n src?: never;\n}\n\nexport type FilePreviewProps = FilePreviewBaseProps & (FilePreviewSrcProps | FilePreviewBlobProps);\n\nfunction createUnsupportedFileError(fileName: string) {\n const extension = getFileExtension(fileName);\n const type = extension ? `\".${extension}\" files` : 'Files without an extension';\n\n return new Error(\n `[web-file-preview] Cannot preview \"${fileName}\": ${type} are not supported. ` +\n 'Check isFilePreviewSupported(fileName) before rendering FilePreview ' +\n 'to offer a download instead.',\n );\n}\n\n/**\n * Owns the load status of a file preview and shares it with `FilePreviewFile`,\n * `FilePreviewLoader` and `FilePreviewError`, so consumers compose their own\n * loading and error UI.\n *\n * The file comes from exactly one of `src` or `fileBlob`. Either way renderers get the\n * `Blob` and a `blob:` URL of it, never `src` itself. Fetching `src` up front turns a 404,\n * a CORS refusal or a network failure into a real error before any renderer runs, and\n * every renderer reads the same in-memory file. The cost is that `src` must allow CORS and\n * the whole file downloads before it shows. A `fileBlob` skips the request entirely.\n */\nexport function FilePreview({\n src,\n fileBlob,\n fileName,\n className,\n children,\n onLoad,\n onError,\n}: FilePreviewProps) {\n if (src !== undefined && fileBlob !== undefined) {\n throw new Error(\n '[web-file-preview] <FilePreview> received both \"src\" and \"fileBlob\". ' +\n 'Pass exactly one: \"src\" for a URL to fetch, or \"fileBlob\" for a file already in memory.',\n );\n }\n\n if (src === undefined && fileBlob === undefined) {\n throw new Error(\n '[web-file-preview] <FilePreview> needs a file. ' +\n 'Pass \"src\" for a URL to fetch, or \"fileBlob\" for a file already in memory.',\n );\n }\n\n const source = src ?? fileBlob;\n const isSupported = getFileKind(fileName) !== null;\n const [loadStatus, setStatus] = useState<FilePreviewStatus>('loading');\n const [loadError, setError] = useState<Error | null>(null);\n const [loaded, setLoaded] = useState<{ objectUrl: string; blob: Blob } | null>(null);\n const [prev, setPrev] = useState({ source, isSupported });\n\n // Reset during render rather than in an effect, so a new file never paints one frame\n // with the previous file's status.\n if (source !== prev.source || isSupported !== prev.isSupported) {\n setPrev({ source, isSupported });\n setStatus('loading');\n setError(null);\n setLoaded(null);\n }\n\n // Derived rather than set from the effect, so an unsupported file shows its error on\n // the first paint instead of flashing the loader.\n const unsupportedError = useMemo(\n () => (isSupported ? null : createUnsupportedFileError(fileName)),\n [isSupported, fileName],\n );\n const status: FilePreviewStatus = unsupportedError ? 'error' : loadStatus;\n const error = unsupportedError ?? loadError;\n\n // Stable, and read the latest props when called, so an inline `onLoad`/`onError` or a\n // renamed file neither refetches nor re-runs a renderer's parse, both of which key their\n // effects on these handlers.\n const handleLoad = useEventCallback(() => {\n setStatus('loaded');\n setError(null);\n onLoad?.();\n });\n\n const handleError = useEventCallback((nextError: Error) => {\n setStatus('error');\n setError(nextError);\n onError?.(nextError);\n });\n\n const reportUnsupported = useEventCallback((nextError: Error) => onError?.(nextError));\n\n /** Read at failure time, so the message names the file as it is called now. */\n const getFileName = useEventCallback(() => fileName);\n\n useEffect(() => {\n if (unsupportedError) {\n reportUnsupported(unsupportedError);\n return;\n }\n\n let createdUrl: string | null = null;\n\n const show = (blob: Blob) => {\n try {\n createdUrl = URL.createObjectURL(blob);\n setLoaded({ objectUrl: createdUrl, blob });\n } catch (cause) {\n handleError(new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, { cause }));\n }\n };\n\n // Synchronous for a blob in memory, so it shows without waiting a tick.\n if (fileBlob) {\n show(fileBlob);\n\n return () => {\n if (createdUrl) {\n URL.revokeObjectURL(createdUrl);\n }\n };\n }\n\n const controller = new AbortController();\n\n loadFileBlob({ src, getFileName, signal: controller.signal }).then(\n (blob) => {\n if (!controller.signal.aborted) {\n show(blob);\n }\n },\n (error: unknown) => {\n if (!controller.signal.aborted) {\n handleError(\n error instanceof Error\n ? error\n : new Error(`[web-file-preview] Failed to read \"${getFileName()}\".`, {\n cause: error,\n }),\n );\n }\n },\n );\n\n return () => {\n controller.abort();\n\n if (createdUrl) {\n URL.revokeObjectURL(createdUrl);\n }\n };\n }, [src, fileBlob, unsupportedError, getFileName, handleError, reportUnsupported]);\n\n const theme = useFilePreviewTheme();\n\n const contextValue = useMemo(\n () => ({\n fileName,\n objectUrl: loaded?.objectUrl ?? null,\n blob: loaded?.blob ?? null,\n status,\n error,\n handleLoad,\n handleError,\n }),\n [fileName, loaded, status, error, handleLoad, handleError],\n );\n\n return (\n <FilePreviewContext.Provider value={contextValue}>\n <div\n data-slot=\"file-preview\"\n data-testid=\"file-preview\"\n data-status={status}\n // Scopes the design system's `theme-light:` variant to this preview.\n data-theme={theme}\n className={cn('group/file-preview relative size-full', className)}\n >\n {children}\n </div>\n </FilePreviewContext.Provider>\n );\n}\n\nexport interface FilePreviewFileProps {\n className?: string;\n}\n\n/**\n * The file itself, drawn by the renderer its extension calls for: the Extend PDF viewer\n * for PDF; native `<img>`, `<video>` and `<pre>` for images, video and text; a table for\n * CSV; a spreadsheet grid for Excel; laid-out pages for `.docx`; the Extend\n * `PptxViewerPreview` for PowerPoint; sanitised Markdown; and HTML in a `sandbox=\"\"` frame,\n * the only type ever framed.\n *\n * The ref is the renderer's root `HTMLDivElement`.\n */\nexport const FilePreviewFile = forwardRef<HTMLElement, FilePreviewFileProps>(\n ({ className }, ref) => {\n const { objectUrl, blob, fileName, status, handleLoad, handleError } =\n useFilePreviewContext('FilePreviewFile');\n const theme = useFilePreviewTheme();\n const kind = getFileKind(fileName);\n\n if (!objectUrl || !blob || !kind || status === 'error') {\n return null;\n }\n\n const props: FilePreviewRendererProps = {\n blob,\n objectUrl,\n fileName,\n theme,\n // Hidden from the root's `data-status`, so a half-rendered file never shows under the\n // loader. Only `loading` needs it: nothing renders on `error`.\n className: cn('size-full group-data-[status=loading]/file-preview:invisible', className),\n onLoad: handleLoad,\n onError: handleError,\n rootRef: ref,\n };\n\n const Renderer = RENDERERS[kind];\n\n return (\n // Keyed by the URL so a new file gets a fresh boundary after a render failure.\n <RendererBoundary key={objectUrl} fileName={fileName} onError={handleError}>\n {/* `null`: the preview is still `loading`, so FilePreviewLoader already shows. */}\n <Suspense fallback={null}>\n <Renderer {...props} />\n </Suspense>\n </RendererBoundary>\n );\n },\n);\n\nFilePreviewFile.displayName = 'FilePreviewFile';\n\nexport interface FilePreviewErrorRenderProps {\n error: Error;\n}\n\nexport interface FilePreviewErrorProps {\n asChild?: boolean;\n /**\n * A render function rather than a node, so the message can depend on the error without\n * the consumer mirroring it into their own state from `onError`.\n */\n children: (props: FilePreviewErrorRenderProps) => ReactNode;\n className?: string;\n}\n\nexport const FilePreviewError = forwardRef<HTMLDivElement, FilePreviewErrorProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status, error } = useFilePreviewContext('FilePreviewError');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'error' || !error) {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n role=\"alert\"\n data-slot=\"file-preview-error\"\n data-testid=\"file-preview-error\"\n className={cn('absolute inset-0', className)}\n >\n {children({ error })}\n </Component>\n );\n },\n);\n\nFilePreviewError.displayName = 'FilePreviewError';\n\n/** How long a load runs before the skeleton shows, so fast loads never flash it. */\nconst SKELETON_DELAY_MS = 300;\n/** How long a load runs before the skeleton says it is taking longer than expected. */\nconst SLOW_LOAD_DELAY_MS = 5000;\n\n// Paragraph widths alternate, so the placeholder reads as text rather than boxes.\nconst LINE_WIDTHS = ['w-11/12', 'w-full', 'w-4/5', 'w-full', 'w-2/3'] as const;\nconst LINE_COUNT = 30;\n\nfunction useElapsed(delayMs: number) {\n const [elapsed, setElapsed] = useState(false);\n useTimeout(() => setElapsed(true), delayMs);\n\n return elapsed;\n}\n\n/**\n * The loader's default content: document lines built from `Skeleton`, shown once the load\n * has run 300ms. It mounts with the loader, so every load restarts both delays.\n */\nfunction FilePreviewLoaderSkeleton({ fileName }: { fileName: string }) {\n const isShown = useElapsed(SKELETON_DELAY_MS);\n const isSlow = useElapsed(SLOW_LOAD_DELAY_MS);\n\n if (!isShown) {\n return null;\n }\n\n return (\n <div className=\"flex size-full flex-col gap-16 p-24\">\n <VisuallyHidden>Loading {fileName}</VisuallyHidden>\n <div className=\"flex min-h-0 flex-1 flex-col gap-12 overflow-hidden\">\n <Skeleton className=\"h-20 w-1/3 shrink-0\" />\n {Array.from({ length: LINE_COUNT }, (_, index) => (\n <Skeleton\n key={index}\n className={cn('h-12 shrink-0', LINE_WIDTHS[index % LINE_WIDTHS.length])}\n />\n ))}\n </div>\n {isSlow && (\n <Typography variant=\"caption-md\" className=\"text-typography-text-secondary\">\n This is taking longer than expected…\n </Typography>\n )}\n </div>\n );\n}\n\nexport interface FilePreviewLoaderProps {\n asChild?: boolean;\n /** Your own loading UI. Leave it out to get the default `Skeleton` document lines. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * Shown while the file downloads and renders, over the space the file will fill. A\n * `role=\"status\"` region; without `children` it shows `Skeleton` lines after 300ms, names\n * the file for screen readers, and adds \"This is taking longer than expected…\" after 5s.\n */\nexport const FilePreviewLoader = forwardRef<HTMLDivElement, FilePreviewLoaderProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status, fileName } = useFilePreviewContext('FilePreviewLoader');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'loading') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n role=\"status\"\n aria-live=\"polite\"\n aria-busy=\"true\"\n data-slot=\"file-preview-loader\"\n data-testid=\"file-preview-loader\"\n className={cn('absolute inset-0', className)}\n >\n {children ?? <FilePreviewLoaderSkeleton fileName={fileName} />}\n </Component>\n );\n },\n);\n\nFilePreviewLoader.displayName = 'FilePreviewLoader';\n","import { useEffect } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport type { FileThumbnailProducerProps } from '../thumbnail-types';\n\n/**\n * An HTML page, drawn by `HtmlPreview`'s sandboxed frames.\n *\n * From `src`, the inner frame loads the page by URL: never fetched here, so no CORS. From\n * `fileBlob`, the page's markup goes into the inner frame's `srcdoc` instead. A `blob:` URL\n * cannot work there: it belongs to the host's origin, and the outer frame - sandboxed, with\n * an opaque origin - is refused it, leaving the tile blank.\n */\nexport function HtmlThumbnail({\n src,\n fileBlob,\n fileName,\n onSource,\n onError,\n}: FileThumbnailProducerProps) {\n const reportSource = useEventCallback(onSource);\n const reportError = useEventCallback(onError);\n\n useEffect(() => {\n if (src !== undefined) {\n reportSource({ type: 'html', url: src });\n return;\n }\n\n if (!fileBlob) {\n return;\n }\n\n let isCancelled = false;\n\n // Wrapped so a synchronous throw arrives as a rejection.\n Promise.resolve()\n .then(() => fileBlob.text())\n .then(\n (html) => {\n if (!isCancelled) {\n reportSource({ type: 'html', html });\n }\n },\n (cause: unknown) => {\n if (!isCancelled) {\n reportError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`, { cause }));\n }\n },\n );\n\n return () => {\n isCancelled = true;\n };\n }, [src, fileBlob, fileName, reportSource, reportError]);\n\n return null;\n}\n","import { useEffect, useState } from 'react';\n\ninterface ObjectUrlState {\n /** `blob:` URL of the blob, `null` until the effect has created it. */\n url: string | null;\n /** `URL.createObjectURL` threw, so there is nothing to draw. */\n failed: boolean;\n}\n\nconst EMPTY: ObjectUrlState = { url: null, failed: false };\n\ninterface UseObjectUrlOptions {\n /**\n * Creates the URL only while `true`. Switching it off revokes the current URL and returns\n * to `{ url: null, failed: false }`, as a missing blob does. Defaults to `true`.\n */\n isEnabled?: boolean;\n}\n\n/**\n * A `blob:` URL for `blob`, revoked when the blob changes, `isEnabled` turns off, or the\n * component unmounts.\n *\n * Created in an effect rather than a `useMemo`: StrictMode runs the memo twice and would leak\n * the first URL, and a memo has no cleanup to revoke it in.\n */\nexport function useObjectUrl(\n blob: Blob | undefined,\n { isEnabled = true }: UseObjectUrlOptions = {},\n): ObjectUrlState {\n const [state, setState] = useState<ObjectUrlState>(EMPTY);\n\n useEffect(() => {\n if (!blob || !isEnabled) {\n setState(EMPTY);\n return;\n }\n\n let url: string;\n\n try {\n url = URL.createObjectURL(blob);\n } catch {\n setState({ url: null, failed: true });\n return;\n }\n\n setState({ url, failed: false });\n\n return () => {\n URL.revokeObjectURL(url);\n };\n }, [blob, isEnabled]);\n\n return state;\n}\n","import { useEffect } from 'react';\nimport { useEventCallback } from 'usehooks-ts';\n\nimport type { FileThumbnailProducerProps } from '../components/thumbnail-types';\n\nimport { useObjectUrl } from './use-object-url';\n\n/**\n * An image file's own URL: `src`, or a `blob:` URL of `fileBlob` that lives as long as the\n * subcomponent - which `FileThumbnail` keeps mounted for as long as it shows this file.\n *\n * Never fetches: the `<img>` loads the URL itself, so no CORS is needed.\n */\nexport function useImageUrlSource({\n src,\n fileBlob,\n fileName,\n onSource,\n onError,\n}: FileThumbnailProducerProps) {\n const objectUrl = useObjectUrl(fileBlob, { isEnabled: src === undefined });\n const url = src ?? objectUrl.url;\n const reportSource = useEventCallback(onSource);\n const reportError = useEventCallback(onError);\n\n useEffect(() => {\n if (url) {\n reportSource({ type: 'image', url });\n }\n }, [url, reportSource]);\n\n useEffect(() => {\n if (objectUrl.failed) {\n reportError(new Error(`[web-file-preview] Failed to read \"${fileName}\".`));\n }\n }, [objectUrl.failed, fileName, reportError]);\n}\n","import { useImageUrlSource } from '../../hooks/use-url-source';\nimport type { FileThumbnailProducerProps } from '../thumbnail-types';\n\n/** An image file draws as itself. */\nexport function ImageThumbnail(props: FileThumbnailProducerProps) {\n useImageUrlSource(props);\n\n return null;\n}\n","import { cn } from '@swisper.ai/web-core';\n\n/**\n * Extend's reveal: every preview stays mounted while it loads, hidden and blurred, then\n * fades and sharpens in once drawn. Shared so image, Markdown and HTML reveal alike.\n *\n * Styled from the preview's own `data-status`, so a consumer can restyle either state with the\n * same selector (`data-[status=loaded]:opacity-90`).\n */\nexport const revealClassName = cn(\n 'transition-[opacity,filter] duration-[160ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none',\n 'opacity-0 blur-sm',\n 'data-[status=loaded]:opacity-100 data-[status=loaded]:blur-none',\n);\n","import { useEffect, useState, type RefObject } from 'react';\n\ninterface ScaleToFit {\n /** `0` until the container has been measured, so nothing paints at the wrong size. */\n scale: number;\n /** The container's height in design pixels: how much of the page is visible. */\n designHeight: number;\n}\n\n/**\n * How much to shrink content laid out at `designWidth` so it spans the container's width.\n *\n * Documents are laid out at a readable page width and scaled down, rather than laid out at\n * the tile's width: a 120px-wide page would wrap every line and look nothing like the file.\n */\nexport function useScaleToFit(ref: RefObject<HTMLElement | null>, designWidth: number): ScaleToFit {\n const [size, setSize] = useState({ width: 0, height: 0 });\n\n useEffect(() => {\n const element = ref.current;\n\n // jsdom has no ResizeObserver; the preview then stays unscaled, which tests don't see.\n if (!element || typeof ResizeObserver === 'undefined') {\n return;\n }\n\n const observer = new ResizeObserver(([entry]) => {\n if (entry) {\n setSize({ width: entry.contentRect.width, height: entry.contentRect.height });\n }\n });\n\n observer.observe(element);\n\n return () => observer.disconnect();\n }, [ref]);\n\n const scale = size.width > 0 ? size.width / designWidth : 0;\n\n return { scale, designHeight: scale > 0 ? size.height / scale : 0 };\n}\n","import { useRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { PreviewRevealStatus } from '../../hooks/use-preview-reveal';\nimport { useScaleToFit } from '../../hooks/use-scale-to-fit';\n\ninterface ScaledPageProps {\n /** The width the content is laid out at, in CSS pixels, before it is scaled to the tile. */\n designWidth: number;\n /** The preview's load status, exposed as `data-status` for the reveal. */\n status: PreviewRevealStatus;\n className?: string;\n children: ReactNode;\n}\n\n/**\n * A white page laid out at `designWidth` and scaled down to the tile's width, top-left\n * anchored, cropped at the tile's bottom - the first screen of the document in miniature.\n */\nexport function ScaledPage({ designWidth, status, className, children }: ScaledPageProps) {\n const ref = useRef<HTMLDivElement>(null);\n const { scale, designHeight } = useScaleToFit(ref, designWidth);\n\n return (\n <div\n ref={ref}\n aria-hidden\n data-slot=\"file-thumbnail-preview\"\n data-status={status}\n className={cn('pointer-events-none absolute inset-0 overflow-hidden bg-white', className)}\n >\n <div\n className=\"origin-top-left\"\n style={{\n width: designWidth,\n height: designHeight || undefined,\n transform: scale ? `scale(${scale})` : undefined,\n // Unmeasured, the page would flash at full size for a frame.\n visibility: scale ? undefined : 'hidden',\n }}\n >\n {children}\n </div>\n </div>\n );\n}\n","import { cn } from '@swisper.ai/web-core';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\nimport { ScaledPage } from './scaled-page';\n\n/** A desktop-width layout viewport: pages are designed for one, and wrap badly narrower. */\nconst PAGE_DESIGN_WIDTH = 1024;\n\nexport interface HtmlPreviewProps extends PreviewProps {\n /** The page, by URL (an `.html` file), or its markup (a table built from CSV). */\n page: { url: string } | { html: string };\n /**\n * The width the page is laid out at before it is scaled to the tile. Defaults to a desktop\n * viewport, which suits web pages; generated markup can ask for less so it stays legible.\n */\n designWidth?: number;\n}\n\nfunction escapeAttribute(value: string) {\n return value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n}\n\n/**\n * The outer frame's document: nothing but the inner frame, filling it. Built as a string for\n * `srcdoc`, so the outer frame needs no URL of its own.\n */\nfunction frameDocument(page: HtmlPreviewProps['page']) {\n const source =\n 'url' in page ? `src=\"${escapeAttribute(page.url)}\"` : `srcdoc=\"${escapeAttribute(page.html)}\"`;\n\n return (\n '<!doctype html><html><head><meta charset=\"utf-8\"><style>' +\n 'html,body{margin:0;height:100%;overflow:hidden;background:#fff}' +\n 'iframe{display:block;width:100%;height:100%;border:0}' +\n '</style></head><body>' +\n `<iframe sandbox=\"\" referrerpolicy=\"no-referrer\" ${source}></iframe>` +\n '</body></html>'\n );\n}\n\n/**\n * An HTML page in miniature, through two frames, both `sandbox=\"\"`:\n *\n * - The outer frame is the tile's fixed-width \"screen\". It is laid out at `designWidth` and\n * scaled down, and its `load` fires only once the inner frame has loaded, which is the\n * reveal signal - a cross-origin inner page would report nothing to this document.\n * - The inner frame takes the file itself as `src`, so the file is never fetched or parsed\n * here; the browser loads it like any page, minus script, forms, popups and navigation,\n * and with an opaque origin that cannot reach the host's cookies or storage.\n *\n * A sandboxed frame reports no load failure: a broken URL shows the browser's error page.\n */\nexport function HtmlPreview({\n page,\n designWidth = PAGE_DESIGN_WIDTH,\n status,\n onLoad,\n className,\n}: HtmlPreviewProps) {\n return (\n <ScaledPage\n designWidth={designWidth}\n status={status}\n className={cn(revealClassName, className)}\n >\n <iframe\n title=\"Page preview\"\n tabIndex={-1}\n sandbox=\"\"\n srcDoc={frameDocument(page)}\n data-testid=\"file-thumbnail-preview\"\n onLoad={onLoad}\n className=\"block size-full border-0\"\n />\n </ScaledPage>\n );\n}\n","import { forwardRef, useCallback, useEffect, useRef, type SyntheticEvent } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { ImageFit } from '../thumbnail-types';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\n\nexport interface ImagePreviewProps extends PreviewProps {\n url: string;\n fit?: ImageFit;\n}\n\nconst FIT_CLASS: Record<ImageFit, string> = {\n photo: 'object-cover object-center',\n page: 'object-cover object-top',\n sheet: 'object-contain object-left-top',\n slide: 'object-contain object-center',\n};\n\n/** A `load` with no pixels (a zero-size or undecodable image) is a failure to draw. */\nfunction hasPixels(image: HTMLImageElement) {\n return image.naturalWidth > 0 && image.naturalHeight > 0;\n}\n\n/**\n * A picture, cropped to fill the tile: an image file, a `previewImageUrl`, or the page,\n * sheet or slide an engine rasterised. The ref is the `<img>`.\n */\nexport const ImagePreview = forwardRef<HTMLImageElement, ImagePreviewProps>(\n ({ url, fit = 'photo', status, onLoad, onError, className }, ref) => {\n const imageRef = useRef<HTMLImageElement | null>(null);\n\n const setImage = useCallback(\n (image: HTMLImageElement | null) => {\n imageRef.current = image;\n\n if (typeof ref === 'function') {\n ref(image);\n } else if (ref) {\n ref.current = image;\n }\n },\n [ref],\n );\n\n const settle = useCallback(\n (image: HTMLImageElement) => (hasPixels(image) ? onLoad() : onError()),\n [onLoad, onError],\n );\n\n // An image that finished loading before React attached `onLoad` (from the browser cache,\n // say) never fires the event, so check once it is mounted.\n useEffect(() => {\n const image = imageRef.current;\n\n if (image?.complete && image.currentSrc) {\n settle(image);\n }\n }, [settle, url]);\n\n return (\n <img\n ref={setImage}\n src={url}\n // The root carries the file name; the picture adds nothing to announce.\n alt=\"\"\n draggable={false}\n loading=\"lazy\"\n decoding=\"async\"\n data-slot=\"file-thumbnail-preview\"\n data-status={status}\n data-testid=\"file-thumbnail-preview\"\n onLoad={(event: SyntheticEvent<HTMLImageElement>) => settle(event.currentTarget)}\n onError={onError}\n className={cn(\n 'absolute inset-0 block size-full bg-white',\n FIT_CLASS[fit],\n revealClassName,\n className,\n )}\n />\n );\n },\n);\n\nImagePreview.displayName = 'ImagePreview';\n","import { Suspense } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { lazyRenderer } from '../../../file-preview/components/lazy-renderer';\n\nimport type { PreviewProps } from './preview-props';\nimport { revealClassName } from './reveal-class-name';\nimport { ScaledPage } from './scaled-page';\n\n/** Roughly a rendered README's text column: wide enough that lines wrap as they would. */\nconst DESIGN_WIDTH = 640;\n\nconst MarkdownPage = lazyRenderer(() =>\n import('./markdown-page').then((module) => module.MarkdownPage),\n);\n\nexport interface MarkdownPreviewProps extends PreviewProps {\n markdown: string;\n fileName: string;\n}\n\n/** Rendered Markdown in miniature: the top of the document, laid out as a page. */\nexport function MarkdownPreview({\n markdown,\n fileName,\n status,\n onLoad,\n onError,\n className,\n}: MarkdownPreviewProps) {\n return (\n <ScaledPage\n designWidth={DESIGN_WIDTH}\n status={status}\n className={cn(revealClassName, className)}\n >\n <div data-testid=\"file-thumbnail-preview\">\n <Suspense fallback={null}>\n <MarkdownPage\n markdown={markdown}\n fileName={fileName}\n onLoad={onLoad}\n onError={() => onError()}\n />\n </Suspense>\n </div>\n </ScaledPage>\n );\n}\n","/**\n * The reveal logic of the Extend UI registry's `file-thumbnail.tsx`, adapted to report a\n * status for any preview (image, Markdown, HTML) instead of taking `isLoading` / `hasError`\n * from the caller.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type PreviewRevealStatus = 'loading' | 'loaded' | 'error';\n\n/**\n * Preview keys that have finished their reveal this session. Switching views or tabs\n * remounts thumbnails; a key in here shows at once instead of replaying the blur-in, so only\n * a picture's first load animates. Module scope because it has to outlive the component.\n */\nconst revealedKeys = new Set<string>();\n\nfunction initialLoadedKey(key: string | null) {\n return key && revealedKeys.has(key) ? key : null;\n}\n\n/**\n * Load status of the preview drawn for `key`: `loading` until the preview calls\n * `markLoaded`, then `loaded` two frames later (so the hidden state paints first and the\n * reveal has something to transition from), or `error` after `markFailed`.\n */\nexport function usePreviewReveal(key: string | null) {\n const revealFrameRef = useRef<number | null>(null);\n const [loadedKey, setLoadedKey] = useState(() => initialLoadedKey(key));\n const [failedKey, setFailedKey] = useState<string | null>(null);\n const [prevKey, setPrevKey] = useState(key);\n\n // Reset during render rather than in an effect, so a new picture never paints one frame\n // with the previous one's status.\n if (key !== prevKey) {\n setPrevKey(key);\n setLoadedKey(initialLoadedKey(key));\n }\n\n const cancelReveal = useCallback(() => {\n if (revealFrameRef.current !== null) {\n window.cancelAnimationFrame(revealFrameRef.current);\n revealFrameRef.current = null;\n }\n }, []);\n\n // A pending reveal belongs to the key it was scheduled for.\n useEffect(() => cancelReveal, [cancelReveal, key]);\n\n const markLoaded = useCallback(() => {\n if (!key || revealedKeys.has(key)) {\n if (key) {\n setLoadedKey(key);\n }\n return;\n }\n\n setFailedKey(null);\n revealedKeys.add(key);\n cancelReveal();\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = window.requestAnimationFrame(() => {\n revealFrameRef.current = null;\n setLoadedKey(key);\n });\n });\n }, [cancelReveal, key]);\n\n const markFailed = useCallback(() => {\n if (!key) {\n return;\n }\n\n revealedKeys.delete(key);\n cancelReveal();\n setFailedKey(key);\n setLoadedKey((current) => (current === key ? null : current));\n }, [cancelReveal, key]);\n\n let status: PreviewRevealStatus = 'loading';\n\n if (key && failedKey === key) {\n status = 'error';\n } else if (key && loadedKey === key) {\n status = 'loaded';\n }\n\n return { status, markLoaded, markFailed };\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n forwardRef,\n Suspense,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ComponentType,\n type ReactNode,\n} from 'react';\nimport { useEventCallback, useIntersectionObserver } from 'usehooks-ts';\n\nimport { getFileExtension, getFileKind, type FileKind } from '@/lib/file-kinds';\nimport { loadFileBlob } from '@/lib/load-file-blob';\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { lazyRenderer } from '../file-preview/components/lazy-renderer';\nimport { RendererBoundary } from '../file-preview/components/renderer-boundary';\nimport { getConfiguredWasmSources } from '../file-preview/components/wasm-sources';\nimport { useFilePreviewTheme } from '../file-preview/hooks/use-file-preview-theme';\n\nimport { HtmlThumbnail } from './components/html/html-thumbnail';\nimport { ImageThumbnail } from './components/image/image-thumbnail';\nimport { HtmlPreview } from './components/previews/html-preview';\nimport { ImagePreview } from './components/previews/image-preview';\nimport { MarkdownPreview } from './components/previews/markdown-preview';\nimport type {\n FileThumbnailProducerProps,\n ThumbnailSource,\n ThumbnailSourceData,\n} from './components/thumbnail-types';\nimport { usePreviewReveal, type PreviewRevealStatus } from './hooks/use-preview-reveal';\n\nexport type FileThumbnailStatus = PreviewRevealStatus;\n\n/** Checkerboard tile behind the picture, so transparent areas of an image read as transparent. */\nconst CHECKER_BG =\n 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAMIElEQVR4AezbS25b2RJEUYMTqPmPsVrVrc57FYANGIJkkYz7OZ9lOCGLZGRk7jQC7NzHv//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NYKXtBcBK17QLAi8SEAAvAvNxBFYiIABWuqZdEHiRgAB4EZiP701gte0feSa4qTyT3FTjHW3jHW16NJUeTTXe0Tbe0aZHU+nRVOMdbeMdbXo0lR5NNd7RNt7R+gawWqTbB4EXCAiAF2D5KAKrERAAq13UPqcRWLGxAFjxqnZC4EkCAuBJUD6GwIoEBMCKV7UTAk8SEABPgvKxvQmsur0AWPWy9kLgCQIC4AlIPoLAqgQEwKqXtRcCTxAQAE9A8pG9Cay8vQBY+bp2Q+AbAgLgG0DeRmBlAgJg5evaDYFvCAiAbwB5e28Cq2//yDPBTeWZ5KYa72gb72jTo6n0aKrxjrbxjjY9mkqPphrvaBvvaNOjqfRoqvGOtvGO1jeA1SPefgj8gYAA+AMcbyGwOgEBsPqF7fc2gR2EAmCHK9sRgS8ICIAvwHgZgR0ICIAdrmxHBL4gIAC+AOPlvQnssr0A2OXS9kTgEwIC4BMoXkJgFwICYJdL2xOBTwgIgE+geGlvAjttLwB2urZdEfhAQAB8AOJXBHYiIAB2urZdEfhAQAB8AOLXvQnstv0jzwQ3lWeSm2q8o228o02PptKjqcY72sY72vRoKj2aaryjbbyjTY+m0qOpxjvaxjta3wB2i3z7IvAbAQHwGwz/RGA3AgJgt4vb90sCO74hAHa8up0R+ElAAPwE4QcCOxIQADte3c4I/CQgAH6C8GNvArtuLwB2vby9EfiPgAD4D4K/COxKQADsenl7I/AfAQHwHwR/9yaw8/YCYOfr2317AgJg+/8CAOxMQADsfH27b09AAGz/X2BvALtv/38AAAD//xLPItAAAAAGSURBVAMAOitaB8Pc+tcAAAAASUVORK5CYII=';\n\n/** The loader's and the fallback's shared surface, so a load that fails only stops pulsing. */\nconst SURFACE_STYLE = { backgroundImage: `url(${CHECKER_BG})` };\n\n/**\n * Rasterised thumbnails are drawn this wide, in CSS pixels: sharp in tiles up to about this\n * size, and small enough that a gallery of data URLs stays cheap.\n */\nconst THUMBNAIL_WIDTH = 320;\n\n/** Past 2x the extra pixels are invisible at tile size, and cost memory per cached tile. */\nconst MAX_PIXEL_RATIO = 2;\n\n/**\n * Without `IntersectionObserver` (jsdom, very old browsers) there is no way to tell, so every\n * tile counts as on screen and loads when it mounts.\n */\nfunction canObserveVisibility() {\n return typeof window !== 'undefined' && 'IntersectionObserver' in window;\n}\n\n// Each engine arrives in its own chunk, only for hosts that show that type. The WASM engines\n// get the host's configured source as their chunk loads, before first use - the only point\n// at which they accept one (see `file-preview.tsx`).\nconst PdfThumbnail = lazyRenderer(() =>\n import('./components/pdf/pdf-thumbnail').then((module) => {\n module.applyPdfiumWasmUrl(getConfiguredWasmSources().pdf);\n return module.PdfThumbnail;\n }),\n);\nconst SpreadsheetThumbnail = lazyRenderer(() =>\n import('./components/spreadsheet/spreadsheet-thumbnail').then((module) => {\n module.applySpreadsheetThumbnailWasmSource(getConfiguredWasmSources().spreadsheet);\n return module.SpreadsheetThumbnail;\n }),\n);\nconst PresentationThumbnail = lazyRenderer(() =>\n import('./components/presentation/presentation-thumbnail').then((module) => {\n module.applyPresentationThumbnailWasmSource(getConfiguredWasmSources().presentation);\n return module.PresentationThumbnail;\n }),\n);\nconst DocxThumbnail = lazyRenderer(() =>\n import('./components/docx/docx-thumbnail').then((module) => {\n module.applyDocxThumbnailWasmSource(getConfiguredWasmSources().docx);\n return module.DocxThumbnail;\n }),\n);\nconst MarkdownThumbnail = lazyRenderer(() =>\n import('./components/markdown/markdown-thumbnail').then((module) => module.MarkdownThumbnail),\n);\nconst CsvThumbnail = lazyRenderer(() =>\n import('./components/csv/csv-thumbnail').then((module) => module.CsvThumbnail),\n);\n\n/**\n * The subcomponent that turns each kind into a picture, like `RENDERERS` in\n * `file-preview.tsx`. `null` kinds get the fallback: a video's first frame would need the\n * whole file seeked and decoded per tile, and plain text reads no better small than the name.\n */\nconst THUMBNAILS: Record<FileKind, ComponentType<FileThumbnailProducerProps> | null> = {\n image: ImageThumbnail,\n html: HtmlThumbnail,\n pdf: PdfThumbnail,\n spreadsheet: SpreadsheetThumbnail,\n presentation: PresentationThumbnail,\n docx: DocxThumbnail,\n markdown: MarkdownThumbnail,\n csv: CsvThumbnail,\n video: null,\n text: null,\n};\n\n/**\n * Kinds whose picture is generated from the file's bytes, and so worth keeping: a remounted\n * tile (a view or tab switch) shows the cached picture instead of parsing the file again.\n * Images and HTML are not cached here; the browser caches their URLs itself.\n */\nconst GENERATED_KINDS = new Set<FileKind>([\n 'pdf',\n 'spreadsheet',\n 'presentation',\n 'docx',\n 'markdown',\n 'csv',\n]);\n\n// Session caches of generated pictures, by URL and by in-memory file. The `WeakMap` lets a\n// `Blob` and its picture be collected together; `src` entries live for the session, one\n// small data URL each.\nconst sourcesBySrc = new Map<string, ThumbnailSource>();\nconst sourcesByBlob = new WeakMap<Blob, ThumbnailSource>();\n\nlet blobIdCounter = 0;\nconst blobIds = new WeakMap<Blob, number>();\n\n/** A stable string for a file, for keys: the URL, or an id per in-memory `Blob`. */\nfunction fileIdentity(src: string | undefined, fileBlob: Blob | undefined) {\n if (src !== undefined) {\n return `src:${src}`;\n }\n\n if (!fileBlob) {\n return 'none';\n }\n\n let id = blobIds.get(fileBlob);\n\n if (id === undefined) {\n blobIdCounter += 1;\n id = blobIdCounter;\n blobIds.set(fileBlob, id);\n }\n\n return `blob:${id}`;\n}\n\nfunction readCachedSource(src: string | undefined, fileBlob: Blob | undefined) {\n return src !== undefined ? sourcesBySrc.get(src) : fileBlob && sourcesByBlob.get(fileBlob);\n}\n\nfunction writeCachedSource(\n src: string | undefined,\n fileBlob: Blob | undefined,\n source: ThumbnailSource,\n) {\n if (src !== undefined) {\n sourcesBySrc.set(src, source);\n } else if (fileBlob) {\n sourcesByBlob.set(fileBlob, source);\n }\n}\n\ninterface FileThumbnailContextValue {\n fileName: string;\n /** What `FileThumbnailPreview` draws, `null` until there is a picture. */\n source: ThumbnailSource | null;\n status: FileThumbnailStatus;\n markLoaded: () => void;\n markFailed: () => void;\n}\n\nconst FileThumbnailContext = createContext<FileThumbnailContextValue>(null!);\n\nfunction useFileThumbnailContext(component: string) {\n const context = useContext(FileThumbnailContext);\n\n if (!context) {\n throw new Error(\n `[web-file-preview] <${component}> must be used within <FileThumbnail>. ` +\n 'Render it as a child of the FileThumbnail that owns the file.',\n );\n }\n\n return context;\n}\n\ninterface FileThumbnailBaseProps {\n /**\n * The original file name. Its extension picks how the file is drawn (see\n * `isFileThumbnailSupported`), and labels the fallback.\n */\n fileName: string;\n /**\n * A picture of the file rendered elsewhere - a first page from your server, say. Drawn\n * instead of the file for any kind, and nothing is fetched or parsed: use it when you\n * already have one, or to spare the browser the engines in a long list.\n */\n previewImageUrl?: string;\n /**\n * Shows `FileThumbnailLoader` whatever the file, and holds off drawing it, while your own\n * pipeline is still producing `previewImageUrl`. Without it the thumbnail would start\n * drawing the file itself, then jump to your picture.\n */\n isLoading?: boolean;\n /**\n * Additional CSS classes to apply\n */\n className?: string;\n /** `FileThumbnailPreview`, `FileThumbnailLoader` and `FileThumbnailFallback`. */\n children: ReactNode;\n /**\n * Called the first time the tile is on screen for this `fileName` and `src`, whatever the\n * file, `fileBlob` or `isLoading`: the moment to start getting a file you pass as\n * `fileBlob={null}` until it arrives. Not called again when it scrolls away and returns.\n */\n onLoadAvailable?: () => void;\n /**\n * Called when the tile starts drawing the file: once it is on screen, has the file and\n * `isLoading` is off. Called again if it scrolls away before the picture is drawn and\n * returns, since the work restarts. A picture generated earlier this session (a PDF page,\n * say) shows at once and never calls it.\n */\n onLoadStarted?: () => void;\n /**\n * Called once the picture has drawn and the tile shows it, including a picture generated\n * earlier this session, which shows at once without `onLoadStarted`.\n */\n onLoaded?: () => void;\n /**\n * Called whenever the fallback takes over, and only then: the file failed to load or draw,\n * or it is a kind the tile never draws (video, plain text, an unsupported type), reported\n * once as the tile first paints. A `null` `fileBlob` is a file still on its way, never a\n * failure.\n */\n onLoadFailed?: (error: Error) => void;\n}\n\ninterface FileThumbnailSrcProps {\n /**\n * URL of the file. Images and HTML pages load from it directly (no CORS needed). Every other\n * kind is fetched and parsed in the browser, so like `FilePreview`'s `src` it must be\n * same-origin or allow this origin through CORS - otherwise the tile falls back.\n * Pass either `src` or `fileBlob`, never both.\n */\n src: string;\n fileBlob?: never;\n}\n\ninterface FileThumbnailBlobProps {\n /**\n * The file itself, already in memory. Nothing is fetched. `null` while your app is still\n * getting it: the tile shows `FileThumbnailLoader`, and draws the file once it arrives.\n * Pass either `src` or `fileBlob`, never both.\n */\n fileBlob: Blob | null | undefined;\n src?: never;\n}\n\nexport type FileThumbnailProps = FileThumbnailBaseProps &\n (FileThumbnailSrcProps | FileThumbnailBlobProps);\n\n/**\n * A small tile standing for a file. Owns the picture and its load status and shares them\n * with `FileThumbnailPreview`, `FileThumbnailLoader` and `FileThumbnailFallback`, which\n * each render only in their state, so consumers compose their own loading and fallback UI:\n *\n * @example ```tsx\n * <FileThumbnail fileName={name} src={url}>\n * <FileThumbnailLoader />\n * <FileThumbnailPreview />\n * <FileThumbnailFallback />\n * </FileThumbnail>\n * ```\n *\n * The picture is `previewImageUrl` when given. Otherwise a per-type subcomponent draws the\n * file: an image as itself, a PDF's first page, a workbook's first sheet, a deck's first\n * slide, a Word document's first page, rendered Markdown, an HTML page in a sandboxed frame,\n * or a CSV's first rows. Anything else - video, plain text, an unsupported type, a file that\n * fails to load or parse - is the fallback, never an error: a grid of tiles should not break\n * on one odd file.\n *\n * A `fileBlob` of `null` is a file still on its way: the tile shows the loader, not the\n * fallback, until it arrives.\n *\n * Nothing loads until the tile is on screen (in the viewport, not clipped by a scrolling\n * ancestor). Work that has not produced a picture stops when the tile scrolls away and\n * restarts when it returns; a picture already drawn stays.\n */\nexport const FileThumbnail = forwardRef<HTMLDivElement, FileThumbnailProps>(\n (\n {\n fileName,\n src,\n fileBlob: pendingFileBlob,\n previewImageUrl,\n isLoading = false,\n className,\n children,\n onLoadAvailable,\n onLoadStarted,\n onLoaded,\n onLoadFailed,\n },\n ref,\n ) => {\n // A `null` blob is on its way: nothing to draw yet, but nothing has failed either.\n const fileBlob = pendingFileBlob ?? undefined;\n const hasFile = src !== undefined || fileBlob !== undefined;\n const theme = useFilePreviewTheme();\n const kind = getFileKind(fileName);\n const Thumbnail = previewImageUrl || !kind ? null : THUMBNAILS[kind];\n const identity = `${kind ?? 'unsupported'}|${fileIdentity(src, fileBlob)}`;\n\n // Relative to the viewport, which also counts a tile clipped by a scrolling ancestor as\n // off screen. Not frozen once visible: work that has not produced a picture yet stops when\n // the tile scrolls away, so a fast scroll does not queue every tile it passed.\n const { ref: observeRef, isIntersecting: isVisible } = useIntersectionObserver({\n initialIsIntersecting: !canObserveVisibility(),\n });\n\n const rootRef = useCallback(\n (node: HTMLDivElement | null) => {\n observeRef(node);\n\n if (typeof ref === 'function') {\n ref(node);\n } else if (ref) {\n ref.current = node;\n }\n },\n [observeRef, ref],\n );\n\n // What the subcomponent produced, and whether it failed, for this file only. Reset during\n // render rather than in an effect, so a new file never paints the previous one's picture.\n const [produced, setProduced] = useState<ThumbnailSource | null>(null);\n const [failedIdentity, setFailedIdentity] = useState<string | null>(null);\n const [prevIdentity, setPrevIdentity] = useState(identity);\n // The file whose tile has been on screen, so `previewImageUrl` stays up once it scrolls away.\n const [seenIdentity, setSeenIdentity] = useState<string | null>(null);\n\n if (identity !== prevIdentity) {\n setPrevIdentity(identity);\n setProduced(null);\n }\n\n if (isVisible && seenIdentity !== identity) {\n setSeenIdentity(identity);\n }\n\n // Not the blob: its arrival is what `onLoadAvailable` asks for, so it must not call it again.\n const availableKey = `${fileName}|${src ?? ''}`;\n const reportedAvailableRef = useRef<string | null>(null);\n const reportLoadAvailable = useEventCallback(() => onLoadAvailable?.());\n\n useEffect(() => {\n if (isVisible && reportedAvailableRef.current !== availableKey) {\n reportedAvailableRef.current = availableKey;\n reportLoadAvailable();\n }\n }, [isVisible, availableKey, reportLoadAvailable]);\n\n const cached = kind && GENERATED_KINDS.has(kind) ? readCachedSource(src, fileBlob) : undefined;\n const hasProduced = Boolean(produced?.key.startsWith(`${identity}|`));\n let source: ThumbnailSource | null = null;\n\n if (previewImageUrl) {\n if (isVisible || seenIdentity === identity) {\n source = { type: 'image', url: previewImageUrl, key: `preview:${previewImageUrl}` };\n }\n } else if (cached) {\n // A data URL made earlier this session: nothing to load, so it shows even off screen.\n source = cached;\n } else if (hasProduced) {\n source = produced;\n }\n\n const { status: revealStatus, markLoaded, markFailed } = usePreviewReveal(source?.key ?? null);\n const hasFailed = failedIdentity === identity;\n\n // Nothing to draw it with, whatever the file: the extension alone decides.\n const isUndrawable = !previewImageUrl && !Thumbnail;\n let status: FileThumbnailStatus;\n\n if (isLoading) {\n status = 'loading';\n } else if (isUndrawable || hasFailed) {\n // Decided here rather than after a failed load, so the fallback is the first paint.\n status = 'error';\n } else if (!source) {\n status = 'loading';\n } else {\n status = revealStatus;\n }\n\n const handleSource = useEventCallback((data: ThumbnailSourceData) => {\n const next = { ...data, key: `${identity}|${data.type}` };\n\n if (kind && GENERATED_KINDS.has(kind)) {\n writeCachedSource(src, fileBlob, next);\n }\n\n setProduced(next);\n });\n\n const handleError = useEventCallback((error: Error) => {\n setFailedIdentity(identity);\n // Surfaced for developers only; the tile itself shows the fallback, not the message.\n console.warn(error);\n onLoadFailed?.(error);\n });\n\n // The preview found it cannot draw the picture (an `<img>` error, say): same fallback,\n // same report.\n const handlePreviewFailed = useEventCallback(() => {\n markFailed();\n onLoadFailed?.(new Error(`[web-file-preview] Could not draw a thumbnail of \"${fileName}\".`));\n });\n\n /** The entry's download, handed to the lazy chunks as a prop (see `thumbnail-types.ts`). */\n const loadBlob = useCallback(\n (signal: AbortSignal) => loadFileBlob({ src, fileBlob, getFileName: () => fileName, signal }),\n // `fileName` only names errors; a rename must not restart the work.\n\n [src, fileBlob],\n );\n\n // Unmounting the subcomponent aborts its download and frees its generation slot. Once it has\n // produced, it stays: an image's blob URL lives only as long as it does.\n const shouldProduce =\n Boolean(Thumbnail) &&\n hasFile &&\n !cached &&\n !isLoading &&\n !hasFailed &&\n (isVisible || hasProduced);\n const pixelRatio = Math.min(\n typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1,\n MAX_PIXEL_RATIO,\n );\n\n // Loading with work under way, as opposed to waiting for the file, for `isLoading` or to\n // scroll on screen.\n const isDrawing = status === 'loading' && (shouldProduce || source !== null);\n const reportLoadStarted = useEventCallback(() => onLoadStarted?.());\n\n useEffect(() => {\n if (isDrawing) {\n reportLoadStarted();\n }\n }, [isDrawing, identity, reportLoadStarted]);\n\n // The fallback shows for an undrawable kind without anything failing, so report it here:\n // every fallback comes with an `onLoadFailed`.\n const reportUndrawable = useEventCallback(() =>\n onLoadFailed?.(\n new Error(\n `[web-file-preview] No thumbnail for \"${fileName}\": its type is not drawn. ` +\n 'Check isFileThumbnailSupported(fileName) to show your own tile instead.',\n ),\n ),\n );\n\n useEffect(() => {\n if (isUndrawable && !isLoading) {\n reportUndrawable();\n }\n }, [isUndrawable, isLoading, identity, reportUndrawable]);\n\n const isLoaded = status === 'loaded';\n const reportLoaded = useEventCallback(() => onLoaded?.());\n\n useEffect(() => {\n if (isLoaded) {\n reportLoaded();\n }\n }, [isLoaded, source?.key, reportLoaded]);\n\n const contextValue = useMemo(\n () => ({ fileName, source, status, markLoaded, markFailed: handlePreviewFailed }),\n [fileName, source, status, markLoaded, handlePreviewFailed],\n );\n\n return (\n <FileThumbnailContext.Provider value={contextValue}>\n <div\n ref={rootRef}\n role=\"img\"\n aria-label={fileName}\n aria-busy={status === 'loading' || undefined}\n title={fileName}\n data-slot=\"file-thumbnail\"\n data-testid=\"file-thumbnail\"\n data-kind={kind ?? 'unsupported'}\n data-status={status}\n // Scopes the design system's `theme-light:` variant to this thumbnail.\n data-theme={theme}\n className={cn(\n 'group/file-thumbnail relative size-full overflow-hidden',\n 'user-select-no',\n 'rounded-[8px]',\n 'bg-white',\n '[contain:layout_paint]',\n className,\n )}\n >\n {shouldProduce && Thumbnail && (\n // Keyed by file, so each file gets a fresh subcomponent - and a fresh boundary\n // after an engine throws.\n <RendererBoundary key={identity} fileName={fileName} onError={handleError}>\n <Suspense fallback={null}>\n <Thumbnail\n fileName={fileName}\n src={src}\n fileBlob={fileBlob}\n loadBlob={loadBlob}\n width={THUMBNAIL_WIDTH}\n pixelRatio={pixelRatio}\n onSource={handleSource}\n onError={handleError}\n />\n </Suspense>\n </RendererBoundary>\n )}\n {children}\n </div>\n </FileThumbnailContext.Provider>\n );\n },\n);\n\nFileThumbnail.displayName = 'FileThumbnail';\n\nexport interface FileThumbnailPreviewProps {\n className?: string;\n}\n\n/**\n * The picture, filling the tile: an image cropped to cover, or a Markdown or HTML page laid\n * out at page width and scaled down. Mounted while loading too, hidden and blurred, because\n * it is what loads: without this part the tile never leaves `loading`. It fades in once\n * drawn; a picture that has already done so this session shows at once.\n *\n * The ref is the `<img>` when the picture is an image, and unset otherwise.\n */\nexport const FileThumbnailPreview = forwardRef<HTMLImageElement, FileThumbnailPreviewProps>(\n ({ className }, ref) => {\n const { fileName, source, status, markLoaded, markFailed } =\n useFileThumbnailContext('FileThumbnailPreview');\n\n if (!source || status === 'error') {\n return null;\n }\n\n const previewProps = { status, onLoad: markLoaded, onError: markFailed, className };\n\n switch (source.type) {\n case 'image':\n return (\n <ImagePreview\n key={source.key}\n ref={ref}\n url={source.url}\n fit={source.fit}\n {...previewProps}\n />\n );\n case 'markdown':\n return (\n <MarkdownPreview\n key={source.key}\n markdown={source.markdown}\n fileName={fileName}\n {...previewProps}\n />\n );\n case 'html':\n return (\n <HtmlPreview\n key={source.key}\n page={'url' in source ? { url: source.url } : { html: source.html }}\n designWidth={'html' in source ? source.designWidth : undefined}\n {...previewProps}\n />\n );\n }\n },\n);\n\nFileThumbnailPreview.displayName = 'FileThumbnailPreview';\n\nexport interface FileThumbnailLoaderProps {\n asChild?: boolean;\n /** Replaces the default pulsing surface. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * Shown while the tile waits to scroll on screen, while `fileBlob` is `null`, while the\n * picture is produced and loads, or while `isLoading` is set. It starts\n * transparent and fades in slowly, so a picture that is quick to draw never flashes it. It is\n * mounted only while loading, so each load starts its own fade.\n */\nexport const FileThumbnailLoader = forwardRef<HTMLDivElement, FileThumbnailLoaderProps>(\n ({ asChild = false, children, className }, ref) => {\n const { status } = useFileThumbnailContext('FileThumbnailLoader');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'loading') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n // The root's `aria-busy` already announces the loading.\n aria-hidden\n data-slot=\"file-thumbnail-loader\"\n data-testid=\"file-thumbnail-loader\"\n style={SURFACE_STYLE}\n className={cn(\n 'absolute inset-0',\n // The pulse animates `opacity` too, so it waits for the fade to finish.\n children === undefined &&\n 'animate-pulse [animation-delay:1300ms] motion-reduce:animate-none',\n className,\n )}\n >\n {children}\n </Component>\n );\n },\n);\n\nFileThumbnailLoader.displayName = 'FileThumbnailLoader';\n\nexport interface FileThumbnailFallbackProps {\n asChild?: boolean;\n /** Replaces the default file-name label. */\n children?: ReactNode;\n className?: string;\n /** Extra classes for the default file-name label. Unused once `children` replace it. */\n labelClassName?: string;\n}\n\ninterface FileNameLabelProps {\n fileName: string;\n className?: string;\n}\n\n/**\n * The file name, truncated in the middle so the extension stays visible: `longfilena…pdf`.\n * The stem keeps its trailing dot and takes the ellipsis; the extension never shrinks.\n */\nfunction FileNameLabel({ fileName, className }: FileNameLabelProps) {\n const extensionLength = getFileExtension(fileName).length;\n const stem = extensionLength ? fileName.slice(0, -extensionLength) : fileName;\n const extension = extensionLength ? fileName.slice(-extensionLength) : '';\n\n return (\n // `asChild`, so the slot name is the label's own: Typography sets `data-slot` on its element.\n <Typography\n variant=\"body-small-low\"\n className={cn('flex min-w-0', 'text-black', className)}\n asChild\n >\n <p data-slot=\"file-thumbnail-fallback-label\">\n <span className=\"truncate\">{stem}</span>\n {extension && <span className=\"shrink-0\">{extension}</span>}\n </p>\n </Typography>\n );\n}\n\n/**\n * Shown when there is no picture: video, plain text, an unsupported type, or a file that\n * failed to load or draw. By default it is the loader's surface, still, labelled with the file\n * name, truncated in the middle so the extension stays visible (`longfilena…pdf`).\n */\nexport const FileThumbnailFallback = forwardRef<HTMLDivElement, FileThumbnailFallbackProps>(\n ({ asChild = false, children, className, labelClassName }, ref) => {\n const { fileName, status } = useFileThumbnailContext('FileThumbnailFallback');\n const Component = asChild ? Slot : 'div';\n\n if (status !== 'error') {\n return null;\n }\n\n return (\n <Component\n ref={ref}\n data-slot=\"file-thumbnail-fallback\"\n data-testid=\"file-thumbnail-fallback\"\n // By default the loader's surface, still, with the name on it.\n style={children === undefined ? SURFACE_STYLE : undefined}\n className={cn('absolute inset-0 flex items-center justify-center p-8', className)}\n >\n {children ?? <FileNameLabel fileName={fileName} className={labelClassName} />}\n </Component>\n );\n },\n);\n\nFileThumbnailFallback.displayName = 'FileThumbnailFallback';\n"],"mappings":";;;;;;;AAkBA,IAAaG,IAA0B;CAErC,KAAK,CAAC,KAAK;CACX,OAAO;EAAC;EAAO;EAAQ;EAAO;EAAO;EAAO;EAAQ;CAAM;CAE1D,OAAO,CAAC,OAAO,MAAM;CACrB,MAAM,CAAC,KAAK;CAEZ,KAAK,CAAC,KAAK;CAMX,aAAa;EAAC;EAAQ;EAAQ;CAAK;CAKnC,MAAM,CAAC,MAAM;CAKb,cAAc,CAAC,QAAQ,KAAK;CAE5B,UAAU,CAAC,MAAM,UAAU;CAE3B,MAAM,CAAC,QAAQ,KAAK;AACtB,GAKMC,IAAoB,IAAI,IAC3B,OAAO,KAAKD,CAAuB,CAAC,CAAgB,SAAS,MAC5DA,EAAwBE,EAAK,CAAC,KAAK,MAAc,CAACC,GAAWD,CAAI,CAAU,CAC7E,CACF;AAGA,SAAgBE,EAAiB,GAA0B;CACzD,IAAMC,IAAWC,EAAS,YAAY,GAAG;CAEzC,OAAOD,IAAW,IAAIC,EAAS,MAAMD,IAAW,CAAC,CAAC,CAAC,YAAY,IAAI;AACrE;AASA,SAAgBE,EAAY,GAAmC;CAC7D,OAAON,EAAkB,IAAIG,EAAiBE,CAAQ,CAAC,KAAK;AAC9D;AAUA,SAAgBE,EAAuB,GAA2B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