FilePreview
Shows one file in the browser's own viewers — PDF, image, video, sound, text — behind an allowlist that keeps uploaded HTML and SVG from running as your app. Plus openFile, for "open in a new tab".
FilePreview shows one file: a PDF in the browser's built-in PDF viewer, an image, a video or a sound with native controls, a text file as text, and anything else as a panel with a download button. It's the body you put in a Modal, a Drawer or a page. There is no PDF library: the browser renders the file itself.
The kit makes no request. Give it the file as a File or Blob, as a URL the browser loads itself, or as a function of yours that resolves either one.
import { FilePreview } from '@42-central/ui-react/file-preview';
<FilePreview file={pickedFile} />
<FilePreview src={document.url} name={document.name} />
<FilePreview
name="contract.pdf"
data={({ signal }) => api.get(`/documents/${id}`, { signal }).then((r) => r.blob())}
/>Playground
Component
Dir
Presets
Props
Code
<Component withHeader />A PDF
A PDF loads in the browser's own viewer, through an <object type="application/pdf">: pages, zoom, search, print and save come with it. The header shows the name, the extension and size, an Open in new tab button and a Download button. The root has a height of its own (min(75dvh, 48rem)), so a PDF has room on a page and in a dialog without any sizing; override it with className (h-96, or h-full in a parent with a definite height).
Code
<FilePreview src="/files/internship-agreement.pdf" name="internship-agreement.pdf" />Both get the same viewer in Chromium, Firefox and Safari. The difference is the keyboard inside a Modal or a Drawer: their focus trap looks inside a same-origin frame for tab stops, finds Chrome's viewer document empty, and leaves the frame out, so Tab cycled through the dialog's buttons and never reached the PDF (measured in Chromium). It counts an <object> as one stop, and End then scrolls the PDF to its last page. The type attribute is no safety net (Chromium rendered an HTML resource behind type="application/pdf"), which is why only a re-typed PDF is ever embedded; see Security.
Every kind of file
The renderer follows the file's kind (fileKind, from its type, then its extension) and the allowlist below. Switch the file:
Code
<FilePreview
name="campus.jpg"
data={({ signal }) => fetch('/files/campus.jpg', { signal }).then((r) => r.blob())}
/>
<FilePreview file={new File([html], 'cover-letter.html', { type: 'text/html' })} />| The file | Shown as |
|---|---|
The browser's PDF viewer, in an <object> named "Preview of internship-agreement.pdf" (translations.label). | |
| PNG, JPEG, GIF, WebP, AVIF, BMP | The kit Image, contained in the box. |
| SVG | An <img>, from a data: URL (see Security). |
| MP4, WebM, Ogg, QuickTime; MP3, AAC, WAV, Ogg, FLAC | <video> or <audio> with the browser's controls. |
| Text, CSV, TSV, JSON, code, Markdown, logs | Its characters, in a scrolling <pre>. Only from a File or Blob, which can be read; see below. |
| Anything else, or a PDF where the browser has no PDF viewer | The panel: the kind icon, the name, the extension and size, "No preview for this file type", and a download button. |
Text is read from the Blob and shown as characters, never parsed: the HTML file above shows its source, and its <script> is text. A file longer than limit (500 kB by default, FILE_PREVIEW_TEXT_LIMIT) is cut there, with "Showing the first 500 kB of 1.2 MB" above it. It's decoded as UTF-8; a character cut in half at the limit is dropped rather than shown as �. A text URL gets the panel instead: reading it would mean fetching it, and the kit doesn't. Return a Blob from data to preview it.
Your own fetch
A URL in a link can't carry a bearer token. Pass data instead: a function that receives an AbortSignal and returns a Blob or a URL (a presigned link), or a promise of one. It runs when the preview mounts; while it's pending, the content shows a spinner named "Loading internship-agreement.pdf…" and is aria-busy. Give name (and type when the name has no extension) so the header and the renderer are right before the file arrives.
Code
<FilePreview
name="internship-agreement.pdf"
data={async ({ signal }) => {
const response = await fetch(`/api/documents/${id}`, {
headers: { Authorization: `Bearer ${token}` },
signal,
});
if (!response.ok) throw new Error(response.statusText);
return response.blob();
}}
/>When the preview unmounts first (the dialog closes), signal aborts and a late result is ignored; pass it on to fetch so the request stops too. data runs once per mount: to show another file, give the preview a key.
The header's buttons work while the file is still loading. Download waits for the same promise, without a second request. Open in new tab opens the tab inside the click, as browsers require, and shows the file once it arrives.
Errors and Retry
When data rejects (or throws), the content shows "medical-certificate.pdf couldn't be loaded" with a Retry button, and a polite status region announces it. Retry calls data again; focus moves to the content area, so it isn't dropped with the button. This demo fails once, then succeeds.
Code
<FilePreview name="medical-certificate.pdf" data={fetchCertificate} />In a Modal or a Drawer
The usual place for a preview: opened from a FileItem row's actions, in a Modal on a desktop and a bottom Drawer on a phone. The overlay's title names the file, so the preview drops its own name and keeps the meta and the actions. Narrow the window below 40rem to get the drawer.
- internship-agreement.pdf4.98 kB
- campus.jpg21.8 kB
- meeting-notes.txt452 byte
Code
const phone = useMediaQuery('(width < 40rem)');
const [open, setOpen] = useState<Document | null>(null);
const preview = (className?: string) => open && (
<FilePreview.Root
className={className}
name={open.name}
type={open.type}
size={open.size}
data={({ signal }) => fetchDocument(open.id, signal)}
>
<FilePreview.Header>
<FilePreview.Meta className="flex-1" />
<FilePreview.Actions>
<FilePreview.Open />
<FilePreview.Download />
</FilePreview.Actions>
</FilePreview.Header>
<FilePreview.Content />
</FilePreview.Root>
);
<FileItem
file={document}
actions={
<ActionIcon variant="subtle" color="neutral" size="xs" aria-label={`View ${document.name}`}
aria-haspopup="dialog" onClick={() => setOpen(document)}>
<Eye className={iconStroke} aria-hidden />
</ActionIcon>
}
/>
{phone ? (
<Drawer open={open !== null} onOpenChange={(next) => !next && setOpen(null)} placement="bottom"
title={open?.name} withGrabber>
{preview('h-[60dvh]')}
</Drawer>
) : (
<Modal open={open !== null} onOpenChange={(next) => !next && setOpen(null)} title={open?.name} size="xl">
{preview()}
</Modal>
)}Focus moves into the dialog and is trapped there, as with any Modal. The PDF frame, the text region and the media controls come in the tab order after the header's buttons.
Parts
<FilePreview> is a ready-made arrangement. withHeader={false} drops the header, meta replaces the extension and size, and actions adds your buttons before Open and Download. For your own layout:
| Part | Renders | Notes |
|---|---|---|
FilePreview.Root | A <div>, a flex column | The file (file, src or data), name, type, size, limit, translations, icons. Loads data. |
FilePreview.Header | The bar above the file | A size container: below 28rem the action labels fold into their icons. |
FilePreview.Name | The name, truncated, with a title | asChild makes it your heading. |
FilePreview.Meta | "PDF · 4.98 kB" | children replace it. |
FilePreview.Actions | A row of buttons | |
FilePreview.Open | A Button, through openFile | Renders only for a file a tab may show. Prominent on a touch screen. |
FilePreview.Download | A DownloadButton | Saves the file at hand, or waits for data. |
FilePreview.Content | The file, or its loading, error or no-preview state | Fills the rest of the root; the file scrolls inside it. |
openFile
"Open in a new tab" on its own, for a row action or a link-like button: openFile(source, { name, type, signal }). The source is a Blob, a URL, or a function resolving one. Call it in a click handler; it resolves "opened", or "saved" when it saved the file instead.
Opens a new tab.
Code
<Button onClick={() => openFile(notes)}>Open the notes</Button>
<Button onClick={() => openFile(({ signal }) => fetchAgreement(signal), { name: 'internship-agreement.pdf' })}>
Open the agreement
</Button>- The tab opens inside the click. Browsers block a popup opened after an
await. With a function, the tab opens first (blank, titled withname), then shows the file when the promise resolves, and closes if it rejects orsignalaborts. - A blocked popup saves the file. When the browser blocks the tab,
openFilecallssaveFileand resolves"saved". - Only allowlisted files are shown. Anything else is saved, never navigated to (see Security). That includes a file a function resolves: the blank tab closes, and the file downloads.
- The tab can't reach back. Its
openeris cut before anything loads. (window.open'snoopenerwould return no window to point at the file.) - The object URL lives while the tab shows it. The 42-frontend helper this replaces revoked it after 60 seconds, after which saving from Chrome's PDF viewer or reloading the tab failed.
openFilechecks the tab every 2 seconds (OPEN_FILE_POLL) and revokes the URL once the tab is closed or has navigated elsewhere, and after an hour (OPEN_FILE_MAX_AGE) at the latest, so a tab left open all day doesn't pin the Blob in memory forever. A background tab's timers are throttled to once a minute in Chrome, which only delays the revoke. Closing or reloading your app revokes every object URL it made, whatever the timer says.
A tab showing a Blob is titled by the PDF's own Title metadata, and by the object URL's id when the PDF has none: in Chromium, our sample PDF's tab reads "Internship agreement - sample", the same file without the metadata reads e14db6a9-cf59-…. The fix belongs where the PDF is made: have your generator set the document title. We tried hosting the PDF in a titled blank page of our own instead; the title was right, but reloading that tab shows an empty page, and iOS shows only the first page of a PDF in a frame, which defeats the point of opening it. So openFile doesn't.
Security
A Blob's object URL has your app's origin. If an uploaded .html or .svg were loaded from one, in a frame or in a tab, its script would run as your app, with your cookies' reach and your API: stored XSS in an admin tool. We checked which types do this in Chromium and WebKit (the engine behind Safari), with a script that writes to the app's localStorage:
| Content | Typed as | Chromium | WebKit |
|---|---|---|---|
| HTML | text/html | runs | runs |
| HTML | application/octet-stream, application/zip, or no type | downloads | runs (sniffed as HTML) |
| SVG markup | image/svg+xml, application/xml, text/xml | runs | runs |
| HTML or SVG | application/pdf, text/plain, image/png, image/jpeg, video/mp4, audio/mpeg | inert | inert |
| HTML | text/html, behind <object type="application/pdf"> | runs | inert |
| SVG markup | an <img> from an object URL, then "Open image in new tab" | runs | runs |
| SVG markup | an <img> from a data: URL, then opened in a tab | inert | inert |
| Any of the above | saved through a download link | inert | inert |
So re-typing an unknown file as "binary" isn't a defence (WebKit sniffs it), and neither is <object type> (Chromium ignores it). What FilePreview and openFile do instead:
- An allowlist of types, not of files.
viewableType(type, name)maps a file to one of a fixed set:application/pdf, a raster image type, a common video or audio type, ortext/plain. Never the file's own type passed through. A Blob is re-wrapped under it (blob.slice(0, size, type)) before it gets a URL, so HTML that calls itselfcontract.pdfwith no type is rendered as a PDF, which fails to load and runs nothing. A specific type wins over a reassuring name: HTML typedtext/htmlbut namedcontract.pdfis not framed. - Only PDFs are embedded. Not in a
sandboxed frame, which would be the textbook fix: Chrome refuses to run its PDF viewer in one (it shows an error page, measured), so the protection is that nothing but a re-typed PDF ever reaches the viewer. - Text is a text node. Never
innerHTML, so markup stays characters. - SVG is an
<img>, from adata:URL. An<img>never runs an SVG's script, but "Open image in new tab" on an object URL would, as the app. Adata:URL's document has an opaque origin, so even then the script can't touch the app. - Everything else is saved, never navigated to. The panel's button and
openFilesave it through adownloadlink.
Rules 1 and 4 aren't FilePreview's own: they are useObjectUrl, the one way the kit turns a Blob into a URL, so FileItem and FileUpload thumbnails, ImageCropper and PhotoCapture follow them too. Before it, their thumbnails used the file's own type, and an uploaded SVG's "Open image in new tab" ran as the app. The table above is re-measured by pnpm run security:files, a Playwright harness in packages/react/scripts/security/ that pushes hostile HTML and SVG through every one of these surfaces in Chromium and WebKit and fails on any script that runs with the app's origin.
What the kit can't check is a URL: the browser follows the server's Content-Type. A cross-origin URL (a presigned S3 link) is safe to frame or open, since its script runs with that origin and the tab has no opener. A same-origin URL is framed or opened only when its type or name is viewable, but then the server decides. Serve uploads from a separate origin when you can; otherwise send the real Content-Type, X-Content-Type-Options: nosniff and Content-Disposition: attachment for anything not on the list. openFile never opens a blob: or data: string, whose real type it can't check: pass the Blob.
A PDF can carry JavaScript of its own. Chrome's and Firefox's viewers run it in their own sandbox, not with your origin, and the allowlist doesn't change that.
Phones and tablets
- iOS shows only the first page of a PDF inline. Safari on iPhone and iPad draws a framed PDF as a still image of its first page, with no scrolling. On a touch screen (
pointer: coarse), FilePreview adds "Only the first page may show here." above the PDF with its own Open in new tab button, and the header's Open button turns prominent. In a tab, iOS shows the whole document in its viewer. - Android has no inline PDF viewer. Chrome on Android reports
navigator.pdfViewerEnabled === false, so FilePreview shows the panel ("This browser can't show PDFs here") with Download and Open, which hands the PDF to the system's viewer. - What we could check. Playwright's WebKit doesn't render PDFs at all, so the iOS behaviour above comes from Safari itself, not from our automation. In WebKit we checked the security table, the panel, the image and text renderers and
openFile's tab; in Chromium, the PDF viewer too.
Documents in a Lightbox
Not yet. The open-index seam is how it would come: a list of document tiles under an OpenIndexProvider, and a viewer that renders a FilePreview for the opened index, the way a Lightbox.Slide takes custom media.
Internationalization
Every string is in translations. The download button's own strings sit under download. Sizes follow the IntlProvider locale.
| Key | Default |
|---|---|
label | (name) => `Preview of ${name}` (the frame's title, the media's and the text region's names) |
loading | (name) => `Loading ${name}…` |
error | (name) => `${name} couldn't be loaded` |
retry | "Retry" |
unsupported | "No preview for this file type" |
viewer | "This browser can't show PDFs here" |
truncated | (shown, total) => `Showing the first ${shown} of ${total}` |
pages | "Only the first page may show here." |
open | "Open in new tab" |
openError | (name) => `${name} couldn't be opened` |
download | { label, loading, error }, as on DownloadButton |
cv-lina-haddad.docx
Aucun aperçu pour ce type de fichier
Code
<IntlProvider locale="fr-FR">
<FilePreview
file={cv}
translations={{
label: (name) => `Aperçu de ${name}`,
loading: (name) => `Chargement de ${name}…`,
error: (name) => `Impossible de charger ${name}`,
retry: 'Réessayer',
unsupported: 'Aucun aperçu pour ce type de fichier',
viewer: 'Ce navigateur ne peut pas afficher les PDF ici',
truncated: (shown, total) => `Affichage des ${shown} premiers sur ${total}`,
pages: 'Seule la première page peut s’afficher ici.',
open: 'Ouvrir dans un nouvel onglet',
openError: (name) => `Impossible d’ouvrir ${name}`,
download: { label: 'Télécharger' },
}}
/>
</IntlProvider>On a right-to-left page the header mirrors (logical properties throughout), and text files set dir="auto", so an Arabic or Hebrew file reads from its own side. The PDF viewer and the media controls are the browser's, in the browser's language.
Accessibility
- A named, reachable PDF. The PDF's
<object>has anaria-label("Preview of contract.pdf", fromtranslations.label) and is a tab stop; the video and audio elements are named the same way. Once focus is inside, the browser's viewer owns the keys (arrows andEndscroll the pages);Shift+Tabcomes back out to the header. Focused, it shows the kit's ring, drawn on an overlay after it (peer-focus-visible): its own ring would paint under the viewer. - A reachable text region. Text sits in a
ScrollAreanamed the same way, a region that joins the tab order while it overflows, so a keyboard user can scroll it with the arrow keys. Its ring is the kit's, inside its edge. - Real buttons. Open, Download and Retry are buttons named by their text; in a narrow header the text is visually hidden but stays the name.
- Loading and errors. The spinner is named "Loading contract.pdf…" and the content is
aria-busy. A failure is announced once, through a polite status region, and focus moves to the content on Retry. - Captions are the file's own: the kit has no track to add to a video.
API
Prop
Type
The root carries data-view (pdf, image, video, audio, text or none), data-kind and data-status (loading, error or ready), for styling and tests. FilePreview.Open takes onError, and Button's props; FilePreview.Download takes DownloadButton's, except data and name.
Changelog
- #494
FilePreview's text pane and CalendarHeatmap's weeks scroll with the kit's scrollbars
- #371
New
FilePreviewshows a PDF, image, video, audio or text file with the browser's own viewers fromfile,srcor an asyncdataloader, with Open and Download actions; only allowlisted types render, so an uploaded HTML or SVG never runs as your app.openFile(source)opens one in a tab under the same rules
Lightbox
A full-screen image viewer that grows out of the thumbnail you clicked, with swipe, pinch, zoom and drag-to-dismiss, and shrinks back into the tile of the image you end on.
Carousel
A row of slides that scrolls a page at a time, with buttons, page dots and an optional autoplay. Built on native scroll snap, so touch, trackpads and right-to-left work as the browser does.