feat: embeddable, byte-based ReaderJS (iframe widget + lazy engines)
Expose ReaderJS as a read-only, self-contained, same-origin embed:
ReaderJS.mount(container, { blob|arrayBuffer, name, mime }) -> { load, destroy }
The host hands in document bytes (not a File); the filename's extension picks
the renderer. Isolated in a same-origin iframe so the viewer's full-page CSS,
JS globals and CSP surface stay out of the host page. Also supports a zero-JS
iframe variant: reader.html?src=<url>&name=<file> (self-fetches same-origin).
- main.js: lazy per-format renderer registry (pdf.js/jszip/foliate split into
on-demand chunks) + loadBytes(bytes, name, mime); openFile delegates; export
DocumentViewer; null-tolerant UI wiring; auto-init gated on #dropzone.
- reader.html (trimmed index.html, no upload UI) + src/reader.js bootstrap
(?src self-fetch or origin-checked postMessage handshake).
- src/readerjs.js: IIFE loader exposing window.ReaderJS.mount (sandboxed iframe,
structured-clone copy so the host buffer is not neutered).
- vite.config.app.js + vite.config.embed.js -> dist-embed/ (base:'./', workers/
wasm/public assets bundle-relative); npm run build:embed.
- i18n.js: localStorage guarded for sandboxed contexts.
- CREDITS.md (all engines permissive; pptxviewjs MIT; WebODF reference-only, not
bundled) + EMBEDDING.md (API, iframe variant, CSP asset list).
Verified against the built artifact: bytes-mode renders DjVu (dejaview module
worker under base:'./'), ?src mode renders CSV, per-format lazy chunks, zero
external-origin requests, destroy() cleanup. Demo app build unaffected.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
node_modules/
|
||||
dist/
|
||||
dist-embed/
|
||||
.env
|
||||
.env.*
|
||||
*.local
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Credits & Licenses
|
||||
|
||||
ReaderJS is MIT-licensed and **permissive-core**: every engine bundled into the
|
||||
runtime (the app *and* the embeddable build) uses a permissive license
|
||||
(MIT / BSD / Apache-2.0 / 0BSD / public-domain). There are **no GPL/AGPL/LGPL
|
||||
dependencies** in anything that ships.
|
||||
|
||||
## Runtime engines
|
||||
|
||||
| Library | License | Used for |
|
||||
|---------|---------|----------|
|
||||
| [pdf.js](https://github.com/mozilla/pdf.js) (`pdfjs-dist`) | Apache-2.0 | PDF rendering |
|
||||
| [DejaView](https://github.com/Alpaq92/dejaview) | MIT | DjVu decoding/rendering (Web Worker) |
|
||||
| [mammoth.js](https://github.com/mwilliamson/mammoth.js) | BSD-2-Clause | DOCX → HTML |
|
||||
| [JSDoc](https://github.com/Alpaq92/JSDoc) | 0BSD | Legacy `.doc` (binary Word) |
|
||||
| [RTF.js](https://github.com/tbluemel/rtf.js) | MIT | RTF (with EMFJS/WMFJS) |
|
||||
| [jQuery](https://github.com/jquery/jquery) | MIT | DOM utility required by RTF.js |
|
||||
| [PptxViewJS](https://github.com/gptsci/pptxviewjs) | **MIT** | PPTX slide rendering |
|
||||
| [Chart.js](https://github.com/chartjs/Chart.js) | MIT | charts inside PPTX (PptxViewJS dep) |
|
||||
| [SheetJS](https://sheetjs.com/) (`xlsx`) | Apache-2.0 | XLSX/XLS spreadsheets |
|
||||
| [Papa Parse](https://www.papaparse.com/) | MIT | CSV/TSV |
|
||||
| [highlight.js](https://highlightjs.org/) | BSD-3-Clause | source-code highlighting |
|
||||
| [marked](https://github.com/markedjs/marked) | MIT | Markdown |
|
||||
| [JSZip](https://github.com/Stuk/jszip) | MIT (dual MIT/GPLv3 — MIT taken) | ODF/CBZ ZIP containers |
|
||||
| [libarchive.js](https://github.com/nika-begiashvili/libarchivejs) | MIT (bundled libarchive = BSD) | CBR/CBT (RAR/TAR) via WASM |
|
||||
| [foliate-js](https://github.com/johnfactotum/foliate-js) | MIT | EPUB/MOBI/AZW3/FB2 |
|
||||
| [UTIF.js](https://github.com/photopea/UTIF.js) | MIT | TIFF images |
|
||||
| [exifr](https://github.com/MikeKovarik/exifr) | MIT | EXIF/GPS metadata |
|
||||
| [Vite](https://github.com/vitejs/vite) | MIT | build tooling |
|
||||
| [Material Design Icons](https://pictogrammers.com/library/mdi/) | Apache-2.0 | UI icons |
|
||||
|
||||
## Not shipped
|
||||
|
||||
- **WebODF** is present as a git submodule (reference only) and is **AGPL-3.0**.
|
||||
It is **never imported or bundled** — ODF files are handled by `odf-renderer.js`
|
||||
using JSZip + the browser's `DOMParser`, not WebODF. It does not appear in any
|
||||
build output (`dist/` or `dist-embed/`).
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# Embedding ReaderJS
|
||||
|
||||
ReaderJS can be embedded into another app as a **read-only**, **self-contained**,
|
||||
**same-origin** document viewer. It accepts document **bytes + a filename** (the
|
||||
filename's extension selects the renderer) — no file picker, no uploads, no
|
||||
external network requests. The viewer runs inside an **iframe** so its full-page
|
||||
CSS, JS globals, and CSP surface stay isolated from the host page.
|
||||
|
||||
## Build the artifact
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run build:embed # → dist-embed/
|
||||
```
|
||||
|
||||
Vendor the whole `dist-embed/` folder somewhere **same-origin** on your site,
|
||||
e.g. `frontend/static/readerjs/`. It is self-contained:
|
||||
|
||||
```
|
||||
dist-embed/
|
||||
readerjs.js # the loader — exposes window.ReaderJS.mount()
|
||||
reader.html # the viewer page (loaded inside the iframe)
|
||||
assets/ # lazy per-format chunks + workers (pdf.worker, dejaview)
|
||||
rtfjs/ # RTF.js vendored scripts (RTF)
|
||||
libarchive/ # worker-bundle.js + libarchive.wasm (CBR/CBT)
|
||||
jsdoc/ # docToText.js (legacy .doc)
|
||||
```
|
||||
|
||||
All asset URLs are **relative to `reader.html`**, so the folder works from any
|
||||
path you mount it at.
|
||||
|
||||
## Usage
|
||||
|
||||
### Option A — JS API (`mount`)
|
||||
|
||||
Load the loader, then hand ReaderJS the bytes you already have (e.g. from a
|
||||
same-origin, cookie-authed `/raw` endpoint):
|
||||
|
||||
```html
|
||||
<script src="/static/readerjs/readerjs.js"></script>
|
||||
<div id="viewer" style="width:100%; height:80vh"></div>
|
||||
<script>
|
||||
const res = await fetch('/raw/123', { credentials: 'same-origin' })
|
||||
const blob = await res.blob()
|
||||
|
||||
const inst = ReaderJS.mount(document.getElementById('viewer'), {
|
||||
blob, // or arrayBuffer: <ArrayBuffer>
|
||||
name: 'report.pdf', // REQUIRED — its extension picks the renderer
|
||||
mime: blob.type, // optional
|
||||
})
|
||||
|
||||
// inst.load(otherBlob, 'next.docx') // swap the document at runtime
|
||||
// inst.setLang('pl') // change UI language
|
||||
// inst.destroy() // remove the iframe + listeners
|
||||
</script>
|
||||
```
|
||||
|
||||
The container must have a height (the iframe fills `100%`).
|
||||
|
||||
### Option B — iframe with `?src` (zero JS)
|
||||
|
||||
Let the iframe fetch the document itself (same-origin, sends cookies):
|
||||
|
||||
```html
|
||||
<iframe src="/static/readerjs/reader.html?src=/raw/123&name=report.pdf"
|
||||
style="width:100%; height:80vh; border:0"></iframe>
|
||||
```
|
||||
|
||||
Pass `name` whenever the URL has no usable extension (e.g. `/raw/123`).
|
||||
|
||||
## `ReaderJS.mount(container, opts) → instance`
|
||||
|
||||
| `opts` field | | |
|
||||
|---|---|---|
|
||||
| `blob` / `arrayBuffer` | bytes mode | the document bytes |
|
||||
| `src` | url mode | same-origin URL the iframe fetches itself |
|
||||
| `name` | required | filename whose extension selects the renderer |
|
||||
| `mime` | optional | passed through (dispatch is by extension) |
|
||||
|
||||
`instance`: `{ load(blobOrBuffer, name, mime?), setLang(code), destroy(), iframe }`.
|
||||
|
||||
Bytes are sent to the iframe as a **structured-clone copy** (your `ArrayBuffer`
|
||||
is not neutered). The host↔iframe handshake is origin-checked and same-origin only.
|
||||
|
||||
## Content-Security-Policy
|
||||
|
||||
Everything is same-origin under the vendored folder. The viewer loads:
|
||||
|
||||
- `assets/*.js` — lazy per-format engine chunks, incl. `pdf.worker.min.mjs` and the dejaview worker
|
||||
- `rtfjs/*.js` — RTF.js (RTF documents)
|
||||
- `libarchive/worker-bundle.js` + `libarchive/libarchive.wasm` — CBR/CBT
|
||||
- `jsdoc/docToText.js` — legacy `.doc`
|
||||
|
||||
Recommended directives for the page hosting the iframe (tighten origins to your host):
|
||||
|
||||
```
|
||||
frame-src 'self';
|
||||
script-src 'self' 'wasm-unsafe-eval'; # WASM = libarchive (CBR/CBT); no eval otherwise
|
||||
worker-src 'self' blob:;
|
||||
connect-src 'self'; # asset fetches + ?src document fetch
|
||||
img-src 'self' blob: data:; # renderers use object/data URLs
|
||||
style-src 'self' 'unsafe-inline'; # highlight.js injects its theme as <style>; inline el.style
|
||||
font-src 'self' data:;
|
||||
```
|
||||
|
||||
Two directives are load-bearing: **`'wasm-unsafe-eval'`** (only needed if you use
|
||||
CBR/CBT) and **`style-src 'unsafe-inline'`** (the dynamically-injected highlight.js
|
||||
theme + inline `style` attributes). No `'unsafe-eval'` is required.
|
||||
|
||||
## Notes
|
||||
|
||||
- **Read-only.** No upload UI; the host owns editing.
|
||||
- **Same-origin.** Vendor `dist-embed/` on your own origin; the iframe relies on
|
||||
`allow-same-origin` for workers, WASM, and `localStorage`.
|
||||
- **Lazy.** Each document pulls only its own engine chunk (a DjVu pulls the
|
||||
dejaview chunk, a DOCX pulls mammoth, etc.) — the initial load stays small.
|
||||
- **Formats:** PDF, DjVu, ODF (ODT/ODS/ODP/ODG), RTF, DOC, DOCX, PPTX,
|
||||
XLSX/XLS, CSV/TSV, Markdown, source code, images (+TIFF/EXIF),
|
||||
comic archives (CBZ/CBR/CBT), e-books (EPUB/MOBI/AZW3/FB2), plain text.
|
||||
- See [CREDITS.md](CREDITS.md) — every bundled engine is permissively licensed.
|
||||
@@ -35,6 +35,19 @@ To give it a try without installing anything, visit the [live demo](https://alpa
|
||||
- Client-side only — documents are never uploaded or transmitted
|
||||
- Multilingual UI — auto-detects your browser language with a manual switcher (English, Polish, Spanish, French, German, Portuguese, Chinese, Japanese, Russian)
|
||||
|
||||
## Embedding
|
||||
|
||||
ReaderJS can be embedded into another app as a read-only, self-contained,
|
||||
same-origin viewer that takes document **bytes + a filename** (no upload UI):
|
||||
|
||||
```js
|
||||
const inst = ReaderJS.mount(container, { blob, name: 'report.pdf' })
|
||||
```
|
||||
|
||||
Build the vendorable artifact with `npm run build:embed` (→ `dist-embed/`). See
|
||||
[EMBEDDING.md](EMBEDDING.md) for the full API, the `?src` iframe variant, and the
|
||||
CSP asset list.
|
||||
|
||||
## Running Locally
|
||||
|
||||
```bash
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build:embed:app": "vite build --config vite.config.app.js",
|
||||
"build:embed:loader": "vite build --config vite.config.embed.js",
|
||||
"build:embed": "npm run build:embed:app && npm run build:embed:loader",
|
||||
"preview": "vite preview",
|
||||
"submodules:init": "git submodule update --init --recursive",
|
||||
"docs": "jsdoc src -r -d docs"
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title data-i18n="app.title">ReaderJS — Universal Document Viewer</title>
|
||||
<link rel="stylesheet" href="/src/style.css" />
|
||||
<!-- WebODF is loaded on-demand by odf-renderer.js when an ODF file is opened -->
|
||||
</head>
|
||||
<body>
|
||||
<div id="outerContainer">
|
||||
|
||||
<!-- Sidebar: page thumbnails -->
|
||||
<div id="sidebarContainer">
|
||||
<div id="sidebarToolbar">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
|
||||
<path d="M3,11H11V3H3M3,21H11V13H3M13,21H21V13H13M13,3V11H21V3" />
|
||||
</svg>
|
||||
<span class="sidebar-title" data-i18n="sidebar.pages">Pages</span>
|
||||
</div>
|
||||
<div id="sidebarContent">
|
||||
<div id="thumbsContent"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main content -->
|
||||
<div id="mainContainer">
|
||||
|
||||
<!-- Top toolbar -->
|
||||
<div id="toolbarContainer">
|
||||
<div id="toolbarLeft">
|
||||
<button id="sidebarToggle" class="toolbar-btn" title="Toggle Sidebar" data-i18n-title="tip.sidebar">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
|
||||
<path d="M12,16A2,2 0 0,1 14,18A2,2 0 0,1 12,20A2,2 0 0,1 10,18A2,2 0 0,1 12,16M12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12A2,2 0 0,1 12,10M12,4A2,2 0 0,1 14,6A2,2 0 0,1 12,8A2,2 0 0,1 10,6A2,2 0 0,1 12,4Z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div class="toolbar-separator"></div>
|
||||
|
||||
<button id="prevPage" class="toolbar-btn" title="Previous Page (←)" data-i18n-title="tip.prevPage" disabled>
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
|
||||
<path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<div id="pageNumberGroup">
|
||||
<input id="pageNumber" type="number" value="1" min="1" max="1" title="Current Page" data-i18n-title="tip.currentPage" />
|
||||
<span class="page-sep">/</span>
|
||||
<span id="totalPages">—</span>
|
||||
</div>
|
||||
|
||||
<button id="nextPage" class="toolbar-btn" title="Next Page (→)" data-i18n-title="tip.nextPage" disabled>
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
|
||||
<path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="toolbarMiddle">
|
||||
<button id="zoomOut" class="toolbar-btn" title="Zoom Out (Ctrl -)" data-i18n-title="tip.zoomOut">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
|
||||
<path d="M19,13H5V11H19V13Z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<select id="scaleSelect" title="Zoom" data-i18n-title="tip.zoom">
|
||||
<option value="auto" data-i18n="zoom.auto">Auto</option>
|
||||
<option value="page-fit" data-i18n="zoom.pageFit">Page Fit</option>
|
||||
<option value="page-width" data-i18n="zoom.pageWidth">Page Width</option>
|
||||
<option value="page-height" data-i18n="zoom.fitHeight">Fit Height</option>
|
||||
<option value="0.5">50%</option>
|
||||
<option value="0.75">75%</option>
|
||||
<option value="1" selected>100%</option>
|
||||
<option value="1.25">125%</option>
|
||||
<option value="1.5">150%</option>
|
||||
<option value="2">200%</option>
|
||||
<option value="3">300%</option>
|
||||
</select>
|
||||
|
||||
<button id="zoomIn" class="toolbar-btn" title="Zoom In (Ctrl +)" data-i18n-title="tip.zoomIn">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
|
||||
<path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="toolbarRight">
|
||||
<select id="langSelect" title="Language" data-i18n-title="tip.language">
|
||||
<option value="en">English</option>
|
||||
<option value="pl">Polski</option>
|
||||
<option value="es">Español</option>
|
||||
<option value="fr">Français</option>
|
||||
<option value="de">Deutsch</option>
|
||||
<option value="pt">Português</option>
|
||||
<option value="zh">中文</option>
|
||||
<option value="ja">日本語</option>
|
||||
<option value="ru">Русский</option>
|
||||
</select>
|
||||
|
||||
<div class="toolbar-separator"></div>
|
||||
|
||||
<span id="formatBadge" class="hidden"></span>
|
||||
|
||||
<div class="toolbar-separator"></div>
|
||||
|
||||
<button id="printBtn" class="toolbar-btn" title="Print (Ctrl+P)" data-i18n-title="tip.print">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
|
||||
<path d="M18,3H6V7H18M19,12A1,1 0 0,1 18,11A1,1 0 0,1 19,10A1,1 0 0,1 20,11A1,1 0 0,1 19,12M16,19H8V14H16M19,8H5A3,3 0 0,0 2,11V17H6V21H18V17H22V11A3,3 0 0,0 19,8Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading bar -->
|
||||
<div id="loadingBar" class="hidden">
|
||||
<div id="loadingBarProgress"></div>
|
||||
</div>
|
||||
|
||||
<!-- Error bar -->
|
||||
<div id="errorBar" class="hidden" role="alert">
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" style="flex-shrink:0">
|
||||
<path d="M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" />
|
||||
</svg>
|
||||
<span id="errorMsg"></span>
|
||||
<button id="errorClose" aria-label="Dismiss" data-i18n-aria="aria.dismiss">
|
||||
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
|
||||
<path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Viewer -->
|
||||
<div id="viewerContainer">
|
||||
|
||||
<!-- Document render target (the host hands documents in as bytes) -->
|
||||
<div id="docContainer"></div>
|
||||
|
||||
</div><!-- /viewerContainer -->
|
||||
</div><!-- /mainContainer -->
|
||||
</div><!-- /outerContainer -->
|
||||
|
||||
<!-- Print layer: populated by PDF renderer before window.print() -->
|
||||
<div id="printLayer" aria-hidden="true"></div>
|
||||
|
||||
<script type="module" src="/src/reader.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+3
-2
@@ -371,7 +371,8 @@ const dict = {
|
||||
const STORAGE_KEY = 'readerjs-lang'
|
||||
|
||||
function detectLang() {
|
||||
const saved = localStorage.getItem(STORAGE_KEY)
|
||||
let saved = null
|
||||
try { saved = localStorage.getItem(STORAGE_KEY) } catch { /* storage blocked (e.g. sandboxed/embedded) */ }
|
||||
if (saved && dict[saved]) return saved
|
||||
const nav = (navigator.language || 'en').split('-')[0].toLowerCase()
|
||||
return dict[nav] ? nav : 'en'
|
||||
@@ -397,7 +398,7 @@ export function applyTranslations(root = document) {
|
||||
export function setLang(code) {
|
||||
if (!dict[code]) return
|
||||
lang = code
|
||||
localStorage.setItem(STORAGE_KEY, code)
|
||||
try { localStorage.setItem(STORAGE_KEY, code) } catch { /* storage blocked (e.g. sandboxed/embedded) */ }
|
||||
document.documentElement.lang = code
|
||||
applyTranslations()
|
||||
}
|
||||
|
||||
+95
-70
@@ -1,20 +1,26 @@
|
||||
import { PDFRenderer } from './renderers/pdf-renderer.js'
|
||||
import { ODFRenderer } from './renderers/odf-renderer.js'
|
||||
import { RTFRenderer } from './renderers/rtf-renderer.js'
|
||||
import { DOCXRenderer } from './renderers/docx-renderer.js'
|
||||
import { DOCRenderer } from './renderers/doc-renderer.js'
|
||||
import { MDRenderer } from './renderers/md-renderer.js'
|
||||
import { TXTRenderer } from './renderers/txt-renderer.js'
|
||||
import { ComicRenderer } from './renderers/comic-renderer.js'
|
||||
import { EPUBRenderer } from './renderers/epub-renderer.js'
|
||||
import { ImageRenderer } from './renderers/image-renderer.js'
|
||||
import { PPTXRenderer } from './renderers/pptx-renderer.js'
|
||||
import { CSVRenderer } from './renderers/csv-renderer.js'
|
||||
import { CodeRenderer } from './renderers/code-renderer.js'
|
||||
import { XLSXRenderer } from './renderers/xlsx-renderer.js'
|
||||
import { DjVuRenderer } from './renderers/djvu-renderer.js'
|
||||
import { t, applyTranslations, setLang, getLang } from './i18n.js'
|
||||
|
||||
// Each format's renderer module is imported on demand, so opening a document
|
||||
// only pulls that format's engine (pdf.js, mammoth, foliate, libarchive, …).
|
||||
// Keeps the initial bundle lean — important for the embeddable build.
|
||||
const RENDERER_LOADERS = {
|
||||
pdf: () => import('./renderers/pdf-renderer.js').then(m => new m.PDFRenderer()),
|
||||
odf: () => import('./renderers/odf-renderer.js').then(m => new m.ODFRenderer()),
|
||||
rtf: () => import('./renderers/rtf-renderer.js').then(m => new m.RTFRenderer()),
|
||||
docx: () => import('./renderers/docx-renderer.js').then(m => new m.DOCXRenderer()),
|
||||
doc: () => import('./renderers/doc-renderer.js').then(m => new m.DOCRenderer()),
|
||||
md: () => import('./renderers/md-renderer.js').then(m => new m.MDRenderer()),
|
||||
txt: () => import('./renderers/txt-renderer.js').then(m => new m.TXTRenderer()),
|
||||
comic: () => import('./renderers/comic-renderer.js').then(m => new m.ComicRenderer()),
|
||||
epub: () => import('./renderers/epub-renderer.js').then(m => new m.EPUBRenderer()),
|
||||
image: () => import('./renderers/image-renderer.js').then(m => new m.ImageRenderer()),
|
||||
pptx: () => import('./renderers/pptx-renderer.js').then(m => new m.PPTXRenderer()),
|
||||
xlsx: () => import('./renderers/xlsx-renderer.js').then(m => new m.XLSXRenderer()),
|
||||
csv: () => import('./renderers/csv-renderer.js').then(m => new m.CSVRenderer()),
|
||||
code: () => import('./renderers/code-renderer.js').then(m => new m.CodeRenderer()),
|
||||
djvu: () => import('./renderers/djvu-renderer.js').then(m => new m.DjVuRenderer()),
|
||||
}
|
||||
|
||||
const CODE_EXTS = ['js','mjs','cjs','jsx','ts','tsx','json','jsonc','xml','html','htm',
|
||||
'yaml','yml','css','scss','less','py','java','c','h','cpp','cc','hpp','cs','go','rs',
|
||||
'rb','php','sh','bash','sql','kt','swift','toml','ini','diff']
|
||||
@@ -39,25 +45,10 @@ const EXT_MAP = {
|
||||
fb2: 'epub', fbz: 'epub',
|
||||
}
|
||||
|
||||
class DocumentViewer {
|
||||
export class DocumentViewer {
|
||||
constructor() {
|
||||
this.renderers = {
|
||||
pdf: new PDFRenderer(),
|
||||
odf: new ODFRenderer(),
|
||||
rtf: new RTFRenderer(),
|
||||
docx: new DOCXRenderer(),
|
||||
doc: new DOCRenderer(),
|
||||
md: new MDRenderer(),
|
||||
txt: new TXTRenderer(),
|
||||
comic: new ComicRenderer(),
|
||||
epub: new EPUBRenderer(),
|
||||
image: new ImageRenderer(),
|
||||
pptx: new PPTXRenderer(),
|
||||
xlsx: new XLSXRenderer(),
|
||||
csv: new CSVRenderer(),
|
||||
code: new CodeRenderer(),
|
||||
djvu: new DjVuRenderer(),
|
||||
}
|
||||
this._rendererCache = new Map() // format → renderer instance (built once, reused)
|
||||
this._rendererPromises = new Map() // format → in-flight import promise (dedupes concurrent opens)
|
||||
this.activeRenderer = null
|
||||
this.currentPage = 1
|
||||
this.numPages = 0
|
||||
@@ -71,38 +62,45 @@ class DocumentViewer {
|
||||
_initI18n() {
|
||||
document.documentElement.lang = getLang()
|
||||
const sel = document.getElementById('langSelect')
|
||||
sel.value = getLang()
|
||||
sel.addEventListener('change', e => setLang(e.target.value))
|
||||
if (sel) {
|
||||
sel.value = getLang()
|
||||
sel.addEventListener('change', e => setLang(e.target.value))
|
||||
}
|
||||
applyTranslations()
|
||||
}
|
||||
|
||||
/* ── UI wiring ───────────────────────────────────────────────────────── */
|
||||
_bindUI() {
|
||||
// File open
|
||||
document.getElementById('fileInput').addEventListener('change', e => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
e.target.value = '' // allow re-opening same file
|
||||
})
|
||||
|
||||
// Drag-drop on the full window
|
||||
document.addEventListener('dragover', e => e.preventDefault())
|
||||
document.addEventListener('drop', e => {
|
||||
e.preventDefault()
|
||||
const f = e.dataTransfer.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
})
|
||||
// File open + drag-drop — only in the full app. The embeddable build omits
|
||||
// the dropzone/file input (the host hands documents in as bytes), so this
|
||||
// whole block is skipped when those elements are absent.
|
||||
const fileInput = document.getElementById('fileInput')
|
||||
const dz = document.getElementById('dropzone')
|
||||
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag-over') })
|
||||
dz.addEventListener('dragleave', () => dz.classList.remove('drag-over'))
|
||||
dz.addEventListener('drop', e => {
|
||||
e.preventDefault(); dz.classList.remove('drag-over')
|
||||
const f = e.dataTransfer.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
})
|
||||
dz.addEventListener('click', e => {
|
||||
if (e.target.tagName !== 'LABEL') document.getElementById('fileInput').click()
|
||||
})
|
||||
if (fileInput && dz) {
|
||||
fileInput.addEventListener('change', e => {
|
||||
const f = e.target.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
e.target.value = '' // allow re-opening same file
|
||||
})
|
||||
|
||||
// Drag-drop on the full window
|
||||
document.addEventListener('dragover', e => e.preventDefault())
|
||||
document.addEventListener('drop', e => {
|
||||
e.preventDefault()
|
||||
const f = e.dataTransfer.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
})
|
||||
dz.addEventListener('dragover', e => { e.preventDefault(); dz.classList.add('drag-over') })
|
||||
dz.addEventListener('dragleave', () => dz.classList.remove('drag-over'))
|
||||
dz.addEventListener('drop', e => {
|
||||
e.preventDefault(); dz.classList.remove('drag-over')
|
||||
const f = e.dataTransfer.files?.[0]
|
||||
if (f) this.openFile(f)
|
||||
})
|
||||
dz.addEventListener('click', e => {
|
||||
if (e.target.tagName !== 'LABEL') fileInput.click()
|
||||
})
|
||||
}
|
||||
|
||||
// Navigation
|
||||
document.getElementById('prevPage').addEventListener('click', () => this.changePage(-1))
|
||||
@@ -137,8 +135,30 @@ class DocumentViewer {
|
||||
}
|
||||
|
||||
/* ── File loading ────────────────────────────────────────────────────── */
|
||||
async openFile(file) {
|
||||
const ext = file.name.split('.').pop().toLowerCase()
|
||||
// Lazily import + instantiate a format's renderer. Cached so it's built once;
|
||||
// concurrent opens of the same format share a single in-flight import.
|
||||
_getRenderer(format) {
|
||||
if (this._rendererCache.has(format)) return Promise.resolve(this._rendererCache.get(format))
|
||||
if (this._rendererPromises.has(format)) return this._rendererPromises.get(format)
|
||||
const p = RENDERER_LOADERS[format]().then(inst => {
|
||||
this._rendererCache.set(format, inst)
|
||||
this._rendererPromises.delete(format)
|
||||
return inst
|
||||
})
|
||||
this._rendererPromises.set(format, p)
|
||||
return p
|
||||
}
|
||||
|
||||
// Full app: open a picked File (dropzone / file input / drag-drop).
|
||||
openFile(file) {
|
||||
return this.loadBytes(file, file.name, file.type)
|
||||
}
|
||||
|
||||
// Render raw bytes given a filename — its extension selects the renderer.
|
||||
// The embeddable build feeds documents this way (no File object needed).
|
||||
// `source` is a Blob/File or an ArrayBuffer.
|
||||
async loadBytes(source, name, mime) {
|
||||
const ext = (name || '').split('.').pop().toLowerCase()
|
||||
const format = EXT_MAP[ext]
|
||||
|
||||
if (!format) {
|
||||
@@ -150,9 +170,9 @@ class DocumentViewer {
|
||||
this._hideDropzone()
|
||||
|
||||
try {
|
||||
const buffer = await file.arrayBuffer()
|
||||
const renderer = this.renderers[format]
|
||||
this.currentFileName = file.name // used by foliate for format hinting
|
||||
const buffer = source instanceof ArrayBuffer ? source : await source.arrayBuffer()
|
||||
const renderer = await this._getRenderer(format)
|
||||
this.currentFileName = name // used by foliate for format hinting
|
||||
|
||||
this.activeRenderer?.destroy()
|
||||
this.activeRenderer = renderer
|
||||
@@ -169,17 +189,18 @@ class DocumentViewer {
|
||||
// Renderers may prefer a default zoom (e.g. comics fit to width);
|
||||
// otherwise keep 100% without forcing a redundant re-render.
|
||||
const scaleOpt = renderer.defaultScaleOption || '1'
|
||||
document.getElementById('scaleSelect').value = scaleOpt
|
||||
const scaleSel = document.getElementById('scaleSelect')
|
||||
if (scaleSel) scaleSel.value = scaleOpt
|
||||
if (renderer.defaultScaleOption) this._applyScaleOption(scaleOpt)
|
||||
else this.scale = 1.0
|
||||
|
||||
this.updatePageInfo()
|
||||
this._refreshThumbsPlaceholder()
|
||||
this._setFormatBadge(format)
|
||||
document.title = `${file.name} — ReaderJS`
|
||||
document.title = `${name} — ReaderJS`
|
||||
} catch (err) {
|
||||
console.error('[ReaderJS] load error:', err)
|
||||
this._showError(t('err.couldNotOpen', { name: file.name, msg: err.message }))
|
||||
this._showError(t('err.couldNotOpen', { name, msg: err.message }))
|
||||
} finally {
|
||||
this._setLoading(false)
|
||||
}
|
||||
@@ -298,8 +319,8 @@ class DocumentViewer {
|
||||
}
|
||||
|
||||
_hideDropzone() {
|
||||
document.getElementById('dropzone').classList.add('hidden')
|
||||
document.getElementById('docContainer').classList.remove('hidden')
|
||||
document.getElementById('dropzone')?.classList.add('hidden')
|
||||
document.getElementById('docContainer')?.classList.remove('hidden')
|
||||
}
|
||||
|
||||
_setFormatBadge(format) {
|
||||
@@ -327,6 +348,10 @@ class DocumentViewer {
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-boot the full app. The embeddable page (reader.html) has no #dropzone
|
||||
// and boots its own viewer via src/reader.js, so this stays out of its way.
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.viewer = new DocumentViewer()
|
||||
if (document.getElementById('dropzone')) {
|
||||
window.viewer = new DocumentViewer()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Bootstrap for the read-only embed page (reader.html). A document arrives one
|
||||
// of two ways:
|
||||
// 1. ?src=<url>&name=<file> — the iframe self-fetches same-origin (cookie-authed).
|
||||
// 2. postMessage({ type:'readerjs:load', buffer, name, mime }) — the host (via
|
||||
// readerjs.js mount()) hands bytes in.
|
||||
// `name`'s extension selects the renderer, so the host must pass it when the URL
|
||||
// has no extension (e.g. /raw/123).
|
||||
import { DocumentViewer } from './main.js'
|
||||
import { setLang } from './i18n.js'
|
||||
|
||||
function boot() {
|
||||
const viewer = new DocumentViewer()
|
||||
window.viewer = viewer
|
||||
|
||||
const params = new URLSearchParams(location.search)
|
||||
const src = params.get('src')
|
||||
const name = params.get('name') ||
|
||||
(src ? decodeURIComponent(src.split('/').pop().split('?')[0] || 'document') : 'document')
|
||||
|
||||
if (src) {
|
||||
// URL mode: self-fetch from the same origin (no JS on the host required).
|
||||
fetch(src, { credentials: 'same-origin' })
|
||||
.then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.arrayBuffer() })
|
||||
.then(buf => viewer.loadBytes(buf, name))
|
||||
.catch(err => viewer._showError(String(err?.message || err)))
|
||||
return
|
||||
}
|
||||
|
||||
// Bytes mode: accept the document only from our own parent, same origin.
|
||||
window.addEventListener('message', e => {
|
||||
if (e.source !== window.parent || e.origin !== location.origin) return
|
||||
const m = e.data
|
||||
if (!m || typeof m !== 'object') return
|
||||
if (m.type === 'readerjs:load') viewer.loadBytes(m.buffer, m.name, m.mime)
|
||||
else if (m.type === 'readerjs:setLang' && m.lang) setLang(m.lang)
|
||||
})
|
||||
|
||||
// Tell the host we're listening, so it can post the bytes.
|
||||
const parentOrigin = document.referrer ? new URL(document.referrer).origin : '*'
|
||||
try { window.parent.postMessage({ type: 'readerjs:ready' }, parentOrigin) } catch { /* opened standalone */ }
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot)
|
||||
else boot()
|
||||
@@ -0,0 +1,81 @@
|
||||
// ReaderJS embed loader. Vendor the built folder (dist-embed/) somewhere
|
||||
// same-origin and load readerjs.js — it exposes `window.ReaderJS.mount()`:
|
||||
//
|
||||
// const inst = ReaderJS.mount(container, { blob | arrayBuffer, name, mime }) // bytes
|
||||
// const inst = ReaderJS.mount(container, { src, name }) // url (iframe self-fetches)
|
||||
// inst.load(blob, 'next.pdf') // swap the document
|
||||
// inst.destroy()
|
||||
//
|
||||
// mount() embeds reader.html (this file's sibling) in a same-origin iframe and
|
||||
// hands it the document over postMessage (or via ?src). The iframe isolates the
|
||||
// viewer's full-page CSS, JS globals and CSP surface from the host page.
|
||||
|
||||
// Resolve our own script URL at eval time — an IIFE has no import.meta.url, and
|
||||
// document.currentScript is only valid during this synchronous top-level run.
|
||||
const SELF = (document.currentScript && document.currentScript.src) || (() => {
|
||||
const s = [...document.getElementsByTagName('script')].reverse()
|
||||
.find(el => /readerjs(\.min)?\.js(\?|#|$)/.test(el.src || ''))
|
||||
return s ? s.src : location.href
|
||||
})()
|
||||
|
||||
function readerHtmlUrl(opts) {
|
||||
const url = new URL('./reader.html', SELF) // reader.html sits beside readerjs.js
|
||||
if (opts.src) url.searchParams.set('src', opts.src)
|
||||
if (opts.name) url.searchParams.set('name', opts.name)
|
||||
return url.href
|
||||
}
|
||||
|
||||
export function mount(container, opts = {}) {
|
||||
if (!container) throw new Error('ReaderJS.mount: a container element is required')
|
||||
|
||||
const iframe = document.createElement('iframe')
|
||||
iframe.src = readerHtmlUrl(opts)
|
||||
iframe.title = 'ReaderJS document viewer'
|
||||
iframe.style.cssText = 'width:100%;height:100%;border:0;display:block'
|
||||
// First-party, same-origin content. allow-same-origin is required for Web
|
||||
// Workers, WASM, blob: URLs and localStorage; allow-modals lets the in-frame
|
||||
// print dialog open. Top-navigation stays blocked (no allow-top-navigation).
|
||||
iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-modals allow-popups')
|
||||
|
||||
const frameOrigin = new URL(iframe.src, location.href).origin
|
||||
let ready = false
|
||||
let queued = null // payload held until the frame reports ready
|
||||
|
||||
const postToFrame = (payload) => iframe.contentWindow.postMessage(payload, frameOrigin)
|
||||
|
||||
function onMessage(e) {
|
||||
if (e.source !== iframe.contentWindow || e.origin !== frameOrigin) return
|
||||
if (e.data && e.data.type === 'readerjs:ready') {
|
||||
ready = true
|
||||
if (queued) { postToFrame(queued); queued = null }
|
||||
}
|
||||
}
|
||||
window.addEventListener('message', onMessage)
|
||||
|
||||
// Send bytes to the frame. Structured-clone COPY (no transfer) so the host's
|
||||
// own ArrayBuffer is not neutered.
|
||||
function load(source, name, mime) {
|
||||
Promise.resolve(source instanceof Blob ? source.arrayBuffer() : source).then(buffer => {
|
||||
const payload = { type: 'readerjs:load', buffer, name, mime }
|
||||
if (ready) postToFrame(payload)
|
||||
else queued = payload
|
||||
})
|
||||
}
|
||||
|
||||
container.appendChild(iframe)
|
||||
|
||||
// Bytes mode queues the document; URL mode is served by reader.html via ?src.
|
||||
if (!opts.src && (opts.blob || opts.arrayBuffer)) {
|
||||
load(opts.blob || opts.arrayBuffer, opts.name, opts.mime)
|
||||
}
|
||||
|
||||
return {
|
||||
load, // swap document at runtime (bytes mode)
|
||||
setLang(lang) { if (ready) postToFrame({ type: 'readerjs:setLang', lang }) },
|
||||
iframe,
|
||||
destroy() {
|
||||
window.removeEventListener('message', onMessage)
|
||||
iframe.remove()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import baseConfig from './vite.config.js'
|
||||
|
||||
// Embed build #1 — the read-only viewer page (reader.html) plus per-format lazy
|
||||
// chunks, workers, and the copied public/ assets (rtfjs/, libarchive/, jsdoc/).
|
||||
// `base: './'` makes every asset URL resolve relative to wherever the host
|
||||
// vendors the dist-embed/ folder. Reuses the base config's stubFoliatePdf
|
||||
// plugin + optimizeDeps + target.
|
||||
export default defineConfig({
|
||||
...baseConfig,
|
||||
base: './',
|
||||
worker: { format: 'es' }, // pdf.js + dejaview are module workers
|
||||
build: {
|
||||
...baseConfig.build, // target: 'es2020'
|
||||
outDir: 'dist-embed',
|
||||
emptyOutDir: true, // first build: start from a clean folder
|
||||
rollupOptions: {
|
||||
input: { reader: fileURLToPath(new URL('./reader.html', import.meta.url)) },
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
// Embed build #2 — the tiny loader IIFE (readerjs.js) exposing window.ReaderJS.
|
||||
// Runs AFTER the app build, into the SAME folder, WITHOUT emptying it.
|
||||
export default defineConfig({
|
||||
base: './',
|
||||
build: {
|
||||
outDir: 'dist-embed',
|
||||
emptyOutDir: false, // keep the app build's reader.html + chunks
|
||||
target: 'es2020',
|
||||
lib: {
|
||||
entry: fileURLToPath(new URL('./src/readerjs.js', import.meta.url)),
|
||||
name: 'ReaderJS',
|
||||
formats: ['iife'],
|
||||
fileName: () => 'readerjs.js',
|
||||
},
|
||||
rollupOptions: { output: { extend: true } },
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user