Merge pull request #1 from Alpaq92/feat/djvu-support

feat: DjVu (.djvu/.djv) support via DejaView + scale-dropdown fit fix
This commit is contained in:
2026-06-25 14:50:02 +02:00
committed by GitHub
7 changed files with 246 additions and 1 deletions
+3
View File
@@ -19,3 +19,6 @@
[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
+2
View File
@@ -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) |
| DjVu | `.djvu` `.djv` | DejaView |
| ODF — Writer, Calc, Impress | `.odt` `.ods` `.odp` `.odg` | JSZip + DOMParser |
| Rich Text Format | `.rtf` | RTF.js |
| Legacy Word 97–2003 | `.doc` | JSDoc |
@@ -50,6 +51,7 @@ ReaderJS is built on these open-source libraries:
| Library | Author / Source | Role |
|---------|----------------|------|
| **[PDF.js](https://github.com/mozilla/pdf.js)** | Mozilla Foundation | PDF rendering (via `pdfjs-dist`) |
| **[DejaView](https://github.com/Alpaq92/dejaview)** | Alpaq92 | Pure-JS DjVu decoder/renderer — clean-room implementation of the public format (cross-referenced against MIT [DjvuNet](https://github.com/DjvuNet/DjvuNet)), no GPL DjVuLibre code |
| **[JSDoc](https://github.com/Alpaq92/JSDoc)** | Alpaq92 | Binary `.doc` (Word 97–2003) reading and rendering — pure JS, zero dependencies, clean-room [MS-CFB] / [MS-DOC] implementation |
| **[mammoth.js](https://github.com/mwilliamson/mammoth.js)** | Michael Williamson | `.docx` (Word Open XML) → HTML conversion |
| **[PptxViewJS](https://github.com/gptsci/pptxviewjs)** | Alex Wong / gptsci | `.pptx` (PowerPoint) slide rendering to canvas |
+3 -1
View File
@@ -115,7 +115,7 @@
</svg>
</label>
<input id="fileInput" type="file"
accept=".pdf,.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,.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"
aria-label="Open document file" data-i18n-aria="aria.openFile" />
</div>
</div>
@@ -153,6 +153,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-djvu">DJVU</span>
<span class="format-tag tag-odf">ODT</span>
<span class="format-tag tag-odf">ODS</span>
<span class="format-tag tag-odf">ODP</span>
@@ -182,6 +183,7 @@
<div class="powered-by">
<span data-i18n="dropzone.poweredBy">Powered by</span>
<a href="https://github.com/mozilla/pdf.js" target="_blank" rel="noopener">PDF.js</a>
· <a href="https://github.com/Alpaq92/dejaview" target="_blank" rel="noopener">DejaView</a>
· <a href="https://github.com/Alpaq92/JSDoc" target="_blank" rel="noopener">JSDoc</a>
· <a href="https://github.com/tbluemel/rtf.js" target="_blank" rel="noopener">RTF.js</a>
· <a href="https://github.com/mwilliamson/mammoth.js" target="_blank" rel="noopener">mammoth.js</a>
+3
View File
@@ -12,6 +12,7 @@ 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'
const CODE_EXTS = ['js','mjs','cjs','jsx','ts','tsx','json','jsonc','xml','html','htm',
@@ -20,6 +21,7 @@ const CODE_EXTS = ['js','mjs','cjs','jsx','ts','tsx','json','jsonc','xml','html'
const EXT_MAP = {
pdf: 'pdf',
djvu: 'djvu', djv: 'djvu',
odt: 'odf', ods: 'odf', odp: 'odf', odg: 'odf', odm: 'odf', odf: 'odf',
rtf: 'rtf',
docx: 'docx',
@@ -54,6 +56,7 @@ class DocumentViewer {
xlsx: new XLSXRenderer(),
csv: new CSVRenderer(),
code: new CodeRenderer(),
djvu: new DjVuRenderer(),
}
this.activeRenderer = null
this.currentPage = 1
+218
View File
@@ -0,0 +1,218 @@
import { BaseRenderer } from './base-renderer.js'
const MAX_RENDER_W = 2000 // cap page render resolution (crisp at fit + moderate zoom)
const THUMB_W = 200
/**
* Renders DjVu documents (.djvu / .djv) with DejaView (MIT) — a pure-JS DjVu
* decoder that runs in a Web Worker. Pages are rendered lazily on scroll (DjVu
* files are typically large scanned books) and cleared when far off-screen.
*/
export class DjVuRenderer extends BaseRenderer {
constructor() {
super()
this._worker = null
this._reqId = 0
this._pending = new Map()
this._infos = []
this._pageW = 800
this._pageH = 1000
this._gen = 0
this._renderObs = null
this._pageObs = null
this.defaultScaleOption = 'page-height'
this.buildsThumbnailsAsync = true
}
_call(type, params) {
return new Promise((resolve, reject) => {
const id = ++this._reqId
this._pending.set(id, { resolve, reject })
this._worker.postMessage({ id, type, ...params })
})
}
_logical(info) {
const dpi = info?.dpi || 300
return {
w: Math.max(1, Math.round((info?.width || 800) * 96 / dpi)),
h: Math.max(1, Math.round((info?.height || 1000) * 96 / dpi)),
}
}
async load(buffer, container, viewer) {
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)
}
const meta = await this._call('open', { buffer })
if (gen !== this._gen) return
this.numPages = meta.pageCount || 1
this._infos = meta.infos || []
const l0 = this._logical(this._infos[0])
this._pageW = l0.w
this._pageH = l0.h
container.innerHTML = ''
for (let i = 0; i < this.numPages; i++) {
const lg = this._logical(this._infos[i])
const wrap = document.createElement('div')
wrap.className = 'djvu-page'
wrap.dataset.page = i + 1
wrap.dataset.lw = lg.w
wrap.dataset.lh = lg.h
container.appendChild(wrap)
}
this.setScale(this.scale) // size the placeholders
this._attachObservers()
this._renderWindow(0) // first pages right away
this._buildThumbnails(gen)
}
// Render a small window around a page proactively (navigation + initial view),
// so rendering never depends solely on the scroll IntersectionObserver.
_renderWindow(center) {
for (let i = center - 1; i <= center + 1; i++) {
if (i >= 0 && i < this.numPages) this._renderPage(i)
}
}
/* ── Lazy rendering ──────────────────────────────────────────────────── */
_attachObservers() {
const root = this.container.parentElement
// render pages near the viewport; drop their canvas when they leave (bounds memory)
this._renderObs = new IntersectionObserver(entries => {
entries.forEach(e => {
const i = +e.target.dataset.page - 1
if (e.isIntersecting) this._renderPage(i)
else this._clearPage(e.target)
})
}, { root, rootMargin: '150% 0px', threshold: 0 })
// track the current page (most visible)
this._pageObs = new IntersectionObserver(entries => {
let best = { ratio: 0, page: this.viewer?.currentPage || 1 }
entries.forEach(e => {
if (e.intersectionRatio > best.ratio) best = { ratio: e.intersectionRatio, page: +e.target.dataset.page }
})
if (best.ratio > 0 && this.viewer && best.page !== this.viewer.currentPage) {
this.viewer.currentPage = best.page
this.viewer.updatePageInfo()
this._highlightThumb(best.page)
}
}, { root, threshold: [0, 0.25, 0.5, 0.75, 1] })
this.container.querySelectorAll('.djvu-page').forEach(el => {
this._renderObs.observe(el)
this._pageObs.observe(el)
})
}
_subsample(info) {
const w = info?.width || 800
return Math.max(1, Math.round(w / Math.min(w, MAX_RENDER_W)))
}
async _renderPage(i) {
const wrap = this.container?.querySelector(`.djvu-page[data-page="${i + 1}"]`)
if (!wrap || wrap.dataset.rendered) return
wrap.dataset.rendered = '1'
const gen = this._gen
try {
const res = await this._call('render', { index: i, subsample: this._subsample(this._infos[i]) })
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)
wrap.innerHTML = ''
wrap.appendChild(canvas)
} catch {
wrap.dataset.rendered = '' // allow a later retry
}
}
_clearPage(wrap) {
if (wrap.dataset.rendered) {
wrap.innerHTML = ''
wrap.dataset.rendered = ''
}
}
/* ── Zoom (CSS — placeholders + canvases scale together) ─────────────── */
setScale(scale) {
this.scale = scale
this.container?.querySelectorAll('.djvu-page').forEach(el => {
el.style.width = `${Math.round((+el.dataset.lw || this._pageW) * scale)}px`
el.style.height = `${Math.round((+el.dataset.lh || this._pageH) * scale)}px`
})
}
getPageWidth() { return this._pageW }
getPageHeight() { return this._pageH }
scrollToPage(pageNum) {
const el = this.container?.querySelector(`.djvu-page[data-page="${pageNum}"]`)
if (!el) return
this._renderWindow(pageNum - 1) // render target (+ neighbours) regardless of the observer
el.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
/* ── Thumbnails ──────────────────────────────────────────────────────── */
async _buildThumbnails(gen) {
const box = document.getElementById('thumbsContent')
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 }
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 img = document.createElement('img')
img.src = canvas.toDataURL('image/png')
const wrap = document.createElement('div')
wrap.className = 'thumb'
wrap.dataset.thumbPage = i + 1
const lbl = document.createElement('div')
lbl.className = 'thumb-label'
lbl.textContent = i + 1
wrap.append(img, lbl)
wrap.addEventListener('click', () => this.viewer?.goToPage(i + 1))
box.appendChild(wrap)
}
this._highlightThumb(this.viewer?.currentPage || 1)
}
_highlightThumb(pageNum) {
document.querySelectorAll('#thumbsContent .thumb').forEach(t => {
t.classList.toggle('active', +t.dataset.thumbPage === pageNum)
})
}
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()
}
}
+16
View File
@@ -199,6 +199,11 @@ html, body {
cursor: pointer;
max-width: 110px;
}
/* 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; }
/* Format badge */
@@ -223,6 +228,7 @@ html, body {
#formatBadge.badge-xlsx { background: #217346; color: #fff; }
#formatBadge.badge-csv { background: #7cb342; color: #fff; }
#formatBadge.badge-code { background: #546e7a; color: #fff; }
#formatBadge.badge-djvu { background: #3949ab; color: #fff; }
/* File input — hidden, triggered by label */
#fileInput { display: none; }
@@ -355,6 +361,7 @@ html, body {
.tag-xlsx { background: #217346; color: #fff; }
.tag-csv { background: #7cb342; color: #fff; }
.tag-code { background: #546e7a; color: #fff; }
.tag-djvu { background: #3949ab; color: #fff; }
.powered-by {
margin-top: 22px;
@@ -385,6 +392,15 @@ html, body {
}
.pdf-page canvas { display: block; }
/* ── DjVu pages (DejaView) ─────────────────────────────────────────────── */
.djvu-page {
background: #fff;
box-shadow: 0 2px 10px rgba(0,0,0,.5);
flex-shrink: 0;
line-height: 0;
}
.djvu-page canvas { display: block; width: 100%; height: 100%; }
/* ── Comic pages (CBZ / CBR / CBT) ─────────────────────────────────────── */
.comic-page {
background: #fff;
Submodule submodules/dejaview added at 5a4ef8a81c