Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
850d436f50 | ||
|
|
7aa9b845e0 | ||
|
|
2ed0ea63e6 | ||
|
|
b418ad60ed | ||
|
|
89d1981e9d | ||
|
|
7df65692f6 | ||
|
|
a760004b09 | ||
|
|
7ce2f4ff73 | ||
|
|
1542458383 | ||
|
|
9791b6c697 | ||
|
|
10d09bd294 | ||
|
|
f1c497c0bf | ||
|
|
3df5627b9f | ||
|
|
f6897f803e | ||
|
|
4643132582 | ||
|
|
52233830d1 | ||
|
|
fe76a8db17 | ||
|
|
e5a2d970ed | ||
|
|
e16a032dd9 | ||
|
|
34e8323e27 | ||
|
|
0bf5053458 | ||
|
|
530f88e880 | ||
|
|
c4e8b08a4a | ||
|
|
3c97ffd1f5 | ||
|
|
fddc552d49 | ||
|
|
8b45c7fa16 | ||
|
|
e1ea9e4385 | ||
|
|
951059d75d | ||
|
|
d11e845da6 | ||
|
|
9c179cc730 | ||
|
|
13a4c3306b | ||
|
|
700f0f18be | ||
|
|
ac7446e6e7 | ||
|
|
9aa4cbf407 | ||
|
|
950b1fad6d | ||
|
|
9aa3009f6d | ||
|
|
a46b454fd2 | ||
|
|
6a8d5e4841 | ||
|
|
b0a6e7c607 | ||
|
|
c80ed0e59a | ||
|
|
e407565e94 | ||
|
|
9bbfa66ad9 | ||
|
|
39ecfee868 | ||
|
|
60af9ff9c6 | ||
|
|
89bb800d5a | ||
|
|
9f7e3ff45f | ||
|
|
defc9e9373 | ||
|
|
9ceeabda90 | ||
|
|
1b4fbe9356 | ||
|
|
982a85151f | ||
|
|
d11396691d | ||
|
|
1e785cd69f | ||
|
|
f6455ae3ee | ||
|
|
1eea327214 | ||
|
|
1c24ffb4de | ||
|
|
5339effffd | ||
|
|
12810f3915 | ||
|
|
45397b0e67 | ||
|
|
dd2fd55ae7 |
@@ -0,0 +1,34 @@
|
||||
# Binary assets — never apply line-ending conversion (it corrupts byte offsets,
|
||||
# e.g. in uncompressed PDFs and font/image tables).
|
||||
*.pdf binary
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
*.avif binary
|
||||
*.bmp binary
|
||||
*.ico binary
|
||||
*.tif binary
|
||||
*.tiff binary
|
||||
*.djvu binary
|
||||
*.djv binary
|
||||
*.epub binary
|
||||
*.mobi binary
|
||||
*.azw3 binary
|
||||
*.fb2 binary
|
||||
*.cbz binary
|
||||
*.cbr binary
|
||||
*.cbt binary
|
||||
*.docx binary
|
||||
*.doc binary
|
||||
*.xlsx binary
|
||||
*.pptx binary
|
||||
*.odt binary
|
||||
*.ods binary
|
||||
*.odp binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.wasm binary
|
||||
@@ -0,0 +1,17 @@
|
||||
name: CI
|
||||
# Build check: the app and the embeddable bundle build from a clean install (Node 22: Vite 8 needs
|
||||
# ^20.19 or >=22.12). Galena pins a ReaderJS commit; the kaskada repo bumps that pin once main is green.
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm run build:embed
|
||||
@@ -1,48 +0,0 @@
|
||||
name: Deploy to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- run: npx vite build --base /ReaderJS/
|
||||
|
||||
- uses: actions/configure-pages@v5
|
||||
|
||||
- uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: dist
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
@@ -1,66 +0,0 @@
|
||||
name: Monthly Submodule Update
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 1 * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
update:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: recursive
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Update submodules to latest
|
||||
run: git submodule update --remote --merge
|
||||
|
||||
- name: Sync public assets from submodules
|
||||
run: cp submodules/JSDoc/src/docToText.js public/jsdoc/docToText.js
|
||||
|
||||
- name: Check for changes
|
||||
id: changes
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
if [ -z "$(git status --porcelain)" ]; then
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Commit and push
|
||||
if: steps.changes.outputs.changed == 'true'
|
||||
run: |
|
||||
git add -A
|
||||
git commit -m "chore: monthly submodule update $(date +%Y-%m)"
|
||||
git push
|
||||
|
||||
- name: Build release artifact
|
||||
if: steps.changes.outputs.changed == 'true'
|
||||
run: |
|
||||
npx vite build --base /ReaderJS/
|
||||
cd dist && zip -r ../release.zip . && cd ..
|
||||
|
||||
- name: Create GitHub release
|
||||
if: steps.changes.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
TAG="v$(date +%Y.%m)"
|
||||
gh release create "$TAG" release.zip \
|
||||
--title "Monthly Update $(date +%Y-%m)" \
|
||||
--notes "Automated monthly submodule update. Submodules updated to their latest commits; bundled assets refreshed." \
|
||||
--latest
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
[submodule "submodules/pdf.js"]
|
||||
path = submodules/pdf.js
|
||||
url = https://github.com/mozilla/pdf.js
|
||||
[submodule "submodules/JSDoc"]
|
||||
path = submodules/JSDoc
|
||||
url = https://github.com/Alpaq92/JSDoc
|
||||
[submodule "submodules/docx"]
|
||||
path = submodules/docx
|
||||
url = https://github.com/dolanmiu/docx
|
||||
[submodule "submodules/WebODF"]
|
||||
path = submodules/WebODF
|
||||
url = https://github.com/webodf/WebODF
|
||||
[submodule "submodules/rtf.js"]
|
||||
path = submodules/rtf.js
|
||||
url = https://github.com/tbluemel/rtf.js
|
||||
[submodule "submodules/marked"]
|
||||
path = submodules/marked
|
||||
url = https://github.com/markedjs/marked
|
||||
[submodule "submodules/foliate-js"]
|
||||
path = submodules/foliate-js
|
||||
url = https://github.com/johnfactotum/foliate-js
|
||||
[submodule "submodules/dejaview"]
|
||||
path = submodules/dejaview
|
||||
url = https://github.com/Alpaq92/dejaview
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# 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 |
|
||||
| [jsdiff](https://github.com/kpdecker/jsdiff) (`diff`) | BSD-3-Clause | text diff engine for the compare view |
|
||||
| [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 |
|
||||
| [mhtml-to-html](https://github.com/gildas-lormeau/mhtml-to-html) | MIT | MHTML/`.mht` web archives → HTML |
|
||||
| [CHMate](https://github.com/Alpaq92/CHMate) | MIT | CHM (`.chm`) reading + rendering — pure-JS ITSF container + LZX, no WASM |
|
||||
| [Riposte](https://github.com/Alpaq92/Riposte) | MIT | PostScript / EPS (`.ps`/`.eps`) interpreter + canvas renderer — pure-JS, zero-dep, no WASM |
|
||||
| [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 |
|
||||
| [Open-Color](https://github.com/yeun/open-color) | MIT | compare/diff view colour palette |
|
||||
|
||||
## 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/`).
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
# 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?), compare(a, b, opts?), 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.
|
||||
|
||||
## Comparing two versions (with blame)
|
||||
|
||||
For any document with extractable text — **PDF**, **DjVu**, **e-books**
|
||||
(EPUB/MOBI/AZW3/FB2), and the text/Office formats (md, docx, rtf, odf, doc, txt,
|
||||
source code, csv/tsv, xlsx) — you can show a diff of two versions, with each
|
||||
change carrying **blame** the host supplies:
|
||||
|
||||
```js
|
||||
const inst = ReaderJS.mount(container, {})
|
||||
inst.compare(
|
||||
{ source: blobA, name: 'report-v1.md' }, // source: Blob or ArrayBuffer
|
||||
{ source: blobB, name: 'report-v2.md' },
|
||||
{
|
||||
mode: 'side-by-side', // 'side-by-side' (default) | 'unified' | 'inline'
|
||||
blame: { // keyed by NEW-side (right) line number
|
||||
12: { author: 'Ana Ruiz', date: '2026-06-20', commit: '9f3a1c2', message: 'bump version' },
|
||||
18: { author: 'Tom Lee', date: '2026-06-22', commit: 'b7e4d80', message: 'add dark mode' },
|
||||
},
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
Or compare straight from `mount`: `ReaderJS.mount(el, { compare: { a, b, blame, mode } })`.
|
||||
|
||||
- The viewer offers a toggle between **side-by-side / unified / inline**.
|
||||
- Hover a changed line → a tooltip shows its blame; click 📌 to **pin** it open (multiple pins allowed).
|
||||
- **`blame` must be plain data** — functions don't survive `postMessage`. Keys are
|
||||
the line numbers of the *new* version (matching `git blame`).
|
||||
- Only image, comic-archive and slide (PPTX) formats have no extractable text and
|
||||
show an "unavailable" message.
|
||||
|
||||
## 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),
|
||||
web archives (MHTML), Compiled HTML Help (CHM), PostScript/EPS, plain text.
|
||||
- See [CREDITS.md](CREDITS.md) — every bundled engine is permissively licensed.
|
||||
@@ -1,10 +1,10 @@
|
||||
# ReaderJS — Universal Document Viewer
|
||||
|
||||
A browser-based document viewer that renders **PDF, ODF, RTF, DOC, DOCX, Markdown, plain text, images, comic-book archives, and e-books (EPUB/MOBI)** natively in the browser — no server, no upload, no conversion. Everything runs client-side; your files never leave your machine.
|
||||
A single browser-based document viewer that opens and renders PDF, ODF, RTF, DOC, DOCX, Markdown, plain text, images, comic-book archives, e-books (EPUB/MOBI), web archives (MHTML), Compiled HTML Help (CHM), and PostScript/EPS natively in the browser — no server, no upload, no conversion, and nothing to install. Everything runs client-side, so your files never leave your machine.
|
||||
|
||||
To give it a try without installing anything, visit the [live demo](https://alpaq92.github.io/ReaderJS/).
|
||||
|
||||

|
||||

|
||||
|
||||
---
|
||||
|
||||
@@ -13,6 +13,7 @@ To give it a try without installing anything, visit the [live demo](https://alpa
|
||||
| Format | Extension(s) | Engine |
|
||||
|--------|-------------|--------|
|
||||
| PDF | `.pdf` | PDF.js (Mozilla) |
|
||||
| PostScript / EPS | `.ps` `.eps` `.epsf` | Riposte |
|
||||
| DjVu | `.djvu` `.djv` | DejaView |
|
||||
| ODF — Writer, Calc, Impress | `.odt` `.ods` `.odp` `.odg` | JSZip + DOMParser |
|
||||
| Rich Text Format | `.rtf` | RTF.js |
|
||||
@@ -27,18 +28,35 @@ To give it a try without installing anything, visit the [live demo](https://alpa
|
||||
| Image (+ EXIF) | `.png` `.jpg` `.gif` `.webp` `.avif` `.bmp` `.svg` `.tiff` | native + UTIF.js (TIFF) + exifr (EXIF) |
|
||||
| Comic Book Archive | `.cbz` `.cbr` `.cbt` | JSZip (CBZ) + libarchive.js (CBR/CBT) |
|
||||
| E-book | `.epub` `.mobi` `.azw3` `.fb2` | foliate-js |
|
||||
| Web archive (MHTML) | `.mht` `.mhtml` | mhtml-to-html |
|
||||
| Compiled HTML Help | `.chm` | CHMate |
|
||||
|
||||
## Features
|
||||
|
||||
- PDF.js-inspired UI — sidebar thumbnails, page navigation, zoom, print
|
||||
- Drag & drop or browse to open files
|
||||
- Compare two document versions (PDF, DjVu, e-books, Office, text) — side-by-side / unified / inline, with word-level highlights, pinnable blame-aware tooltips, and page-by-page diff for multi-page PDF/DjVu
|
||||
- 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)
|
||||
- Light / dark / follow-the-system theme, with a localized switcher beside the language one — defaults to following the OS, and the light palette is [Open Color](https://yeun.github.io/open-color/)
|
||||
|
||||
## 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
|
||||
git clone --recurse-submodules https://github.com/Alpaq92/ReaderJS.git
|
||||
git clone https://github.com/Alpaq92/ReaderJS.git
|
||||
cd ReaderJS
|
||||
npm install
|
||||
npm run dev
|
||||
@@ -62,24 +80,26 @@ ReaderJS is built on these open-source libraries:
|
||||
| **[JSZip](https://github.com/Stuk/jszip)** | Stuk | ODF / ZIP container reading |
|
||||
| **[jQuery](https://github.com/jquery/jquery)** | OpenJS Foundation | DOM utility required internally by RTF.js |
|
||||
| **[marked](https://github.com/markedjs/marked)** | Christopher Jeffrey et al. | Markdown → HTML parsing and rendering |
|
||||
| **[jsdiff](https://github.com/kpdecker/jsdiff)** | Kevin Decker | Text diffing engine behind the two-version compare view (BSD-3) |
|
||||
| **[libarchive.js](https://github.com/nika-begiashvili/libarchivejs)** | Nika Begiashvili | CBR/CBT (RAR/TAR) extraction via a WASM build of libarchive — uses libarchive's own BSD-licensed RAR decoder, no UnRAR code |
|
||||
| **[foliate-js](https://github.com/johnfactotum/foliate-js)** | John Factotum | EPUB / MOBI / KF8 (AZW3) / FB2 parsing and paginated rendering |
|
||||
| **[mhtml-to-html](https://github.com/gildas-lormeau/mhtml-to-html)** | Gildas Lormeau | MHTML (`.mht` / `.mhtml`) web archives → one self-contained HTML document |
|
||||
| **[CHMate](https://github.com/Alpaq92/CHMate)** | Alpaq92 | Pure-JS Microsoft Compiled HTML Help (`.chm`) reader — ITSF container + LZX decompression + sanitizing topic renderer, no WASM |
|
||||
| **[Riposte](https://github.com/Alpaq92/Riposte)** | Alpaq92 | Pure-JS PostScript / EPS interpreter and renderer — rasterizes each page to `<canvas>`, zero runtime deps, no WASM |
|
||||
| **[UTIF.js](https://github.com/photopea/UTIF.js)** | Photopea | TIFF image decoding |
|
||||
| **[exifr](https://github.com/MikeKovarik/exifr)** | Mike Kovarik | EXIF / GPS metadata parsing for images |
|
||||
| **[Vite](https://github.com/vitejs/vite)** | Evan You / Vite contributors | Build tooling and development server |
|
||||
| **[Material Design Icons](https://pictogrammers.com/library/mdi/)** | Pictogrammers | UI icons (Apache-2.0) |
|
||||
| **[Open-Color](https://github.com/yeun/open-color)** | Heeyeun Jeong | Colour palette for the compare / diff view |
|
||||
|
||||
### Submodules (reference / bundled)
|
||||
|
||||
| Submodule | Author / Source | Notes |
|
||||
|-----------|----------------|-------|
|
||||
| [mozilla/pdf.js](https://github.com/mozilla/pdf.js) | Mozilla | Pinned for worker build |
|
||||
| [Alpaq92/JSDoc](https://github.com/Alpaq92/JSDoc) | Alpaq92 | Bundled source for `.doc` rendering |
|
||||
| [dolanmiu/docx](https://github.com/dolanmiu/docx) | dolanmiu | Reference |
|
||||
| [webodf/WebODF](https://github.com/webodf/WebODF) | webodf | Reference |
|
||||
| [tbluemel/rtf.js](https://github.com/tbluemel/rtf.js) | tbluemel | Reference |
|
||||
| [markedjs/marked](https://github.com/markedjs/marked) | Christopher Jeffrey et al. | Reference |
|
||||
| [johnfactotum/foliate-js](https://github.com/johnfactotum/foliate-js) | John Factotum | Bundled source for EPUB/MOBI rendering (pinned commit) |
|
||||
Every library above is a normal **npm dependency** — `npm install` is all you
|
||||
need, no git submodules. The four that aren't published to npm
|
||||
([foliate-js](https://github.com/johnfactotum/foliate-js) for e-books,
|
||||
[DejaView](https://github.com/Alpaq92/dejaview) for DjVu,
|
||||
[CHMate](https://github.com/Alpaq92/CHMate) for CHM, and
|
||||
[Riposte](https://github.com/Alpaq92/Riposte) for PostScript) are pinned to
|
||||
commits as git dependencies in `package.json`. Every engine is permissively licensed
|
||||
(MIT / BSD / Apache-2.0 / 0BSD).
|
||||
|
||||
## Gallery
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
var e=class{constructor(){this.numPages=1,this.scale=1,this.container=null,this.viewer=null,this.defaultScaleOption=`page-width`}async load(e,t,n){this.container=t,this.viewer=n}scrollToPage(e){let t=this.container?.querySelector(`[data-page="${e}"]`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})}setScale(e){this.scale=e,this.container?.querySelectorAll(`.doc-page`).forEach(t=>{t.style.zoom=e===1?``:e})}getPageWidth(){return 816}getPageHeight(){return null}async preparePrint(){}cleanupAfterPrint(){}destroy(){this.container&&(this.container.innerHTML=``)}};export{e as t};
|
||||
@@ -0,0 +1 @@
|
||||
import{c as e,n as t,r as n,t as r}from"./driver-0cTj10HJ.js";var i=class extends t{constructor(e){super(),this.ctx=e}beginPage(e,t){super.beginPage(e,t),this.ctx.clearRect(0,0,e,t)}_trace(e){let t=this.ctx;t.beginPath();for(let n of e.segs)n.op===`M`?t.moveTo(n.x,n.y):n.op===`L`?t.lineTo(n.x,n.y):n.op===`C`?t.bezierCurveTo(n.x1,n.y1,n.x2,n.y2,n.x3,n.y3):n.op===`Z`&&t.closePath()}fill(t,n,r){this.ctx.fillStyle=e(r),this._trace(t),this.ctx.fill(n)}stroke(t,i,a){let o=this.ctx;o.strokeStyle=e(a),o.lineWidth=i.width,o.lineCap=r[i.cap]||`butt`,o.lineJoin=n[i.join]||`miter`,o.miterLimit=i.miter,o.setLineDash(i.dash||[]),o.lineDashOffset=i.offset||0,this._trace(t),o.stroke()}clip(e,t){this._trace(e),this.ctx.clip(t)}save(){this.ctx.save()}restore(){this.ctx.restore()}showText(t,n,r,i,a){let o=this.ctx;o.save(),o.setTransform(n[0],n[1],n[2],n[3],n[4],n[5]),o.fillStyle=e(i),o.font=`${(a.italic?`italic `:``)+(a.bold?`bold `:``)}${r}px ${a.family}`,o.textBaseline=`alphabetic`,o.fillText(t,0,0),o.restore()}};export{i as CanvasDriver};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=null,r=class extends t{constructor(){super(),this._reader=null,this._blobs=null,this._frame=null,this._onFrameClick=this._onFrameClick.bind(this)}async load(t,r,i){await super.load(t,r,i);let[{ChmReader:a},o]=await Promise.all([e(()=>import(`./chm-reader-Bjyc0KjP.js`),[],import.meta.url),e(()=>import(`./render-D6jv0HaF.js`),[],import.meta.url)]);n=o.renderTopic;let s=a.open(t);this._reader=s,this._blobs=new o.BlobCache(s),r.innerHTML=``;let c=document.createElement(`div`);c.className=`doc-page chm-page`,c.dataset.page=1;let l=document.createElement(`iframe`);l.className=`chm-frame`,l.sandbox=`allow-same-origin`,this._frame=l,c.appendChild(l),r.appendChild(c),this._buildContents(s);let u=s.defaultTopic||s.listFiles().find(e=>/\.html?$/i.test(e));u?this._navigate(u):l.srcdoc=`<!DOCTYPE html><meta charset="utf-8"><body style="font:14px sans-serif;padding:24px;color:#555">This .chm has no displayable HTML topic.</body>`,this.numPages=1}_navigate(e,t=``){let r=this._reader;if(!r)return;let i=e.indexOf(`#`);if(i>=0&&(t=t||e.slice(i+1),e=e.slice(0,i)),!r.hasFile(e))return;let a=this._frame;a.onload=()=>{let n=a.contentDocument;if(n){if(a.style.height=`${n.documentElement.scrollHeight}px`,n.addEventListener(`click`,this._onFrameClick,!0),t){let e=n.getElementById(t)||n.querySelector(`a[name="${CSS.escape(t)}"]`);e&&e.scrollIntoView({block:`start`})}this._highlightContents(e)}},a.srcdoc=n(r,e,this._blobs)}_onFrameClick(e){let t=e.target.closest?.(`a`);if(!t)return;let n=t.getAttribute(`data-chm-href`),r=t.getAttribute(`data-chm-ext`);n?(e.preventDefault(),this._navigate(n,t.getAttribute(`data-chm-frag`)||``)):r&&(e.preventDefault(),confirm(`Open external link?\n\n${r}`)&&window.open(r,`_blank`,`noopener`))}_buildContents(e){let t=document.getElementById(`thumbsContent`);if(!t)return;let n=e.getContents();if(!n?.length)return;this.buildsThumbnailsAsync=!0,t.innerHTML=``;let r=document.createElement(`div`);r.className=`chm-toc`,this._renderNodes(e,n,r),t.appendChild(r)}_renderNodes(e,t,n){for(let r of t){let t=document.createElement(`div`);t.className=`chm-toc-row`,t.textContent=r.name||`(untitled)`;let i=this._nodeTarget(e,r);if(i&&(t.classList.add(`chm-toc-link`),t.dataset.target=i,t.addEventListener(`click`,()=>this._navigate(i))),n.appendChild(t),r.children?.length){let t=document.createElement(`div`);t.className=`chm-toc-children`,this._renderNodes(e,r.children,t),n.appendChild(t)}}}_nodeTarget(e,t){if(t.url||!t.local)return null;let n=e.resolvePath(e.contentsPath||`/`,t.local).replace(/#.*$/,``);return e.hasFile(n)?n:null}_highlightContents(e){let t=document.getElementById(`thumbsContent`);t&&(t.querySelectorAll(`.chm-toc-active`).forEach(e=>e.classList.remove(`chm-toc-active`)),t.querySelectorAll(`.chm-toc-row[data-target="${CSS.escape(e)}"]`).forEach(e=>e.classList.add(`chm-toc-active`)))}destroy(){this._blobs?.revokeAll(),this._blobs=null,this._reader=null,this._frame=null;let e=document.getElementById(`thumbsContent`);e&&(e.innerHTML=``),super.destroy()}};export{r as CHMRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
function e(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function t(t,n){e(t,n),n.add(t)}function n(t,n,r){e(t,n),n.set(t,r)}function r(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function i(e,t){return e.get(r(e,t))}function a(e,t,n){return e.set(r(e,t),n),n}export{t as a,n as i,i as n,r,a as t};
|
||||
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./common-D7sP-4Y_.js","./rolldown-runtime-DAXXjFlN.js","./github-DdKuH37F.css"])))=>i.map(i=>d[i]);
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n={js:`javascript`,mjs:`javascript`,cjs:`javascript`,jsx:`javascript`,ts:`typescript`,tsx:`typescript`,json:`json`,jsonc:`json`,xml:`xml`,html:`xml`,htm:`xml`,yaml:`yaml`,yml:`yaml`,css:`css`,scss:`scss`,less:`less`,py:`python`,java:`java`,c:`c`,h:`c`,cpp:`cpp`,cc:`cpp`,hpp:`cpp`,cs:`csharp`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sh:`bash`,bash:`bash`,sql:`sql`,kt:`kotlin`,swift:`swift`,toml:`ini`,ini:`ini`,diff:`diff`},r=class extends t{async load(t,r,i){await super.load(t,r,i);let a=(await e(async()=>{let{default:e}=await import(`./common-D7sP-4Y_.js`);return{default:e}},__vite__mapDeps([0,1]),import.meta.url)).default;await e(()=>Promise.resolve({}),__vite__mapDeps([2]),import.meta.url);let o=new TextDecoder(`utf-8`).decode(t),s=n[(i?.currentFileName||``).split(`.`).pop().toLowerCase()];if(s===`json`)try{o=JSON.stringify(JSON.parse(o),null,2)}catch{}let c=s&&a.getLanguage(s)?a.highlight(o,{language:s}):a.highlightAuto(o);r.innerHTML=``;let l=document.createElement(`div`);l.className=`doc-page`,l.dataset.page=1;let u=document.createElement(`pre`);u.className=`code-content`;let d=document.createElement(`code`);d.className=`hljs`,d.innerHTML=c.value,u.appendChild(d),l.appendChild(u),r.appendChild(l),this.numPages=1}};export{r as CodeRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
var e=({entries:e,loadBlob:t,getSize:n},r)=>{let i=new Map,a=new Map,o=async e=>{if(i.has(e))return i.get(e);let n=URL.createObjectURL(await t(e)),r=URL.createObjectURL(new Blob([`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin: 0"><img src="${n}"></body></html>`],{type:`text/html`}));return a.set(e,[n,r]),i.set(e,r),r},s=e=>{a.get(e)?.forEach?.(e=>URL.revokeObjectURL(e)),a.delete(e),i.delete(e)},c=[`.jpg`,`.jpeg`,`.png`,`.gif`,`.bmp`,`.webp`,`.svg`,`.jxl`,`.avif`],l=e.map(e=>e.filename).filter(e=>c.some(t=>e.endsWith(t))).sort(new Intl.Collator([],{numeric:!0}).compare);if(!l.length)throw Error(`No supported image files in archive`);let u={};return u.getCover=()=>t(l[0]),u.metadata={title:r.name},u.sections=l.map(e=>({id:e,load:()=>o(e),unload:()=>s(e),size:n(e)})),u.toc=l.map(e=>({label:e,href:e})),u.rendition={layout:`pre-paginated`},u.resolveHref=e=>({index:u.sections.findIndex(t=>t.id===e)}),u.splitTOCHref=e=>[e,null],u.getTOCFragment=e=>e.documentElement,u.destroy=()=>{for(let e of a.values())for(let t of e)URL.revokeObjectURL(t)},u};export{e as makeComicBook};
|
||||
@@ -0,0 +1 @@
|
||||
import{o as e}from"./rolldown-runtime-DAXXjFlN.js";import{t}from"./reader-Bd1ccloG.js";import{t as n}from"./jszip.min-C__FR9jF.js";import{t as r}from"./base-renderer-DM6Nw1yD.js";var i=e(n()),a=/\.(jpe?g|png|gif|webp|bmp|avif)$/i,o={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,avif:`image/avif`};function s(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}var c=class extends r{constructor(){super(),this._imgUrls=[],this._observer=null,this._naturalW=0,this._naturalH=0,this.defaultScaleOption=`page-height`}async load(e,t,n){await super.load(e,t,n);let r=await this._extract(e);if(!r.length)throw Error(`No images found in comic archive`);t.innerHTML=``;for(let[e,n]of r.entries()){let r=document.createElement(`div`);r.className=`comic-page`,r.dataset.page=e+1;let i=document.createElement(`img`);i.src=n.url,i.alt=n.name,i.loading=`lazy`,i.draggable=!1,r.appendChild(i),t.appendChild(r)}this.numPages=r.length,await this._measureFirst(r[0].url),this.setScale(this.scale),this._attachScrollObserver(),this._buildThumbnails(r)}async _extract(e){let t=new Uint8Array(e.slice(0,4));return t[0]===80&&t[1]===75?this._extractZip(e):this._extractArchive(e)}async _extractZip(e){let t=await i.default.loadAsync(e),n=[];t.forEach((e,t)=>{!t.dir&&a.test(e)&&n.push({path:e,file:t})}),n.sort((e,t)=>s(e.path,t.path));let r=[];for(let{path:e,file:t}of n){let n=await t.async(`uint8array`);r.push({name:e,url:this._toUrl(n,e)})}return r}async _extractArchive(e){let{Archive:n}=await t(async()=>{let{Archive:e}=await import(`./libarchive-Dhbbd3NZ.js`);return{Archive:e}},[],import.meta.url);n.init({workerUrl:`./libarchive/worker-bundle.js`});let r=await n.open(new Blob([e])),i=(await r.getFilesArray()).filter(e=>a.test(e.file.name)).sort((e,t)=>s((e.path||``)+e.file.name,(t.path||``)+t.file.name)),o=[];for(let e of i){let t=await e.file.extract(),n=new Uint8Array(await t.arrayBuffer());o.push({name:e.file.name,url:this._toUrl(n,e.file.name)})}return await r.close?.(),o}_toUrl(e,t){let n=o[t.split(`.`).pop().toLowerCase()]??`application/octet-stream`,r=URL.createObjectURL(new Blob([e],{type:n}));return this._imgUrls.push(r),r}_measureFirst(e){return new Promise(t=>{let n=new Image;n.onload=()=>{this._naturalW=n.naturalWidth,this._naturalH=n.naturalHeight,t()},n.onerror=()=>t(),n.src=e})}setScale(e){if(this.scale=e,!this._naturalW)return;let t=Math.round(this._naturalW*e);this.container?.querySelectorAll(`.comic-page`).forEach(e=>{e.style.width=`${t}px`})}getPageWidth(){return this._naturalW||null}getPageHeight(){return this._naturalH||null}_attachScrollObserver(){this._observer&&this._observer.disconnect();let e=this.container.parentElement;this._observer=new IntersectionObserver(e=>{let t={ratio:0,page:this.viewer?.currentPage||1};e.forEach(e=>{e.intersectionRatio>t.ratio&&(t={ratio:e.intersectionRatio,page:+e.target.dataset.page})}),t.ratio>0&&this.viewer&&t.page!==this.viewer.currentPage&&(this.viewer.currentPage=t.page,this.viewer.updatePageInfo(),this._highlightThumb(t.page))},{threshold:[0,.25,.5,.75,1],root:e}),this.container.querySelectorAll(`.comic-page`).forEach(e=>this._observer.observe(e))}_buildThumbnails(e){let t=document.getElementById(`thumbsContent`);t&&(t.innerHTML=``,e.forEach((e,n)=>{let r=document.createElement(`div`);r.className=`thumb`,r.dataset.thumbPage=n+1,r.title=`Page ${n+1}`;let i=document.createElement(`img`);i.src=e.url,i.loading=`lazy`;let a=document.createElement(`div`);a.className=`thumb-label`,a.textContent=n+1,r.appendChild(i),r.appendChild(a),r.addEventListener(`click`,()=>this.viewer?.goToPage(n+1)),t.appendChild(r)}))}_highlightThumb(e){document.querySelectorAll(`.thumb`).forEach(t=>{t.classList.toggle(`active`,+t.dataset.thumbPage===e)})}scrollToPage(e){let t=this.container?.querySelector(`.comic-page[data-page="${e}"]`);t&&t.scrollIntoView({behavior:`smooth`,block:`start`})}destroy(){this._observer?.disconnect(),this._observer=null,this._imgUrls.forEach(e=>URL.revokeObjectURL(e)),this._imgUrls=[],super.destroy()}};export{c as ComicRenderer};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./papaparse.min-D30bkSB7.js","./rolldown-runtime-DAXXjFlN.js"])))=>i.map(i=>d[i]);
|
||||
import{o as e}from"./rolldown-runtime-DAXXjFlN.js";import{t}from"./reader-Bd1ccloG.js";import{t as n}from"./base-renderer-DM6Nw1yD.js";var r=class extends n{async load(n,r,i){await super.load(n,r,i);let a=(await t(async()=>{let{default:t}=await import(`./papaparse.min-D30bkSB7.js`).then(t=>e(t.default));return{default:t}},__vite__mapDeps([0,1]),import.meta.url)).default,o=new TextDecoder(`utf-8`).decode(n),s=i?.currentFileName||``,c=/\.tsv$/i.test(s)?` `:``,l=a.parse(o,{delimiter:c,skipEmptyLines:!0}).data;r.innerHTML=``;let u=document.createElement(`div`);u.className=`doc-page`,u.dataset.page=1;let d=document.createElement(`table`);d.className=`data-table`,l.forEach((e,t)=>{let n=document.createElement(`tr`);e.forEach(e=>{let r=document.createElement(t===0?`th`:`td`);r.textContent=e,n.appendChild(r)}),d.appendChild(n)});let f=document.createElement(`div`);f.className=`data-table-wrap`,f.appendChild(d),u.appendChild(f),r.appendChild(u),this.numPages=1}};export{r as CSVRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}function t(t,n){if(e(t)!=`object`||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,n||`default`);if(e(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(t)}function n(n){var r=t(n,`string`);return e(r)==`symbol`?r:r+``}function r(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}export{r as t};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
import{t as e}from"./base-renderer-DM6Nw1yD.js";var t=2e3,n=200,r=class extends e{constructor(){super(),this._worker=null,this._reqId=0,this._pending=new Map,this._infos=[],this._pageW=800,this._pageH=1e3,this._gen=0,this._renderObs=null,this._pageObs=null,this.defaultScaleOption=`page-height`,this.buildsThumbnailsAsync=!0}_call(e,t){return new Promise((n,r)=>{let i=++this._reqId;this._pending.set(i,{resolve:n,reject:r}),this._worker.postMessage({id:i,type:e,...t})})}_spawnWorker(){this._worker=new Worker(new URL(``+new URL(`worker-OhPDRroP.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),this._worker.onmessage=e=>{let{id:t,error:n}=e.data,r=this._pending.get(t);r&&(this._pending.delete(t),n?r.reject(Error(n)):r.resolve(e.data))}}async extractText(e){this._spawnWorker();try{let t=await this._call(`open`,{buffer:e}),n=[];for(let e=0;e<(t.pageCount||1);e++){let{words:t}=await this._call(`text`,{index:e}),r=[],i=[],a=null;for(let e of t||[]){let t=e.ymax-e.ymin||10;a!=null&&Math.abs(e.ymin-a)>t*.7&&(r.push(i.join(` `)),i=[]),i.push(e.str),a=e.ymin}i.length&&r.push(i.join(` `)),n.push(r.join(`
|
||||
`))}return n}finally{this._worker?.terminate(),this._worker=null}}_logical(e){let t=e?.dpi||300;return{w:Math.max(1,Math.round((e?.width||800)*96/t)),h:Math.max(1,Math.round((e?.height||1e3)*96/t))}}async load(e,t,n){await super.load(e,t,n);let r=++this._gen;this._spawnWorker();let i=await this._call(`open`,{buffer:e});if(r!==this._gen)return;this.numPages=i.pageCount||1,this._infos=i.infos||[];let a=this._logical(this._infos[0]);this._pageW=a.w,this._pageH=a.h,t.innerHTML=``;for(let e=0;e<this.numPages;e++){let n=this._logical(this._infos[e]),r=document.createElement(`div`);r.className=`djvu-page`,r.dataset.page=e+1,r.dataset.lw=n.w,r.dataset.lh=n.h,t.appendChild(r)}this.setScale(this.scale),this._attachObservers(),this._renderWindow(0),this._buildThumbnails(r)}_renderWindow(e){for(let t=e-1;t<=e+1;t++)t>=0&&t<this.numPages&&this._renderPage(t)}_attachObservers(){let e=this.container.parentElement;this._renderObs=new IntersectionObserver(e=>{e.forEach(e=>{let t=e.target.dataset.page-1;e.isIntersecting?this._renderPage(t):this._clearPage(e.target)})},{root:e,rootMargin:`150% 0px`,threshold:0}),this._pageObs=new IntersectionObserver(e=>{let t={ratio:0,page:this.viewer?.currentPage||1};e.forEach(e=>{e.intersectionRatio>t.ratio&&(t={ratio:e.intersectionRatio,page:+e.target.dataset.page})}),t.ratio>0&&this.viewer&&t.page!==this.viewer.currentPage&&(this.viewer.currentPage=t.page,this.viewer.updatePageInfo(),this._highlightThumb(t.page))},{root:e,threshold:[0,.25,.5,.75,1]}),this.container.querySelectorAll(`.djvu-page`).forEach(e=>{this._renderObs.observe(e),this._pageObs.observe(e)})}_subsample(e,t){let n=e?.width||800;return Math.max(1,Math.round(n/Math.min(n,t)))}_canvasFromRender(e){let t=document.createElement(`canvas`);return t.width=e.width,t.height=e.height,t.getContext(`2d`).putImageData(new ImageData(e.rgba,e.width,e.height),0,0),t}async _renderPage(e){let n=this.container?.querySelector(`.djvu-page[data-page="${e+1}"]`);if(!n||n.dataset.rendered)return;n.dataset.rendered=`1`;let r=this._gen;try{let i=await this._call(`render`,{index:e,subsample:this._subsample(this._infos[e],t)});if(r!==this._gen||!this._worker)return;let a=this._canvasFromRender(i);n.innerHTML=``,n.appendChild(a)}catch{n.dataset.rendered=``}}_clearPage(e){e.dataset.rendered&&(e.innerHTML=``,e.dataset.rendered=``)}setScale(e){this.scale=e,this.container?.querySelectorAll(`.djvu-page`).forEach(t=>{t.style.width=`${Math.round((+t.dataset.lw||this._pageW)*e)}px`,t.style.height=`${Math.round((+t.dataset.lh||this._pageH)*e)}px`})}getPageWidth(){return this._pageW}getPageHeight(){return this._pageH}scrollToPage(e){let t=this.container?.querySelector(`.djvu-page[data-page="${e}"]`);t&&(this._renderWindow(e-1),t.scrollIntoView({behavior:`smooth`,block:`start`}))}async _buildThumbnails(e){let t=document.getElementById(`thumbsContent`);if(t){for(let r=0;r<this.numPages;r++){let i=this._infos[r],a;try{a=await this._call(`render`,{index:r,subsample:this._subsample(i,n)})}catch{continue}if(e!==this._gen||!this._worker)return;let o=this._canvasFromRender(a),s=document.createElement(`img`);s.src=o.toDataURL(`image/png`);let c=document.createElement(`div`);c.className=`thumb`,c.dataset.thumbPage=r+1;let l=document.createElement(`div`);l.className=`thumb-label`,l.textContent=r+1,c.append(s,l),c.addEventListener(`click`,()=>this.viewer?.goToPage(r+1)),t.appendChild(c)}this._highlightThumb(this.viewer?.currentPage||1)}}_highlightThumb(e){document.querySelectorAll(`#thumbsContent .thumb`).forEach(t=>{t.classList.toggle(`active`,+t.dataset.thumbPage===e)})}destroy(){this._gen++,this._renderObs?.disconnect(),this._pageObs?.disconnect(),this._renderObs=this._pageObs=null,this._pending.clear(),this._worker?.terminate(),this._worker=null,super.destroy()}};export{r as DjVuRenderer};
|
||||
@@ -0,0 +1,2 @@
|
||||
import{t as e}from"./base-renderer-DM6Nw1yD.js";var t=[``,`center`,`right`,`justify`],n=null;function r(){return window.docToText?Promise.resolve():n||(n=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=`./jsdoc/docToText.js`,n.onload=()=>{e()},n.onerror=()=>t(Error(`Failed to load /jsdoc/docToText.js`)),document.head.appendChild(n)}),n)}function i(e){return String(e).replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e])}function a(e){if(!e)return``;let t=``;return e.indL&&(t+=`margin-left:${e.indL/20}pt;`),e.indR&&(t+=`margin-right:${e.indR/20}pt;`),e.ind1&&(t+=`text-indent:${e.ind1/20}pt;`),e.spB&&(t+=`margin-bottom:${e.spB/20}pt;`),e.spA&&(t+=`margin-top:${e.spA/20}pt;`),e.line&&(t+=`line-height:${e.lineMult?e.line/240:Math.abs(e.line)/20+`pt`};`),t}function o(e){let t=``;e.b&&(t+=`font-weight:bold;`),e.i&&(t+=`font-style:italic;`);let n=(e.u?`underline `:``)+(e.strike?`line-through`:``);return n.trim()&&(t+=`text-decoration:${n.trim()};`),e.size&&(t+=`font-size:${e.size}pt;`),e.font&&(t+=`font-family:'${String(e.font).replace(/['\\<>]/g,``)}';`),e.color!=null&&(t+=`color:rgb(${e.color&255},${e.color>>8&255},${e.color>>16&255});`),t}function s(e,t){let n=``;for(let r of e||[])if(r.image&&r.image.bytes)try{let e=URL.createObjectURL(new Blob([r.image.bytes],{type:r.image.mime||`image/png`}));t.push(e),n+=`<img class="docimg" src="${e}" alt="embedded image">`}catch{}else if(r.ftnRef!=null)n+=`<sup class="ftnref" title="footnote ${r.ftnRef+1}">${r.ftnRef+1}</sup>`;else if(r.endRef!=null){let e=[`i`,`ii`,`iii`,`iv`,`v`,`vi`,`vii`,`viii`,`ix`,`x`][r.endRef]||r.endRef+1;n+=`<sup class="ftnref" title="endnote ${r.endRef+1}">${e}</sup>`}else if(r.comRef!=null)n+=`<sup class="comref" title="comment ${r.comRef+1}">✎</sup>`;else if(r.text){let e=o(r),t=e?`<span style="${e}">${i(r.text)}</span>`:i(r.text);r.url&&(t=`<a href="${i(r.url)}" target="_blank" rel="noopener nofollow">${t}</a>`),n+=t}return n}function c(e,n){let r=``,i=0,o=null,c=()=>{o&&(r+=`</${o}>`,o=null)};for(;i<e.length;){let l=e[i];if(l.kind===`cell`||l.kind===`rowEnd`){c();let t=[],a=[];for(;i<e.length&&(e[i].kind===`cell`||e[i].kind===`rowEnd`);)a.push(e[i]),e[i].kind===`rowEnd`&&(t.push({cells:a.slice(),tblw:e[i].tblw,shd:e[i].tblShd}),a=[]),i++;a.length&&t.push({cells:a,tblw:null,shd:null});let o={};t.forEach(e=>{e.tblw&&e.tblw.forEach(e=>{o[e]=1})});let l=Object.keys(o).map(Number).sort((e,t)=>e-t),u=l.length>2,d=``;if(u){let e=l[l.length-1]-l[0];if(e>0){d=`<colgroup>`;for(let t=0;t<l.length-1;t++)d+=`<col style="width:${((l[t+1]-l[t])/e*100).toFixed(2)}%">`;d+=`</colgroup>`}}r+=`<table class="doc-table${u?` sized`:``}">${d}<tbody>`,t.forEach(e=>{r+=`<tr>`;for(let t=0;t<e.cells.length;t++){let i=1;if(e.tblw&&e.tblw.length===e.cells.length+1&&l.length>2){let n=e.tblw[t],r=e.tblw[t+1],a=0;for(let e=0;e<l.length;e++)l[e]>n&&l[e]<r&&a++;i=a+1}let a=e.shd&&e.shd[t]!=null?e.shd[t]:null,o=a==null?``:`rgb(${a&255},${a>>8&255},${a>>16&255})`;r+=`<td${i>1?` colspan="${i}"`:``}${o?` style="background:${o}"`:``}>${s(e.cells[t].runs,n)||` `}</td>`}r+=`</tr>`}),r+=`</tbody></table>`}else{let e=l.align?`text-align:${t[l.align]};`:``,u=s(l.runs,n);if(l.list){let t=l.list.kind===`number`?`ol`:`ul`;o!==t&&(c(),r+=`<${t}>`,o=t),r+=`<li${e?` style="${e}"`:``}>${u||` `}</li>`}else{c();let t=e+a(l.pp);r+=`<p${t?` style="${t}"`:``}>${u||`<br>`}</p>`}i++}}return c(),r||`<p><em>(document contains no main-body text)</em></p>`}function l(e){let t=e.split(`
|
||||
`),n=``,r=0;for(;r<t.length;)if(t[r].includes(` `)){let e=[];for(;r<t.length&&t[r].includes(` `);)e.push(t[r].split(` `)),r++;n+=`<table class="doc-table"><tbody>`;for(let t=0;t<e.length;t++){let r=t===0?`th`:`td`;n+=`<tr>`+e[t].map(e=>`<${r}>${e}</${r}>`).join(``)+`</tr>`}n+=`</tbody></table>`}else t[r].trim()&&(n+=`<p>${t[r]}</p>`),r++;return n||`<p><em>(document contains no main-body text)</em></p>`}var u=class extends e{constructor(){super(),this._imgUrls=[]}async load(e,t,n){await super.load(e,t,n),await r();let a=window.docToText;if(typeof a!=`function`)throw Error(`docToText library failed to load.`);let o=null;try{o=a.model(e)}catch{}let s;if(o&&o.body){if(s=c(o.body,this._imgUrls),o.props){let e=[];[[`title`,`Title`],[`author`,`Author`],[`subject`,`Subject`]].forEach(([t,n])=>{o.props[t]&&e.push(`<b>${n}:</b> ${i(o.props[t])}`)}),e.length&&(s=`<div class="docprops">${e.join(` · `)}</div>`+s)}for(let[e,t]of[[`footnotes`,`Footnotes`],[`endnotes`,`Endnotes`],[`annotations`,`Comments`],[`textboxes`,`Text boxes`]])o[e]&&o[e].length&&(s+=`<h3 class="sec">${t}</h3>`+c(o[e],this._imgUrls));o.header&&o.header.length&&(s+=`<h3 class="sec">Header</h3>`+c(o.header,this._imgUrls)),o.footer&&o.footer.length&&(s+=`<h3 class="sec">Footer</h3>`+c(o.footer,this._imgUrls))}else{let t=null;try{t=a.html(e)}catch{}if(!t||!t.body)throw Error(`Could not read .doc file — may be Word 6/95, encrypted, or corrupt.`);s=l(t.body)}t.innerHTML=``;let u=document.createElement(`div`);u.className=`doc-page`,u.dataset.page=1,u.innerHTML=s,t.appendChild(u),this.numPages=1}destroy(){this._imgUrls.forEach(e=>URL.revokeObjectURL(e)),this._imgUrls=[],super.destroy()}};export{u as DOCRenderer};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./lib-sUWhpJan.js","./rolldown-runtime-DAXXjFlN.js","./jszip.min-C__FR9jF.js"])))=>i.map(i=>d[i]);
|
||||
import{o as e}from"./rolldown-runtime-DAXXjFlN.js";import{t}from"./reader-Bd1ccloG.js";import{t as n}from"./base-renderer-DM6Nw1yD.js";var r=class extends n{async load(n,r,i){await super.load(n,r,i);let a;try{let n=await t(()=>import(`./lib-sUWhpJan.js`).then(t=>e(t.default)),__vite__mapDeps([0,1,2]),import.meta.url);a=n.default??n}catch(e){throw Error(`mammoth could not be loaded: ${e.message}`)}let o=await a.convertToHtml({arrayBuffer:n});o.messages?.length&&console.warn(`[DOCX] conversion messages:`,o.messages),r.innerHTML=``;let s=document.createElement(`div`);s.className=`doc-page`,s.dataset.page=1,s.innerHTML=o.value,r.appendChild(s),this.numPages=1}};export{r as DOCXRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
var e=e=>e<0?0:e>1?1:e,t=e=>({space:`gray`,c:[e]}),n=(e,t,n)=>({space:`rgb`,c:[e,t,n]}),r=(e,t,n,r)=>({space:`cmyk`,c:[e,t,n,r]});function i(e,t,r){e=(e%1+1)%1;let i=Math.floor(e*6),a=e*6-i,o=r*(1-t),s=r*(1-a*t),c=r*(1-(1-a)*t),[l,u,d]=[[r,c,o],[s,r,o],[o,r,c],[o,s,r],[c,o,r],[r,o,s]][i%6];return n(l,u,d)}function a(t){switch(t.space){case`gray`:{let n=e(t.c[0]);return{r:n,g:n,b:n,a:1}}case`rgb`:return{r:e(t.c[0]),g:e(t.c[1]),b:e(t.c[2]),a:1};case`cmyk`:{let[n,r,i,a]=t.c;return{r:(1-e(n))*(1-e(a)),g:(1-e(r))*(1-e(a)),b:(1-e(i))*(1-e(a)),a:1}}default:return{r:0,g:0,b:0,a:1}}}function o(t){let n=t=>Math.round(e(t)*255).toString(16).padStart(2,`0`);return`#`+n(t.r)+n(t.g)+n(t.b)}function s(t){let n=t=>Math.round(e(t)*255);return`rgba(${n(t.r)},${n(t.g)},${n(t.b)},${t.a})`}var c=class{beginPage(e,t){this.width=e,this.height=t}save(){}restore(){}fill(e,t,n){}stroke(e,t,n){}clip(e,t){}showText(e,t,n,r,i){}showPage(){}endPage(){}},l=[`butt`,`round`,`square`],u=[`miter`,`round`,`bevel`];export{t as a,s as c,r as i,o as l,c as n,i as o,u as r,n as s,l as t,a as u};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
var e=(e,t)=>e.map((e,n,r)=>t(e,n,r)?n:null).filter(e=>e!=null),t=(e,t)=>[-1,...t,e.length].reduce(({xs:t,a:n},r)=>({xs:t?.concat([e.slice(n+1,r)])??[],a:r}),{}).xs,n=(e,t)=>e.slice(0,-1).concat([e[e.length-1].concat(t[0])]).concat(t.slice(1)),r=/\d/,i=/^epubcfi\((.*)\)$/,a=e=>e.replace(/[\^[\](),;=]/g,`^$&`),o=e=>i.test(e)?e:`epubcfi(${e})`,s=e=>e.match(i)?.[1]??e,c=(e=>(...t)=>`epubcfi(${e(...t.map(e=>e.match(i)?.[1]??e))})`)((...e)=>e.join(`!`)),l=e=>{let t=[],n,i,a=``,o=e=>(t.push(e),n=null,a=``),s=e=>(a+=e,i=!1);for(let t of Array.from(e.trim()).concat(``)){if(t===`^`&&!i){i=!0;continue}if(n===`!`)o([`!`]);else if(n===`,`)o([`,`]);else if(n===`/`||n===`:`)if(r.test(t)){s(t);continue}else o([n,parseInt(a)]);else if(n===`~`)if(r.test(t)||t===`.`){s(t);continue}else o([`~`,parseFloat(a)]);else if(n===`@`){if(t===`:`){o([`@`,parseFloat(a)]),n=`@`;continue}if(r.test(t)||t===`.`){s(t);continue}else o([`@`,parseFloat(a)])}else if(n===`[`){t===`;`&&!i?(o([`[`,a]),n=`;`):t===`,`&&!i?(o([`[`,a]),n=`[`):t===`]`&&!i?o([`[`,a]):s(t);continue}else if(n?.startsWith(`;`)){t===`=`&&!i?(n=`;${a}`,a=``):t===`;`&&!i?(o([n,a]),n=`;`):t===`]`&&!i?o([n,a]):s(t);continue}(t===`/`||t===`:`||t===`~`||t===`@`||t===`[`||t===`!`||t===`,`)&&(n=t)}return t},u=(t,n)=>e(t,([e])=>e===n),d=e=>{let t=[],n;for(let[r,i]of e){if(r===`/`)t.push({index:i});else{let e=t[t.length-1];if(r===`:`)e.offset=i;else if(r===`~`)e.temporal=i;else if(r===`@`)e.spatial=(e.spatial??[]).concat(i);else if(r===`;s`)e.side=i;else if(r===`[`)if(n===`/`&&i)e.id=i;else{e.text=(e.text??[]).concat(i);continue}}n=r}return t},f=e=>t(e,u(e,`!`)).map(d),p=e=>{let n=l(s(e)),r=u(n,`,`);if(!r.length)return f(n);let[i,a,o]=t(n,r).map(f);return{parent:i,start:a,end:o}},m=({index:e,id:t,offset:n,temporal:r,spatial:i,text:o,side:s})=>{let c=s?`;s=${s}`:``;return`/${e}`+(t?`[${a(t)}${c}]`:``)+(n!=null&&e%2?`:${n}`:``)+(r?`~${r}`:``)+(i?`@${i.join(`:`)}`:``)+(o||!t&&s?`[`+(o?.map(a)?.join(`,`)??``)+c+`]`:``)},h=e=>e.parent?[e.parent,e.start,e.end].map(h).join(`,`):e.map(e=>e.map(m).join(``)).join(`!`),g=e=>o(h(e)),_=(e,t)=>typeof e==`string`?g(_(p(e),t)):e.parent?n(e.parent,e[t?`end`:`start`]):e,v=(e,t)=>{typeof e==`string`&&(e=p(e)),typeof t==`string`&&(t=p(t)),e=_(e),t=_(t,!0);let n=e[e.length-1],r=t[t.length-1],i=[],a=[],o=[],s=!0,c=Math.max(n.length,r.length);for(let e=0;e<c;e++){let t=n[e],c=r[e];s&&(s=t?.index===c?.index&&!t?.offset&&!c?.offset),s?i.push(t):(t&&a.push(t),c&&o.push(c))}return g({parent:e.slice(0,-1).concat([i]),start:[a],end:[o]})},y=({nodeType:e})=>e===3||e===4,b=({nodeType:e})=>e===1,x=(e,t)=>{let n=Array.from(e.childNodes).filter(e=>y(e)||b(e));return t?n.map(e=>{let n=t(e);return n===NodeFilter.FILTER_REJECT?null:n===NodeFilter.FILTER_SKIP?x(e,t):e}).flat().filter(e=>e):n},S=(e,t)=>{let n=x(e,t).reduce((e,t)=>{let n=e[e.length-1];return n?y(t)?Array.isArray(n)?n.push(t):y(n)?e[e.length-1]=[n,t]:e.push(t):b(n)?e.push(null,t):e.push(t):e.push(t),e},[]);return b(n[0])&&n.unshift(`first`),b(n[n.length-1])&&n.push(`last`),n.unshift(`before`),n.push(`after`),n},C=(e,t,n)=>{let{id:r}=t[t.length-1];if(r){let t=e.ownerDocument.getElementById(r);if(t)return{node:t,offset:0}}for(let{index:r}of t){let t=e?S(e,n)[r]:null;if(t===`first`)return{node:e.firstChild??e};if(t===`last`)return{node:e.lastChild??e};if(t===`before`)return{node:e,before:!0};if(t===`after`)return{node:e,after:!0};e=t}let{offset:i}=t[t.length-1];if(!Array.isArray(e))return{node:e,offset:i};let a=0;for(let t of e){let{length:e}=t.nodeValue;if(a+e>=i)return{node:t,offset:i-a};a+=e}},w=(e,t,n)=>{let{id:r,parentNode:i}=e;for(;n&&i&&i!==e.ownerDocument.documentElement&&n(i)===NodeFilter.FILTER_SKIP;)i=i.parentNode;let a=S(i,n),o=a.findIndex(t=>Array.isArray(t)?t.some(t=>t===e):t===e),s=a[o];if(Array.isArray(s)){let n=0;for(let r of s)if(r===e){n+=t;break}else n+=r.nodeValue.length;t=n}let c={id:r,index:o,offset:t};return(i===e.ownerDocument.documentElement?[c]:w(i,null,n).concat(c)).filter(e=>e.index!==-1)},T=(e,t)=>{let{startContainer:n,startOffset:r,endContainer:i,endOffset:a}=e,o=w(n,r,t);if(e.collapsed)return g([o]);let s=w(i,a,t);return v([o],[s])},E=(e,t,n)=>{let r=_(t),i=_(t,!0),a=e.documentElement,o=C(a,r[0],n),s=C(a,i[0],n),c=e.createRange();return o.before?c.setStartBefore(o.node):o.after?c.setStartAfter(o.node):c.setStart(o.node,o.offset),s.before?c.setEndBefore(s.node):s.after?c.setEndAfter(s.node):c.setEnd(s.node,s.offset),c},D=e=>{let t=[],{parentNode:n}=e[0],r=w(n);for(let[i,a]of S(n).entries()){let n=e[t.length];a===n&&t.push(g([r.concat({id:n.id,index:i})]))}return t},O=(e,t)=>C(e.documentElement,_(t)).node,k={fromIndex:e=>o(`/6/${(e+1)*2}`),toIndex:e=>e?.at(-1).index/2-1};export{c as a,E as c,i,D as n,p as o,T as r,O as s,k as t};
|
||||
@@ -0,0 +1,53 @@
|
||||
var e=e=>e?e.replace(/[\t\n\f\r ]+/g,` `).replace(/^[\t\n\f\r ]+/,``).replace(/[\t\n\f\r ]+$/,``):``,t=t=>e(t?.textContent),n={XLINK:`http://www.w3.org/1999/xlink`,EPUB:`http://www.idpf.org/2007/ops`},r={XML:`application/xml`,XHTML:`application/xhtml+xml`},i={strong:[`strong`,`self`],emphasis:[`em`,`self`],style:[`span`,`self`],a:`anchor`,strikethrough:[`s`,`self`],sub:[`sub`,`self`],sup:[`sup`,`self`],code:[`code`,`self`],image:`image`},a={tr:[`tr`,{th:[`th`,i,[`colspan`,`rowspan`,`align`,`valign`]],td:[`td`,i,[`colspan`,`rowspan`,`align`,`valign`]]},[`align`]]},o={epigraph:[`blockquote`],subtitle:[`h2`,i],"text-author":[`p`,i],date:[`p`,i],stanza:`stanza`},s={title:[`header`,{p:[`h1`,i],"empty-line":[`br`]}],epigraph:[`blockquote`,`self`],image:`image`,annotation:[`aside`],section:[`section`,`self`],p:[`p`,i],poem:[`blockquote`,o],subtitle:[`h2`,i],cite:[`blockquote`,`self`],"empty-line":[`br`],table:[`table`,a],"text-author":[`p`,i]};o.epigraph.push(s);var c={image:`image`,title:[`section`,{p:[`h1`,i],"empty-line":[`br`]}],epigraph:[`section`,s],section:[`section`,s]},l=class{constructor(e){this.fb2=e,this.doc=document.implementation.createDocument(n.XHTML,`html`),this.bins=new Map(Array.from(this.fb2.getElementsByTagName(`binary`),e=>[e.id,e]))}getImageSrc(e){let t=e.getAttributeNS(n.XLINK,`href`);if(!t)return`data:,`;let[,r]=t.split(`#`);if(!r)return t;let i=this.bins.get(r);return i?`data:${i.getAttribute(`content-type`)};base64,${i.textContent}`:t}image(e){let t=this.doc.createElement(`img`);return t.alt=e.getAttribute(`alt`),t.title=e.getAttribute(`title`),t.setAttribute(`src`,this.getImageSrc(e)),t}anchor(e){let t=this.convert(e,{a:[`a`,i]});return t.setAttribute(`href`,e.getAttributeNS(n.XLINK,`href`)),e.getAttribute(`type`)===`note`&&t.setAttributeNS(n.EPUB,`epub:type`,`noteref`),t}stanza(e){let t=this.convert(e,{stanza:[`p`,{title:[`header`,{p:[`strong`,i],"empty-line":[`br`]}],subtitle:[`p`,i]}]});for(let n of e.children)n.nodeName===`v`&&(t.append(this.doc.createTextNode(n.textContent)),t.append(this.doc.createElement(`br`)));return t}convert(e,t){if(e.nodeType===3)return this.doc.createTextNode(e.textContent);if(e.nodeType===4)return this.doc.createCDATASection(e.textContent);if(e.nodeType===8)return this.doc.createComment(e.textContent);let n=t?.[e.nodeName];if(!n)return null;if(typeof n==`string`)return this[n](e);let[r,i,a]=n,o=this.doc.createElement(r);if(e.id&&(o.id=e.id),o.classList.add(e.nodeName),Array.isArray(a))for(let t of a){let n=e.getAttribute(t);n&&o.setAttribute(t,n)}let s=i===`self`?t:i,c=e.firstChild;for(;c;){let e=this.convert(c,s);e&&o.append(e),c=c.nextSibling}return o}},u=async e=>{let t=await e.arrayBuffer(),n=new TextDecoder(`utf-8`).decode(t),i=new DOMParser,a=i.parseFromString(n,r.XML),o=a.xmlEncoding||n.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1];if(o&&o.toLowerCase()!==`utf-8`){let e=new TextDecoder(o).decode(t);return i.parseFromString(e,r.XML)}return a},d=URL.createObjectURL(new Blob([`
|
||||
@namespace epub "http://www.idpf.org/2007/ops";
|
||||
body > img, section > img {
|
||||
display: block;
|
||||
margin: auto;
|
||||
}
|
||||
.title h1 {
|
||||
text-align: center;
|
||||
}
|
||||
body > section > .title, body.notesBodyType > .title {
|
||||
margin: 3em 0;
|
||||
}
|
||||
body.notesBodyType > section .title h1 {
|
||||
text-align: start;
|
||||
}
|
||||
body.notesBodyType > section .title {
|
||||
margin: 1em 0;
|
||||
}
|
||||
p {
|
||||
text-indent: 1em;
|
||||
margin: 0;
|
||||
}
|
||||
:not(p) + p, p:first-child {
|
||||
text-indent: 0;
|
||||
}
|
||||
.poem p {
|
||||
text-indent: 0;
|
||||
margin: 1em 0;
|
||||
}
|
||||
.text-author, .date {
|
||||
text-align: end;
|
||||
}
|
||||
.text-author:before {
|
||||
content: "—";
|
||||
}
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
td, th {
|
||||
padding: .25em;
|
||||
}
|
||||
a[epub|type~="noteref"] {
|
||||
font-size: .75em;
|
||||
vertical-align: super;
|
||||
}
|
||||
body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {
|
||||
margin: 3em 0;
|
||||
}
|
||||
`],{type:`text/css`})),f=e=>`<?xml version="1.0" encoding="utf-8"?>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><link href="${d}" rel="stylesheet" type="text/css"/></head>
|
||||
<body>${e}</body>
|
||||
</html>`,p=`data-foliate-id`,m=async n=>{let i={},a=await u(n),o=new l(a),d=e=>a.querySelector(e),m=e=>[...a.querySelectorAll(e)],h=e=>{let n=t(e.querySelector(`nickname`));if(n)return n;let r=t(e.querySelector(`first-name`)),i=t(e.querySelector(`middle-name`)),a=t(e.querySelector(`last-name`));return{name:[r,i,a].filter(e=>e).join(` `),sortAs:a?[a,[r,i].filter(e=>e).join(` `)].join(`, `):null}},g=e=>e?.getAttribute(`value`)??t(e),_=d(`title-info annotation`);if(i.metadata={title:t(d(`title-info book-title`)),identifier:t(d(`document-info id`)),language:t(d(`title-info lang`)),author:m(`title-info author`).map(h),translator:m(`title-info translator`).map(h),contributor:m(`document-info author`).map(h).concat(m(`document-info program-used`).map(t)).map(e=>Object.assign(typeof e==`string`?{name:e}:e,{role:`bkp`})),publisher:t(d(`publish-info publisher`)),published:g(d(`title-info date`)),modified:g(d(`document-info date`)),description:_?o.convert(_,{annotation:[`div`,s]}).innerHTML:null,subject:m(`title-info genre`).map(t)},d(`coverpage image`)){let e=o.getImageSrc(d(`coverpage image`));i.getCover=()=>fetch(e).then(e=>e.blob())}else i.getCover=()=>null;let v=Array.from(a.querySelectorAll(`body`),e=>{let t=o.convert(e,{body:[`body`,c]});return[Array.from(t.children,e=>({el:e,ids:[e,...e.querySelectorAll(`[id]`)].map(e=>e.id)})),t]}),y=[],b=v[0][0].map(({el:e,ids:n})=>({ids:n,titles:Array.from(e.querySelectorAll(`:scope > section > .title`),(e,n)=>(e.setAttribute(p,n),{title:t(e),index:n})),el:e})).concat(v.slice(1).map(([e,t])=>{let n=e.map(e=>e.ids).flat();return t.classList.add(`notesBodyType`),{ids:n,el:t,linear:`no`}})).map(({ids:t,titles:n,el:i,linear:a})=>{let o=f(i.outerHTML),s=new Blob([o],{type:r.XHTML}),c=URL.createObjectURL(s);return y.push(c),{ids:t,title:e(i.querySelector(`.title, .subtitle, p`)?.textContent??(i.classList.contains(`title`)?i.textContent:``)),titles:n,load:()=>c,createDocument:()=>new DOMParser().parseFromString(o,r.XHTML),size:s.size-Array.from(i.querySelectorAll(`[src]`),e=>e.getAttribute(`src`)?.length??0).reduce((e,t)=>e+t,0),linear:a}}),x=new Map;return i.sections=b.map((e,t)=>{let{ids:n,load:r,createDocument:i,size:a,linear:o}=e;for(let e of n)e&&x.set(e,t);return{id:t,load:r,createDocument:i,size:a,linear:o}}),i.toc=b.map(({title:e,titles:t},n)=>{let r=n.toString();return{label:e,href:r,subitems:t?.length?t.map(({title:e,index:t})=>({label:e,href:`${r}#${t}`})):null}}).filter(e=>e),i.resolveHref=e=>{let[t,n]=e.split(`#`);return t?{index:Number(t),anchor:e=>e.querySelector(`[${p}="${n}"]`)}:{index:x.get(n),anchor:e=>e.getElementById(n)}},i.splitTOCHref=e=>e?.split(`#`)?.map(e=>Number(e))??[],i.getTOCFragment=(e,t)=>e.querySelector(`[${p}="${t}"]`),i.isExternal=e=>/^\w+:/i.test(e),i.destroy=()=>{for(let e of y)URL.revokeObjectURL(e)},i};export{m as makeFB2};
|
||||
@@ -0,0 +1 @@
|
||||
var e=Uint8Array,t=Uint16Array,n=Int32Array,r=new e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=function(e,r){for(var i=new t(31),a=0;a<31;++a)i[a]=r+=1<<e[a-1];var o=new n(i[30]);for(a=1;a<30;++a)for(var s=i[a];s<i[a+1];++s)o[s]=s-i[a]<<5|a;return{b:i,r:o}},s=o(r,2),c=s.b,l=s.r;c[28]=258,l[258]=28;for(var u=o(i,0).b,d=new t(32768),f=0;f<32768;++f){var p=(43690&f)>>1|(21845&f)<<1;p=(61680&(p=(52428&p)>>2|(13107&p)<<2))>>4|(3855&p)<<4,d[f]=((65280&p)>>8|(255&p)<<8)>>1}var m=function(e,n,r){for(var i=e.length,a=0,o=new t(n);a<i;++a)e[a]&&++o[e[a]-1];var s,c=new t(n);for(a=1;a<n;++a)c[a]=c[a-1]+o[a-1]<<1;if(r){s=new t(1<<n);var l=15-n;for(a=0;a<i;++a)if(e[a])for(var u=a<<4|e[a],f=n-e[a],p=c[e[a]-1]++<<f,m=p|(1<<f)-1;p<=m;++p)s[d[p]>>l]=u}else for(s=new t(i),a=0;a<i;++a)e[a]&&(s[a]=d[c[e[a]-1]++]>>15-e[a]);return s},h=new e(288);for(f=0;f<144;++f)h[f]=8;for(f=144;f<256;++f)h[f]=9;for(f=256;f<280;++f)h[f]=7;for(f=280;f<288;++f)h[f]=8;var g=new e(32);for(f=0;f<32;++f)g[f]=5;var _=m(h,9,1),ee=m(g,5,1),v=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},y=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},b=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},te=function(e){return(e+7)/8|0},x=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],S=function(e,t,n){var r=Error(t||x[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,S),!n)throw r;return r},C=function(t,n,o,s){var l=t.length,d=s?s.length:0;if(!l||n.f&&!n.l)return o||new e(0);var f=!o,p=f||n.i!=2,h=n.i;f&&(o=new e(3*l));var g=function(t){var n=o.length;if(t>n){var r=new e(Math.max(2*n,t));r.set(o),o=r}},x=n.f||0,C=n.p||0,w=n.b||0,T=n.l,E=n.d,D=n.m,O=n.n,k=8*l;do{if(!T){x=y(t,C,1);var A=y(t,C+1,3);if(C+=3,!A){var j=t[(B=te(C)+4)-4]|t[B-3]<<8,M=B+j;if(M>l){h&&S(0);break}p&&g(w+j),o.set(t.subarray(B,M),w),n.b=w+=j,n.p=C=8*M,n.f=x;continue}if(A==1)T=_,E=ee,D=9,O=5;else if(A==2){var N=y(t,C,31)+257,P=y(t,C+10,15)+4,F=N+y(t,C+5,31)+1;C+=14;for(var I=new e(F),L=new e(19),R=0;R<P;++R)L[a[R]]=y(t,C+3*R,7);C+=3*P;var z=v(L),ne=(1<<z)-1,re=m(L,z,1);for(R=0;R<F;){var B,V=re[y(t,C,ne)];if(C+=15&V,(B=V>>4)<16)I[R++]=B;else{var H=0,U=0;for(B==16?(U=3+y(t,C,3),C+=2,H=I[R-1]):B==17?(U=3+y(t,C,7),C+=3):B==18&&(U=11+y(t,C,127),C+=7);U--;)I[R++]=H}}var W=I.subarray(0,N),G=I.subarray(N);D=v(W),O=v(G),T=m(W,D,1),E=m(G,O,1)}else S(1);if(C>k){h&&S(0);break}}p&&g(w+131072);for(var ie=(1<<D)-1,ae=(1<<O)-1,K=C;;K=C){var q=(H=T[b(t,C)&ie])>>4;if((C+=15&H)>k){h&&S(0);break}if(H||S(2),q<256)o[w++]=q;else{if(q==256){K=C,T=null;break}var J=q-254;if(q>264){var Y=r[R=q-257];J=y(t,C,(1<<Y)-1)+c[R],C+=Y}var X=E[b(t,C)&ae],Z=X>>4;if(X||S(3),C+=15&X,G=u[Z],Z>3&&(Y=i[Z],G+=b(t,C)&(1<<Y)-1,C+=Y),C>k){h&&S(0);break}p&&g(w+131072);var Q=w+J;if(w<G){var $=d-G,oe=Math.min(G,Q);for($+w<0&&S(3);w<oe;++w)o[w]=s[$+w]}for(;w<Q;++w)o[w]=o[w-G]}}n.l=T,n.p=K,n.b=w,n.f=x,T&&(x=1,n.m=D,n.d=E,n.n=O)}while(!x);return w!=o.length&&f?function(t,n,r){return(r==null||r>t.length)&&(r=t.length),new e(t.subarray(n,r))}(o,0,w):o.subarray(0,w)},w=new e(0);function T(e,t){return C(e.subarray((n=e,r=t&&t.dictionary,((15&n[0])!=8||n[0]>>4>7||(n[0]<<8|n[1])%31)&&S(6,`invalid zlib data`),(n[1]>>5&1)==+!r&&S(6,`invalid zlib data: `+(32&n[1]?`need`:`unexpected`)+` dictionary`),2+(n[1]>>3&4)),-4),{i:2},t&&t.out,t&&t.dictionary);var n,r}var E=typeof TextDecoder<`u`&&new TextDecoder;try{E.decode(w,{stream:!0})}catch{}export{T as unzlibSync};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
var e=()=>{throw Error(`PDFs are handled by ReaderJS PDFRenderer, not foliate-js`)};export{e as makePDF};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
pre code.hljs{padding:1em;display:block;overflow-x:auto}code.hljs{padding:3px 5px}.hljs{color:#24292e;background:#fff}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#d73a49}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#6f42c1}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-variable,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id{color:#005cc5}.hljs-regexp,.hljs-string,.hljs-meta .hljs-string{color:#032f62}.hljs-built_in,.hljs-symbol{color:#e36209}.hljs-comment,.hljs-code,.hljs-formula{color:#6a737d}.hljs-name,.hljs-quote,.hljs-selector-tag,.hljs-selector-pseudo{color:#22863a}.hljs-subst{color:#24292e}.hljs-section{color:#005cc5;font-weight:700}.hljs-bullet{color:#735c0f}.hljs-emphasis{color:#24292e;font-style:italic}.hljs-strong{color:#24292e;font-weight:700}.hljs-addition{color:#22863a;background-color:#f0fff4}.hljs-deletion{color:#b31d28;background-color:#ffeef0}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./marked.esm-N0v7i-_3.js","./defineProperty-BbfpZ9Tg.js"])))=>i.map(i=>d[i]);
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=class extends t{async load(t,n,r){await super.load(t,n,r);let{marked:i}=await e(async()=>{let{marked:e}=await import(`./marked.esm-N0v7i-_3.js`);return{marked:e}},__vite__mapDeps([0,1]),import.meta.url),a=new TextDecoder().decode(t),o=await i.parse(a,{async:!1});n.innerHTML=``;let s=document.createElement(`div`);s.className=`doc-page`,s.dataset.page=1,s.innerHTML=o,n.appendChild(s),this.numPages=1}};export{n as MDRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=class extends t{async load(t,n,r){await super.load(t,n,r);let{convert:i}=await e(async()=>{let{convert:e}=await import(`./lib-CTiWugWo.js`);return{convert:e}},[],import.meta.url),{data:a}=await i(new Uint8Array(t),{enableScripts:!1,fetchMissingResources:!1});n.innerHTML=``;let o=document.createElement(`div`);o.className=`doc-page mhtml-page`,o.dataset.page=1;let s=document.createElement(`iframe`);s.className=`mhtml-frame`,s.sandbox=`allow-same-origin`,s.srcdoc=a,s.addEventListener(`load`,()=>{let e=s.contentDocument;e&&(s.style.height=`${e.documentElement.scrollHeight}px`)}),o.appendChild(s),n.appendChild(o),this.numPages=1}};export{n as MHTMLRenderer};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{o as e}from"./rolldown-runtime-DAXXjFlN.js";import{t}from"./jszip.min-C__FR9jF.js";import{t as n}from"./base-renderer-DM6Nw1yD.js";var r=e(t()),i={text:`urn:oasis:names:tc:opendocument:xmlns:text:1.0`,table:`urn:oasis:names:tc:opendocument:xmlns:table:1.0`,draw:`urn:oasis:names:tc:opendocument:xmlns:drawing:1.0`,xlink:`http://www.w3.org/1999/xlink`,style:`urn:oasis:names:tc:opendocument:xmlns:style:1.0`,fo:`urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0`};function a(e,t,n){return e.getElementsByTagNameNS(t,n)[0]??null}var o=class extends n{constructor(){super(),this._imgUrls=[]}async load(e,t,n){await super.load(e,t,n);let i=await r.default.loadAsync(e),o=i.file(`mimetype`);if(!o)throw Error(`Not a valid ODF file (missing mimetype entry)`);let s=(await o.async(`string`)).trim();if(!s.startsWith(`application/vnd.oasis.opendocument`))throw Error(`Unexpected MIME type: ${s}`);let c=i.file(`content.xml`);if(!c)throw Error(`ODF file has no content.xml`);let l=await c.async(`string`),u=new DOMParser().parseFromString(l,`application/xml`),d=a(u,`http://www.mozilla.org/newlayout/xml/parsererror.xml`,`parseerror`);if(d)throw Error(`content.xml parse error: ${d.textContent.slice(0,120)}`);let f=await this._extractImages(i),p=await this._convertToHtml(u,f);t.innerHTML=``;let m=document.createElement(`div`);m.className=`doc-page`,m.dataset.page=1,m.innerHTML=p,t.appendChild(m),this.numPages=1}async _extractImages(e){let t={};e.forEach((e,n)=>{/^(Pictures|images)\//i.test(e)&&!n.dir&&(t[e]=n)});let n={};for(let[e,r]of Object.entries(t)){let t=await r.async(`uint8array`),i={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,svg:`image/svg+xml`}[e.split(`.`).pop().toLowerCase()]??`application/octet-stream`,a=URL.createObjectURL(new Blob([t],{type:i}));this._imgUrls.push(a),n[e]=a}return n}_convertToHtml(e,t){let n=e.querySelector(`*|body`)??e.documentElement,r=[];return this._nodeToHtml(n,r,t),r.join(``)}_nodeToHtml(e,t,n){if(e.nodeType===Node.TEXT_NODE){t.push(this._esc(e.textContent));return}if(e.nodeType!==Node.ELEMENT_NODE)return;let r=e.namespaceURI,a=e.localName;if(r===i.text){if(a===`p`){t.push(`<p>`),this._childrenToHtml(e,t,n),t.push(`</p>`);return}if(a===`h`){let r=Math.min(6,Math.max(1,parseInt(e.getAttributeNS(i.text,`outline-level`)||`1`,10)));t.push(`<h${r}>`),this._childrenToHtml(e,t,n),t.push(`</h${r}>`);return}if(a===`span`){t.push(`<span>`),this._childrenToHtml(e,t,n),t.push(`</span>`);return}if(a===`a`){let r=e.getAttributeNS(i.xlink,`href`)||`#`;t.push(`<a href="${this._esc(r)}" target="_blank" rel="noopener">`),this._childrenToHtml(e,t,n),t.push(`</a>`);return}if(a===`line-break`){t.push(`<br>`);return}if(a===`s`){t.push(` `);return}if(a===`tab`){t.push(` `);return}if(a===`list`){t.push(`<ul>`),this._childrenToHtml(e,t,n),t.push(`</ul>`);return}if(a===`list-item`){t.push(`<li>`),this._childrenToHtml(e,t,n),t.push(`</li>`);return}}if(r===i.table){if(a===`table`){t.push(`<table>`),this._childrenToHtml(e,t,n),t.push(`</table>`);return}if(a===`table-row`){t.push(`<tr>`),this._childrenToHtml(e,t,n),t.push(`</tr>`);return}if(a===`table-cell`){t.push(`<td>`),this._childrenToHtml(e,t,n),t.push(`</td>`);return}}if(r===i.draw){if(a===`frame`){this._childrenToHtml(e,t,n);return}if(a===`image`){let r=e.getAttributeNS(i.xlink,`href`)||``,a=n[r]??n[r.replace(/^\//,``)]??``;a&&t.push(`<img src="${a}" style="max-width:100%;height:auto">`);return}}this._childrenToHtml(e,t,n)}_childrenToHtml(e,t,n){for(let r of e.childNodes)this._nodeToHtml(r,t,n)}_esc(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`)}destroy(){this._imgUrls.forEach(e=>URL.revokeObjectURL(e)),this._imgUrls=[],super.destroy()}};export{o as ODFRenderer};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./document-BvO1jqhz.js","./driver-0cTj10HJ.js","./canvas-driver-BnEksqHW.js"])))=>i.map(i=>d[i]);
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=class extends t{async load(t,n,r){await super.load(t,n,r);let[{loadDocument:i,pageSize:a,renderPageToDriver:o},{CanvasDriver:s}]=await Promise.all([e(()=>import(`./document-BvO1jqhz.js`),__vite__mapDeps([0,1]),import.meta.url),e(()=>import(`./canvas-driver-BnEksqHW.js`),__vite__mapDeps([2,1]),import.meta.url)]),c=t instanceof Uint8Array?t:new Uint8Array(t),l=``;for(let e=0;e<c.length;e+=8192)l+=String.fromCharCode.apply(null,c.subarray(e,e+8192));let u=i(l);n.innerHTML=``;for(let e=0;e<u.pageCount;e++){let{width:t,height:r}=a(u,e),i=document.createElement(`div`);i.className=`postscript-page`,i.dataset.page=String(e+1);let c=document.createElement(`canvas`);c.width=Math.max(1,Math.round(t)),c.height=Math.max(1,Math.round(r));let l=c.getContext(`2d`);try{l&&o(u,e,new s(l))}catch(t){console.warn(`[PostScript] page ${e+1} render error:`,t?.message||t)}i.appendChild(c),n.appendChild(i)}let d=u.pageCount?a(u,0):{width:816,height:1056};this._pageW=Math.round(d.width)||816,this._pageH=Math.round(d.height)||1056,this.numPages=u.pageCount||1}setScale(e){this.scale=e,this.container?.querySelectorAll(`.postscript-page`).forEach(t=>{t.style.zoom=e===1?``:e})}getPageWidth(){return this._pageW||816}getPageHeight(){return this._pageH||null}};export{n as PostScriptRenderer};
|
||||
@@ -0,0 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PptxViewJS.es-DznKWbU1.js","./rolldown-runtime-DAXXjFlN.js","./defineProperty-BbfpZ9Tg.js","./jszip.min-C__FR9jF.js"])))=>i.map(i=>d[i]);
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=9525,r=320,i=400,a=class extends t{constructor(){super(),this._view=null,this._wrap=null,this._canvas=null,this._idx=0,this._slideW=960,this._slideH=720,this._gen=0,this._chain=Promise.resolve(),this.defaultScaleOption=`page-fit`,this.buildsThumbnailsAsync=!0}async load(t,n,r){await super.load(t,n,r);let a=++this._gen,{PPTXViewer:o}=await e(async()=>{let{PPTXViewer:e}=await import(`./PptxViewJS.es-DznKWbU1.js`);return{PPTXViewer:e}},__vite__mapDeps([0,1,2,3]),import.meta.url);n.innerHTML=``;let s=document.createElement(`div`);s.className=`pptx-slide`;let c=document.createElement(`canvas`);s.appendChild(c),n.appendChild(s),this._wrap=s,this._canvas=c,await this._loadWithRetry(t,a,o),setTimeout(()=>{a===this._gen&&this._buildThumbnails(a)},i)}async _loadWithRetry(e,t,r){let i;for(let a=0;a<2;a++)try{if(this._chain=Promise.resolve(),this._view=new r({canvas:this._canvas,slideSizeMode:`fit`}),await this._view.loadFile(e),t!==this._gen)return;this.numPages=this._view.getSlideCount()||1,this._idx=0;let i=this._view.presentation?.slideSize;i?.cx&&i?.cy&&(this._slideW=Math.round(i.cx/n),this._slideH=Math.round(i.cy/n)),await this._renderSlide(0);return}catch(e){i=e,await new Promise(e=>setTimeout(e,200))}throw i}_enqueue(e){let t=this._chain.then(()=>this._view?e():void 0);return this._chain=t.catch(()=>{}),t}_renderSlide(e){return this._enqueue(async()=>{this._canvas.width=this._slideW,this._canvas.height=this._slideH,await this._view.renderSlide(e,this._canvas)})}async _buildThumbnails(e){let t=document.getElementById(`thumbsContent`);if(!t)return;let n=r,i=Math.max(1,Math.round(n*this._slideH/this._slideW)),a=document.createElement(`canvas`);a.width=n,a.height=i;for(let n=0;n<this.numPages;n++){if(await this._enqueue(()=>this._view.renderSlide(n,a)).catch(()=>{}),e!==this._gen||!this._view)return;let r=document.createElement(`img`);r.src=a.toDataURL(`image/png`);let i=document.createElement(`div`);i.className=`thumb`,i.dataset.thumbPage=n+1;let o=document.createElement(`div`);o.className=`thumb-label`,o.textContent=n+1,i.append(r,o),i.addEventListener(`click`,()=>this.viewer?.goToPage(n+1)),t.appendChild(i)}this._highlightThumb(this._idx+1)}scrollToPage(e){this._view&&(this._idx=Math.max(0,Math.min(this.numPages-1,e-1)),this._renderSlide(this._idx).catch(()=>{}),this._highlightThumb(this._idx+1))}_highlightThumb(e){document.querySelectorAll(`#thumbsContent .thumb`).forEach(t=>{t.classList.toggle(`active`,+t.dataset.thumbPage===e)})}setScale(e){this.scale=e,this._wrap&&(this._wrap.style.zoom=e===1?``:e)}getPageWidth(){return this._slideW}getPageHeight(){return this._slideH}destroy(){this._gen++,this._view=null,this._wrap=null,this._canvas=null,super.destroy()}};export{a as PPTXRenderer};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,34 @@
|
||||
var e=/^\s*(javascript|vbscript|data:text\/html|data:application|about|mhtml|file|ms-its|mk):/i,t={css:`text/css`,htm:`text/html`,html:`text/html`,gif:`image/gif`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,bmp:`image/bmp`,ico:`image/x-icon`,svg:`image/svg+xml`,webp:`image/webp`,js:`text/javascript`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`};function n(e){return t[(e.split(`.`).pop()||``).toLowerCase()]||`application/octet-stream`}var r=class{constructor(e){this.reader=e,this.urls=new Map}urlFor(e){if(this.urls.has(e))return this.urls.get(e);let t=this.reader.getFile(e);if(!t)return this.urls.set(e,null),null;let r=new Blob([t],{type:n(e)}),i=URL.createObjectURL(r);return this.urls.set(e,i),i}revokeAll(){for(let e of this.urls.values())e&&URL.revokeObjectURL(e);this.urls.clear()}},i=`default-src 'none'; img-src blob: data:; style-src blob: data: 'unsafe-inline'; font-src blob: data:; media-src blob: data:; frame-src blob:; object-src 'none'; base-uri 'none'; form-action 'none'`,a=`
|
||||
html { background: #f4f4f6; }
|
||||
body { background: #ffffff; color: #1b1b1f; margin: 0; padding: 22px 26px;
|
||||
max-width: 100%; overflow-wrap: break-word; }
|
||||
img { max-width: 100%; height: auto; }
|
||||
a { color: #1a56db; }
|
||||
::selection { background: #b9d2ff; }
|
||||
mark.chm-find { background: #ffd54a; color: #1b1b1f; padding: 0; }
|
||||
mark.chm-find.chm-active { background: #ff9d3b; box-shadow: 0 0 0 2px #ff9d3b; }
|
||||
|
||||
/* Thin, modern scrollbars for the topic (no native stepper arrows). */
|
||||
html { scrollbar-width: thin; scrollbar-color: rgba(135,135,150,0.6) transparent; }
|
||||
::-webkit-scrollbar { width: 12px; height: 12px; }
|
||||
::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-corner { background: transparent; }
|
||||
::-webkit-scrollbar-thumb { background: rgba(135,135,150,0.6); border-radius: 7px;
|
||||
border: 3px solid transparent; background-clip: padding-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: rgba(135,135,150,0.85); }
|
||||
|
||||
/* Document theme. CHM topics carry arbitrary inline colours, so dark mode is
|
||||
a smart-invert filter on the root with media re-inverted back to normal. */
|
||||
html[data-theme="dark"] { filter: invert(1) hue-rotate(180deg); }
|
||||
html[data-theme="dark"] img, html[data-theme="dark"] picture, html[data-theme="dark"] video,
|
||||
html[data-theme="dark"] svg, html[data-theme="dark"] canvas, html[data-theme="dark"] embed,
|
||||
html[data-theme="dark"] object, html[data-theme="dark"] iframe { filter: invert(1) hue-rotate(180deg); }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html[data-theme="system"] { filter: invert(1) hue-rotate(180deg); }
|
||||
html[data-theme="system"] img, html[data-theme="system"] picture, html[data-theme="system"] video,
|
||||
html[data-theme="system"] svg, html[data-theme="system"] canvas, html[data-theme="system"] embed,
|
||||
html[data-theme="system"] object, html[data-theme="system"] iframe { filter: invert(1) hue-rotate(180deg); }
|
||||
}
|
||||
`;function o(t,n,r){let o=t.getText(n)||``,c=new DOMParser().parseFromString(o,`text/html`);c.querySelectorAll(`script, noscript, base, meta[http-equiv], object, embed, applet`).forEach(e=>e.remove());for(let t of c.querySelectorAll(`*`))for(let n of Array.from(t.attributes)){let r=n.name.toLowerCase();if(r.startsWith(`on`)){t.removeAttribute(n.name);continue}(r===`href`||r===`src`||r===`background`)&&e.test(n.value)&&t.removeAttribute(n.name)}let l=e=>t.resolvePath(n,e);c.querySelectorAll(`img[src], input[type="image"][src]`).forEach(e=>{let t=r.urlFor(l(e.getAttribute(`src`)));t?e.setAttribute(`src`,t):e.removeAttribute(`src`),e.removeAttribute(`srcset`),e.removeAttribute(`loading`)}),c.querySelectorAll(`[background]`).forEach(e=>{let t=r.urlFor(l(e.getAttribute(`background`)));t?e.setAttribute(`background`,t):e.removeAttribute(`background`)}),c.querySelectorAll(`link[rel~="stylesheet" i][href]`).forEach(e=>{let n=l(e.getAttribute(`href`)),i=t.getFile(n);if(i){let a=new TextDecoder(`utf-8`).decode(i),o=c.createElement(`style`);o.textContent=s(a,n,t,r),e.replaceWith(o)}else e.remove()}),c.querySelectorAll(`style`).forEach(e=>{e.textContent=s(e.textContent||``,n,t,r)}),c.querySelectorAll(`[style]`).forEach(e=>{let i=e.getAttribute(`style`);i&&i.includes(`url(`)&&e.setAttribute(`style`,s(i,n,t,r))}),c.querySelectorAll(`frame[src], iframe[src]`).forEach(e=>{let t=r.urlFor(l(e.getAttribute(`src`)));t?e.setAttribute(`src`,t):e.removeAttribute(`src`)}),c.querySelectorAll(`a[href]`).forEach(e=>{let t=e.getAttribute(`href`).trim();if(t.startsWith(`#`))return;if(/^(https?|mailto|ftp):/i.test(t)){e.setAttribute(`data-chm-ext`,t),e.setAttribute(`href`,`#`);return}let n=l(t),r=(t.match(/#(.*)$/)||[,``])[1];e.setAttribute(`data-chm-href`,n),r&&e.setAttribute(`data-chm-frag`,r),e.setAttribute(`href`,`#`)});let u=c.head||c.createElement(`head`),d=c.createElement(`meta`);d.setAttribute(`http-equiv`,`Content-Security-Policy`),d.setAttribute(`content`,i),u.insertBefore(d,u.firstChild);let f=c.createElement(`style`);return f.textContent=a,u.appendChild(f),`<!DOCTYPE html>
|
||||
`+c.documentElement.outerHTML}function s(e,t,n,r){let i=e.replace(/@import\s+[^;]+;/gi,``);return i=i.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/gi,(e,i,a)=>{let o=a.trim();if(/^(data:|blob:|https?:|#)/i.test(o))return e;let s=r.urlFor(n.resolvePath(t,o));return s?`url("${s}")`:`none`}),i}export{r as BlobCache,o as renderTopic};
|
||||
@@ -0,0 +1 @@
|
||||
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},l=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},u=(n,r,a)=>(a=n==null?{}:e(i(n)),l(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),d=e=>a.call(e,`module.exports`)?e[`module.exports`]:l(t({},`__esModule`,{value:!0}),e),f=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});export{d as a,f as i,o as n,u as o,c as r,s as t};
|
||||
@@ -0,0 +1 @@
|
||||
import{t as e}from"./base-renderer-DM6Nw1yD.js";var t=`./`,n=[`${t}rtfjs/jquery.min.js`,`${t}rtfjs/EMFJS.bundle.min.js`,`${t}rtfjs/WMFJS.bundle.min.js`,`${t}rtfjs/RTFJS.bundle.min.js`],r=!1;function i(e){return new Promise((t,n)=>{if(document.querySelector(`script[src="${e}"]`))return t();let r=document.createElement(`script`);r.src=e,r.onload=t,r.onerror=()=>n(Error(`Failed to load: ${e}`)),document.head.appendChild(r)})}async function a(){if(!(r&&window.RTFJS)){for(let e of n)await i(e);if(!window.RTFJS)throw Error(`RTFJS global not set after script load`);r=!0}}var o=class extends e{async load(e,t,n){await super.load(e,t,n),await a();let r=await new window.RTFJS.Document(e).render();t.innerHTML=``;let i=document.createElement(`div`);i.className=`doc-page`,i.dataset.page=1,window.$(i).append(r),t.appendChild(i),this.numPages=1}};export{o as RTFRenderer};
|
||||
@@ -0,0 +1 @@
|
||||
var e=50,t=e=>e.replace(/\s+/g,` `),n=(n,{startIndex:r,startOffset:i,endIndex:a,endOffset:o})=>{let s=n[r],c=n[a],l=s===c?s.slice(i,o):s.slice(i)+n.slice(s+1,c).join(``)+c.slice(0,o),u=t(s.slice(0,i)).trimStart(),d=t(c.slice(o)).trimEnd(),f=u.length<e?``:`…`,p=d.length<e?``:`…`;return{pre:`${f}${u.slice(-50)}`,match:l,post:`${d.slice(0,e)}${p}`}},r=function*(e,t,r={}){let{locales:i=`en`,sensitivity:a}=r,o=a===`variant`,s=e.join(``),c=o?s:s.toLocaleLowerCase(i),l=o?t:t.toLocaleLowerCase(i),u=l.length,d=-1,f=-1,p=0;do if(d=c.indexOf(l,d+1),d>-1){for(;p<=d;)p+=e[++f].length;let t=f,r=d-(p-e[f].length),i=d+u;for(;p<=i;)p+=e[++f].length;let a={startIndex:t,startOffset:r,endIndex:f,endOffset:i-(p-e[f].length)};yield{range:a,excerpt:n(e,a)}}while(d>-1)},i=function*(e,t,r={}){let{locales:i=`en`,granularity:a=`word`,sensitivity:o=`base`}=r,s,c;try{s=new Intl.Segmenter(i,{usage:`search`,granularity:a}),c=new Intl.Collator(i,{sensitivity:o})}catch(e){console.warn(e),s=new Intl.Segmenter(`en`,{usage:`search`,granularity:a}),c=new Intl.Collator(`en`,{sensitivity:o})}let l=Array.from(s.segment(t)).length,u=[],d=0,f=s.segment(e[d])[Symbol.iterator]();main:for(;d<e.length;){for(;u.length<l;){let{done:t,value:n}=f.next();if(t)if(d++,d<e.length){f=s.segment(e[d])[Symbol.iterator]();continue}else break main;let{index:r,segment:i}=n;if(/[^\p{Format}]/u.test(i)){if(/\s/u.test(i)){/\s/u.test(u[u.length-1]?.segment)||u.push({strIndex:d,index:r,segment:` `});continue}n.strIndex=d,u.push(n)}}let r=u.map(e=>e.segment).join(``);if(c.compare(t,r)===0){let t=d,r=u[u.length-1],i=r.index+r.segment.length,a={startIndex:u[0].strIndex,startOffset:u[0].index,endIndex:t,endOffset:i};yield{range:a,excerpt:n(e,a)}}u.shift()}},a=(e,t,n)=>{let{granularity:a=`grapheme`,sensitivity:o=`base`}=n;return!Intl?.Segmenter||a===`grapheme`&&(o===`variant`||o===`accent`)?r(e,t,n):i(e,t,n)},o=(e,t)=>{let{defaultLocale:n,matchCase:r,matchDiacritics:i,matchWholeWords:o,acceptNode:s}=t;return function*(t,c){let l=e(t,function*(e,s){for(let l of a(e,c,{locales:t.body.lang||t.documentElement.lang||n||`en`,granularity:o?`word`:`grapheme`,sensitivity:i&&r?`variant`:i&&!r?`accent`:!i&&r?`case`:`base`})){let{startIndex:e,startOffset:t,endIndex:n,endOffset:r}=l.range;l.range=s(e,t,n,r),yield l}},s);for(let e of l)yield e}};export{o as searchMatcher};
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{t as e}from"./base-renderer-DM6Nw1yD.js";var t=class extends e{async load(e,t,n){await super.load(e,t,n);let r=new TextDecoder(`utf-8`).decode(e);t.innerHTML=``;let i=document.createElement(`div`);i.className=`doc-page`,i.dataset.page=1;let a=document.createElement(`pre`);a.className=`txt-content`,a.textContent=r,i.appendChild(a),t.appendChild(i),this.numPages=1}};export{t as TXTRenderer};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
import{t as e}from"./reader-Bd1ccloG.js";import{t}from"./base-renderer-DM6Nw1yD.js";var n=class extends t{async load(t,n,r){await super.load(t,n,r);let i=await e(()=>import(`./xlsx-vk3JpTXp.js`),[],import.meta.url),a=i.read(new Uint8Array(t),{type:`array`});n.innerHTML=``;let o=document.createElement(`div`);o.className=`doc-page`,o.dataset.page=1;let s=a.SheetNames.length>1;a.SheetNames.forEach(e=>{if(s){let t=document.createElement(`h3`);t.className=`sheet-title`,t.textContent=e,o.appendChild(t)}let t=document.createElement(`div`);t.className=`data-table-wrap`,t.innerHTML=i.utils.sheet_to_html(a.Sheets[e]);let n=t.querySelector(`table`);n&&n.classList.add(`data-table`),o.appendChild(t)}),n.appendChild(o),this.numPages=1}};export{n as XLSXRenderer};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,152 @@
|
||||
<!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>
|
||||
<!-- WebODF is loaded on-demand by odf-renderer.js when an ODF file is opened -->
|
||||
<script type="module" crossorigin src="./assets/reader-Bd1ccloG.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/reader-BsenByj_.css">
|
||||
</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="compareModeSelect" class="compare-only" title="Compare view" data-i18n-title="compare.badge">
|
||||
<option value="side-by-side" data-i18n="compare.modeSideBySide">Side by side</option>
|
||||
<option value="unified" data-i18n="compare.modeUnified">Unified</option>
|
||||
<option value="inline" data-i18n="compare.modeInline">Inline</option>
|
||||
</select>
|
||||
<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>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1 @@
|
||||
(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=document.currentScript&&document.currentScript.src||(()=>{let e=[...document.getElementsByTagName(`script`)].reverse().find(e=>/readerjs(\.min)?\.js(\?|#|$)/.test(e.src||``));return e?e.src:location.href})();function n(e){let n=new URL(`./reader.html`,t);return e.src&&n.searchParams.set(`src`,e.src),e.name&&n.searchParams.set(`name`,e.name),n.href}function r(e,t={}){if(!e)throw Error(`ReaderJS.mount: a container element is required`);let r=document.createElement(`iframe`);r.src=n(t),r.title=`ReaderJS document viewer`,r.style.cssText=`width:100%;height:100%;border:0;display:block`,r.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-modals allow-popups`);let i=new URL(r.src,location.href).origin,a=!1,o=null,s=e=>r.contentWindow.postMessage(e,i);function c(e){e.source!==r.contentWindow||e.origin!==i||e.data&&e.data.type===`readerjs:ready`&&(a=!0,o&&(s(o),o=null))}window.addEventListener(`message`,c);let l=e=>Promise.resolve(e instanceof Blob?e.arrayBuffer():e),u=e=>{a?s(e):o=e};function d(e,t,n){l(e).then(e=>u({type:`readerjs:load`,buffer:e,name:t,mime:n}))}function f(e,t,n={}){Promise.all([l(e.source),l(t.source)]).then(([r,i])=>u({type:`readerjs:compare`,bufferA:r,nameA:e.name,bufferB:i,nameB:t.name,blame:n.blame,mode:n.mode}))}return e.appendChild(r),t.compare?f(t.compare.a,t.compare.b,t.compare):!t.src&&(t.blob||t.arrayBuffer)&&d(t.blob||t.arrayBuffer,t.name,t.mime),{load:d,compare:f,setLang(e){a&&s({type:`readerjs:setLang`,lang:e})},iframe:r,destroy(){window.removeEventListener(`message`,c),r.remove()}}}e.mount=r})(this.ReaderJS=this.ReaderJS||{});
|
||||
Vendored
+2
File diff suppressed because one or more lines are too long
Vendored
+3
File diff suppressed because one or more lines are too long
Vendored
+2
File diff suppressed because one or more lines are too long
Vendored
+2
File diff suppressed because one or more lines are too long
@@ -1,81 +0,0 @@
|
||||
<svg viewBox="0 0 1200 720" xmlns="http://www.w3.org/2000/svg" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">
|
||||
<rect x="0" y="0" width="1200" height="720" rx="10" fill="#525659"/>
|
||||
<rect x="0" y="0" width="1200" height="46" fill="#474747"/>
|
||||
<rect x="0" y="46" width="1200" height="1" fill="#1a1a1a"/>
|
||||
<g transform="translate(14,13) scale(0.8333)"><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" fill="#e8e8e8"/></g>
|
||||
<rect x="44" y="14" width="1" height="20" fill="#666"/>
|
||||
<g transform="translate(56,13) scale(0.7500)"><path d="M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z" fill="#cfcfcf"/></g>
|
||||
<rect x="82" y="13" width="46" height="21" rx="3" fill="#636363" stroke="#3a3a3a"/>
|
||||
<text x="96" y="28" text-anchor="middle" font-size="13" fill="#fff">1</text>
|
||||
<text x="110" y="28" font-size="13" fill="#999">/</text>
|
||||
<text x="118" y="28" font-size="13" fill="#999">—</text>
|
||||
<g transform="translate(132,13) scale(0.7500)"><path d="M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z" fill="#cfcfcf"/></g>
|
||||
<g transform="translate(514.0,13) scale(0.7500)"><path d="M19,13H5V11H19V13Z" fill="#e8e8e8"/></g>
|
||||
<rect x="540.0" y="13" width="74" height="22" rx="3" fill="#636363" stroke="#3a3a3a"/>
|
||||
<text x="550.0" y="28" font-size="12.5" fill="#fff">100%</text>
|
||||
<path d="M598.0 21 l5 5 l5 -5" fill="none" stroke="#fff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<g transform="translate(622.0,13) scale(0.7500)"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z" fill="#e8e8e8"/></g>
|
||||
<rect x="980" y="13" width="86" height="22" rx="3" fill="#636363" stroke="#3a3a3a"/>
|
||||
<text x="990" y="28" font-size="12.5" fill="#fff">English</text>
|
||||
<path d="M1052 21 l5 5 l5 -5" fill="none" stroke="#fff" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="1080" y="14" width="1" height="20" fill="#666"/>
|
||||
<g transform="translate(1096,13) scale(0.8333)"><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" fill="#e8e8e8"/></g>
|
||||
<g transform="translate(1136,13) scale(0.8333)"><path d="M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z" fill="#e8e8e8"/></g>
|
||||
<rect x="240.0" y="110" width="720" height="540" rx="12" fill="none" stroke="#6b6e70" stroke-width="2" stroke-dasharray="7 6"/>
|
||||
<g transform="translate(568.0,160) scale(2.6667)"><path d="M11 20H6.5Q4.22 20 2.61 18.43 1 16.85 1 14.58 1 12.63 2.17 11.1 3.35 9.57 5.25 9.15 5.88 6.85 7.75 5.43 9.63 4 12 4 14.93 4 16.96 6.04 19 8.07 19 11 20.73 11.2 21.86 12.5 23 13.78 23 15.5 23 17.38 21.69 18.69 20.38 20 18.5 20H13V12.85L14.6 14.4L16 13L12 9L8 13L9.4 14.4L11 12.85Z" fill="#90caf9"/></g>
|
||||
<text x="600.0" y="280" text-anchor="middle" font-size="30" fill="#e9e9e9">Open a Document</text>
|
||||
<text x="600.0" y="315" text-anchor="middle" font-size="16" fill="#b9bcbe">Drop a file here, or <tspan fill="#90caf9">browse</tspan></text>
|
||||
<rect x="321.0" y="360" width="51" height="26" rx="13" fill="#e53935"/>
|
||||
<text x="346.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">PDF</text>
|
||||
<rect x="381.0" y="360" width="51" height="26" rx="13" fill="#43a047"/>
|
||||
<text x="406.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">ODT</text>
|
||||
<rect x="441.0" y="360" width="51" height="26" rx="13" fill="#43a047"/>
|
||||
<text x="466.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">ODS</text>
|
||||
<rect x="501.0" y="360" width="51" height="26" rx="13" fill="#43a047"/>
|
||||
<text x="526.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">ODP</text>
|
||||
<rect x="561.0" y="360" width="51" height="26" rx="13" fill="#1e88e5"/>
|
||||
<text x="586.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">RTF</text>
|
||||
<rect x="621.0" y="360" width="51" height="26" rx="13" fill="#2b6cb0"/>
|
||||
<text x="646.5" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">DOC</text>
|
||||
<rect x="681.0" y="360" width="60" height="26" rx="13" fill="#5e35b1"/>
|
||||
<text x="711.0" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">DOCX</text>
|
||||
<rect x="750.0" y="360" width="60" height="26" rx="13" fill="#d24726"/>
|
||||
<text x="780.0" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">PPTX</text>
|
||||
<rect x="819.0" y="360" width="60" height="26" rx="13" fill="#217346"/>
|
||||
<text x="849.0" y="377" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">XLSX</text>
|
||||
<rect x="291.0" y="400" width="42" height="26" rx="13" fill="#d81b60"/>
|
||||
<text x="312.0" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">MD</text>
|
||||
<rect x="342.0" y="400" width="51" height="26" rx="13" fill="#6d4c41"/>
|
||||
<text x="367.5" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">TXT</text>
|
||||
<rect x="402.0" y="400" width="51" height="26" rx="13" fill="#7cb342"/>
|
||||
<text x="427.5" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">CSV</text>
|
||||
<rect x="462.0" y="400" width="60" height="26" rx="13" fill="#546e7a"/>
|
||||
<text x="492.0" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">JSON</text>
|
||||
<rect x="531.0" y="400" width="51" height="26" rx="13" fill="#546e7a"/>
|
||||
<text x="556.5" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">XML</text>
|
||||
<rect x="591.0" y="400" width="60" height="26" rx="13" fill="#546e7a"/>
|
||||
<text x="621.0" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">YAML</text>
|
||||
<rect x="660.0" y="400" width="51" height="26" rx="13" fill="#00acc1"/>
|
||||
<text x="685.5" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">JPG</text>
|
||||
<rect x="720.0" y="400" width="51" height="26" rx="13" fill="#00acc1"/>
|
||||
<text x="745.5" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">PNG</text>
|
||||
<rect x="780.0" y="400" width="60" height="26" rx="13" fill="#00acc1"/>
|
||||
<text x="810.0" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">TIFF</text>
|
||||
<rect x="849.0" y="400" width="60" height="26" rx="13" fill="#00acc1"/>
|
||||
<text x="879.0" y="417" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">EXIF</text>
|
||||
<rect x="381.0" y="440" width="51" height="26" rx="13" fill="#f4511e"/>
|
||||
<text x="406.5" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">CBZ</text>
|
||||
<rect x="441.0" y="440" width="51" height="26" rx="13" fill="#f4511e"/>
|
||||
<text x="466.5" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">CBR</text>
|
||||
<rect x="501.0" y="440" width="51" height="26" rx="13" fill="#f4511e"/>
|
||||
<text x="526.5" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">CBT</text>
|
||||
<rect x="561.0" y="440" width="60" height="26" rx="13" fill="#00897b"/>
|
||||
<text x="591.0" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">EPUB</text>
|
||||
<rect x="630.0" y="440" width="60" height="26" rx="13" fill="#00897b"/>
|
||||
<text x="660.0" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">MOBI</text>
|
||||
<rect x="699.0" y="440" width="60" height="26" rx="13" fill="#00897b"/>
|
||||
<text x="729.0" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">AZW3</text>
|
||||
<rect x="768.0" y="440" width="51" height="26" rx="13" fill="#00897b"/>
|
||||
<text x="793.5" y="457" text-anchor="middle" font-size="12.5" font-weight="700" fill="#fff" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">FB2</text>
|
||||
<text x="600.0" y="624" text-anchor="middle" font-size="12.5" fill="#7f8284">Powered by PDF.js · JSDoc · RTF.js · mammoth.js · PptxViewJS · SheetJS · marked · JSZip · libarchive.js · foliate-js · UTIF.js · exifr</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 9.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 90 KiB |
+33
-2
@@ -5,6 +5,15 @@
|
||||
<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" />
|
||||
<script>
|
||||
// Runs before first paint: style.css defaults to the dark palette, so an explicit
|
||||
// light choice would otherwise flash dark for a frame. 'system' stores nothing and
|
||||
// leaves the prefers-color-scheme block in charge, so there is nothing to apply.
|
||||
try {
|
||||
const t = localStorage.getItem('readerjs-theme')
|
||||
if (t === 'light' || t === 'dark') document.documentElement.dataset.theme = t
|
||||
} catch { /* storage blocked (e.g. sandboxed/embedded) */ }
|
||||
</script>
|
||||
<!-- WebODF is loaded on-demand by odf-renderer.js when an ODF file is opened -->
|
||||
</head>
|
||||
<body>
|
||||
@@ -85,6 +94,11 @@
|
||||
</div>
|
||||
|
||||
<div id="toolbarRight">
|
||||
<select id="compareModeSelect" class="compare-only" title="Compare view" data-i18n-title="compare.badge">
|
||||
<option value="side-by-side" data-i18n="compare.modeSideBySide">Side by side</option>
|
||||
<option value="unified" data-i18n="compare.modeUnified">Unified</option>
|
||||
<option value="inline" data-i18n="compare.modeInline">Inline</option>
|
||||
</select>
|
||||
<select id="langSelect" title="Language" data-i18n-title="tip.language">
|
||||
<option value="en">English</option>
|
||||
<option value="pl">Polski</option>
|
||||
@@ -97,6 +111,12 @@
|
||||
<option value="ru">Русский</option>
|
||||
</select>
|
||||
|
||||
<select id="themeSelect" title="Theme" data-i18n-title="tip.theme">
|
||||
<option value="system" data-i18n="theme.system">System</option>
|
||||
<option value="light" data-i18n="theme.light">Light</option>
|
||||
<option value="dark" data-i18n="theme.dark">Dark</option>
|
||||
</select>
|
||||
|
||||
<div class="toolbar-separator"></div>
|
||||
|
||||
<span id="formatBadge" class="hidden"></span>
|
||||
@@ -115,8 +135,16 @@
|
||||
</svg>
|
||||
</label>
|
||||
<input id="fileInput" type="file"
|
||||
accept=".pdf,.djvu,.djv,.odt,.ods,.odp,.odg,.odm,.odf,.rtf,.doc,.docx,.pptx,.xlsx,.xls,.xlsm,.xlsb,.csv,.tsv,.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,.md,.markdown,.txt,.text,.log,.png,.jpg,.jpeg,.gif,.webp,.avif,.bmp,.svg,.ico,.tif,.tiff,.cbz,.cbr,.cbt,.epub,.mobi,.azw3,.azw,.kf8,.fb2,.fbz"
|
||||
accept=".pdf,.ps,.eps,.epsf,.djvu,.djv,.odt,.ods,.odp,.odg,.odm,.odf,.rtf,.doc,.docx,.mht,.mhtml,.chm,.pptx,.xlsx,.xls,.xlsm,.xlsb,.csv,.tsv,.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,.md,.markdown,.txt,.text,.log,.png,.jpg,.jpeg,.gif,.webp,.avif,.bmp,.svg,.ico,.tif,.tiff,.cbz,.cbr,.cbt,.epub,.mobi,.azw3,.azw,.kf8,.fb2,.fbz"
|
||||
aria-label="Open document file" data-i18n-aria="aria.openFile" />
|
||||
|
||||
<button id="compareBtn" class="toolbar-btn" title="Compare two files…" data-i18n-title="compare.openTwo">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
|
||||
<path d="M21 3C21.53 3 22.04 3.21 22.41 3.59C22.79 3.96 23 4.47 23 5V15C23 15.53 22.79 16.04 22.41 16.41C22.04 16.79 21.53 17 21 17H7C6.47 17 5.96 16.79 5.59 16.41C5.21 16.04 5 15.53 5 15V5C5 4.47 5.21 3.96 5.59 3.59C5.96 3.21 6.47 3 7 3H21M3 19H18V21H3C2.47 21 1.96 20.79 1.59 20.41C1.21 20.04 1 19.53 1 19V8H3V19Z" />
|
||||
</svg>
|
||||
</button>
|
||||
<input id="compareInput" type="file" class="hidden" multiple
|
||||
accept=".pdf,.djvu,.djv,.epub,.mobi,.azw3,.azw,.kf8,.fb2,.fbz,.txt,.text,.log,.md,.markdown,.csv,.tsv,.docx,.doc,.rtf,.odt,.ods,.odp,.odg,.xlsx,.xls,.xlsm,.xlsb,.js,.ts,.json,.xml,.yaml,.yml,.py,.java,.c,.cpp,.cs,.go,.rs,.rb,.php,.sh,.sql,.html,.css" aria-hidden="true" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -145,7 +173,7 @@
|
||||
<div id="dropzone">
|
||||
<div id="dropzoneContent">
|
||||
<div id="dropzoneIcon">
|
||||
<svg viewBox="0 0 24 24" width="72" height="72" fill="#90caf9">
|
||||
<svg viewBox="0 0 24 24" width="72" height="72" fill="currentColor">
|
||||
<path d="M11 20H6.5Q4.22 20 2.61 18.43 1 16.85 1 14.58 1 12.63 2.17 11.1 3.35 9.57 5.25 9.15 5.88 6.85 7.75 5.43 9.63 4 12 4 14.93 4 16.96 6.04 19 8.07 19 11 20.73 11.2 21.86 12.5 23 13.78 23 15.5 23 17.38 21.69 18.69 20.38 20 18.5 20H13V12.85L14.6 14.4L16 13L12 9L8 13L9.4 14.4L11 12.85Z" />
|
||||
</svg>
|
||||
</div>
|
||||
@@ -153,6 +181,7 @@
|
||||
<p><span data-i18n="dropzone.drop">Drop a file here, or</span> <label for="fileInput" data-i18n="dropzone.browse">browse</label></p>
|
||||
<div class="format-tags">
|
||||
<span class="format-tag tag-pdf">PDF</span>
|
||||
<span class="format-tag tag-ps">PS</span>
|
||||
<span class="format-tag tag-djvu">DJVU</span>
|
||||
<span class="format-tag tag-odf">ODT</span>
|
||||
<span class="format-tag tag-odf">ODS</span>
|
||||
@@ -160,6 +189,8 @@
|
||||
<span class="format-tag tag-rtf">RTF</span>
|
||||
<span class="format-tag tag-doc">DOC</span>
|
||||
<span class="format-tag tag-docx">DOCX</span>
|
||||
<span class="format-tag tag-mhtml">MHTML</span>
|
||||
<span class="format-tag tag-chm">CHM</span>
|
||||
<span class="format-tag tag-pptx">PPTX</span>
|
||||
<span class="format-tag tag-xlsx">XLSX</span>
|
||||
<span class="format-tag tag-md">MD</span>
|
||||
|
||||
Generated
+875
-871
File diff suppressed because it is too large
Load Diff
+14
-6
@@ -1,31 +1,39 @@
|
||||
{
|
||||
"name": "preview-js",
|
||||
"version": "1.0.0",
|
||||
"description": "Universal document viewer: PDF, ODF, RTF, DOCX — powered by pdf.js, WebODF, rtf.js and docx submodules",
|
||||
"description": "Client-side universal document viewer — PDF, DjVu, ODF, Office, e-books, comics and images — permissive, no server, no upload",
|
||||
"private": true,
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"chart.js": "^4.5.1",
|
||||
"chmate": "git+http://77.216.148.202:3000/Alpaq/CHMate.git#2ef98fd53abf70be5edec99d45ec969c51905954",
|
||||
"dejaview": "git+http://77.216.148.202:3000/Alpaq/dejaview.git#a2ac4b18cbe4b95f2167e7c0053fad73d8a56df0",
|
||||
"diff": "^9.0.0",
|
||||
"exifr": "^7.1.3",
|
||||
"foliate-js": "git+http://77.216.148.202:3000/Gizmo/foliate-js.git#78914aef4466eb960965702401634c2cb348e9b1",
|
||||
"highlight.js": "^11.11.1",
|
||||
"jszip": "^3.10.1",
|
||||
"libarchive.js": "^2.0.2",
|
||||
"mammoth": "^1.8.0",
|
||||
"mammoth": "^1.12.0",
|
||||
"marked": "^18.0.5",
|
||||
"mhtml-to-html": "^2.0.1",
|
||||
"papaparse": "^5.5.4",
|
||||
"pdfjs-dist": "^4.9.155",
|
||||
"pdfjs-dist": "^6.1.200",
|
||||
"pptxviewjs": "^1.1.9",
|
||||
"rtf.js": "^2.2.0",
|
||||
"riposte": "git+http://77.216.148.202:3000/Alpaq/Riposte.git#a45e8b2382eeb325ed2584e6cf9c5f6923327f14",
|
||||
"rtf.js": "^3.0.9",
|
||||
"utif": "^3.1.0",
|
||||
"xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^6.0.7"
|
||||
"vite": "^8.1.2"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+152
@@ -0,0 +1,152 @@
|
||||
<!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="compareModeSelect" class="compare-only" title="Compare view" data-i18n-title="compare.badge">
|
||||
<option value="side-by-side" data-i18n="compare.modeSideBySide">Side by side</option>
|
||||
<option value="unified" data-i18n="compare.modeUnified">Unified</option>
|
||||
<option value="inline" data-i18n="compare.modeInline">Inline</option>
|
||||
</select>
|
||||
<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>
|
||||
@@ -0,0 +1,61 @@
|
||||
%PDF-1.4
|
||||
1 0 obj
|
||||
<< /Type /Catalog /Pages 2 0 R >>
|
||||
endobj
|
||||
2 0 obj
|
||||
<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>
|
||||
endobj
|
||||
3 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 5 0 R >>
|
||||
endobj
|
||||
4 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 6 0 R >>
|
||||
endobj
|
||||
5 0 obj
|
||||
<< /Length 174 >>
|
||||
stream
|
||||
BT
|
||||
/F1 14 Tf
|
||||
16 TL
|
||||
72 720 Td
|
||||
(Project Aurora Manual) Tj
|
||||
T* (Version 2.3.0) Tj
|
||||
T* (Released June 1, 2026.) Tj
|
||||
T* () Tj
|
||||
T* (Chapter 1: Setup) Tj
|
||||
T* (Install the package.) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
6 0 obj
|
||||
<< /Length 130 >>
|
||||
stream
|
||||
BT
|
||||
/F1 14 Tf
|
||||
16 TL
|
||||
72 720 Td
|
||||
(Chapter 2: Usage) Tj
|
||||
T* (Run the start command.) Tj
|
||||
T* () Tj
|
||||
T* (Known issue: export is slow.) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
7 0 obj
|
||||
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
|
||||
endobj
|
||||
xref
|
||||
0 8
|
||||
0000000000 65535 f
|
||||
0000000009 00000 n
|
||||
0000000058 00000 n
|
||||
0000000121 00000 n
|
||||
0000000247 00000 n
|
||||
0000000373 00000 n
|
||||
0000000598 00000 n
|
||||
0000000779 00000 n
|
||||
trailer
|
||||
<< /Size 8 /Root 1 0 R >>
|
||||
startxref
|
||||
849
|
||||
%%EOF
|
||||
@@ -0,0 +1,61 @@
|
||||
%PDF-1.4
|
||||
1 0 obj
|
||||
<< /Type /Catalog /Pages 2 0 R >>
|
||||
endobj
|
||||
2 0 obj
|
||||
<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>
|
||||
endobj
|
||||
3 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 5 0 R >>
|
||||
endobj
|
||||
4 0 obj
|
||||
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 6 0 R >>
|
||||
endobj
|
||||
5 0 obj
|
||||
<< /Length 189 >>
|
||||
stream
|
||||
BT
|
||||
/F1 14 Tf
|
||||
16 TL
|
||||
72 720 Td
|
||||
(Project Aurora Manual) Tj
|
||||
T* (Version 2.4.0) Tj
|
||||
T* (Released June 24, 2026.) Tj
|
||||
T* () Tj
|
||||
T* (Chapter 1: Setup) Tj
|
||||
T* (Install the package and the embed.) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
6 0 obj
|
||||
<< /Length 129 >>
|
||||
stream
|
||||
BT
|
||||
/F1 14 Tf
|
||||
16 TL
|
||||
72 720 Td
|
||||
(Chapter 2: Usage) Tj
|
||||
T* (Run the start command.) Tj
|
||||
T* () Tj
|
||||
T* (Added page-by-page compare.) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
7 0 obj
|
||||
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
|
||||
endobj
|
||||
xref
|
||||
0 8
|
||||
0000000000 65535 f
|
||||
0000000009 00000 n
|
||||
0000000058 00000 n
|
||||
0000000121 00000 n
|
||||
0000000247 00000 n
|
||||
0000000373 00000 n
|
||||
0000000613 00000 n
|
||||
0000000793 00000 n
|
||||
trailer
|
||||
<< /Size 8 /Root 1 0 R >>
|
||||
startxref
|
||||
863
|
||||
%%EOF
|
||||
@@ -0,0 +1,20 @@
|
||||
# Project Aurora — Release Notes
|
||||
|
||||
## Version 2.3.0
|
||||
|
||||
Released on June 1, 2026.
|
||||
|
||||
### Highlights
|
||||
|
||||
- New dark mode across the app.
|
||||
- Faster startup time (about 30% quicker).
|
||||
- Fixed the login timeout bug.
|
||||
|
||||
### Known Issues
|
||||
|
||||
- Export to PDF is occasionally slow.
|
||||
- Search does not cover archived items.
|
||||
|
||||
### Credits
|
||||
|
||||
Thanks to the whole team for this release.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Project Aurora — Release Notes
|
||||
|
||||
## Version 2.4.0
|
||||
|
||||
Released on June 24, 2026.
|
||||
|
||||
### Highlights
|
||||
|
||||
- New dark mode across the app and the embed.
|
||||
- Faster startup time (about 45% quicker).
|
||||
- Fixed the login timeout bug.
|
||||
- Added two-version document compare with blame.
|
||||
|
||||
### Known Issues
|
||||
|
||||
- Search does not cover archived items.
|
||||
|
||||
### Credits
|
||||
|
||||
Thanks to the whole team and our contributors for this release.
|
||||
@@ -0,0 +1,270 @@
|
||||
// Compare view — diffs two text representations with jsdiff and renders the
|
||||
// result three ways (side-by-side / unified / inline) from a single row model.
|
||||
// Each changed line is hoverable; the tooltip can be pinned and shows blame
|
||||
// data (author/date/commit/message) the host supplies, keyed by new-side line.
|
||||
import * as Diff from 'diff'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// MDI icons (Apache-2.0) for the pin / unpin controls.
|
||||
const ICON_PIN = 'M16,12V4H17V2H7V4H8V12L6,14V16H11.2V22H12.8V16H18V14L16,12Z'
|
||||
const ICON_PIN_OFF = 'M2,5.27L3.28,4L20,20.72L18.73,22L12.8,16.07V22H11.2V16H6V14L8,12V11.27L2,5.27M16,12L18,14V16H17.82L8,6.18V4H7V2H17V4H16V12Z'
|
||||
|
||||
function icon(d) {
|
||||
const NS = 'http://www.w3.org/2000/svg'
|
||||
const svg = document.createElementNS(NS, 'svg')
|
||||
svg.setAttribute('viewBox', '0 0 24 24')
|
||||
svg.setAttribute('width', '15'); svg.setAttribute('height', '15'); svg.setAttribute('fill', 'currentColor')
|
||||
const path = document.createElementNS(NS, 'path'); path.setAttribute('d', d)
|
||||
svg.appendChild(path)
|
||||
return svg
|
||||
}
|
||||
|
||||
/* ── Row model ─────────────────────────────────────────────────────────────
|
||||
* Row = { type:'equal'|'add'|'del'|'mod', leftLineNo, rightLineNo, leftText, rightText }
|
||||
* blame is keyed by rightLineNo (the new revision's line). One Diff.diffLines()
|
||||
* call feeds all three view modes. */
|
||||
|
||||
function splitLines(value) {
|
||||
const lines = value.split('\n')
|
||||
if (lines.length && lines[lines.length - 1] === '') lines.pop() // drop trailing empty
|
||||
return lines
|
||||
}
|
||||
|
||||
function buildRows(leftText, rightText) {
|
||||
const parts = Diff.diffLines(leftText ?? '', rightText ?? '')
|
||||
const rows = []
|
||||
let lL = 0, rL = 0 // 1-based line counters (left / right)
|
||||
let pendingDel = [] // [{ text, lineNo }] removed lines awaiting pairing
|
||||
|
||||
const spillDels = () => {
|
||||
for (const d of pendingDel)
|
||||
rows.push({ type: 'del', leftLineNo: d.lineNo, rightLineNo: null, leftText: d.text, rightText: '' })
|
||||
pendingDel = []
|
||||
}
|
||||
|
||||
for (const part of parts) {
|
||||
const lines = splitLines(part.value)
|
||||
if (part.removed) {
|
||||
for (const text of lines) { lL++; pendingDel.push({ text, lineNo: lL }) }
|
||||
} else if (part.added) {
|
||||
const added = lines.map(text => { rL++; return { text, lineNo: rL } })
|
||||
const n = Math.min(pendingDel.length, added.length) // pair del+add as 'mod'
|
||||
for (let i = 0; i < n; i++)
|
||||
rows.push({ type: 'mod', leftLineNo: pendingDel[i].lineNo, rightLineNo: added[i].lineNo,
|
||||
leftText: pendingDel[i].text, rightText: added[i].text })
|
||||
for (let i = n; i < pendingDel.length; i++) // leftover removals
|
||||
rows.push({ type: 'del', leftLineNo: pendingDel[i].lineNo, rightLineNo: null,
|
||||
leftText: pendingDel[i].text, rightText: '' })
|
||||
for (let i = n; i < added.length; i++) // leftover additions
|
||||
rows.push({ type: 'add', leftLineNo: null, rightLineNo: added[i].lineNo,
|
||||
leftText: '', rightText: added[i].text })
|
||||
pendingDel = []
|
||||
} else {
|
||||
spillDels()
|
||||
for (const text of lines) { lL++; rL++; rows.push({ type: 'equal', leftLineNo: lL, rightLineNo: rL, leftText: text, rightText: text }) }
|
||||
}
|
||||
}
|
||||
spillDels()
|
||||
return rows
|
||||
}
|
||||
|
||||
// Intra-line word diff for 'mod' rows (memoized). diffWordsWithSpace keeps
|
||||
// whitespace so re-indentation and table cells (tab-separated) line up.
|
||||
function wordParts(row) {
|
||||
if (!row._wp) row._wp = Diff.diffWordsWithSpace(row.leftText, row.rightText)
|
||||
return row._wp
|
||||
}
|
||||
|
||||
// Fill `el` with `text`. With word-diff `parts`, wrap added/removed runs; `side`
|
||||
// 'left' drops additions, 'right' drops removals, 'inline' keeps both.
|
||||
function fillText(el, text, parts, side) {
|
||||
if (!parts) { el.textContent = text; return }
|
||||
for (const p of parts) {
|
||||
if (side === 'left' && p.added) continue
|
||||
if (side === 'right' && p.removed) continue
|
||||
if (p.added) { const n = document.createElement('ins'); n.textContent = p.value; el.appendChild(n) }
|
||||
else if (p.removed) { const n = document.createElement('del'); n.textContent = p.value; el.appendChild(n) }
|
||||
else el.appendChild(document.createTextNode(p.value))
|
||||
}
|
||||
}
|
||||
|
||||
function markChange(el, row) { el.classList.add('diff-change'); el._row = row }
|
||||
|
||||
/* ── View renderers (all consume the same rows[]) ──────────────────────────── */
|
||||
|
||||
function sideClass(row, side) {
|
||||
const lineNo = side === 'left' ? row.leftLineNo : row.rightLineNo
|
||||
if (lineNo == null) return 'blank'
|
||||
if (row.type === 'equal') return 'equal'
|
||||
return side === 'left' ? 'del' : 'add' // del/mod-left = red, add/mod-right = green
|
||||
}
|
||||
|
||||
function cell(row, side) {
|
||||
const c = document.createElement('div')
|
||||
c.className = 'diff-cell ' + sideClass(row, side)
|
||||
const ln = document.createElement('span'); ln.className = 'diff-lineno'
|
||||
const txt = document.createElement('span'); txt.className = 'diff-text'
|
||||
const lineNo = side === 'left' ? row.leftLineNo : row.rightLineNo
|
||||
if (lineNo != null) { // a blank side stays empty — sideClass() already gave it .diff-cell.blank
|
||||
ln.textContent = lineNo
|
||||
fillText(txt, side === 'left' ? row.leftText : row.rightText, row.type === 'mod' ? wordParts(row) : null, side)
|
||||
if (row.type !== 'equal') markChange(c, row)
|
||||
}
|
||||
c.append(ln, txt)
|
||||
return c
|
||||
}
|
||||
|
||||
function renderSideBySide(body, rows) {
|
||||
const grid = document.createElement('div')
|
||||
grid.className = 'diff-rows side-by-side'
|
||||
for (const row of rows) grid.append(cell(row, 'left'), cell(row, 'right'))
|
||||
body.appendChild(grid)
|
||||
}
|
||||
|
||||
function uLine(row, kind) { // kind: 'equal' | 'del' | 'add'
|
||||
const line = document.createElement('div')
|
||||
line.className = 'diff-line ' + kind
|
||||
const lo = document.createElement('span'); lo.className = 'diff-lineno old'
|
||||
const ln = document.createElement('span'); ln.className = 'diff-lineno new'
|
||||
const sign = document.createElement('span'); sign.className = 'diff-sign'
|
||||
const txt = document.createElement('span'); txt.className = 'diff-text'
|
||||
const wp = row.type === 'mod' ? wordParts(row) : null
|
||||
if (kind === 'equal') { lo.textContent = row.leftLineNo; ln.textContent = row.rightLineNo; txt.textContent = row.leftText }
|
||||
else if (kind === 'del') { lo.textContent = row.leftLineNo; sign.textContent = '−'; fillText(txt, row.leftText, wp, 'left'); markChange(line, row) }
|
||||
else { ln.textContent = row.rightLineNo; sign.textContent = '+'; fillText(txt, row.rightText, wp, 'right'); markChange(line, row) }
|
||||
line.append(lo, ln, sign, txt)
|
||||
return line
|
||||
}
|
||||
|
||||
function renderUnified(body, rows) {
|
||||
const col = document.createElement('div')
|
||||
col.className = 'diff-rows unified'
|
||||
for (const row of rows) {
|
||||
if (row.type === 'mod') { col.append(uLine(row, 'del'), uLine(row, 'add')) }
|
||||
else col.appendChild(uLine(row, row.type))
|
||||
}
|
||||
body.appendChild(col)
|
||||
}
|
||||
|
||||
function renderInline(body, rows) {
|
||||
const col = document.createElement('div')
|
||||
col.className = 'diff-rows inline'
|
||||
for (const row of rows) {
|
||||
const line = document.createElement('div')
|
||||
line.className = 'diff-line ' + row.type
|
||||
if (row.type === 'equal') line.textContent = row.leftText
|
||||
else if (row.type === 'del') { const d = document.createElement('del'); d.textContent = row.leftText; line.appendChild(d); markChange(line, row) }
|
||||
else if (row.type === 'add') { const i = document.createElement('ins'); i.textContent = row.rightText; line.appendChild(i); markChange(line, row) }
|
||||
else { fillText(line, '', wordParts(row), 'inline'); markChange(line, row) }
|
||||
col.appendChild(line)
|
||||
}
|
||||
body.appendChild(col)
|
||||
}
|
||||
|
||||
const RENDERERS = { 'side-by-side': renderSideBySide, unified: renderUnified, inline: renderInline }
|
||||
|
||||
/* ── Public entry ──────────────────────────────────────────────────────────── */
|
||||
|
||||
export function renderCompare(target, { pages = [], blame = {}, mode = 'side-by-side' } = {}) {
|
||||
// `pages`: one { leftText, rightText } per document page. Most formats are a
|
||||
// single page; PDF/DjVu split per page so the diff can be navigated page by page.
|
||||
if (!pages.length) pages = [{ leftText: '', rightText: '' }]
|
||||
const rowsCache = new Map()
|
||||
const rowsFor = i => { if (!rowsCache.has(i)) rowsCache.set(i, buildRows(pages[i].leftText, pages[i].rightText)); return rowsCache.get(i) }
|
||||
let pageIdx = 0
|
||||
target.innerHTML = ''
|
||||
|
||||
// The view-mode switcher is a dropdown in the host's top toolbar (the app and
|
||||
// the embed both wire it to setMode); the diff itself is just the body.
|
||||
const bodyWrap = document.createElement('div') // position:relative anchor for tooltips/pins
|
||||
bodyWrap.className = 'diff-body'
|
||||
target.appendChild(bodyWrap)
|
||||
|
||||
// transient hover tooltip (with a pin button) + persistent pins
|
||||
const tip = document.createElement('div'); tip.className = 'diff-tooltip hidden'
|
||||
const tipHead = document.createElement('div'); tipHead.className = 'diff-tip-head'
|
||||
const pinBtn = document.createElement('button'); pinBtn.className = 'diff-pin-btn'; pinBtn.appendChild(icon(ICON_PIN))
|
||||
pinBtn.dataset.i18nTitle = 'compare.pin'; pinBtn.title = t('compare.pin')
|
||||
pinBtn.addEventListener('click', e => { e.stopPropagation(); if (tip._row && tip._anchor) pinTooltip(tip._row, tip._anchor) })
|
||||
tipHead.appendChild(pinBtn)
|
||||
const tipBody = document.createElement('div'); tipBody.className = 'diff-tip-body'
|
||||
tip.append(tipHead, tipBody)
|
||||
bodyWrap.appendChild(tip)
|
||||
const pins = []
|
||||
|
||||
function fillBlame(host, row) {
|
||||
host.innerHTML = ''
|
||||
const h = document.createElement('h3'); h.dataset.i18n = 'blame.heading'; h.textContent = t('blame.heading'); host.appendChild(h)
|
||||
const data = row.rightLineNo != null ? blame[row.rightLineNo] : null
|
||||
if (data) {
|
||||
const dl = document.createElement('dl')
|
||||
for (const k of ['author', 'date', 'commit', 'message']) {
|
||||
if (data[k] == null || data[k] === '') continue
|
||||
const dt = document.createElement('dt'); dt.dataset.i18n = 'blame.' + k; dt.textContent = t('blame.' + k)
|
||||
const dd = document.createElement('dd'); dd.textContent = data[k]
|
||||
dl.append(dt, dd)
|
||||
}
|
||||
host.appendChild(dl)
|
||||
} else {
|
||||
const note = document.createElement('p'); note.className = 'diff-tip-note'
|
||||
const key = row.rightLineNo == null ? 'compare.removed' : 'compare.noBlame'
|
||||
note.dataset.i18n = key; note.textContent = t(key); host.appendChild(note)
|
||||
}
|
||||
}
|
||||
|
||||
function position(el, anchor) {
|
||||
const b = bodyWrap.getBoundingClientRect()
|
||||
const a = anchor.getBoundingClientRect()
|
||||
el.style.top = (a.bottom - b.top + 4) + 'px'
|
||||
el.style.left = Math.max(4, Math.min(a.left - b.left, bodyWrap.clientWidth - el.offsetWidth - 8)) + 'px'
|
||||
}
|
||||
|
||||
function pinTooltip(row, anchor) {
|
||||
const pin = document.createElement('div'); pin.className = 'diff-pin'
|
||||
const head = document.createElement('div'); head.className = 'diff-tip-head'
|
||||
const close = document.createElement('button'); close.className = 'diff-pin-close'; close.appendChild(icon(ICON_PIN_OFF))
|
||||
close.dataset.i18nTitle = 'compare.unpin'; close.title = t('compare.unpin')
|
||||
close.addEventListener('click', () => { pin.remove(); const i = pins.indexOf(pin); if (i >= 0) pins.splice(i, 1) })
|
||||
head.appendChild(close)
|
||||
const pb = document.createElement('div'); pb.className = 'diff-tip-body'; fillBlame(pb, row)
|
||||
pin.append(head, pb); bodyWrap.appendChild(pin); position(pin, anchor); pins.push(pin); hideTip()
|
||||
}
|
||||
|
||||
let hideTimer = null
|
||||
const hideTip = () => tip.classList.add('hidden')
|
||||
function showTipFor(el) {
|
||||
clearTimeout(hideTimer)
|
||||
tip._row = el._row; tip._anchor = el
|
||||
fillBlame(tipBody, el._row)
|
||||
tip.classList.remove('hidden')
|
||||
position(tip, el)
|
||||
}
|
||||
const scheduleHide = () => { clearTimeout(hideTimer); hideTimer = setTimeout(hideTip, 180) }
|
||||
|
||||
bodyWrap.addEventListener('mouseover', e => { const el = e.target.closest('.diff-change'); if (el && el._row) showTipFor(el) })
|
||||
bodyWrap.addEventListener('mouseout', e => { if (e.target.closest('.diff-change')) scheduleHide() })
|
||||
tip.addEventListener('mouseenter', () => clearTimeout(hideTimer))
|
||||
tip.addEventListener('mouseleave', scheduleHide)
|
||||
|
||||
let current = RENDERERS[mode] ? mode : 'side-by-side'
|
||||
function render() {
|
||||
[...bodyWrap.children].forEach(c => { if (c !== tip) c.remove() })
|
||||
pins.splice(0).forEach(p => p.remove()) // re-render invalidates anchors
|
||||
hideTip()
|
||||
RENDERERS[current](bodyWrap, rowsFor(pageIdx))
|
||||
}
|
||||
function setMode(m) { if (RENDERERS[m]) { current = m; render() } }
|
||||
function setPage(i) { if (i >= 0 && i < pages.length && i !== pageIdx) { pageIdx = i; render() } }
|
||||
|
||||
render()
|
||||
|
||||
return {
|
||||
setMode,
|
||||
setPage,
|
||||
destroy() {
|
||||
pins.splice(0).forEach(p => p.remove())
|
||||
tip.remove()
|
||||
target.innerHTML = ''
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Flatten an element to text, inserting a newline at each block boundary — plain
|
||||
// textContent collapses every paragraph onto one line. `block` is the set of tag
|
||||
// names that end a line; `skip` (optional) is dropped entirely (e.g. SCRIPT/STYLE).
|
||||
export function flattenBlocks(root, block, skip) {
|
||||
let out = ''
|
||||
const walk = node => {
|
||||
for (const child of node.childNodes) {
|
||||
if (child.nodeType === 3) out += child.nodeValue
|
||||
else if (child.nodeType === 1) {
|
||||
const tag = child.tagName?.toUpperCase()
|
||||
if (tag === 'BR') { out += '\n'; continue }
|
||||
if (skip?.has(tag)) continue
|
||||
walk(child)
|
||||
if (block.has(tag)) out += '\n'
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
return out
|
||||
}
|
||||
+55
-2
@@ -368,10 +368,41 @@ const dict = {
|
||||
},
|
||||
}
|
||||
|
||||
// Compare-view strings, merged into each language dict (grouped here rather than
|
||||
// scattered through every block above).
|
||||
const COMPARE = {
|
||||
en: { 'compare.badge':'Compare', 'compare.modeSideBySide':'Side by side', 'compare.modeUnified':'Unified', 'compare.modeInline':'Inline', 'compare.openTwo':'Compare two files…', 'compare.unsupported':"Comparison isn't available for {format} documents.", 'compare.removed':'Removed line', 'compare.noBlame':'No blame data', 'compare.pickTwo':'Select two files to compare.', 'compare.pin':'Pin', 'compare.unpin':'Unpin', 'blame.heading':'Blame', 'blame.author':'Author', 'blame.date':'Date', 'blame.commit':'Commit', 'blame.message':'Message' },
|
||||
pl: { 'compare.badge':'Porównanie', 'compare.modeSideBySide':'Obok siebie', 'compare.modeUnified':'Ujednolicony', 'compare.modeInline':'W tekście', 'compare.openTwo':'Porównaj dwa pliki…', 'compare.unsupported':'Porównywanie nie jest dostępne dla dokumentów {format}.', 'compare.removed':'Usunięty wiersz', 'compare.noBlame':'Brak danych blame', 'compare.pickTwo':'Wybierz dwa pliki do porównania.', 'compare.pin':'Przypnij', 'compare.unpin':'Odepnij', 'blame.heading':'Autorstwo', 'blame.author':'Autor', 'blame.date':'Data', 'blame.commit':'Commit', 'blame.message':'Wiadomość' },
|
||||
es: { 'compare.badge':'Comparar', 'compare.modeSideBySide':'Lado a lado', 'compare.modeUnified':'Unificado', 'compare.modeInline':'En línea', 'compare.openTwo':'Comparar dos archivos…', 'compare.unsupported':'La comparación no está disponible para documentos {format}.', 'compare.removed':'Línea eliminada', 'compare.noBlame':'Sin datos de autoría', 'compare.pickTwo':'Selecciona dos archivos para comparar.', 'compare.pin':'Fijar', 'compare.unpin':'Soltar', 'blame.heading':'Autoría', 'blame.author':'Autor', 'blame.date':'Fecha', 'blame.commit':'Commit', 'blame.message':'Mensaje' },
|
||||
fr: { 'compare.badge':'Comparer', 'compare.modeSideBySide':'Côte à côte', 'compare.modeUnified':'Unifié', 'compare.modeInline':'En ligne', 'compare.openTwo':'Comparer deux fichiers…', 'compare.unsupported':'La comparaison n’est pas disponible pour les documents {format}.', 'compare.removed':'Ligne supprimée', 'compare.noBlame':'Aucune donnée d’attribution', 'compare.pickTwo':'Sélectionnez deux fichiers à comparer.', 'compare.pin':'Épingler', 'compare.unpin':'Détacher', 'blame.heading':'Attribution', 'blame.author':'Auteur', 'blame.date':'Date', 'blame.commit':'Commit', 'blame.message':'Message' },
|
||||
de: { 'compare.badge':'Vergleich', 'compare.modeSideBySide':'Nebeneinander', 'compare.modeUnified':'Vereinheitlicht', 'compare.modeInline':'Inline', 'compare.openTwo':'Zwei Dateien vergleichen…', 'compare.unsupported':'Der Vergleich ist für {format}-Dokumente nicht verfügbar.', 'compare.removed':'Entfernte Zeile', 'compare.noBlame':'Keine Blame-Daten', 'compare.pickTwo':'Wählen Sie zwei Dateien zum Vergleichen.', 'compare.pin':'Anheften', 'compare.unpin':'Lösen', 'blame.heading':'Blame', 'blame.author':'Autor', 'blame.date':'Datum', 'blame.commit':'Commit', 'blame.message':'Nachricht' },
|
||||
pt: { 'compare.badge':'Comparar', 'compare.modeSideBySide':'Lado a lado', 'compare.modeUnified':'Unificado', 'compare.modeInline':'Em linha', 'compare.openTwo':'Comparar dois ficheiros…', 'compare.unsupported':'A comparação não está disponível para documentos {format}.', 'compare.removed':'Linha removida', 'compare.noBlame':'Sem dados de autoria', 'compare.pickTwo':'Selecione dois ficheiros para comparar.', 'compare.pin':'Fixar', 'compare.unpin':'Soltar', 'blame.heading':'Autoria', 'blame.author':'Autor', 'blame.date':'Data', 'blame.commit':'Commit', 'blame.message':'Mensagem' },
|
||||
zh: { 'compare.badge':'比较', 'compare.modeSideBySide':'并排', 'compare.modeUnified':'统一', 'compare.modeInline':'行内', 'compare.openTwo':'比较两个文件…', 'compare.unsupported':'{format} 文档不支持比较。', 'compare.removed':'已删除的行', 'compare.noBlame':'无追溯数据', 'compare.pickTwo':'请选择两个文件进行比较。', 'compare.pin':'固定', 'compare.unpin':'取消固定', 'blame.heading':'追溯', 'blame.author':'作者', 'blame.date':'日期', 'blame.commit':'提交', 'blame.message':'消息' },
|
||||
ja: { 'compare.badge':'比較', 'compare.modeSideBySide':'左右に並べる', 'compare.modeUnified':'統合', 'compare.modeInline':'インライン', 'compare.openTwo':'2つのファイルを比較…', 'compare.unsupported':'{format} ドキュメントは比較できません。', 'compare.removed':'削除された行', 'compare.noBlame':'ブレーム情報なし', 'compare.pickTwo':'比較する2つのファイルを選択してください。', 'compare.pin':'固定', 'compare.unpin':'固定解除', 'blame.heading':'ブレーム', 'blame.author':'作成者', 'blame.date':'日付', 'blame.commit':'コミット', 'blame.message':'メッセージ' },
|
||||
ru: { 'compare.badge':'Сравнение', 'compare.modeSideBySide':'Рядом', 'compare.modeUnified':'Объединённый', 'compare.modeInline':'Встроенный', 'compare.openTwo':'Сравнить два файла…', 'compare.unsupported':'Сравнение недоступно для документов {format}.', 'compare.removed':'Удалённая строка', 'compare.noBlame':'Нет данных об авторстве', 'compare.pickTwo':'Выберите два файла для сравнения.', 'compare.pin':'Закрепить', 'compare.unpin':'Открепить', 'blame.heading':'Авторство', 'blame.author':'Автор', 'blame.date':'Дата', 'blame.commit':'Коммит', 'blame.message':'Сообщение' },
|
||||
}
|
||||
for (const code in COMPARE) Object.assign(dict[code], COMPARE[code])
|
||||
|
||||
// Theme switcher (light / dark / follow the OS). Kept as its own table and merged
|
||||
// like COMPARE above, so adding a UI area does not mean editing nine nested objects.
|
||||
const THEME = {
|
||||
en: { 'tip.theme':'Theme', 'theme.system':'System', 'theme.light':'Light', 'theme.dark':'Dark' },
|
||||
pl: { 'tip.theme':'Motyw', 'theme.system':'Systemowy', 'theme.light':'Jasny', 'theme.dark':'Ciemny' },
|
||||
es: { 'tip.theme':'Tema', 'theme.system':'Sistema', 'theme.light':'Claro', 'theme.dark':'Oscuro' },
|
||||
fr: { 'tip.theme':'Thème', 'theme.system':'Système', 'theme.light':'Clair', 'theme.dark':'Sombre' },
|
||||
de: { 'tip.theme':'Design', 'theme.system':'System', 'theme.light':'Hell', 'theme.dark':'Dunkel' },
|
||||
pt: { 'tip.theme':'Tema', 'theme.system':'Sistema', 'theme.light':'Claro', 'theme.dark':'Escuro' },
|
||||
zh: { 'tip.theme':'主题', 'theme.system':'跟随系统', 'theme.light':'浅色', 'theme.dark':'深色' },
|
||||
ja: { 'tip.theme':'テーマ', 'theme.system':'システム', 'theme.light':'ライト', 'theme.dark':'ダーク' },
|
||||
ru: { 'tip.theme':'Тема', 'theme.system':'Системная', 'theme.light':'Светлая', 'theme.dark':'Тёмная' },
|
||||
}
|
||||
for (const code in THEME) Object.assign(dict[code], THEME[code])
|
||||
|
||||
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 +428,29 @@ 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()
|
||||
}
|
||||
|
||||
/* ── Theme ───────────────────────────────────────────────────────────────
|
||||
Three states: 'system' (default), 'light', 'dark'. Only an explicit choice is
|
||||
stored and only an explicit choice sets data-theme; in system mode the
|
||||
attribute is absent and style.css's prefers-color-scheme block decides. */
|
||||
const THEME_KEY = 'readerjs-theme'
|
||||
export const THEMES = ['system', 'light', 'dark']
|
||||
|
||||
export function getTheme() {
|
||||
try {
|
||||
const v = localStorage.getItem(THEME_KEY)
|
||||
if (THEMES.includes(v)) return v
|
||||
} catch { /* storage blocked (e.g. sandboxed/embedded) */ }
|
||||
return 'system'
|
||||
}
|
||||
|
||||
export function setTheme(mode) {
|
||||
if (!THEMES.includes(mode)) return
|
||||
if (mode === 'system') document.documentElement.removeAttribute('data-theme')
|
||||
else document.documentElement.dataset.theme = mode
|
||||
try { localStorage.setItem(THEME_KEY, mode) } catch { /* storage blocked */ }
|
||||
}
|
||||
|
||||
+317
-76
@@ -1,31 +1,67 @@
|
||||
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'
|
||||
import { t, applyTranslations, setLang, getLang, getTheme, setTheme } from './i18n.js'
|
||||
import { flattenBlocks } from './dom-text.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()),
|
||||
mhtml: () => import('./renderers/mhtml-renderer.js').then(m => new m.MHTMLRenderer()),
|
||||
chm: () => import('./renderers/chm-renderer.js').then(m => new m.CHMRenderer()),
|
||||
ps: () => import('./renderers/postscript-renderer.js').then(m => new m.PostScriptRenderer()),
|
||||
}
|
||||
|
||||
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']
|
||||
|
||||
/**
|
||||
* Heuristic: does this look like a binary file rather than text?
|
||||
*
|
||||
* A NUL byte is the classic marker — no text encoding this decoder handles produces one — and a
|
||||
* high density of other C0 control characters catches the rest. Deliberately cheap and
|
||||
* conservative: the cost of a false "binary" is a file the user must rename to read, while a
|
||||
* false "text" is a screen of replacement characters, so it errs toward trying to read.
|
||||
*
|
||||
* @param {ArrayBuffer} buffer First few KB of the file.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function looksBinary(buffer) {
|
||||
const bytes = new Uint8Array(buffer)
|
||||
if (!bytes.length) return false
|
||||
let control = 0
|
||||
for (const b of bytes) {
|
||||
if (b === 0) return true
|
||||
// C0 controls except tab (9), LF (10), CR (13) and form feed (12)
|
||||
if (b < 9 || (b > 13 && b < 32)) control++
|
||||
}
|
||||
return control / bytes.length > 0.3
|
||||
}
|
||||
|
||||
const EXT_MAP = {
|
||||
pdf: 'pdf',
|
||||
ps: 'ps', eps: 'ps', epsf: 'ps',
|
||||
djvu: 'djvu', djv: 'djvu',
|
||||
odt: 'odf', ods: 'odf', odp: 'odf', odg: 'odf', odm: 'odf', odf: 'odf',
|
||||
rtf: 'rtf',
|
||||
docx: 'docx',
|
||||
doc: 'doc',
|
||||
mht: 'mhtml', mhtml: 'mhtml',
|
||||
chm: 'chm',
|
||||
pptx: 'pptx',
|
||||
xlsx: 'xlsx', xls: 'xlsx', xlsm: 'xlsx', xlsb: 'xlsx',
|
||||
csv: 'csv', tsv: 'csv',
|
||||
@@ -39,25 +75,39 @@ const EXT_MAP = {
|
||||
fb2: 'epub', fbz: 'epub',
|
||||
}
|
||||
|
||||
class DocumentViewer {
|
||||
// Formats whose rendered output is text/HTML we can diff. The rest (pdf, djvu,
|
||||
// comic, image, pptx, epub) are canvas/reflowable → not text-comparable.
|
||||
const DIFFABLE = new Set(['txt', 'md', 'docx', 'rtf', 'odf', 'doc', 'code', 'csv', 'xlsx'])
|
||||
|
||||
// Tags that imply a line break when flattening rich HTML to comparable text.
|
||||
const BLOCK_TAGS = new Set(['P','DIV','LI','H1','H2','H3','H4','H5','H6','TR','TABLE',
|
||||
'BLOCKQUOTE','PRE','HR','SECTION','ARTICLE','UL','OL','DD','DT','FIGURE','FIGCAPTION'])
|
||||
|
||||
// Rows of `.data-table` / xlsx sheets → tab-separated lines (so diffLines aligns
|
||||
// per row and the word diff aligns per cell).
|
||||
function tableText(page) {
|
||||
const out = []
|
||||
page.querySelectorAll('.sheet-title, table').forEach(node => {
|
||||
if (node.tagName === 'H3') out.push('# ' + node.textContent)
|
||||
else for (const tr of node.querySelectorAll('tr'))
|
||||
out.push([...tr.children].map(c => c.textContent.replace(/\t/g, ' ')).join('\t'))
|
||||
})
|
||||
return out.join('\n')
|
||||
}
|
||||
|
||||
// A diffable text representation of a freshly-rendered `.doc-page`.
|
||||
function extractRendered(host, format) {
|
||||
const page = host.querySelector('.doc-page') || host
|
||||
if (format === 'txt') return (page.querySelector('.txt-content') || page).textContent
|
||||
if (format === 'code') return (page.querySelector('pre code') || page).textContent
|
||||
if (format === 'csv' || format === 'xlsx') return tableText(page)
|
||||
return flattenBlocks(page, BLOCK_TAGS).replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim()
|
||||
}
|
||||
|
||||
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 +121,73 @@ 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))
|
||||
}
|
||||
this._initTheme()
|
||||
applyTranslations()
|
||||
}
|
||||
|
||||
// Light / dark / follow-the-OS. The stored choice is already applied by the inline
|
||||
// script in index.html (before first paint); this only syncs the control and handles
|
||||
// changes. In 'system' mode nothing is stored and no data-theme is set, so the
|
||||
// prefers-color-scheme block in style.css follows the OS live - including a change
|
||||
// made while the app is open, with no listener needed.
|
||||
_initTheme() {
|
||||
const sel = document.getElementById('themeSelect')
|
||||
if (!sel) return
|
||||
sel.value = getTheme()
|
||||
sel.addEventListener('change', e => setTheme(e.target.value))
|
||||
}
|
||||
|
||||
/* ── 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()
|
||||
})
|
||||
|
||||
// Compare: pick two files in one dialog (a chained second file dialog is
|
||||
// blocked by browsers — no user gesture). The embed passes versions +
|
||||
// blame programmatically via compare().
|
||||
const cmpBtn = document.getElementById('compareBtn')
|
||||
const cmpInput = document.getElementById('compareInput')
|
||||
if (cmpBtn && cmpInput) {
|
||||
cmpBtn.addEventListener('click', () => cmpInput.click())
|
||||
cmpInput.addEventListener('change', e => {
|
||||
const files = [...(e.target.files || [])].sort((a, b) => a.name.localeCompare(b.name))
|
||||
e.target.value = ''
|
||||
if (files.length >= 2) this.compare(files[0], files[0].name, files[1], files[1].name)
|
||||
else if (files.length === 1) this._showError(t('compare.pickTwo'))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation
|
||||
document.getElementById('prevPage').addEventListener('click', () => this.changePage(-1))
|
||||
@@ -126,6 +211,23 @@ class DocumentViewer {
|
||||
|
||||
// Sidebar
|
||||
document.getElementById('sidebarToggle').addEventListener('click', () => this._toggleSidebar())
|
||||
// Double-click the sidebar header ("Pages") to close the thumbnail sidebar.
|
||||
document.getElementById('sidebarToolbar')?.addEventListener('dblclick', () => {
|
||||
document.getElementById('outerContainer').classList.remove('sidebar-open')
|
||||
})
|
||||
|
||||
// Re-fit the page whenever the viewer area resizes — toggling the sidebar or
|
||||
// resizing the window changes the available width, and the fit-to-width /
|
||||
// -height / -page modes must track it (otherwise the page stays at its old
|
||||
// scale and clips). Manual zoom levels are left untouched.
|
||||
if ('ResizeObserver' in window) {
|
||||
const FIT_OPTIONS = new Set(['auto', 'page-fit', 'page-width', 'page-height'])
|
||||
new ResizeObserver(() => {
|
||||
if (!this.activeRenderer) return
|
||||
const opt = document.getElementById('scaleSelect').value
|
||||
if (FIT_OPTIONS.has(opt)) this._applyScaleOption(opt)
|
||||
}).observe(document.getElementById('viewerContainer'))
|
||||
}
|
||||
|
||||
// Error bar
|
||||
document.getElementById('errorClose').addEventListener('click', () => {
|
||||
@@ -137,23 +239,61 @@ class DocumentViewer {
|
||||
}
|
||||
|
||||
/* ── File loading ────────────────────────────────────────────────────── */
|
||||
async openFile(file) {
|
||||
const ext = file.name.split('.').pop().toLowerCase()
|
||||
const format = EXT_MAP[ext]
|
||||
// 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()
|
||||
let format = EXT_MAP[ext]
|
||||
|
||||
if (!format) {
|
||||
this._showError(t('err.unsupported', { ext, list: Object.keys(EXT_MAP).join(', ') }))
|
||||
return
|
||||
// Unknown extension: try to read it as text rather than refusing outright. Most files
|
||||
// without a dedicated renderer — config, logs, dotfiles, source in a language not in
|
||||
// CODE_EXTS — are perfectly readable that way, and refusing them is a worse default than
|
||||
// showing them.
|
||||
//
|
||||
// Binaries are the exception: decoding an executable as UTF-8 produces a screenful of
|
||||
// replacement characters, which is less useful than saying so. Sniff the first 4 KB and
|
||||
// keep the error for that case only. Reading just the head keeps this an early return,
|
||||
// before any loading state has been set up.
|
||||
const head = source instanceof ArrayBuffer
|
||||
? source.slice(0, 4096)
|
||||
: await source.slice(0, 4096).arrayBuffer()
|
||||
if (looksBinary(head)) {
|
||||
this._showError(t('err.unsupported', { ext, list: Object.keys(EXT_MAP).join(', ') }))
|
||||
return
|
||||
}
|
||||
format = 'txt'
|
||||
}
|
||||
|
||||
this._setLoading(true)
|
||||
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._clearCompare()
|
||||
this.activeRenderer?.destroy()
|
||||
this.activeRenderer = renderer
|
||||
|
||||
@@ -169,32 +309,129 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Compare two versions ────────────────────────────────────────────── */
|
||||
// Render a version's bytes with a FRESH renderer into a detached node and
|
||||
// extract a diffable text representation — never touches the live viewer.
|
||||
async _extractText(buffer, name) {
|
||||
const ext = (name || '').split('.').pop().toLowerCase()
|
||||
const format = EXT_MAP[ext]
|
||||
const unsupported = () => Object.assign(new Error('unsupported-compare'), { code: 'unsupported-compare', format: format || ext })
|
||||
if (!format) throw unsupported()
|
||||
const renderer = await RENDERER_LOADERS[format]() // fresh, not the cached singleton
|
||||
try {
|
||||
// Renderers that read text straight from their engine (e.g. PDF's text
|
||||
// layer) skip the DOM render entirely.
|
||||
if (typeof renderer.extractText === 'function') {
|
||||
return { pages: await renderer.extractText(buffer, name), format } // string[] — one per page
|
||||
}
|
||||
if (!DIFFABLE.has(format)) throw unsupported()
|
||||
const host = document.createElement('div') // detached — off the live DOM
|
||||
await renderer.load(buffer, host, { currentFileName: name })
|
||||
return { pages: [extractRendered(host, format)], format } // continuous formats: one page
|
||||
} finally {
|
||||
renderer.destroy?.()
|
||||
}
|
||||
}
|
||||
|
||||
// Compare two document versions. `opts`: { blame: { [newLineNo]: {...} }, mode }.
|
||||
async compare(srcA, nameA, srcB, nameB, opts = {}) {
|
||||
this._setLoading(true)
|
||||
this._hideDropzone()
|
||||
try {
|
||||
const toBuf = s => (s instanceof ArrayBuffer ? s : s.arrayBuffer())
|
||||
const [bufA, bufB] = await Promise.all([toBuf(srcA), toBuf(srcB)])
|
||||
const [a, b] = await Promise.all([this._extractText(bufA, nameA), this._extractText(bufB, nameB)])
|
||||
|
||||
this._clearCompare()
|
||||
this.activeRenderer?.destroy()
|
||||
this.activeRenderer = null
|
||||
|
||||
const container = document.getElementById('docContainer')
|
||||
container.innerHTML = ''
|
||||
document.getElementById('thumbsContent').innerHTML = ''
|
||||
|
||||
const page = document.createElement('div')
|
||||
page.className = 'diff-page'
|
||||
container.appendChild(page)
|
||||
document.getElementById('mainContainer').classList.add('is-compare') // full-bleed diff + flat toolbar
|
||||
|
||||
// Each extractor returns its pages (string[]); line them up and diff per page.
|
||||
const aPages = a.pages, bPages = b.pages
|
||||
const pageCount = Math.max(aPages.length, bPages.length)
|
||||
const pages = []
|
||||
for (let i = 0; i < pageCount; i++) pages.push({ leftText: aPages[i] ?? '', rightText: bPages[i] ?? '' })
|
||||
|
||||
const { renderCompare } = await import('./diff-view.js')
|
||||
this._compareCtl = renderCompare(page, {
|
||||
pages, blame: opts.blame || {}, mode: opts.mode || 'side-by-side',
|
||||
})
|
||||
|
||||
// drive the view mode from the top-toolbar dropdown (shown via .is-compare)
|
||||
const modeSel = document.getElementById('compareModeSelect')
|
||||
if (modeSel) {
|
||||
modeSel.value = opts.mode || 'side-by-side'
|
||||
modeSel.onchange = () => this._compareCtl?.setMode(modeSel.value)
|
||||
}
|
||||
|
||||
this.numPages = pageCount; this.currentPage = 1
|
||||
this.updatePageInfo()
|
||||
const badge = document.getElementById('formatBadge')
|
||||
badge.textContent = t('compare.badge')
|
||||
badge.className = 'badge-compare'
|
||||
badge.classList.remove('hidden')
|
||||
document.title = `${nameA} ↔ ${nameB} — ReaderJS`
|
||||
} catch (err) {
|
||||
if (err.code === 'unsupported-compare') {
|
||||
this._showError(t('compare.unsupported', { format: String(err.format || '').toUpperCase() }))
|
||||
} else {
|
||||
console.error('[ReaderJS] compare error:', err)
|
||||
this._showError(t('err.couldNotOpen', { name: `${nameA} ↔ ${nameB}`, msg: err.message }))
|
||||
}
|
||||
} finally {
|
||||
this._setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
_clearCompare() {
|
||||
this._compareCtl?.destroy()
|
||||
this._compareCtl = null
|
||||
document.getElementById('mainContainer')?.classList.remove('is-compare')
|
||||
const modeSel = document.getElementById('compareModeSelect')
|
||||
if (modeSel) modeSel.onchange = null
|
||||
}
|
||||
|
||||
/* ── Page navigation ─────────────────────────────────────────────────── */
|
||||
changePage(delta) {
|
||||
this.goToPage(this.currentPage + delta)
|
||||
}
|
||||
|
||||
goToPage(page) {
|
||||
if (!this.activeRenderer) return
|
||||
if (!this.activeRenderer && !this._compareCtl) return
|
||||
page = Math.max(1, Math.min(this.numPages, page))
|
||||
this.currentPage = page
|
||||
this.activeRenderer.scrollToPage(page)
|
||||
if (this._compareCtl) {
|
||||
this._compareCtl.setPage(page - 1) // compare pages are 0-based
|
||||
document.getElementById('viewerContainer').scrollTop = 0 // show the top of the new page
|
||||
} else {
|
||||
this.activeRenderer.scrollToPage(page)
|
||||
}
|
||||
this.updatePageInfo()
|
||||
}
|
||||
|
||||
@@ -298,8 +535,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 +564,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,45 @@
|
||||
// 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:compare') viewer.compare(m.bufferA, m.nameA, m.bufferB, m.nameB, { blame: m.blame, mode: m.mode })
|
||||
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,92 @@
|
||||
// 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()
|
||||
//
|
||||
// Compare two versions of a text document (txt/md/code/csv/xlsx/docx/rtf/odf/doc):
|
||||
// inst.compare({ source: blobA, name: 'a.md' }, { source: blobB, name: 'b.md' },
|
||||
// { blame: { 12: { author, date, commit, message } }, mode: 'side-by-side' })
|
||||
// or at mount: ReaderJS.mount(el, { compare: { a, b, blame, mode } }).
|
||||
// `blame` is keyed by new-side line number and MUST be plain data — functions do
|
||||
// not survive postMessage. Each change's tooltip shows the blame for its line.
|
||||
//
|
||||
// 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)
|
||||
|
||||
// Structured-clone COPY (no transfer) so the host's own ArrayBuffer isn't neutered.
|
||||
const toBuf = source => Promise.resolve(source instanceof Blob ? source.arrayBuffer() : source)
|
||||
const send = payload => { if (ready) postToFrame(payload); else queued = payload }
|
||||
|
||||
function load(source, name, mime) {
|
||||
toBuf(source).then(buffer => send({ type: 'readerjs:load', buffer, name, mime }))
|
||||
}
|
||||
|
||||
// Compare two versions; a/b are { source: Blob|ArrayBuffer, name }.
|
||||
function compare(a, b, cmp = {}) {
|
||||
Promise.all([toBuf(a.source), toBuf(b.source)]).then(([bufferA, bufferB]) =>
|
||||
send({ type: 'readerjs:compare', bufferA, nameA: a.name, bufferB, nameB: b.name, blame: cmp.blame, mode: cmp.mode }))
|
||||
}
|
||||
|
||||
container.appendChild(iframe)
|
||||
|
||||
// Auto-fire whichever mode was requested at mount.
|
||||
if (opts.compare) compare(opts.compare.a, opts.compare.b, opts.compare)
|
||||
else if (!opts.src && (opts.blob || opts.arrayBuffer)) load(opts.blob || opts.arrayBuffer, opts.name, opts.mime)
|
||||
|
||||
return {
|
||||
load, // swap document at runtime (bytes mode)
|
||||
compare, // compare two versions (with optional blame)
|
||||
setLang(lang) { if (ready) postToFrame({ type: 'readerjs:setLang', lang }) },
|
||||
iframe,
|
||||
destroy() {
|
||||
window.removeEventListener('message', onMessage)
|
||||
iframe.remove()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { BaseRenderer } from './base-renderer.js'
|
||||
|
||||
// CHM (.chm) — Microsoft Compiled HTML Help. CHMate parses the ITSF container
|
||||
// (LZX-decompressing topics) and turns each topic into a sanitized, self-contained
|
||||
// HTML string. CHM is a legacy *and* an active malware vector, so every topic is
|
||||
// treated as hostile: rendered in a sandboxed iframe with no scripts, a strict
|
||||
// CSP, and all resources inlined as blob: URLs — nothing touches the network.
|
||||
|
||||
// CHMate's pure topic renderer, lazy-loaded on first open and shared by every
|
||||
// instance (it carries no per-document state).
|
||||
let renderTopic = null
|
||||
|
||||
export class CHMRenderer extends BaseRenderer {
|
||||
constructor() {
|
||||
super()
|
||||
this._reader = null
|
||||
this._blobs = null
|
||||
this._frame = null
|
||||
this._onFrameClick = this._onFrameClick.bind(this)
|
||||
}
|
||||
|
||||
async load(buffer, container, viewer) {
|
||||
await super.load(buffer, container, viewer)
|
||||
|
||||
const [{ ChmReader }, render] = await Promise.all([
|
||||
import('chmate'),
|
||||
import('chmate/render'),
|
||||
])
|
||||
renderTopic = render.renderTopic
|
||||
|
||||
const reader = ChmReader.open(buffer)
|
||||
this._reader = reader
|
||||
this._blobs = new render.BlobCache(reader)
|
||||
|
||||
container.innerHTML = ''
|
||||
const page = document.createElement('div')
|
||||
page.className = 'doc-page chm-page'
|
||||
page.dataset.page = 1
|
||||
|
||||
// sandbox WITHOUT allow-scripts: topic scripts can never run. allow-same-origin
|
||||
// only lets the host measure height and attach the link-navigation handler.
|
||||
const frame = document.createElement('iframe')
|
||||
frame.className = 'chm-frame'
|
||||
frame.sandbox = 'allow-same-origin'
|
||||
this._frame = frame
|
||||
page.appendChild(frame)
|
||||
container.appendChild(page)
|
||||
|
||||
this._buildContents(reader)
|
||||
|
||||
const start = reader.defaultTopic || reader.listFiles().find((p) => /\.html?$/i.test(p))
|
||||
if (start) {
|
||||
this._navigate(start)
|
||||
} else {
|
||||
frame.srcdoc = '<!DOCTYPE html><meta charset="utf-8"><body style="font:14px sans-serif;padding:24px;color:#555">This .chm has no displayable HTML topic.</body>'
|
||||
}
|
||||
|
||||
this.numPages = 1
|
||||
}
|
||||
|
||||
// Render a topic into the iframe and wire link navigation + height sizing.
|
||||
_navigate(target, frag = '') {
|
||||
const reader = this._reader
|
||||
if (!reader) return
|
||||
const hash = target.indexOf('#')
|
||||
if (hash >= 0) {
|
||||
frag = frag || target.slice(hash + 1)
|
||||
target = target.slice(0, hash)
|
||||
}
|
||||
if (!reader.hasFile(target)) return
|
||||
|
||||
const frame = this._frame
|
||||
frame.onload = () => {
|
||||
const doc = frame.contentDocument
|
||||
if (!doc) return
|
||||
frame.style.height = `${doc.documentElement.scrollHeight}px`
|
||||
doc.addEventListener('click', this._onFrameClick, true)
|
||||
if (frag) {
|
||||
const el = doc.getElementById(frag) || doc.querySelector(`a[name="${CSS.escape(frag)}"]`)
|
||||
if (el) el.scrollIntoView({ block: 'start' })
|
||||
}
|
||||
this._highlightContents(target)
|
||||
}
|
||||
frame.srcdoc = renderTopic(reader, target, this._blobs)
|
||||
}
|
||||
|
||||
// CHMate marks internal links with data-chm-href and external ones with
|
||||
// data-chm-ext (their real href is neutralised to "#"); the host drives both.
|
||||
_onFrameClick(e) {
|
||||
const a = e.target.closest?.('a')
|
||||
if (!a) return
|
||||
const internal = a.getAttribute('data-chm-href')
|
||||
const external = a.getAttribute('data-chm-ext')
|
||||
if (internal) {
|
||||
e.preventDefault()
|
||||
this._navigate(internal, a.getAttribute('data-chm-frag') || '')
|
||||
} else if (external) {
|
||||
e.preventDefault()
|
||||
if (confirm(`Open external link?\n\n${external}`)) window.open(external, '_blank', 'noopener')
|
||||
}
|
||||
}
|
||||
|
||||
// ── Table of contents (.hhc) in the sidebar ───────────────────────────────
|
||||
_buildContents(reader) {
|
||||
const box = document.getElementById('thumbsContent')
|
||||
if (!box) return
|
||||
const tree = reader.getContents()
|
||||
if (!tree?.length) return // leave buildsThumbnailsAsync falsy → "no thumbnails" placeholder
|
||||
this.buildsThumbnailsAsync = true // we fill the sidebar ourselves
|
||||
box.innerHTML = ''
|
||||
const root = document.createElement('div')
|
||||
root.className = 'chm-toc'
|
||||
this._renderNodes(reader, tree, root)
|
||||
box.appendChild(root)
|
||||
}
|
||||
|
||||
_renderNodes(reader, nodes, parent) {
|
||||
for (const node of nodes) {
|
||||
const row = document.createElement('div')
|
||||
row.className = 'chm-toc-row'
|
||||
row.textContent = node.name || '(untitled)'
|
||||
const target = this._nodeTarget(reader, node)
|
||||
if (target) {
|
||||
row.classList.add('chm-toc-link')
|
||||
row.dataset.target = target
|
||||
row.addEventListener('click', () => this._navigate(target))
|
||||
}
|
||||
parent.appendChild(row)
|
||||
if (node.children?.length) {
|
||||
const kids = document.createElement('div')
|
||||
kids.className = 'chm-toc-children'
|
||||
this._renderNodes(reader, node.children, kids)
|
||||
parent.appendChild(kids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TOC "Local" paths are relative to the contents (.hhc) file's location.
|
||||
_nodeTarget(reader, node) {
|
||||
if (node.url || !node.local) return null
|
||||
const abs = reader.resolvePath(reader.contentsPath || '/', node.local).replace(/#.*$/, '')
|
||||
return reader.hasFile(abs) ? abs : null
|
||||
}
|
||||
|
||||
_highlightContents(path) {
|
||||
const box = document.getElementById('thumbsContent')
|
||||
if (!box) return
|
||||
box.querySelectorAll('.chm-toc-active').forEach((r) => r.classList.remove('chm-toc-active'))
|
||||
box.querySelectorAll(`.chm-toc-row[data-target="${CSS.escape(path)}"]`).forEach((r) => r.classList.add('chm-toc-active'))
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this._blobs?.revokeAll()
|
||||
this._blobs = null
|
||||
this._reader = null
|
||||
this._frame = null
|
||||
const box = document.getElementById('thumbsContent')
|
||||
if (box) box.innerHTML = ''
|
||||
super.destroy()
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,45 @@ export class DjVuRenderer extends BaseRenderer {
|
||||
})
|
||||
}
|
||||
|
||||
// Inline new URL(...) so Vite emits the dejaview worker as its own chunk.
|
||||
_spawnWorker() {
|
||||
this._worker = new Worker(new URL('dejaview/src/worker.js', import.meta.url), { type: 'module' })
|
||||
this._worker.onmessage = (e) => {
|
||||
const { id, error } = e.data
|
||||
const p = this._pending.get(id)
|
||||
if (!p) return
|
||||
this._pending.delete(id)
|
||||
error ? p.reject(new Error(error)) : p.resolve(e.data)
|
||||
}
|
||||
}
|
||||
|
||||
// Plain text of the DjVu for the compare view — the worker returns word zones
|
||||
// ({xmin,ymin,xmax,ymax,str}) per page; group them into lines by baseline.
|
||||
// Returns an array of per-page text, so the compare view can diff page-by-page.
|
||||
async extractText(buffer) {
|
||||
this._spawnWorker()
|
||||
try {
|
||||
const meta = await this._call('open', { buffer })
|
||||
const pages = []
|
||||
for (let i = 0; i < (meta.pageCount || 1); i++) {
|
||||
const { words } = await this._call('text', { index: i })
|
||||
const lines = []
|
||||
let line = [], lineY = null
|
||||
for (const w of (words || [])) {
|
||||
const h = (w.ymax - w.ymin) || 10
|
||||
if (lineY != null && Math.abs(w.ymin - lineY) > h * 0.7) { lines.push(line.join(' ')); line = [] }
|
||||
line.push(w.str); lineY = w.ymin
|
||||
}
|
||||
if (line.length) lines.push(line.join(' '))
|
||||
pages.push(lines.join('\n'))
|
||||
}
|
||||
return pages
|
||||
} finally {
|
||||
this._worker?.terminate()
|
||||
this._worker = null
|
||||
}
|
||||
}
|
||||
|
||||
_logical(info) {
|
||||
const dpi = info?.dpi || 300
|
||||
return {
|
||||
@@ -44,17 +83,7 @@ export class DjVuRenderer extends BaseRenderer {
|
||||
await super.load(buffer, container, viewer)
|
||||
const gen = ++this._gen
|
||||
|
||||
// Inline new URL(...) so Vite emits the dejaview worker as its own chunk.
|
||||
this._worker = new Worker(
|
||||
new URL('../../submodules/dejaview/src/worker.js', import.meta.url),
|
||||
{ type: 'module' })
|
||||
this._worker.onmessage = (e) => {
|
||||
const { id, error } = e.data
|
||||
const p = this._pending.get(id)
|
||||
if (!p) return
|
||||
this._pending.delete(id)
|
||||
error ? p.reject(new Error(error)) : p.resolve(e.data)
|
||||
}
|
||||
this._spawnWorker()
|
||||
|
||||
const meta = await this._call('open', { buffer })
|
||||
if (gen !== this._gen) return
|
||||
@@ -120,9 +149,19 @@ export class DjVuRenderer extends BaseRenderer {
|
||||
})
|
||||
}
|
||||
|
||||
_subsample(info) {
|
||||
// downscale factor to keep a render under `capW` px wide (1 = full resolution)
|
||||
_subsample(info, capW) {
|
||||
const w = info?.width || 800
|
||||
return Math.max(1, Math.round(w / Math.min(w, MAX_RENDER_W)))
|
||||
return Math.max(1, Math.round(w / Math.min(w, capW)))
|
||||
}
|
||||
|
||||
// worker render result (transferable rgba) → a ready-to-mount canvas
|
||||
_canvasFromRender(res) {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = res.width
|
||||
canvas.height = res.height
|
||||
canvas.getContext('2d').putImageData(new ImageData(res.rgba, res.width, res.height), 0, 0)
|
||||
return canvas
|
||||
}
|
||||
|
||||
async _renderPage(i) {
|
||||
@@ -131,12 +170,9 @@ export class DjVuRenderer extends BaseRenderer {
|
||||
wrap.dataset.rendered = '1'
|
||||
const gen = this._gen
|
||||
try {
|
||||
const res = await this._call('render', { index: i, subsample: this._subsample(this._infos[i]) })
|
||||
const res = await this._call('render', { index: i, subsample: this._subsample(this._infos[i], MAX_RENDER_W) })
|
||||
if (gen !== this._gen || !this._worker) return
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = res.width
|
||||
canvas.height = res.height
|
||||
canvas.getContext('2d').putImageData(new ImageData(res.rgba, res.width, res.height), 0, 0)
|
||||
const canvas = this._canvasFromRender(res)
|
||||
wrap.innerHTML = ''
|
||||
wrap.appendChild(canvas)
|
||||
} catch {
|
||||
@@ -176,14 +212,10 @@ export class DjVuRenderer extends BaseRenderer {
|
||||
if (!box) return
|
||||
for (let i = 0; i < this.numPages; i++) {
|
||||
const info = this._infos[i]
|
||||
const sub = Math.max(1, Math.round((info?.width || 800) / THUMB_W))
|
||||
let res
|
||||
try { res = await this._call('render', { index: i, subsample: sub }) } catch { continue }
|
||||
try { res = await this._call('render', { index: i, subsample: this._subsample(info, THUMB_W) }) } catch { continue }
|
||||
if (gen !== this._gen || !this._worker) return
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = res.width
|
||||
canvas.height = res.height
|
||||
canvas.getContext('2d').putImageData(new ImageData(res.rgba, res.width, res.height), 0, 0)
|
||||
const canvas = this._canvasFromRender(res)
|
||||
const img = document.createElement('img')
|
||||
img.src = canvas.toDataURL('image/png')
|
||||
const wrap = document.createElement('div')
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { BaseRenderer } from './base-renderer.js'
|
||||
// Registers the <foliate-view> custom element. foliate-js is vendored as a
|
||||
// git submodule (its recommended integration method) and is MIT-licensed.
|
||||
import '../../submodules/foliate-js/view.js'
|
||||
// `makeBook` parses any e-book (epub/mobi/azw3/fb2) into sections; importing the
|
||||
// module also registers the <foliate-view> custom element. foliate-js (MIT)
|
||||
// isn't on npm, so it's a pinned git dependency in package.json.
|
||||
import { makeBook } from 'foliate-js/view.js'
|
||||
import { flattenBlocks } from '../dom-text.js'
|
||||
|
||||
// Reflowable books are styled by injecting CSS into each section document.
|
||||
// "Zoom" maps to font-size since EPUB/MOBI have no fixed page geometry.
|
||||
@@ -10,6 +12,14 @@ const bookCSS = (scale) => `
|
||||
p, li, blockquote, dd { line-height: 1.5; }
|
||||
`
|
||||
|
||||
// Flatten a section document to text, breaking at block boundaries (skipping
|
||||
// SCRIPT/STYLE, whose text isn't content).
|
||||
const BLOCK = new Set(['P','DIV','LI','H1','H2','H3','H4','H5','H6','BLOCKQUOTE',
|
||||
'PRE','TR','SECTION','ARTICLE','FIGCAPTION','DD','DT'])
|
||||
const SKIP = new Set(['SCRIPT', 'STYLE'])
|
||||
const docText = root =>
|
||||
flattenBlocks(root, BLOCK, SKIP).replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n')
|
||||
|
||||
/**
|
||||
* Renders reflowable e-books — EPUB, MOBI and KF8/AZW3 — via foliate-js's
|
||||
* <foliate-view> paginator. Page turns and the page counter are driven by
|
||||
@@ -93,6 +103,26 @@ export class EPUBRenderer extends BaseRenderer {
|
||||
getPageWidth() { return null }
|
||||
getPageHeight() { return null }
|
||||
|
||||
// Plain text of the whole book for the compare view — walk every section's
|
||||
// document (works for epub/mobi/azw3/fb2 via foliate's makeBook).
|
||||
async extractText(buffer, name) {
|
||||
const book = await makeBook(new File([buffer], name || 'book.epub'))
|
||||
try {
|
||||
const parts = []
|
||||
for (const section of (book.sections || [])) {
|
||||
if (typeof section.createDocument !== 'function') continue
|
||||
let doc
|
||||
try { doc = await section.createDocument() } catch { continue }
|
||||
const body = doc?.body || doc?.documentElement
|
||||
const text = body ? docText(body).trim() : ''
|
||||
if (text) parts.push(text)
|
||||
}
|
||||
return [parts.join('\n\n')] // reflowable books compare as a single page
|
||||
} finally {
|
||||
book?.destroy?.()
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (this._onResize) window.removeEventListener('resize', this._onResize)
|
||||
this._onResize = null
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { BaseRenderer } from './base-renderer.js'
|
||||
|
||||
// MHTML (.mht/.mhtml) — a "Web Archive" MIME container holding a saved page plus
|
||||
// its resources. mhtml-to-html unpacks the MIME parts and inlines every resource
|
||||
// as a data: URI, producing one self-contained HTML string.
|
||||
export class MHTMLRenderer extends BaseRenderer {
|
||||
async load(buffer, container, viewer) {
|
||||
await super.load(buffer, container, viewer)
|
||||
|
||||
const { convert } = await import('mhtml-to-html/browser')
|
||||
|
||||
// A saved web page is untrusted content: keep scripts disabled and never hit
|
||||
// the network — resources come inlined from the archive, not from origin.
|
||||
const { data: html } = await convert(new Uint8Array(buffer), {
|
||||
enableScripts: false,
|
||||
fetchMissingResources: false,
|
||||
})
|
||||
|
||||
container.innerHTML = ''
|
||||
|
||||
const page = document.createElement('div')
|
||||
page.className = 'doc-page mhtml-page'
|
||||
page.dataset.page = 1
|
||||
|
||||
// Render in a sandboxed iframe so the page's CSS can't leak into the app and
|
||||
// no script can run (allow-scripts is intentionally omitted). allow-same-origin
|
||||
// only lets us measure the content height to size the frame.
|
||||
const frame = document.createElement('iframe')
|
||||
frame.className = 'mhtml-frame'
|
||||
frame.sandbox = 'allow-same-origin'
|
||||
frame.srcdoc = html
|
||||
frame.addEventListener('load', () => {
|
||||
const doc = frame.contentDocument
|
||||
if (doc) frame.style.height = `${doc.documentElement.scrollHeight}px`
|
||||
})
|
||||
|
||||
page.appendChild(frame)
|
||||
container.appendChild(page)
|
||||
|
||||
this.numPages = 1
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export class PDFRenderer extends BaseRenderer {
|
||||
constructor() {
|
||||
super()
|
||||
this.pdfDoc = null
|
||||
this._task = null
|
||||
this._pageW = 0
|
||||
this._pageH = 0
|
||||
this._observer = null
|
||||
@@ -19,8 +20,8 @@ export class PDFRenderer extends BaseRenderer {
|
||||
async load(buffer, container, viewer) {
|
||||
await super.load(buffer, container, viewer)
|
||||
|
||||
const task = pdfjsLib.getDocument({ data: new Uint8Array(buffer) })
|
||||
this.pdfDoc = await task.promise
|
||||
this._task = pdfjsLib.getDocument({ data: new Uint8Array(buffer) })
|
||||
this.pdfDoc = await this._task.promise
|
||||
this.numPages = this.pdfDoc.numPages
|
||||
|
||||
const first = await this.pdfDoc.getPage(1)
|
||||
@@ -171,10 +172,40 @@ export class PDFRenderer extends BaseRenderer {
|
||||
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}
|
||||
|
||||
// Plain-text of the PDF for the compare view — pulled from pdf.js's text
|
||||
// layer (no canvas render). Lines are split on pdf.js's hasEOL flag and on a
|
||||
// baseline (y) change, so reflowed runs land on the right line.
|
||||
// Returns an array of per-page text, so the compare view can diff page-by-page.
|
||||
async extractText(buffer) {
|
||||
const task = pdfjsLib.getDocument({ data: new Uint8Array(buffer) })
|
||||
const doc = await task.promise
|
||||
const pages = []
|
||||
try {
|
||||
for (let p = 1; p <= doc.numPages; p++) {
|
||||
const { items } = await (await doc.getPage(p)).getTextContent()
|
||||
const lines = []
|
||||
let line = '', lastY = null
|
||||
for (const it of items) {
|
||||
const y = it.transform?.[5]
|
||||
if (line && lastY != null && y != null && Math.abs(y - lastY) > 4) { lines.push(line); line = '' }
|
||||
line += it.str
|
||||
if (y != null) lastY = y
|
||||
if (it.hasEOL) { lines.push(line); line = ''; lastY = null }
|
||||
}
|
||||
if (line) lines.push(line)
|
||||
pages.push(lines.join('\n'))
|
||||
}
|
||||
} finally {
|
||||
await task.destroy() // pdf.js 6: destroy the loading task, not the document proxy
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this._observer?.disconnect()
|
||||
this.pdfDoc?.destroy()
|
||||
this._task?.destroy() // pdf.js 6: destroy the loading task, not the document proxy
|
||||
this.pdfDoc = null
|
||||
this._task = null
|
||||
super.destroy()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { BaseRenderer } from './base-renderer.js'
|
||||
|
||||
// PostScript / EPS (.ps / .eps) — interpreted and rasterized by Riposte, a
|
||||
// pure-JS PostScript interpreter (MIT, zero runtime deps). Each page is rendered
|
||||
// to a <canvas>, following the paged-canvas model the PDF / DjVu / comic
|
||||
// renderers use (a `.postscript-page` per page, CSS `zoom` for scaling).
|
||||
export class PostScriptRenderer extends BaseRenderer {
|
||||
async load(buffer, container, viewer) {
|
||||
await super.load(buffer, container, viewer)
|
||||
|
||||
const [{ loadDocument, pageSize, renderPageToDriver }, { CanvasDriver }] = await Promise.all([
|
||||
import('riposte/engine/document.js'),
|
||||
import('riposte/engine/graphics/canvas-driver.js'),
|
||||
])
|
||||
|
||||
// PostScript is byte-oriented; decode as Latin-1 (1 byte = 1 code unit) so
|
||||
// the source stays byte-exact for the interpreter.
|
||||
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
|
||||
let src = ''
|
||||
for (let i = 0; i < bytes.length; i += 8192) {
|
||||
src += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192))
|
||||
}
|
||||
const doc = loadDocument(src)
|
||||
|
||||
container.innerHTML = ''
|
||||
for (let i = 0; i < doc.pageCount; i++) {
|
||||
const { width, height } = pageSize(doc, i)
|
||||
const page = document.createElement('div')
|
||||
page.className = 'postscript-page'
|
||||
page.dataset.page = String(i + 1)
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(width)) // natural size; CSS zoom scales it
|
||||
canvas.height = Math.max(1, Math.round(height))
|
||||
const ctx = canvas.getContext('2d')
|
||||
// An unsupported operator on one page must not sink the whole document:
|
||||
// keep whatever rendered, warn, and move on to the remaining pages.
|
||||
try {
|
||||
if (ctx) renderPageToDriver(doc, i, new CanvasDriver(ctx))
|
||||
} catch (e) {
|
||||
console.warn(`[PostScript] page ${i + 1} render error:`, e?.message || e)
|
||||
}
|
||||
|
||||
page.appendChild(canvas)
|
||||
container.appendChild(page)
|
||||
}
|
||||
|
||||
const first = doc.pageCount ? pageSize(doc, 0) : { width: 816, height: 1056 }
|
||||
this._pageW = Math.round(first.width) || 816
|
||||
this._pageH = Math.round(first.height) || 1056
|
||||
this.numPages = doc.pageCount || 1
|
||||
}
|
||||
|
||||
setScale(scale) {
|
||||
this.scale = scale
|
||||
this.container?.querySelectorAll('.postscript-page').forEach((el) => {
|
||||
el.style.zoom = scale === 1 ? '' : scale
|
||||
})
|
||||
}
|
||||
|
||||
getPageWidth() { return this._pageW || 816 }
|
||||
getPageHeight() { return this._pageH || null }
|
||||
}
|
||||
+294
-66
@@ -1,17 +1,144 @@
|
||||
/* ── Reset ─────────────────────────────────────────────────────────────── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
/* ── Open-Color palette (https://yeun.github.io/open-color/, MIT) ──────────
|
||||
The subset used by the compare/diff view and by the light theme, so both stay
|
||||
on a principled scale and read as part of the same design. */
|
||||
:root {
|
||||
--oc-gray-0: #f8f9fa;
|
||||
--oc-gray-1: #f1f3f5;
|
||||
--oc-gray-2: #e9ecef;
|
||||
--oc-gray-3: #dee2e6;
|
||||
--oc-gray-4: #ced4da;
|
||||
--oc-gray-5: #adb5bd;
|
||||
--oc-gray-6: #868e96;
|
||||
--oc-gray-7: #495057;
|
||||
--oc-gray-8: #343a40;
|
||||
--oc-gray-9: #212529;
|
||||
--oc-red-1: #ffe3e3;
|
||||
--oc-red-6: #fa5252; --oc-red-6-rgb: 250, 82, 82;
|
||||
--oc-green-1: #d3f9d8;
|
||||
--oc-green-6: #40c057; --oc-green-6-rgb: 64, 192, 87;
|
||||
--oc-blue-3: #74c0fc;
|
||||
--oc-blue-7: #1971c2;
|
||||
--oc-blue-8: #1864ab;
|
||||
--oc-indigo-6: #4c6ef5;
|
||||
}
|
||||
|
||||
/* ── Theme tokens ─────────────────────────────────────────────────────────
|
||||
Three states, and the order below is what makes all three work:
|
||||
* bare :root — the DARK palette, i.e. the app's original look, and
|
||||
the value every rule actually resolves against;
|
||||
* prefers-color-scheme — SYSTEM mode, guarded with :not([data-theme="dark"])
|
||||
so an explicit dark choice still beats a light OS;
|
||||
* [data-theme="light"] — an explicit choice, which must win in both
|
||||
directions, hence a third block rather than relying
|
||||
on the media query alone.
|
||||
"System" is the default: main.js only sets data-theme once the user picks
|
||||
something, so with no stored preference the media query is in charge.
|
||||
Document surfaces (.pdf-page, .image-info, …) are deliberately NOT themed —
|
||||
a page is white paper in both themes; only the chrome around it flips. */
|
||||
:root {
|
||||
--bg-app: #525659; /* the surround the pages sit on */
|
||||
--bg-toolbar: #474747;
|
||||
--bg-sidebar: #3a3a3a;
|
||||
--bg-sidebar-head: #2e2e2e;
|
||||
--bg-field: #636363; /* inputs and selects */
|
||||
--bg-hover: #666;
|
||||
--bg-active: #555;
|
||||
--border: #3a3a3a; /* field outlines */
|
||||
--border-strong: #111; /* structural edges */
|
||||
--border-toolbar: #1a1a1a;
|
||||
--fg: #fff;
|
||||
--fg-strong: #ddd;
|
||||
--fg-muted: #aaa;
|
||||
--fg-faint: #777;
|
||||
--fg-dim: #666;
|
||||
--fg-sep: #888;
|
||||
--dropzone-border: #666;
|
||||
--accent: #90caf9;
|
||||
--accent-rgb: 144, 202, 249;
|
||||
--shadow-toolbar: rgba(0, 0, 0, .45);
|
||||
--shadow-thumb: rgba(0, 0, 0, .5);
|
||||
--diff-bg: var(--oc-gray-9);
|
||||
--diff-fg: var(--oc-gray-3);
|
||||
/* A custom property cannot be interpolated inside url(), so the whole image is
|
||||
the token rather than just its stroke colour. */
|
||||
--select-chevron: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M6 9l6 6 6-6'/></svg>");
|
||||
}
|
||||
|
||||
/* The light palette, defined once and referenced by both selectors below. */
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme="dark"]) {
|
||||
--bg-app: var(--oc-gray-3);
|
||||
--bg-toolbar: var(--oc-gray-0);
|
||||
--bg-sidebar: var(--oc-gray-1);
|
||||
--bg-sidebar-head: var(--oc-gray-2);
|
||||
--bg-field: #fff;
|
||||
--bg-hover: var(--oc-gray-2);
|
||||
--bg-active: var(--oc-gray-3);
|
||||
--border: var(--oc-gray-4);
|
||||
--border-strong: var(--oc-gray-4);
|
||||
--border-toolbar: var(--oc-gray-4);
|
||||
--fg: var(--oc-gray-9);
|
||||
--fg-strong: var(--oc-gray-8);
|
||||
--fg-muted: var(--oc-gray-7);
|
||||
--fg-faint: var(--oc-gray-7);
|
||||
--fg-dim: var(--oc-gray-6);
|
||||
--fg-sep: var(--oc-gray-7);
|
||||
--dropzone-border: var(--oc-gray-6);
|
||||
--accent: var(--oc-blue-8);
|
||||
--accent-rgb: 24, 100, 171;
|
||||
--shadow-toolbar: rgba(0, 0, 0, .18);
|
||||
--shadow-thumb: rgba(0, 0, 0, .25);
|
||||
--diff-bg: var(--oc-gray-0);
|
||||
--diff-fg: var(--oc-gray-9);
|
||||
--select-chevron: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23212529' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M6 9l6 6 6-6'/></svg>");
|
||||
}
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--bg-app: var(--oc-gray-3);
|
||||
--bg-toolbar: var(--oc-gray-0);
|
||||
--bg-sidebar: var(--oc-gray-1);
|
||||
--bg-sidebar-head: var(--oc-gray-2);
|
||||
--bg-field: #fff;
|
||||
--bg-hover: var(--oc-gray-2);
|
||||
--bg-active: var(--oc-gray-3);
|
||||
--border: var(--oc-gray-4);
|
||||
--border-strong: var(--oc-gray-4);
|
||||
--border-toolbar: var(--oc-gray-4);
|
||||
--fg: var(--oc-gray-9);
|
||||
--fg-strong: var(--oc-gray-8);
|
||||
--fg-muted: var(--oc-gray-7);
|
||||
--fg-faint: var(--oc-gray-7);
|
||||
--fg-dim: var(--oc-gray-6);
|
||||
--fg-sep: var(--oc-gray-7);
|
||||
--dropzone-border: var(--oc-gray-6);
|
||||
--accent: var(--oc-blue-8);
|
||||
--accent-rgb: 24, 100, 171;
|
||||
--shadow-toolbar: rgba(0, 0, 0, .18);
|
||||
--shadow-thumb: rgba(0, 0, 0, .25);
|
||||
--diff-bg: var(--oc-gray-0);
|
||||
--diff-fg: var(--oc-gray-9);
|
||||
--select-chevron: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23212529' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M6 9l6 6 6-6'/></svg>");
|
||||
}
|
||||
|
||||
/* Let form controls, scrollbars and the like follow the resolved theme. */
|
||||
:root { color-scheme: dark; }
|
||||
@media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) { color-scheme: light; } }
|
||||
:root[data-theme="light"] { color-scheme: light; }
|
||||
|
||||
/* ── Scrollbars — slim, dark, to match the app chrome ──────────────────── */
|
||||
* { scrollbar-width: thin; scrollbar-color: #5e5e5e transparent; }
|
||||
* { scrollbar-width: thin; scrollbar-color: var(--fg-dim) transparent; }
|
||||
::-webkit-scrollbar { width: 11px; height: 11px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #5a5a5a;
|
||||
background: var(--fg-dim);
|
||||
border: 3px solid transparent; /* breathing room → a slimmer-looking thumb */
|
||||
border-radius: 8px;
|
||||
background-clip: padding-box;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover { background: #787878; background-clip: padding-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background: var(--fg-faint); background-clip: padding-box; }
|
||||
::-webkit-scrollbar-corner { background: transparent; }
|
||||
|
||||
html, body {
|
||||
@@ -19,8 +146,8 @@ html, body {
|
||||
overflow: hidden;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 13px;
|
||||
background: #525659;
|
||||
color: #fff;
|
||||
background: var(--bg-app);
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* ── Outer layout ───────────────────────────────────────────────────────── */
|
||||
@@ -34,8 +161,8 @@ html, body {
|
||||
#sidebarContainer {
|
||||
width: 0;
|
||||
min-width: 0;
|
||||
background: #3a3a3a;
|
||||
border-right: 1px solid #111;
|
||||
background: var(--bg-sidebar);
|
||||
border-right: 1px solid var(--border-strong);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
@@ -50,21 +177,21 @@ html, body {
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 14px;
|
||||
background: #2e2e2e;
|
||||
border-bottom: 1px solid #111;
|
||||
background: var(--bg-sidebar-head);
|
||||
border-bottom: 1px solid var(--border-strong);
|
||||
flex-shrink: 0;
|
||||
min-height: 42px; /* match the main toolbar height */
|
||||
color: #90caf9; /* header icon colour */
|
||||
color: var(--accent); /* header icon colour */
|
||||
}
|
||||
.sidebar-title {
|
||||
color: #bbb;
|
||||
color: var(--fg-strong);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .05em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.thumbs-empty {
|
||||
color: #777;
|
||||
color: var(--fg-faint);
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
padding: 24px 8px;
|
||||
@@ -90,10 +217,10 @@ html, body {
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,.5);
|
||||
box-shadow: 0 1px 4px var(--shadow-thumb);
|
||||
}
|
||||
.thumb-label {
|
||||
color: #aaa;
|
||||
color: var(--fg-muted);
|
||||
font-size: 11px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
@@ -109,9 +236,9 @@ html, body {
|
||||
|
||||
/* ── Toolbar ────────────────────────────────────────────────────────────── */
|
||||
#toolbarContainer {
|
||||
background: #474747;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
box-shadow: 0 2px 5px rgba(0,0,0,.45);
|
||||
background: var(--bg-toolbar);
|
||||
border-bottom: 1px solid var(--border-toolbar);
|
||||
box-shadow: 0 2px 5px var(--shadow-toolbar);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px 6px;
|
||||
@@ -128,7 +255,7 @@ html, body {
|
||||
.toolbar-btn {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #fff;
|
||||
color: var(--fg);
|
||||
cursor: pointer;
|
||||
padding: 5px 6px;
|
||||
border-radius: 3px;
|
||||
@@ -141,14 +268,14 @@ html, body {
|
||||
transition: background 0.1s;
|
||||
user-select: none;
|
||||
}
|
||||
.toolbar-btn:hover:not(:disabled) { background: #666; }
|
||||
.toolbar-btn:active:not(:disabled) { background: #555; }
|
||||
.toolbar-btn:hover:not(:disabled) { background: var(--bg-hover); }
|
||||
.toolbar-btn:active:not(:disabled) { background: var(--bg-active); }
|
||||
.toolbar-btn:disabled { opacity: 0.35; cursor: default; }
|
||||
|
||||
.toolbar-separator {
|
||||
width: 1px;
|
||||
height: 22px;
|
||||
background: #666;
|
||||
background: var(--fg-dim);
|
||||
margin: 0 3px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -158,7 +285,7 @@ html, body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: #ddd;
|
||||
color: var(--fg-strong);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@@ -166,34 +293,36 @@ html, body {
|
||||
width: 48px;
|
||||
height: 21px;
|
||||
padding: 0 5px;
|
||||
background: #636363;
|
||||
border: 1px solid #3a3a3a;
|
||||
background: var(--bg-field);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
color: #fff;
|
||||
color: var(--fg);
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
line-height: 19px; /* center the digit in the 19px content box (21px - 2px border) */
|
||||
font-family: inherit; /* match the toolbar text — UA default is Arial, which sits off the baseline */
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
#pageNumber::-webkit-inner-spin-button,
|
||||
#pageNumber::-webkit-outer-spin-button { -webkit-appearance: none; }
|
||||
#pageNumber:focus { outline: none; border-color: #90caf9; }
|
||||
#pageNumber:focus { outline: none; border-color: var(--accent); }
|
||||
|
||||
.page-sep { color: #888; }
|
||||
.page-sep { color: var(--fg-sep); }
|
||||
|
||||
/* Zoom */
|
||||
#scaleSelect, #langSelect {
|
||||
#scaleSelect, #langSelect, #themeSelect, #compareModeSelect {
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
appearance: none;
|
||||
background-color: #636363;
|
||||
background-color: var(--bg-field);
|
||||
/* slim stroked chevron-down, replacing the chunky native arrow */
|
||||
background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23ffffff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M6 9l6 6 6-6'/></svg>");
|
||||
background-image: var(--select-chevron);
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 6px center;
|
||||
background-size: 12px;
|
||||
border: 1px solid #3a3a3a;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 3px;
|
||||
color: #fff;
|
||||
color: var(--fg);
|
||||
padding: 3px 22px 3px 7px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
@@ -201,12 +330,18 @@ html, body {
|
||||
}
|
||||
/* The scale dropdown holds longer localized labels (e.g. PL "Dopasuj wysokość",
|
||||
RU "По размеру страницы"); give it room so the selected value isn't clipped.
|
||||
A native <select> still sizes to its widest option, so short-label languages
|
||||
(English etc.) stay compact — this is only a ceiling. */
|
||||
#scaleSelect { max-width: 160px; }
|
||||
#scaleSelect:focus, #langSelect:focus { outline: none; }
|
||||
min-width guarantees comfortable slack (not an exact hug of the text), and
|
||||
max-width lets the longest labels grow while keeping it from getting silly. */
|
||||
#scaleSelect { min-width: 140px; max-width: 170px; }
|
||||
#compareModeSelect { min-width: 132px; max-width: 180px; }
|
||||
#scaleSelect:focus, #langSelect:focus, #themeSelect:focus { outline: none; }
|
||||
|
||||
/* Format badge */
|
||||
/* Format badge.
|
||||
It sits between two toolbar separators; with no document open it carries .hidden
|
||||
and the two separators collapse together into a visible double rule. Drop the
|
||||
trailing one in that state - an adjacent-sibling rule reaches it because the
|
||||
hidden badge is still in the DOM between them. */
|
||||
#formatBadge.hidden + .toolbar-separator { display: none; }
|
||||
#formatBadge {
|
||||
padding: 2px 9px;
|
||||
border-radius: 10px;
|
||||
@@ -229,6 +364,9 @@ html, body {
|
||||
#formatBadge.badge-csv { background: #7cb342; color: #fff; }
|
||||
#formatBadge.badge-code { background: #546e7a; color: #fff; }
|
||||
#formatBadge.badge-djvu { background: #3949ab; color: #fff; }
|
||||
#formatBadge.badge-mhtml { background: #8e24aa; color: #fff; }
|
||||
#formatBadge.badge-chm { background: #006064; color: #fff; }
|
||||
#formatBadge.badge-ps { background: #880e4f; color: #fff; }
|
||||
|
||||
/* File input — hidden, triggered by label */
|
||||
#fileInput { display: none; }
|
||||
@@ -236,7 +374,7 @@ html, body {
|
||||
/* ── Loading bar ────────────────────────────────────────────────────────── */
|
||||
#loadingBar {
|
||||
height: 3px;
|
||||
background: #3a3a3a;
|
||||
background: var(--bg-sidebar);
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
@@ -244,7 +382,7 @@ html, body {
|
||||
#loadingBarProgress {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(90deg, #90caf9 0%, #42a5f5 50%, #90caf9 100%);
|
||||
background: linear-gradient(90deg, var(--accent) 0%, rgba(var(--accent-rgb), .55) 50%, var(--accent) 100%);
|
||||
background-size: 200% 100%;
|
||||
animation: loading-sweep 1.4s linear infinite;
|
||||
}
|
||||
@@ -282,7 +420,7 @@ html, body {
|
||||
#viewerContainer {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
background: #525659;
|
||||
background: var(--bg-app);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -297,7 +435,7 @@ html, body {
|
||||
justify-content: center;
|
||||
width: min(90%, 620px);
|
||||
min-height: 360px;
|
||||
border: 2px dashed #666;
|
||||
border: 2px dashed var(--dropzone-border);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: border-color .2s, background .2s;
|
||||
@@ -305,29 +443,29 @@ html, body {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
#dropzone.drag-over {
|
||||
border-color: #90caf9;
|
||||
background: rgba(144,202,249,.07);
|
||||
border-color: var(--accent);
|
||||
background: rgba(var(--accent-rgb), .07);
|
||||
}
|
||||
|
||||
#dropzoneContent {
|
||||
text-align: center;
|
||||
padding: 40px 24px;
|
||||
color: #aaa;
|
||||
color: var(--fg-muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
#dropzoneContent label { pointer-events: auto; }
|
||||
|
||||
#dropzoneIcon { margin-bottom: 16px; }
|
||||
#dropzoneIcon { margin-bottom: 16px; color: var(--accent); } /* the SVG fills with currentColor */
|
||||
|
||||
#dropzoneContent h2 {
|
||||
font-size: 22px;
|
||||
font-weight: 300;
|
||||
color: #ddd;
|
||||
color: var(--fg-strong);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
#dropzoneContent p { font-size: 14px; }
|
||||
#dropzoneContent label {
|
||||
color: #90caf9;
|
||||
color: var(--accent);
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
pointer-events: all;
|
||||
@@ -362,14 +500,17 @@ html, body {
|
||||
.tag-csv { background: #7cb342; color: #fff; }
|
||||
.tag-code { background: #546e7a; color: #fff; }
|
||||
.tag-djvu { background: #3949ab; color: #fff; }
|
||||
.tag-mhtml { background: #8e24aa; color: #fff; }
|
||||
.tag-chm { background: #006064; color: #fff; }
|
||||
.tag-ps { background: #880e4f; color: #fff; }
|
||||
|
||||
.powered-by {
|
||||
margin-top: 22px;
|
||||
font-size: 11px;
|
||||
color: #666;
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.powered-by a { color: #777; }
|
||||
.powered-by a:hover { color: #aaa; }
|
||||
.powered-by a { color: var(--fg-muted); }
|
||||
.powered-by a:hover { color: var(--fg-muted); }
|
||||
|
||||
/* ── Document container ─────────────────────────────────────────────────── */
|
||||
#docContainer {
|
||||
@@ -392,6 +533,15 @@ html, body {
|
||||
}
|
||||
.pdf-page canvas { display: block; }
|
||||
|
||||
/* ── PostScript / EPS pages (Riposte) ──────────────────────────────────── */
|
||||
.postscript-page {
|
||||
background: #fff;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,.5);
|
||||
flex-shrink: 0;
|
||||
line-height: 0;
|
||||
}
|
||||
.postscript-page canvas { display: block; }
|
||||
|
||||
/* ── DjVu pages (DejaView) ─────────────────────────────────────────────── */
|
||||
.djvu-page {
|
||||
background: #fff;
|
||||
@@ -446,6 +596,89 @@ html, body {
|
||||
.image-info dt { color: #666; }
|
||||
.image-info dd { color: #111; word-break: break-word; }
|
||||
|
||||
/* ── Compare / diff view — Open-Color palette, aligned to the app chrome ── */
|
||||
.diff-page {
|
||||
background: var(--diff-bg);
|
||||
color: var(--diff-fg);
|
||||
width: 100%;
|
||||
min-height: 100%;
|
||||
align-self: stretch;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
/* compare mode: full-bleed — flatten the toolbar's drop shadow, drop the viewer
|
||||
padding, and stretch docContainer so the diff meets the toolbar cleanly */
|
||||
#mainContainer.is-compare #toolbarContainer { box-shadow: none; }
|
||||
#mainContainer.is-compare #viewerContainer { padding: 0; }
|
||||
#mainContainer.is-compare #docContainer { align-self: stretch; padding-bottom: 0; }
|
||||
/* compare mode swaps the inert zoom controls for the view-mode dropdown */
|
||||
.compare-only { display: none; }
|
||||
#mainContainer.is-compare #zoomOut,
|
||||
#mainContainer.is-compare #scaleSelect,
|
||||
#mainContainer.is-compare #zoomIn { display: none; }
|
||||
#mainContainer.is-compare .compare-only { display: inline-block; }
|
||||
|
||||
.diff-body { position: relative; flex: 1 1 auto; }
|
||||
.diff-rows { font-family: ui-monospace, 'Cascadia Code', Menlo, Consolas, monospace; font-size: 12.5px; line-height: 1.55; }
|
||||
|
||||
/* side-by-side: aligned two-column grid */
|
||||
.diff-rows.side-by-side { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.diff-cell { display: flex; min-height: 1.55em; border-bottom: 1px solid rgba(255,255,255,.04); }
|
||||
.diff-cell:nth-child(odd) { border-right: 1px solid rgba(255,255,255,.07); }
|
||||
.diff-lineno {
|
||||
flex: 0 0 46px; text-align: right; padding: 1px 8px;
|
||||
color: var(--oc-gray-6); background: rgba(0,0,0,.22); user-select: none; border-right: 1px solid rgba(255,255,255,.05);
|
||||
}
|
||||
.diff-text { flex: 1; padding: 1px 9px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.diff-cell.equal { background: transparent; }
|
||||
.diff-cell.del { background: rgba(var(--oc-red-6-rgb), .15); }
|
||||
.diff-cell.add { background: rgba(var(--oc-green-6-rgb), .16); }
|
||||
.diff-cell.blank { background: rgba(0,0,0,.16); }
|
||||
|
||||
/* unified: single column with old/new gutters + sign */
|
||||
.diff-rows.unified .diff-line { display: flex; min-height: 1.55em; border-bottom: 1px solid rgba(255,255,255,.03); }
|
||||
.diff-rows.unified .diff-lineno { flex: 0 0 40px; }
|
||||
.diff-rows.unified .diff-sign { flex: 0 0 18px; text-align: center; color: var(--oc-gray-6); user-select: none; }
|
||||
.diff-rows.unified .diff-line.del { background: rgba(var(--oc-red-6-rgb), .15); }
|
||||
.diff-rows.unified .diff-line.add { background: rgba(var(--oc-green-6-rgb), .16); }
|
||||
|
||||
/* inline: flowing track-changes */
|
||||
.diff-rows.inline { padding: 12px 18px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.diff-rows.inline .diff-line { display: block; }
|
||||
|
||||
/* ins / del word marks */
|
||||
.diff-text ins, .diff-rows.inline ins { background: rgba(var(--oc-green-6-rgb), .4); color: var(--oc-green-1); text-decoration: none; border-radius: 2px; }
|
||||
.diff-text del, .diff-rows.inline del { background: rgba(var(--oc-red-6-rgb), .4); color: var(--oc-red-1); text-decoration: none; border-radius: 2px; }
|
||||
.diff-rows.inline del { text-decoration: line-through; }
|
||||
|
||||
/* hoverable change rows */
|
||||
.diff-change { cursor: help; }
|
||||
.diff-change:hover { outline: 1px solid var(--oc-blue-3); outline-offset: -1px; }
|
||||
|
||||
/* hover tooltip + pinned popovers (raised gray-8 surface, like the app chrome) */
|
||||
.diff-tooltip, .diff-pin {
|
||||
position: absolute; z-index: 30; width: 260px; max-width: 80%;
|
||||
background: var(--oc-gray-8); color: var(--oc-gray-3); border: 1px solid var(--oc-gray-9); border-radius: 5px;
|
||||
box-shadow: 0 4px 16px rgba(0,0,0,.55); padding: 6px 10px 10px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 12px;
|
||||
}
|
||||
.diff-pin { box-shadow: 0 5px 22px rgba(0,0,0,.6); }
|
||||
.diff-tooltip.hidden { display: none; }
|
||||
.diff-tip-head { display: flex; justify-content: flex-end; margin: -2px -4px 2px 0; }
|
||||
.diff-pin-btn, .diff-pin-close {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
background: transparent; border: none; cursor: pointer;
|
||||
padding: 3px; border-radius: 3px; color: var(--oc-gray-5);
|
||||
}
|
||||
.diff-pin-btn:hover, .diff-pin-close:hover { background: rgba(255,255,255,.1); color: #fff; }
|
||||
.diff-tip-body h3 { font-size: 10px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: var(--oc-gray-6); margin-bottom: 6px; }
|
||||
.diff-tip-body dl { display: grid; grid-template-columns: auto 1fr; gap: 3px 10px; }
|
||||
.diff-tip-body dt { color: var(--oc-gray-6); }
|
||||
.diff-tip-body dd { color: var(--oc-gray-3); word-break: break-word; }
|
||||
.diff-tip-note { color: var(--oc-gray-6); font-style: italic; }
|
||||
|
||||
#formatBadge.badge-compare { background: var(--oc-indigo-6); color: #fff; }
|
||||
|
||||
/* ── EPUB / MOBI (foliate-js) ──────────────────────────────────────────── */
|
||||
.epub-view {
|
||||
display: block;
|
||||
@@ -529,15 +762,17 @@ html, body {
|
||||
.doc-page .docbox p { margin: 0; }
|
||||
.doc-page h3.sec { font-size: 11px; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; color: #888; margin: 22px 0 8px; padding-top: 14px; border-top: 1px solid #e0e0e0; }
|
||||
|
||||
/* ── ODF iframe wrapper ─────────────────────────────────────────────────── */
|
||||
.odf-frame {
|
||||
background: #fff;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,.5);
|
||||
width: 816px;
|
||||
height: 1056px;
|
||||
border: none;
|
||||
display: block;
|
||||
}
|
||||
/* ── MHTML / CHM: untrusted full-document HTML in a sandboxed iframe ─────── */
|
||||
.doc-page.mhtml-page, .doc-page.chm-page { padding: 0; overflow: visible; height: auto; }
|
||||
.mhtml-frame, .chm-frame { display: block; width: 100%; border: 0; }
|
||||
|
||||
/* CHM table-of-contents sidebar */
|
||||
.chm-toc { padding: 6px 0; font-size: 13px; }
|
||||
.chm-toc-children { margin-left: 11px; }
|
||||
.chm-toc-row { padding: 3px 10px; color: #c8c8d0; border-radius: 4px; line-height: 1.35; }
|
||||
.chm-toc-row.chm-toc-link { cursor: pointer; }
|
||||
.chm-toc-row.chm-toc-link:hover { background: rgba(255,255,255,.08); color: #fff; }
|
||||
.chm-toc-row.chm-toc-active { background: rgba(120,160,255,.22); color: #fff; }
|
||||
|
||||
/* ── Utilities ──────────────────────────────────────────────────────────── */
|
||||
.hidden { display: none !important; }
|
||||
@@ -593,13 +828,6 @@ html, body {
|
||||
break-after: page;
|
||||
}
|
||||
|
||||
/* ODF iframe */
|
||||
.odf-frame {
|
||||
box-shadow: none;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
/* PDF print layer takes over */
|
||||
#printLayer {
|
||||
display: block;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user