From be3ddaca86105218ad3bdaeb5d4e151ce05244fe Mon Sep 17 00:00:00 2001 From: Kevin van Zonneveld Date: Sat, 28 Nov 2026 13:39:36 +0100 Subject: [PATCH 1/5] Add mobile PDF pages and bounded document previews to Viewer --- .changeset/mobile-document-preview.md | 7 + .github/workflows/ci.yml | 1 + packages/img/browser/documents.spec.ts | 158 ++++++++++ packages/img/browser/fixture.tsx | 38 +++ packages/img/browser/playwright.config.ts | 11 + packages/img/docs/react-storage.md | 97 +++--- packages/img/package.json | 14 +- packages/img/scripts/copy-pdf-worker.ts | 7 + packages/img/src/document.ts | 135 ++++----- packages/img/src/documentViewer.tsx | 71 +++-- packages/img/src/pdfViewer.tsx | 253 ++++++++++++++++ packages/img/src/readPreviewContent.ts | 81 +++++ packages/img/src/renderRtfPreview.ts | 19 +- packages/img/src/useDocumentPreview.ts | 141 +++++++++ packages/img/src/viewer.tsx | 92 +++++- packages/img/test/documentPreview.test.ts | 34 ++- packages/img/test/packaging.test.ts | 3 +- packages/img/test/pdfViewer.test.tsx | 106 +++++++ packages/img/test/useDocumentPreview.test.tsx | 133 +++++++++ packages/img/test/viewer.test.tsx | 47 ++- packages/img/viewer.css | 35 +++ scripts/fixtures/img-next/package-lock.json | 278 ++++++++++++++++++ scripts/fixtures/img-next/package.json | 1 + yarn.lock | 135 +++++++++ 24 files changed, 1736 insertions(+), 161 deletions(-) create mode 100644 .changeset/mobile-document-preview.md create mode 100644 packages/img/browser/documents.spec.ts create mode 100644 packages/img/browser/fixture.tsx create mode 100644 packages/img/browser/playwright.config.ts create mode 100644 packages/img/scripts/copy-pdf-worker.ts create mode 100644 packages/img/src/pdfViewer.tsx create mode 100644 packages/img/src/readPreviewContent.ts create mode 100644 packages/img/src/useDocumentPreview.ts create mode 100644 packages/img/test/pdfViewer.test.tsx create mode 100644 packages/img/test/useDocumentPreview.test.tsx create mode 100644 packages/img/viewer.css diff --git a/.changeset/mobile-document-preview.md b/.changeset/mobile-document-preview.md new file mode 100644 index 00000000..d00344a1 --- /dev/null +++ b/.changeset/mobile-document-preview.md @@ -0,0 +1,7 @@ +--- +'@transloadit/viewer': minor +--- + +Add an opt-in, single-page PDF.js reader for mobile and desktop with a same-origin worker, keyboard navigation, and fit-to-width rendering. Add `viewerKind`, `useDocumentPreview`, typed document error callbacks, an optional stylesheet, and RTF color schemes. Text and Markdown previews honor the MIME charset and display notices for truncation and literal Markdown. + +In this alpha, `documentPreviewKind` recognizes additional file extensions including generic-MIME PDFs. Detection still requires the application to verify a PDF before embedding it. Oversized text/Markdown passed to Viewer now shows the first 2 MiB instead of calling `onError`. The original strict `readDocumentPreview` keeps its runtime return value and error behavior. The exported `DocumentPreviewError.reason` type additionally includes the new preview reasons. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f0b0d60..f149e8f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -253,6 +253,7 @@ jobs: - name: Install Corepack run: npm install --global corepack@0.36.0 - run: corepack yarn install --immutable + - run: corepack yarn workspace @transloadit/viewer test:browser - run: corepack yarn workspace @transloadit/mcp-server test:visual - uses: actions/upload-artifact@v7 if: always() diff --git a/packages/img/browser/documents.spec.ts b/packages/img/browser/documents.spec.ts new file mode 100644 index 00000000..38193c12 --- /dev/null +++ b/packages/img/browser/documents.spec.ts @@ -0,0 +1,158 @@ +import type { Server } from 'node:http' + +import { once } from 'node:events' +import { readFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { basename } from 'node:path' + +import { test as base, expect } from '@playwright/test' +import { build } from 'esbuild' + +// Paint solid colors so the test can distinguish rasterized pages from blank or stale canvases. +function slideDeck(): Buffer { + const objects = [ + '<< /Type /Catalog /Pages 2 0 R >>', + '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', + ...[5, 6].map( + (stream) => + `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << >> /Contents ${stream} 0 R >>`, + ), + ...['1 0 0', '0 0 1'].map((rgb) => { + const content = `${rgb} rg 0 0 200 100 re f\n` + return `<< /Length ${content.length} >>\nstream\n${content}endstream` + }), + ] + let pdf = '%PDF-1.4\n' + const offsets: number[] = [] + for (const [i, object] of objects.entries()) { + offsets.push(pdf.length) + pdf += `${i + 1} 0 obj\n${object}\nendobj\n` + } + const xref = pdf.length + pdf += 'xref\n0 7\n0000000000 65535 f \n' + for (const offset of offsets) pdf += `${String(offset).padStart(10, '0')} 00000 n \n` + return Buffer.from(`${pdf}trailer\n<< /Root 1 0 R /Size 7 >>\nstartxref\n${xref}\n%%EOF\n`) +} + +async function listen(server: Server): Promise { + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (!address || typeof address === 'string') throw new Error('Missing test server port') + return `http://127.0.0.1:${address.port}` +} + +const test = base.extend({ + // biome-ignore lint/correctness/noEmptyPattern: Playwright discovers fixture dependencies from the destructured parameter. + baseURL: async ({}, use) => { + await using files = createServer((req, res) => { + res.setHeader('Access-Control-Allow-Origin', '*') + if (req.url === '/report') { + res.writeHead(200, { 'Content-Type': 'application/pdf' }).end(slideDeck()) + } else if (req.url === '/notes') { + res + .writeHead(200, { 'Content-Type': 'text/markdown; charset=windows-1252' }) + .end( + Buffer.concat([ + Buffer.from([0xe9]), + Buffer.alloc(2 * 1024 * 1024, 65), + Buffer.from('OMITTED'), + ]), + ) + } else res.writeHead(404).end() + }) + const fileOrigin = await listen(files) + const { outputFiles } = await build({ + entryPoints: [new URL('./fixture.tsx', import.meta.url).pathname], + outdir: 'browser-build', + bundle: true, + splitting: true, + format: 'esm', + write: false, + minify: true, + jsx: 'automatic', + define: { fileOrigin: JSON.stringify(fileOrigin) }, + }) + const assets = new Map( + outputFiles.map((file) => [basename(file.path), Buffer.from(file.contents)]), + ) + assets.set( + 'pdf.worker.min.mjs', + await readFile(new URL(import.meta.resolve('@transloadit/viewer/pdf.worker.mjs'))), + ) + await using app = createServer((req, res) => { + if (req.url === '/') { + res + .writeHead(200, { + 'Content-Type': 'text/html', + 'Content-Security-Policy': `default-src 'none'; script-src 'self'; worker-src 'self'; connect-src ${fileOrigin}; style-src 'self'; base-uri 'none'`, + }) + .end( + '
', + ) + return + } + const path = req.url?.slice(1) ?? '' + const bytes = assets.get(path) + if (!bytes) { + res.writeHead(404).end() + return + } + res + .writeHead(200, { + 'Content-Type': path.endsWith('.css') ? 'text/css' : 'application/javascript', + }) + .end(bytes) + }) + await use(await listen(app)) + }, +}) + +test('mobile-sized PDF pages render in a same-origin worker and oversized notes show their prefix', async ({ + page, + baseURL, +}) => { + const errors: string[] = [] + page.on('pageerror', (error) => errors.push(error.message)) + page.on('console', (msg) => { + if (msg.type() === 'error') errors.push(msg.text()) + }) + const worker = page.waitForEvent('worker') + await page.goto('/') + const first = page.getByRole('img', { name: 'PDF page 1' }) + await expect(first).toBeVisible() + expect((await worker).url()).toBe(`${baseURL}/pdf.worker.min.mjs`) + function pixel(element: Element): number[] { + if (!(element instanceof HTMLCanvasElement)) throw new Error('Expected PDF page canvas') + const ctx = element.getContext('2d') + if (!ctx) throw new Error('Missing canvas context') + return [...ctx.getImageData(5, 5, 1, 1).data] + } + expect(await first.evaluate(pixel)).toEqual([255, 0, 0, 255]) + const reader = page.getByRole('region', { name: 'Lecture slides' }) + await reader.focus() + await reader.press('ArrowRight') + const second = page.getByRole('img', { name: 'PDF page 2' }) + await expect(second).toBeVisible() + expect(await second.evaluate(pixel)).toEqual([0, 0, 255, 255]) + await expect(reader.getByRole('img')).toHaveCount(1) + await expect(reader).toBeFocused() + await page.setViewportSize({ width: 320, height: 600 }) + await expect + .poll(() => + second.evaluate((el) => + el instanceof HTMLCanvasElement ? el.width / window.devicePixelRatio : 0, + ), + ) + .toBeCloseTo(304, 0) + await page.getByRole('button', { name: 'Open notes' }).click() + const notes = page.getByRole('article', { name: 'Notes' }) + await expect(notes.getByText('Preview truncated to the first 2 MiB.')).toBeVisible() + await expect(notes.getByText(/Showing Markdown as plain text/)).toBeVisible() + await notes.evaluate((el) => el.style.setProperty('--tl-viewer-padding', '11px')) + await expect(notes).toHaveCSS('padding-left', '11px') + const literal = await notes.locator('pre').textContent() + expect(literal?.length).toBe(2 * 1024 * 1024) + expect(literal?.at(0)).toBe('é') + expect(errors).toEqual([]) +}) diff --git a/packages/img/browser/fixture.tsx b/packages/img/browser/fixture.tsx new file mode 100644 index 00000000..ba8a9b67 --- /dev/null +++ b/packages/img/browser/fixture.tsx @@ -0,0 +1,38 @@ +import { useDocumentPreview, Viewer } from '@transloadit/viewer/react/viewer' +import { createRoot } from 'react-dom/client' +import '@transloadit/viewer/viewer.css' + +declare const fileOrigin: string + +const source = { + asset_id: 'notes', + version_id: '1', + mediaUrl: `${fileOrigin}/notes`, + expiresAt: Date.now() + 60_000, +} + +function Fixture() { + const preview = useDocumentPreview({ source, format: 'markdown' }) + return ( + <> + + + {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..4e2c3a34 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,63 @@ 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. A PDF filename with missing or octet-stream catalog MIME is a candidate for the PDF reader. The delivery endpoint must independently verify the file and serve it as `application/pdf`. ```tsx - - -Loading…

} - errorFallback={

Could not display this document.

} /> - +import { useDocumentPreview, Viewer } from '@transloadit/viewer/react/viewer' +import type { DocumentSource } from '@transloadit/viewer/react/viewer' + +function Notes({ source, renew, size }: { + source: DocumentSource + renew: () => Promise + size: number +}) { + const preview = useDocumentPreview({ source, renew, size, format: 'markdown' }) + return <> + + {preview.status === 'loading' &&

Loading notes…

} + {preview.status === 'error' &&

Preview unavailable ({preview.reason}). +

} + {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 accepts the same version-bound identity and expiry clock as playback. It can renew once per attempt, before reading an expiring grant or after HTTP 401/403. Closing, unmounting, retrying or changing asset/version cancels the old attempt. Status moves from `idle` to `loading`, then `ready` or `error`. A 401 is `expired`, a 403 is `forbidden`, and other fetch failures are `network`. `onError(reason)` on document and PDF.js renderers also distinguishes `too-large`, `parse`, and `unsupported`. Applications own translated errors, retry buttons and original downloads. + +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. Use `colorScheme="dark"` or `"auto"` to override the default light rendering. + +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' + + +``` + +Serve the worker exported at `@transloadit/viewer/pdf.worker.mjs` as a JavaScript module on the application's own origin. Copy it at build time and update it together with the package. Bundlers that emit assets for `new URL('./pdf.worker.min.mjs', import.meta.url)` can omit `workerSrc`. Other bundlers need the explicit public path above. For example, run in your ESM build script after creating the destination directory: + +```ts +import { copyFile } from 'node:fs/promises' + +await copyFile(new URL(import.meta.resolve('@transloadit/viewer/pdf.worker.mjs')), 'public/assets/pdf.worker.min.mjs') +``` + +The document must be served directly from the authorized, separate HTTP(S) origin with CORS and a verified PDF MIME. PDF.js mode checks the GET response, rejects redirects, and omits credentials and the referrer. A trusted PDF-only application endpoint may explicitly set `allowSameOrigin`. Downloads are capped at 64 MiB. One page canvas is fitted to the container and limited to four million backing pixels. The previous canvas is released on navigation or resize. Tab to the reader or its buttons. Left/Right move one page, Home/End jump to the ends, and Escape bubbles to the host dialog. Supply `loadingFallback`, `errorFallback` or `unsupportedFallback` to customize feedback. Remount the reader to retry the same URL. + +A strict CSP can allow `script-src 'self'`, `worker-src 'self'`, `style-src 'self'` and `connect-src 'self' https://your-file-origin.example`. Serve chunks and the worker directly on the app origin. The canvas reader requires neither a blob worker nor unsafe evaluation. For PDFs using predefined CMaps, standard font files, ICC profiles, or supplementary image decoders, serve the matching `pdfjs-dist` directories (`cmaps/`, `standard_fonts/`, `iccs/`, `wasm/`) under a same-origin public directory and set `assetBaseUrl="/assets/pdfjs/"`. The reader selects the JavaScript decoder fallback when available. + +`mode="frame"` remains the default and uses the browser's inline PDF reader. It passes native iframe attributes, including `onLoad`, through to the frame. Provide `unsupportedFallback` (for example a download link) for browsers that report no inline PDF support. For this mode allow your verified file host in `frame-src`. The host must enforce PDF MIME and origin isolation for the entire navigation. Browser frame load events cannot identify HTTP authorization failures. Office documents require conversion to PDF upstream. + +### 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. RTF frame content uses its own color scheme. diff --git a/packages/img/package.json b/packages/img/package.json index 3e436eea..0a7eb1bd 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,20 +82,24 @@ "./documents": { "types": "./dist/document.d.ts", "default": "./dist/document.js" - } + }, + "./viewer.css": "./viewer.css", + "./pdf.worker.mjs": "./dist/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/copy-pdf-worker.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", "@transloadit/utils": "^4.10.1", "hast-util-to-jsx-runtime": "^2.3.0", "hls.js": "^1.6.16", + "pdfjs-dist": "6.5.438", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.0", @@ -120,6 +125,7 @@ } }, "devDependencies": { + "@playwright/test": "1.64.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "esbuild": "^0.28.2", diff --git a/packages/img/scripts/copy-pdf-worker.ts b/packages/img/scripts/copy-pdf-worker.ts new file mode 100644 index 00000000..cdcf9cbd --- /dev/null +++ b/packages/img/scripts/copy-pdf-worker.ts @@ -0,0 +1,7 @@ +import { copyFile } from 'node:fs/promises' + +// The worker must match the parser version, including after a dependency upgrade. +await copyFile( + new URL(import.meta.resolve('pdfjs-dist/legacy/build/pdf.worker.min.mjs')), + new URL('../dist/pdf.worker.min.mjs', import.meta.url), +) diff --git a/packages/img/src/document.ts b/packages/img/src/document.ts index 22630eed..6afdce2c 100644 --- a/packages/img/src/document.ts +++ b/packages/img/src/document.ts @@ -1,95 +1,86 @@ +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 (/\.pdf$/i.test(filename) && type !== 'text/plain') return 'pdf' + 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): ViewerKind | null { + const family = mime?.trim().toLowerCase().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..373b3bc8 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,10 @@ 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 + colorScheme?: 'light' | 'dark' | 'auto' } const markdownProcessor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype) @@ -61,6 +64,7 @@ function RichText({ bytes, title, className, + colorScheme, loadingFallback, errorFallback, onError, @@ -78,7 +82,7 @@ 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)) .then( (html) => { if (active) setResult({ bytes, html }) @@ -86,17 +90,18 @@ function RichText({ () => { if (!active) return setResult({ bytes, failed: true }) - reportError.current?.() + reportError.current?.('parse') }, ) return () => { active = false } - }, [bytes]) + }, [bytes, colorScheme]) if (result?.bytes !== bytes) return loadingFallback if (result.failed || result.html === undefined) return errorFallback return (