diff --git a/EMBEDDING.md b/EMBEDDING.md index 479eced..69a1f16 100644 --- a/EMBEDDING.md +++ b/EMBEDDING.md @@ -84,9 +84,10 @@ is not neutered). The host↔iframe handshake is origin-checked and same-origin ## Comparing two versions (with blame) -For text documents (txt, md, source code, csv/tsv, docx, rtf, odf, doc, xlsx) you -can show a diff of two versions, with each change carrying **blame** the host -supplies: +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, {}) @@ -109,8 +110,8 @@ Or compare straight from `mount`: `ReaderJS.mount(el, { compare: { a, b, blame, - 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`). -- Canvas/reflowable formats (pdf, djvu, images, comics, pptx, epub) aren't text-comparable - and show an "unavailable" message. +- Only image, comic-archive and slide (PPTX) formats have no extractable text and + show an "unavailable" message. ## Content-Security-Policy diff --git a/README.md b/README.md index 910e337..7c6105c 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ To give it a try without installing anything, visit the [live demo](https://alpa - PDF.js-inspired UI β€” sidebar thumbnails, page navigation, zoom, print - Drag & drop or browse to open files -- Compare two versions of a text document (side-by-side / unified / inline) with pinnable, blame-aware tooltips +- Compare two versions of a document β€” PDF, e-books, Office and text formats (side-by-side / unified / inline) with pinnable, blame-aware tooltips - 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) diff --git a/src/renderers/djvu-renderer.js b/src/renderers/djvu-renderer.js index c66e96d..b2b3ce0 100644 --- a/src/renderers/djvu-renderer.js +++ b/src/renderers/djvu-renderer.js @@ -32,6 +32,42 @@ 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. + async extractText(buffer) { + this._spawnWorker() + try { + const meta = await this._call('open', { buffer }) + const lines = [] + for (let i = 0; i < (meta.pageCount || 1); i++) { + const { words } = await this._call('text', { index: i }) + 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(' ')) + } + return lines.join('\n') + } finally { + this._worker?.terminate() + this._worker = null + } + } + _logical(info) { const dpi = info?.dpi || 300 return { @@ -44,17 +80,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('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 diff --git a/src/renderers/epub-renderer.js b/src/renderers/epub-renderer.js index fad234c..c004a59 100644 --- a/src/renderers/epub-renderer.js +++ b/src/renderers/epub-renderer.js @@ -1,7 +1,8 @@ import { BaseRenderer } from './base-renderer.js' -// Registers the custom element. foliate-js (MIT) isn't published -// to npm, so it's pinned to a commit as a git dependency in package.json. -import 'foliate-js/view.js' +// `makeBook` parses any e-book (epub/mobi/azw3/fb2) into sections; importing the +// module also registers the 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' // 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 +11,27 @@ const bookCSS = (scale) => ` p, li, blockquote, dd { line-height: 1.5; } ` +// Flatten a section document to text, breaking at block boundaries. +const BLOCK = new Set(['P','DIV','LI','H1','H2','H3','H4','H5','H6','BLOCKQUOTE', + 'PRE','TR','SECTION','ARTICLE','FIGCAPTION','DD','DT']) +function docText(root) { + 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 (tag === 'SCRIPT' || tag === 'STYLE') continue + walk(child) + if (BLOCK.has(tag)) out += '\n' + } + } + } + walk(root) + return out.replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n') +} + /** * Renders reflowable e-books β€” EPUB, MOBI and KF8/AZW3 β€” via foliate-js's * paginator. Page turns and the page counter are driven by @@ -93,6 +115,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') + } finally { + book?.destroy?.() + } + } + destroy() { if (this._onResize) window.removeEventListener('resize', this._onResize) this._onResize = null