diff --git a/.changeset/mobile-document-preview.md b/.changeset/mobile-document-preview.md new file mode 100644 index 00000000..01aab579 --- /dev/null +++ b/.changeset/mobile-document-preview.md @@ -0,0 +1,9 @@ +--- +'@transloadit/viewer': minor +--- + +Add an opt-in PDF.js reader with a same-origin worker, on-demand ranges, lazy and renewable grants, swipe navigation, a selectable text layer, page jumps, zoom and fit controls. Pass a stable `documentKey` to preserve the current page when signed URLs rotate. The original-file action is opt-in. Add `useDocumentPreview` for bounded text reads, cancellation, retry and automatic opening. Add Markdown typography and configurable RTF colors. + +In frame mode, Viewer now normalizes `src` against the document base URI and writes the absolute URL to the iframe. The frame shows loading feedback and offers Retry after a load timeout or browser error. The frame requires a verified PDF endpoint and accepts a verified `mime`. Its `onLoad` receives the native React iframe event and `onError` receives a preview reason. `viewerKind` excludes SVG and recognizes octet-stream PDF filenames only in PDF.js mode. + +`documentPreviewKind` now also classifies CSV, TSV, JSON, log and YAML files as text. Applications that sign URLs based on this classifier may authorize additional previews. Oversized text and Markdown display their first 2 MiB with a notice. The strict `readDocumentPreview` API keeps its previous size and HTTP error behavior. The exported `DocumentPreviewError.reason` type 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/knip.ts b/knip.ts index d0fd36ba..7f2feb40 100644 --- a/knip.ts +++ b/knip.ts @@ -32,6 +32,8 @@ const config: KnipConfig = { ], project: ['{src,test}/**/*.{ts,tsx}'], ignore: [...sharedIgnore], + // The Viewer build generates this browser module after the clean-checkout dependency check. + ignoreUnresolved: ['#pdfjs'], ignoreDependencies: [ // Knip cannot infer the Vitest environment dependency from its file pragma. 'happy-dom', diff --git a/packages/img/browser/documents.spec.ts b/packages/img/browser/documents.spec.ts new file mode 100644 index 00000000..8ec2fb17 --- /dev/null +++ b/packages/img/browser/documents.spec.ts @@ -0,0 +1,447 @@ +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(sparse = false): Buffer { + const scan = '36FFFF001001>' + const objects = [ + '<< /Type /Catalog /Pages 2 0 R >>', + sparse + ? '<< /Type /Pages /Kids [3 0 R 4 0 R 9 0 R 10 0 R 11 0 R] /Count 5 >>' + : '<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>', + '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << /Font << /F1 8 0 R >> >> /Contents 5 0 R >>', + '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << /XObject << /Scan 7 0 R >> >> /Contents 6 0 R >>', + ...[ + '1 0 0 rg 0 0 200 100 re f BT /F1 12 Tf 10 10 Td (Lecture notes) Tj ET\n', + 'q 200 0 0 100 0 0 cm /Scan Do Q\n', + ].map((content) => { + return `<< /Length ${content.length} >>\nstream\n${content}endstream` + }), + // An 8×8 Group 4 fax strip containing a black half and a white half. + `<< /Type /XObject /Subtype /Image /Width 8 /Height 8 /ColorSpace /DeviceGray /BitsPerComponent 1 /Filter [/ASCIIHexDecode /CCITTFaxDecode] /DecodeParms [null << /K -1 /Columns 8 /Rows 8 >>] /Length ${scan.length} >>\nstream\n${scan}\nendstream`, + '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', + ] + if (sparse) { + // Page five uses the header's text stream. Page two's scan requires a later range. + objects.push(objects[2], objects[2], objects[2]) + } + let pdf = '%PDF-1.4\n' + const offsets: number[] = [] + for (const [i, object] of objects.entries()) { + // Keep page two outside the header and trailer chunks until the reader navigates. + if (sparse && (i === 5 || i === 7)) pdf += `%padding\n${'%pad\n'.repeat(65536)}` + offsets.push(pdf.length) + pdf += `${i + 1} 0 obj\n${object}\nendobj\n` + } + const xref = pdf.length + pdf += `xref\n0 ${objects.length + 1}\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 ${objects.length + 1} >>\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) => { + const deck = slideDeck(true) + let expired = false + let resume: () => void = () => {} + const resumed = new Promise((resolve) => { + resume = resolve + }) + await using files = createServer(async (req, res) => { + res.setHeader('Access-Control-Allow-Origin', '*') + if (req.url === '/expire') { + expired = true + res.writeHead(204).end() + } else if (req.url === '/resume') { + resume() + res.writeHead(204).end() + } else if (req.url === '/frame') { + res.writeHead(200, { 'Content-Type': 'text/html' }).end('

Frame loaded

') + } else if (req.url === '/stalled') { + res.writeHead(200, { 'Content-Type': 'application/pdf' }) + res.write('%PDF-1.4\n') + } else if (req.url?.startsWith('/ranges/')) { + if (req.url === '/ranges/fresh') await resumed + res.setHeader( + 'Access-Control-Expose-Headers', + 'Accept-Ranges, Content-Range, Content-Length', + ) + res.setHeader('Accept-Ranges', 'bytes') + res.setHeader('Content-Type', 'application/octet-stream') + if (expired && req.url === '/ranges/old') { + res.writeHead(403).end() + return + } + const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers.range ?? '') + if (!range) { + res.writeHead(200, { 'Content-Length': deck.length }) + res.flushHeaders() + return + } + const start = Number(range[1]) + const end = Number(range[2]) + res + .writeHead(206, { + 'Content-Range': `bytes ${start}-${end}/${deck.length}`, + 'Content-Length': end - start + 1, + }) + .end(deck.subarray(start, end + 1)) + } else 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( + 'assets/transloadit-viewer/pdf.worker.min.mjs', + await readFile(new URL(import.meta.resolve('@transloadit/viewer/pdf.worker.mjs'))), + ) + assets.set( + 'assets/transloadit-viewer/wasm/jbig2_nowasm_fallback.js', + await readFile( + new URL( + './wasm/jbig2_nowasm_fallback.js', + import.meta.resolve('@transloadit/viewer/pdf.worker.mjs'), + ), + ), + ) + assets.set( + 'assets/transloadit-viewer/standard_fonts/LiberationSans-Regular.ttf', + await readFile( + new URL( + './standard_fonts/LiberationSans-Regular.ttf', + import.meta.resolve('@transloadit/viewer/pdf.worker.mjs'), + ), + ), + ) + await using app = createServer((req, res) => { + if (req.url?.split('?')[0] === '/') { + res + .writeHead(200, { + 'Content-Type': 'text/html', + 'Content-Security-Policy': `default-src 'none'; script-src 'self'; worker-src 'self'; connect-src ${fileOrigin}; font-src 'self'; style-src 'self'; frame-src ${fileOrigin}; 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-Security-Policy': "default-src 'none'; script-src 'self'; connect-src 'self'", + 'Content-Type': path.endsWith('.css') + ? 'text/css' + : path.endsWith('.ttf') + ? 'font/ttf' + : '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}/assets/transloadit-viewer/pdf.worker.min.mjs`) + function pixel(element: Element, fraction: number): 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(Math.floor(element.width * fraction), 5, 1, 1).data] + } + expect(await first.evaluate(pixel, 0.25)).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, 0.25), await second.evaluate(pixel, 0.75)].sort()).toEqual([ + [0, 0, 0, 255], + [255, 255, 255, 255], + ]) + await expect(reader.getByRole('img')).toHaveCount(1) + await expect(reader).toBeFocused() + await expect(reader.getByRole('link', { name: 'Open original PDF' })).toHaveCount(0) + await expect(page.getByLabel('PDF loads')).toHaveText('1') + 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([]) +}) + +test('recovers from a missing worker on the same document', async ({ page }) => { + await page.goto('/?missingWorker') + await expect(page.getByText('network', { exact: true })).toBeVisible() + await page.getByRole('button', { name: 'Retry PDF' }).click() + await expect(page.getByRole('img', { name: 'PDF page 1' })).toBeVisible() + await expect(page.getByLabel('PDF loads')).toHaveText('1') +}) + +test('opens by range, then renews the denied range when jumping to another page', async ({ + page, + request, +}) => { + const ranges: { url: string; range?: string; status: number }[] = [] + page.on('response', (response) => { + if (response.url().includes('/ranges/')) + ranges.push({ + url: response.url(), + range: response.request().headers().range, + status: response.status(), + }) + }) + await page.goto('/?ranges') + await expect(page.getByText('Lecture notes', { exact: true })).toBeVisible() + const firstRange = ranges.find((entry) => entry.status === 206) + expect(firstRange?.range).toMatch(/^bytes=/) + if (!firstRange) throw new Error('Missing first range') + expect((await request.get(new URL('/expire', firstRange.url).href)).status()).toBe(204) + const input = page.getByRole('spinbutton', { name: 'Page number' }) + const renewed = page.waitForRequest('**/ranges/fresh') + await input.fill('2') + await input.press('Enter') + await renewed + await expect(page.getByRole('img', { name: 'PDF page 1' })).toBeVisible() + expect((await request.get(new URL('/resume', firstRange.url).href)).status()).toBe(204) + await expect(page.getByRole('img', { name: 'PDF page 2' })).toBeVisible() + await expect(page.getByRole('status').filter({ hasText: 'Page 2 of 5' })).toBeVisible() + const denied = ranges.find((entry) => entry.status === 403) + expect(denied?.range).toMatch(/^bytes=/) + expect(ranges).toContainEqual({ + url: new URL('/ranges/fresh', firstRange.url).href, + range: denied?.range, + status: 206, + }) + await expect(page.getByLabel('PDF loads')).toHaveText('1') + await page.getByRole('region', { name: 'Lecture slides' }).press('PageUp') + await expect(page.getByRole('img', { name: 'PDF page 1' })).toBeVisible() + await expect(input).toHaveValue('1') +}) + +test('times out a stalled PDF response body', async ({ page }) => { + await page.goto('/?stalled') + await expect(page.getByText('network', { exact: true })).toBeVisible() +}) + +test('zooms selectable text with the canvas and fits the available page height', async ({ + page, +}) => { + await page.goto('/') + const reader = page.getByRole('region', { name: 'Lecture slides' }) + await reader.evaluate((el) => el.style.setProperty('--tl-viewer-pdf-height', '120px')) + const text = reader.getByText('Lecture notes', { exact: true }) + await expect(text).toBeVisible() + const selected = await text.evaluate((el) => { + const range = document.createRange() + range.selectNodeContents(el) + const selection = window.getSelection() + selection?.removeAllRanges() + selection?.addRange(range) + return selection?.toString() + }) + expect(selected).toBe('Lecture notes') + await expect(reader.getByRole('button', { name: 'Fit width', pressed: true })).toBeVisible() + await reader.getByRole('button', { name: 'Fit page' }).click() + await expect(reader.getByRole('button', { name: 'Fit page', pressed: true })).toBeVisible() + const canvas = reader.getByRole('img', { name: 'PDF page 1' }) + await expect(canvas).toHaveCSS('height', '120px') + await reader.getByRole('button', { name: 'Zoom in' }).click() + await expect(canvas).toHaveCSS('height', '150px') + await reader.getByRole('button', { name: 'Zoom out' }).click() + await expect(canvas).toHaveCSS('height', '120px') + await reader.evaluate((el) => el.style.setProperty('--tl-viewer-pdf-height', '0px')) + await expect(canvas).toHaveCSS('height', '120px') + await reader.evaluate((el) => el.style.setProperty('--tl-viewer-pdf-height', '160px')) + await expect(canvas).toHaveCSS('height', '160px') + await reader.getByRole('button', { name: 'Fit width' }).click() + await expect.poll(() => canvas.evaluate((el) => el.clientHeight)).toBeGreaterThan(120) + const zoomIn = reader.getByRole('button', { name: 'Zoom in' }) + const zoomOut = reader.getByRole('button', { name: 'Zoom out' }) + await zoomIn.click({ clickCount: 7 }) + await expect(zoomIn).toBeDisabled() + await reader.getByRole('button', { name: 'Fit width' }).click() + await zoomOut.click({ clickCount: 7 }) + await expect(zoomOut).toBeDisabled() +}) + +test('rotates the grant on page five and uses it for the next range', async ({ page }) => { + await page.goto('/?ranges') + const input = page.getByRole('spinbutton', { name: 'Page number' }) + await input.fill('5') + await input.press('Enter') + const fifth = page.getByRole('img', { name: 'PDF page 5' }) + await expect(fifth).toBeVisible() + await page.getByRole('button', { name: 'Extend expiry' }).click() + await expect(fifth).toBeVisible() + await page.getByRole('button', { name: 'Rotate URL' }).click() + await expect(fifth).toBeVisible() + await expect(input).toHaveValue('5') + const range = page.waitForRequest( + (request) => request.url().includes('/ranges/') && !!request.headers().range, + ) + await input.fill('2') + await input.press('Enter') + expect(new URL((await range).url()).pathname).toBe('/ranges/rotated') + await expect(page.getByRole('img', { name: 'PDF page 2' })).toBeVisible() + await expect(page.getByLabel('PDF loads')).toHaveText('1') + await expect(page.getByLabel('Grant renewals')).toHaveText('0') + await page.getByRole('button', { name: 'Switch version' }).click() + await expect(page.getByRole('img', { name: 'PDF page 1' })).toBeVisible() + await expect(page.getByLabel('PDF loads')).toHaveText('2') +}) + +test('opens a portal PDF from a lazy grant with Safari 17.0 APIs', async ({ page }) => { + function safari17(): void { + Reflect.deleteProperty(URL, 'parse') + Reflect.deleteProperty(AbortSignal, 'any') + Reflect.deleteProperty(Promise, 'withResolvers') + Reflect.deleteProperty(ArrayBuffer.prototype, 'transferToFixedLength') + Reflect.deleteProperty(Response.prototype, 'bytes') + Reflect.deleteProperty(Blob.prototype, 'bytes') + } + await page.addInitScript(safari17) + // Page init scripts don't run in module workers. + await page.route('**/pdf.worker.min.mjs', async (route) => { + const response = await route.fetch() + await route.fulfill({ response, body: `(${safari17.toString()})();\n${await response.text()}` }) + }) + await page.goto('/?lazy') + await expect(page.getByText('Lecture notes', { exact: true })).toBeVisible() + await expect(page.getByLabel('Grant renewals')).toHaveText('1') + await page.getByRole('button', { name: 'Next page' }).click() + await expect(page.getByRole('img', { name: 'PDF page 2' })).toBeVisible() +}) + +test('built-in Retry returns keyboard focus to the reader', async ({ page }) => { + await page.route( + '**/report', + (route) => route.fulfill({ status: 503, headers: { 'Access-Control-Allow-Origin': '*' } }), + { times: 1 }, + ) + await page.goto('/?defaultError') + const retry = page.getByRole('button', { name: 'Retry PDF' }) + await retry.focus() + await retry.press('Enter') + await expect(page.getByRole('img', { name: 'PDF page 1' })).toBeVisible() + await expect(page.getByRole('region', { name: 'Lecture slides' })).toBeFocused() +}) + +test('native frame times out, retries and clears its loading indicator', async ({ page }) => { + let unblock = () => {} + const hold = new Promise((resolve) => { + unblock = resolve + }) + await page.route( + '**/frame', + async (route) => { + await hold + await route.abort() + }, + { times: 1 }, + ) + await page.goto('/?frame', { waitUntil: 'domcontentloaded' }) + await expect(page.getByRole('status')).toHaveText('Loading PDF…') + const retry = page.getByRole('button', { name: 'Retry PDF' }) + await expect(retry).toBeVisible() + unblock() + await retry.press('Enter') + await expect(page.frameLocator('iframe').getByText('Frame loaded')).toHaveCount(1) + await expect(page.getByRole('status')).toHaveCount(0) + await expect(page.getByTitle('Native slides')).toBeFocused() +}) + +test('horizontal swipes turn pages in both directions', async ({ page }) => { + await page.goto('/') + const first = page.getByRole('img', { name: 'PDF page 1' }) + const second = page.getByRole('img', { name: 'PDF page 2' }) + await expect(first).toBeVisible() + await first.dispatchEvent('touchstart', { + touches: [{ identifier: 1, clientX: 240, clientY: 80 }], + }) + await first.dispatchEvent('touchend', { + touches: [], + changedTouches: [{ identifier: 1, clientX: 70, clientY: 84 }], + }) + await expect(second).toBeVisible() + await second.dispatchEvent('touchstart', { + touches: [{ identifier: 1, clientX: 70, clientY: 84 }], + }) + await second.dispatchEvent('touchend', { + touches: [], + changedTouches: [{ identifier: 1, clientX: 240, clientY: 80 }], + }) + await expect(first).toBeVisible() +}) diff --git a/packages/img/browser/fixture.tsx b/packages/img/browser/fixture.tsx new file mode 100644 index 00000000..d34324dd --- /dev/null +++ b/packages/img/browser/fixture.tsx @@ -0,0 +1,110 @@ +import { useDocumentPreview, Viewer } from '@transloadit/viewer/react/viewer' +import { useState } from 'react' +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, +} + +const params = new URLSearchParams(location.search) + +function Fixture() { + const [missingWorker, setMissingWorker] = useState(params.has('missingWorker')) + const [loaded, setLoaded] = useState(0) + const preview = useDocumentPreview({ source, format: 'markdown' }) + const stalled = params.has('stalled') + const ranged = params.has('ranges') + const [rotated, setRotated] = useState(false) + const [version, setVersion] = useState(1) + const [expiry, setExpiry] = useState(() => Date.now() + 60_000) + const [renewals, setRenewals] = useState(0) + if (params.has('frame')) + return ( + + ) + return ( + <> + { + signal.throwIfAborted() + setRenewals((count) => count + 1) + return Promise.resolve({ + mediaUrl: `${fileOrigin}/${ranged ? 'ranges/fresh' : 'report'}`, + }) + }} + title="Lecture slides" + workerSrc={missingWorker ? '/missing-worker.mjs' : undefined} + onLoad={() => setLoaded((count) => count + 1)} + renderError={ + params.has('defaultError') + ? undefined + : (reason, retry) => ( +
+

{reason}

+ +
+ ) + } + /> + + + + {renewals} + {loaded} + + {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…

} - 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: (signal: AbortSignal) => 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 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 (