+ )
+ }
+ />
+
+
+
+
+
+
+ {preview.bytes && (
+
+ )}
+ >
+ )
+}
+
+const root = document.getElementById('root')
+if (!root) throw new Error('Missing fixture root')
+createRoot(root).render()
diff --git a/packages/img/browser/playwright.config.ts b/packages/img/browser/playwright.config.ts
new file mode 100644
index 00000000..7a8be9fa
--- /dev/null
+++ b/packages/img/browser/playwright.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig, devices } from '@playwright/test'
+
+export default defineConfig({
+ testDir: '.',
+ outputDir: '../../../test-results/viewer-documents',
+ projects: [
+ { name: 'chromium', use: { browserName: 'chromium' } },
+ { name: 'mobile-webkit', use: { ...devices['iPhone 13'], defaultBrowserType: 'webkit' } },
+ ],
+ use: { viewport: { width: 390, height: 844 } },
+})
diff --git a/packages/img/docs/react-storage.md b/packages/img/docs/react-storage.md
index 424a2507..db9f87e9 100644
--- a/packages/img/docs/react-storage.md
+++ b/packages/img/docs/react-storage.md
@@ -6,7 +6,7 @@ Built-ins. Install `@transloadit/viewer@alpha` alongside React 19. Receipts come
authenticated data layer; credentials stay in your server route.
The optional `/react/preview` entry requires **0.0.6+**. The `/react/video` entry requires
**0.0.8+**; see [private video playback](#private-video-playback).
-The `/react/viewer` and `/documents` entries require **0.2.0+**.
+The `/react/viewer` and `/documents` entries require **0.2.0+**. The document hook, PDF.js mode, and stylesheet described below are introduced in **0.3.0**.
```tsx
import { Image, getStorageAssetHref } from '@transloadit/viewer/react'
@@ -404,7 +404,7 @@ static catalogs, custom Templates, markup, and low-level models remain supported
`Viewer` from `@transloadit/viewer/react/viewer` serves applications that already authorize
and sign their media. It renders responsive image models, direct thumbnail URLs, native video
-and audio, browser PDF frames, Markdown, plain text, and RTF. The separate entry keeps document
+and audio, paginated PDFs or browser PDF frames, Markdown, plain text, and RTF. The separate entry keeps document
parsers and playback code out of existing image-only entry points. The shared Viewer entry also
loads document parsers and HLS dynamically, so image and native-media previews do not load them.
Direct images default to lazy loading and asynchronous decoding; use `loading="eager"` for a
@@ -480,44 +480,79 @@ fallback waits for it to finish without a client timeout. Unmounting, terminal f
`play()`/`prepare()` attempt aborts the warm-up request. The hook does not inspect the opaque
response or verify that the server prepared the MP4.
-For documents, read the existing authorized URL on demand using `readDocumentPreview` from
-`@transloadit/viewer/documents`, then pass its `ArrayBuffer` to Viewer:
+### Choosing and opening a document
+
+`viewerKind(mime, filename)` from `/documents` or `/react/viewer` returns `image`, `video`, `audio`, `pdf`, `markdown`, `text`, `rtf`, or `null`. Use the last three as the `format` of a `kind="document"` Viewer. It recognizes CSV, JSON, logs, YAML and common Markdown extensions with missing or generic MIME. SVG returns `null` because an SVG opened as a document can contain active content. For the PDF.js reader, pass `viewerKind(mime, filename, 'pdfjs')` to also recognize an `application/octet-stream` file named `.pdf`. Frame classification requires `application/pdf`.
```tsx
-
-
-Loading…
}
+ {preview.bytes && }
+ {preview.status !== 'idle' && }
+ >
+}
```
-`readDocumentPreview` reads are bounded to 2 MiB and omit credentials and referrers.
-HTTP 401 and 403 responses become `DocumentPreviewError` with reason `expired`;
-other HTTP failures and responses without a readable body become `unavailable`,
-and oversized reads become `too-large`; these errors omit signed URLs and response bodies.
-Network, stream, CORS and abort errors propagate unchanged. Cross-origin document URLs must
-allow CORS reads from the application origin.
-
-RTF parsing and rich Markdown are bounded to 256 KiB; larger Markdown is shown as literal text.
-RTF above 256 KiB and any document above 2 MiB render `errorFallback` and call `onError`.
-Markdown skips embedded HTML and shows every image as its alt text without loading it.
-Links render only for absolute `http:`, `https:` and `mailto:` URLs; other links render as plain
-text. RTF is parsed locally, strips active content and embedded resources, and renders in a sandbox
-with a restrictive content security policy. PDF frames use the browser's
-PDF renderer; supply an authorized HTTP(S) URL on a separate user-content origin whose response
-has a verified PDF MIME type. Viewer always rejects non-HTTP(S) locations, including `blob:`,
-`data:` and `javascript:` URLs. It rejects the page's exact origin unless `allowSameOrigin` is set;
-other subdomains of the same site pass this check. The application must verify the PDF MIME type
-and origin isolation; Viewer does not check the response MIME type or sandbox the PDF frame.
-An application with a trusted PDF-only route can explicitly set `allowSameOrigin`; that route must
-verify the response is a PDF and must never serve arbitrary uploaded HTML. Use `errorFallback`
-for a rejected location. Arbitrary HTML and Office documents are not embedded.
-
-`className` styles the Markdown/text article or the RTF iframe. `richClassName` styles rendered
-Markdown only, and `textClassName` styles the literal text view.
-
-Document chunk-load and parser failures render `errorFallback` and notify `onError`. Unmount and
-reopen the preview to create a fresh React lazy loader after a failed chunk request.
-PDF server rendering waits for the client origin before
-deciding whether a URL is allowed, without showing a premature error.
+Opening fetches the authorized `mediaUrl` with omitted credentials and referrer. Cross-origin responses need CORS. The hook requires `asset_id`. Supply `version_id` to bind every renewal to that version. `expiresAt` is optional (epoch milliseconds), and `mediaUrl` may be omitted when `renew(signal)` resolves the initial grant. Set `autoOpen` to open on mount and asset/version changes. It renews once per attempt when the URL is missing, near expiry, or returns HTTP 401/403. Retry renews before reusing a denied grant. Closing, unmounting and changing the selection abort pending work. `timeoutMs` defaults to 30 seconds of inactivity. A 401 is `expired`, a 403 is `forbidden`, and a stall is `network`.
+
+The hook reads at most 2 MiB of text or Markdown plus the stream chunk needed to detect overflow. Pass its `truncated` flag to Viewer for a visible notice and its response `mime` for decoding. When passing your own bytes, supply the corresponding MIME, including its charset. A Unicode BOM takes priority. Unknown encodings fall back to UTF-8. Markdown above 256 KiB displays a notice and literal text. Rich Markdown skips embedded HTML, shows images as alt text, and permits only absolute HTTP(S) and mailto links. RTF requires a complete document of at most 256 KiB. Its formatting-only output is rendered in a sandboxed iframe. Pass the application's explicit `colorScheme` (`'light'` or `'dark'`) or choose `'auto'` to follow the OS. Set `rtfColors={{ text, background }}` for the sandboxed body’s default colors. Explicit document colors take precedence.
+
+Existing callers can still use `readDocumentPreview(url, signal)` from `/documents`. This strict reader returns an ArrayBuffer and rejects oversized reads. Its original HTTP error categories are preserved. Reopening a document remounts its lazy renderer after a chunk-load error.
+
+### PDF pages on phones
+
+```tsx
+import '@transloadit/viewer/viewer.css'
+import { Viewer } from '@transloadit/viewer/react/viewer'
+
+ resolvePdfGrant(asset, signal)}
+ renderError={(reason, retry) => }
+ onLoad={onFirstPageRendered} onError={onPreviewError} />
+```
+
+Deploy the matching browser assets from the Viewer package to the application’s own origin. Copy the whole directory so scanned slides can load their JavaScript image decoders and text can use PDF character maps and fallback fonts. For a site that serves `public/` at its root, run this ESM build step:
+
+```ts
+import { cp } from 'node:fs/promises'
+
+await cp(
+ new URL('.', import.meta.resolve('@transloadit/viewer/pdf.worker.mjs')),
+ 'public/assets/transloadit-viewer',
+ { recursive: true },
+)
+```
+
+Serve the `.mjs` and `.js` files as JavaScript modules. The default worker URL is `/assets/transloadit-viewer/pdf.worker.min.mjs`. Set `workerSrc` if you serve the directory under a different public path. Character maps, fonts and image decoders resolve relative to the worker. Set `assetBaseUrl` if those subdirectories live elsewhere on the app origin. Deploy the assets together with each Viewer update.
+
+The document reader supports Safari 17.0 and later on iPhone, iPad and Mac. It uses the packaged legacy PDF.js browser build.
+
+Give PDF.js the final authorized HTTP(S) URL on a separate origin. The reader sends GET requests with omitted credentials and referrer, rejects redirects and validates each response MIME. For octet-stream PDFs, supply the verified candidate filename when the URL path lacks a `.pdf` extension. Use `allowSameOrigin` only for a trusted PDF-only application endpoint.
+
+PDF.js requests the chunks it needs from servers supporting byte ranges. Serve `Accept-Ranges: bytes`, an accurate `Content-Length`, uncompressed PDF bytes and standard `206` range responses. For a separate file origin enable CORS, including on 401/403 responses, and expose `Accept-Ranges, Content-Length, Content-Range, Content-Encoding`. Without range support, PDF.js streams the GET to its worker. Both paths enforce a 64 MiB file limit.
+
+Set `documentKey` to a stable identifier for the immutable asset version. Updates to `src` or `expiresAt` then apply to subsequent requests while preserving the current page, zoom and loaded document. Changing the key opens the new version on page one. Without a key, the resolved initial URL identifies the document. Omit `src` to obtain the first grant from `renew(signal)`. Bind renewal to the same immutable version. Return `{ mediaUrl, expiresAt? }` on the original file origin. A 401/403 on a later range renews the grant and replays that range with the new URL. Concurrent ranges share a renewal. The optional `timeoutMs` defaults to 30 seconds of inactivity. `onLoad()` fires after the first page renders and `onError(reason)` receives a typed failure. Provide `renderError(reason, retry)` for an application-owned retry button. `invalid-url` and `invalid-mime` use error feedback. `unsupportedFallback` handles missing reader support.
+
+Import the stylesheet for the positioned text layer. Each page keeps its old canvas and text until the replacement is ready, with up to four million backing pixels per canvas. Readers can select text, enter a page number, zoom, fit width or fit the page within `--tl-viewer-pdf-height` (default `70dvh`). Swipe horizontally to turn pages when the page fits the viewport width. Left/Right and PageUp/PageDown move one page, Home/End jump to the ends, and Escape bubbles to the host dialog. Pass an `originalLink` element only when downloads are allowed. For short-lived URLs the app can resolve a fresh grant when the user activates that action.
+
+A strict application CSP can allow `script-src 'self'`, `worker-src 'self'`, `style-src 'self'`, `font-src 'self'` and `connect-src 'self' https://your-file-origin.example`. Serve chunks, fonts and the worker on the app origin. The worker response also needs `connect-src 'self'` and `script-src 'self'` to load matching maps, fonts and scan decoders. This configuration uses PDF.js fallback colors for ICC profiles.
+
+`mode="frame"` is the default. Point it at an endpoint verified to serve `application/pdf` throughout navigation, and allow that host in `frame-src`. Pass its verified `mime` when available. The frame shows `loadingFallback` while opening. A browser error or a load exceeding `timeoutMs` (30 seconds by default) shows Retry. Use `renderError(reason, retry)` to customize this feedback. The browser frame receives an absolute `src` resolved against the document base URI. `onLoad(event)` receives the React iframe load event. `onError(reason)` reports invalid inputs or browser-reported failures. Browsers hide cross-origin HTTP status from iframe callbacks. Set `unsupportedFallback` for browsers that report no inline PDF support. For a GET-only signed URL, resolve the grant from your data layer and pass it directly to PDF.js. Office documents require upstream conversion.
+
+### Document styles
+
+Import `@transloadit/viewer/viewer.css` to opt into default document typography, link colors, wrapping, and page controls. Override `--tl-viewer-font`, `--tl-viewer-color`, `--tl-viewer-background`, `--tl-viewer-padding`, and `--tl-viewer-link` on an ancestor. `className` styles the Markdown/text article or RTF iframe, `richClassName` styles rendered Markdown, and `textClassName` styles literal text. For Markdown, map `--tl-viewer-border`, `--tl-viewer-code-background`, `--tl-viewer-monospace`, `--tl-viewer-heading-weight` and `--tl-viewer-paragraph-gap` to app tokens. For localized PDF controls, pass `labels` with strings for `navigation`, `previous`, `next`, `pageInput`, `zoomIn`, `zoomOut`, `fitWidth`, `fitPage` and `retry`, and formatters for `page(number)` and `position(number, count, percent)`. Set document `notices.truncated` and `notices.rawMarkdown` to translate the visible notices.
diff --git a/packages/img/package.json b/packages/img/package.json
index 3e436eea..af273f5f 100644
--- a/packages/img/package.json
+++ b/packages/img/package.json
@@ -16,7 +16,8 @@
"files": [
"dist",
"docs",
- "README.md"
+ "README.md",
+ "viewer.css"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -81,14 +82,17 @@
"./documents": {
"types": "./dist/document.d.ts",
"default": "./dist/document.js"
- }
+ },
+ "./viewer.css": "./viewer.css",
+ "./pdf.worker.mjs": "./dist/pdf-assets/pdf.worker.min.mjs"
},
"scripts": {
- "build": "../../node_modules/.bin/tsc --build tsconfig.build.json",
+ "build": "../../node_modules/.bin/tsc --build tsconfig.build.json && node ./scripts/prepare-pdf-assets.ts",
"check": "yarn lint:ts && yarn test:unit",
"lint:ts": "../../node_modules/.bin/tsc --build tsconfig.build.json && ../../node_modules/.bin/tsc --noEmit --project tsconfig.json",
"prepack": "yarn build",
- "test:unit": "yarn build && ../../node_modules/.bin/vitest run ./test"
+ "test:unit": "yarn build && ../../node_modules/.bin/vitest run ./test",
+ "test:browser": "yarn build && playwright test --config browser/playwright.config.ts"
},
"dependencies": {
"@noble/ciphers": "^1.3.0",
@@ -120,12 +124,21 @@
}
},
"devDependencies": {
+ "@playwright/test": "1.64.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
+ "core-js": "^3.51.0",
"esbuild": "^0.28.2",
"happy-dom": "^20.9.0",
"next": "16.3.4",
+ "pdfjs-dist": "6.5.438",
"react": "^19.2.6",
"react-dom": "^19.2.6"
+ },
+ "imports": {
+ "#pdfjs": {
+ "types": "pdfjs-dist/legacy/build/pdf.mjs",
+ "default": "./dist/pdf.min.mjs"
+ }
}
}
diff --git a/packages/img/scripts/pdfCompatibility.ts b/packages/img/scripts/pdfCompatibility.ts
new file mode 100644
index 00000000..d77c04c3
--- /dev/null
+++ b/packages/img/scripts/pdfCompatibility.ts
@@ -0,0 +1,3 @@
+// The legacy PDF.js build assumes both APIs exist, including in the module worker.
+import 'core-js/modules/es.array-buffer.transfer-to-fixed-length.js'
+import 'core-js/modules/es.promise.with-resolvers.js'
diff --git a/packages/img/scripts/prepare-pdf-assets.ts b/packages/img/scripts/prepare-pdf-assets.ts
new file mode 100644
index 00000000..cc509ca4
--- /dev/null
+++ b/packages/img/scripts/prepare-pdf-assets.ts
@@ -0,0 +1,44 @@
+import { copyFile, cp, mkdir, readFile, writeFile } from 'node:fs/promises'
+
+import { build } from 'esbuild'
+
+const root = new URL('.', import.meta.resolve('pdfjs-dist/package.json'))
+const dist = new URL('../dist/', import.meta.url)
+const assets = new URL('pdf-assets/', dist)
+await mkdir(new URL('wasm/', assets), { recursive: true })
+
+// Both browser realms need the Safari 17.0 additions before PDF.js initializes.
+const { outputFiles } = await build({
+ absWorkingDir: import.meta.dirname,
+ entryPoints: ['./pdfCompatibility.ts'],
+ bundle: true,
+ format: 'iife',
+ minify: true,
+ target: 'safari17',
+ write: false,
+})
+async function prepareModule(name: string, target: URL, imports = ''): Promise {
+ const source = await readFile(new URL(`legacy/build/${name}.min.mjs`, root), 'utf8')
+ await writeFile(target, [imports, outputFiles[0].text, source].join('\n'))
+}
+
+await Promise.all([
+ prepareModule(
+ 'pdf',
+ new URL('pdf.min.mjs', dist),
+ "import { fetchPdfResource as fetch } from './pdfNetwork.js'",
+ ),
+ prepareModule('pdf.worker', new URL('pdf.worker.min.mjs', assets)),
+ copyFile(new URL('LICENSE', root), new URL('LICENSE.pdfjs', assets)),
+ copyFile(new URL(import.meta.resolve('core-js/LICENSE')), new URL('LICENSE.core-js', assets)),
+ cp(new URL('cmaps/', root), new URL('cmaps/', assets), { recursive: true }),
+ cp(new URL('standard_fonts/', root), new URL('standard_fonts/', assets), { recursive: true }),
+ ...[
+ 'jbig2_nowasm_fallback.js',
+ 'openjpeg_nowasm_fallback.js',
+ 'LICENSE_JBIG2',
+ 'LICENSE_PDFJS_JBIG2',
+ 'LICENSE_OPENJPEG',
+ 'LICENSE_PDFJS_OPENJPEG',
+ ].map((name) => copyFile(new URL(`wasm/${name}`, root), new URL(`wasm/${name}`, assets))),
+])
diff --git a/packages/img/src/document.ts b/packages/img/src/document.ts
index 22630eed..f6a852f4 100644
--- a/packages/img/src/document.ts
+++ b/packages/img/src/document.ts
@@ -1,95 +1,94 @@
+import { DocumentPreviewError, readPreviewContent } from './readPreviewContent.ts'
+
+export type { DocumentPreviewReason } from './readPreviewContent.ts'
+
+export { DocumentPreviewError } from './readPreviewContent.ts'
+
/** Document formats Viewer can display without sending bytes to another service. */
export type DocumentPreviewKind = 'pdf' | 'markdown' | 'text' | 'rtf'
+export type ViewerKind = DocumentPreviewKind | 'audio' | 'image' | 'video'
-/**
- * PDF requires application/pdf. Markdown, RTF and text may use the filename when MIME is null,
- * application/octet-stream or text/plain.
- */
+/** Choose a preview from catalog metadata. PDF detection alone does not authorize embedding. */
export function documentPreviewKind(
- mime: string | null,
+ mime: string | null | undefined,
filename: string,
): DocumentPreviewKind | null {
- const type = mime?.split(';', 1)[0]?.trim().toLowerCase() ?? null
+ const type = mime?.split(';', 1)[0]?.trim().toLowerCase()
if (type === 'application/pdf') return 'pdf'
if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'
if (type === 'application/rtf' || type === 'text/rtf' || type === 'application/x-rtf')
return 'rtf'
- if (type !== null && type !== 'application/octet-stream' && type !== 'text/plain') return null
- const extension = filename.split('.').at(-1)?.toLowerCase()
- if (extension === 'md' || extension === 'markdown') return 'markdown'
- if (extension === 'rtf') return 'rtf'
- if (extension === 'txt' || type === 'text/plain') return 'text'
+ if (
+ type &&
+ /^(?:text\/(?:csv|tab-separated-values|yaml|x-yaml|log)|application\/(?:json|yaml|x-yaml|[\w.+-]+\+json))$/.test(
+ type,
+ )
+ )
+ return 'text'
+ if (type && type !== 'application/octet-stream' && type !== 'text/plain') return null
+ if (/\.(?:md|markdown|mdown|mkdn?|mkdown|mdwn)$/i.test(filename)) return 'markdown'
+ if (/\.rtf$/i.test(filename)) return 'rtf'
+ if (/\.(?:txt|csv|tsv|json|log|ya?ml)$/i.test(filename) || type === 'text/plain') return 'text'
return null
}
-/** Text previews stay bounded even when an origin omits or misreports Content-Length. */
-export const MAX_DOCUMENT_PREVIEW_BYTES = 2 * 1024 * 1024
+/** Classify media and documents consistently across lists and detail views. */
+export function viewerKind(
+ mime: string | null | undefined,
+ filename: string,
+ mode: 'frame' | 'pdfjs' = 'frame',
+): ViewerKind | null {
+ const type = mime?.split(';', 1)[0]?.trim().toLowerCase()
+ // SVG can contain active content when opened directly.
+ if (type === 'image/svg+xml') return null
+ if (mode === 'pdfjs' && type === 'application/octet-stream' && /\.pdf$/i.test(filename))
+ return 'pdf'
+ const family = type?.split('/')[0]
+ if (mime?.includes('/') && (family === 'image' || family === 'video' || family === 'audio'))
+ return family
+ return documentPreviewKind(mime, filename)
+}
-/** Rich document parsers keep a smaller bound than literal text. */
+export const MAX_DOCUMENT_PREVIEW_BYTES = 2 * 1024 * 1024
export const MAX_RICH_DOCUMENT_PREVIEW_BYTES = 256 * 1024
-/** HTTP and size error categories whose messages omit signed URLs and response bodies. */
-export class DocumentPreviewError extends Error {
- readonly reason: 'too-large' | 'expired' | 'unavailable'
-
- constructor(reason: DocumentPreviewError['reason']) {
- super(`Document preview ${reason}`)
- this.reason = reason
- }
-}
-
-/**
- * Read an authorized, CORS-readable URL with a streaming size limit. HTTP and size failures use
- * DocumentPreviewError; network, stream and abort errors propagate unchanged.
- */
+/** Original strict reader, including its 0.2 HTTP error categories. */
export async function readDocumentPreview(url: string, signal: AbortSignal): Promise {
- const response = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' })
- if (!response.ok) {
- await response.body?.cancel()
- throw new DocumentPreviewError(
- response.status === 401 || response.status === 403 ? 'expired' : 'unavailable',
- )
- }
- if (Number(response.headers.get('content-length')) > MAX_DOCUMENT_PREVIEW_BYTES) {
- await response.body?.cancel()
- throw new DocumentPreviewError('too-large')
- }
- if (response.body === null) throw new DocumentPreviewError('unavailable')
- const reader = response.body.getReader()
- const chunks: Uint8Array[] = []
- let length = 0
try {
- while (true) {
- signal.throwIfAborted()
- const { done, value } = await reader.read()
- if (done) break
- length += value.byteLength
- if (length > MAX_DOCUMENT_PREVIEW_BYTES) {
- await reader.cancel()
- throw new DocumentPreviewError('too-large')
- }
- chunks.push(value)
+ return (await readPreviewContent(url, signal, { limit: MAX_DOCUMENT_PREVIEW_BYTES })).bytes
+ } catch (error) {
+ if (error instanceof DocumentPreviewError) {
+ if (error.reason === 'forbidden') throw new DocumentPreviewError('expired')
+ if (error.reason === 'network') throw new DocumentPreviewError('unavailable')
}
- } finally {
- reader.releaseLock()
- }
- const bytes = new Uint8Array(length)
- let offset = 0
- for (const chunk of chunks) {
- bytes.set(chunk, offset)
- offset += chunk.byteLength
+ throw error
}
- return bytes.buffer
}
-/** Preserve UTF-8 and Unicode text exports with a UTF-16 byte-order mark. */
-export function decodeDocumentText(buffer: ArrayBuffer): string {
- const bytes = new Uint8Array(buffer)
- const encoding =
- bytes[0] === 0xff && bytes[1] === 0xfe
- ? 'utf-16le'
- : bytes[0] === 0xfe && bytes[1] === 0xff
- ? 'utf-16be'
- : 'utf-8'
- return new TextDecoder(encoding).decode(bytes)
+/** A Unicode BOM takes precedence over the MIME charset. Unknown labels fall back to UTF-8. */
+export function decodeDocumentText(
+ buffer: ArrayBuffer,
+ mime?: string | null,
+ truncated = false,
+): string {
+ const bytes = new Uint8Array(
+ buffer,
+ 0,
+ truncated ? Math.min(buffer.byteLength, MAX_DOCUMENT_PREVIEW_BYTES) : buffer.byteLength,
+ )
+ let encoding = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;\s]+))/i
+ .exec(mime ?? '')
+ ?.slice(1)
+ .find(Boolean)
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) encoding = 'utf-16le'
+ else if (bytes[0] === 0xfe && bytes[1] === 0xff) encoding = 'utf-16be'
+ else if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) encoding = 'utf-8'
+ let decoder: TextDecoder
+ try {
+ decoder = new TextDecoder(encoding)
+ } catch {
+ decoder = new TextDecoder()
+ }
+ // A partial multibyte character at the truncation boundary belongs to the omitted suffix.
+ return decoder.decode(bytes, { stream: truncated || bytes.byteLength < buffer.byteLength })
}
diff --git a/packages/img/src/documentViewer.tsx b/packages/img/src/documentViewer.tsx
index 29884e4e..815fc2d7 100644
--- a/packages/img/src/documentViewer.tsx
+++ b/packages/img/src/documentViewer.tsx
@@ -3,7 +3,7 @@
import type { Components } from 'hast-util-to-jsx-runtime'
import type { ReactNode } from 'react'
-import type { DocumentPreviewKind } from './document.ts'
+import type { DocumentPreviewKind, DocumentPreviewReason } from './document.ts'
import { toJsxRuntime } from 'hast-util-to-jsx-runtime'
import { Component, Fragment, useEffect, useMemo, useRef, useState } from 'react'
@@ -38,7 +38,12 @@ export interface DocumentViewerProps {
/** Shown when document loading, parsing or size validation fails. */
errorFallback?: ReactNode
/** Reports a document loading, parsing or size failure. */
- onError?: () => void
+ onError?: (reason: DocumentPreviewReason) => void
+ mime?: string | null
+ truncated?: boolean
+ notices?: { truncated?: string; rawMarkdown?: string }
+ rtfColors?: { text?: string; background?: string }
+ colorScheme?: 'light' | 'dark' | 'auto'
}
const markdownProcessor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype)
@@ -61,6 +66,8 @@ function RichText({
bytes,
title,
className,
+ colorScheme,
+ rtfColors,
loadingFallback,
errorFallback,
onError,
@@ -78,7 +85,9 @@ function RichText({
let active = true
// RTF's parser is loaded only when a rich-text document is actually opened.
void import('./renderRtfPreview.ts')
- .then(({ renderRtfPreview }) => renderRtfPreview(bytes))
+ .then(({ renderRtfPreview }) =>
+ renderRtfPreview(bytes, colorScheme, rtfColors?.text, rtfColors?.background),
+ )
.then(
(html) => {
if (active) setResult({ bytes, html })
@@ -86,17 +95,18 @@ function RichText({
() => {
if (!active) return
setResult({ bytes, failed: true })
- reportError.current?.()
+ reportError.current?.('parse')
},
)
return () => {
active = false
}
- }, [bytes])
+ }, [bytes, colorScheme, rtfColors?.text, rtfColors?.background])
if (result?.bytes !== bytes) return loadingFallback
if (result.failed || result.html === undefined) return errorFallback
return (