-
Notifications
You must be signed in to change notification settings - Fork 21
/
epub_module.js
413 lines (369 loc) · 14.2 KB
/
epub_module.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//import './foliate-js/foliate-js/view.js'
//const view = document.createElement('foliate-view')
//document.body.append(view)
/*
view.addEventListener('relocate', e => {
console.log('location changed')
console.log(e.detail)
})
const book =
await view.open(book)
await view.goTo()
*/
import './foliate-js/view.js'
import { createTOCView } from './foliate-js/ui/tree.js'
import { createMenu } from './foliate-js/ui/menu.js'
import { Overlayer } from './foliate-js/overlayer.js'
const isZip = async file => {
const arr = new Uint8Array(await file.slice(0, 4).arrayBuffer())
return arr[0] === 0x50 && arr[1] === 0x4b && arr[2] === 0x03 && arr[3] === 0x04
}
const isPDF = async file => {
const arr = new Uint8Array(await file.slice(0, 5).arrayBuffer())
return arr[0] === 0x25
&& arr[1] === 0x50 && arr[2] === 0x44 && arr[3] === 0x46
&& arr[4] === 0x2d
}
const makeZipLoader = async file => {
const { configure, ZipReader, BlobReader, TextWriter, BlobWriter } =
await import('./foliate-js/vendor/zip.js')
configure({ useWebWorkers: false })
const reader = new ZipReader(new BlobReader(file))
const entries = await reader.getEntries()
const map = new Map(entries.map(entry => [entry.filename, entry]))
const load = f => (name, ...args) =>
map.has(name) ? f(map.get(name), ...args) : null
const loadText = load(entry => entry.getData(new TextWriter()))
const loadBlob = load((entry, type) => entry.getData(new BlobWriter(type)))
const getSize = name => map.get(name)?.uncompressedSize ?? 0
return { entries, loadText, loadBlob, getSize }
}
const getFileEntries = async entry => entry.isFile ? entry
: (await Promise.all(Array.from(
await new Promise((resolve, reject) => entry.createReader()
.readEntries(entries => resolve(entries), error => reject(error))),
getFileEntries))).flat()
const makeDirectoryLoader = async entry => {
const entries = await getFileEntries(entry)
const files = await Promise.all(
entries.map(entry => new Promise((resolve, reject) =>
entry.file(file => resolve([file, entry.fullPath]),
error => reject(error)))))
const map = new Map(files.map(([file, path]) =>
[path.replace(entry.fullPath + '/', ''), file]))
const decoder = new TextDecoder()
const decode = x => x ? decoder.decode(x) : null
const getBuffer = name => map.get(name)?.arrayBuffer() ?? null
const loadText = async name => decode(await getBuffer(name))
const loadBlob = name => map.get(name)
const getSize = name => map.get(name)?.size ?? 0
return { loadText, loadBlob, getSize }
}
const isCBZ = ({ name, type }) =>
type === 'application/vnd.comicbook+zip' || name.endsWith('.cbz')
const isFB2 = ({ name, type }) =>
type === 'application/x-fictionbook+xml' || name.endsWith('.fb2')
const isFBZ = ({ name, type }) =>
type === 'application/x-zip-compressed-fb2'
|| name.endsWith('.fb2.zip') || name.endsWith('.fbz')
window.load_epub = async file => {
let book
if (file.isDirectory) {
const loader = await makeDirectoryLoader(file)
const { EPUB } = await import('./foliate-js/epub.js')
book = await new EPUB(loader).init()
}
else if (!file.size) throw new Error('File not found')
else if (await isZip(file)) {
const loader = await makeZipLoader(file)
if (isCBZ(file)) {
const { makeComicBook } = await import('./foliate-js/comic-book.js')
book = makeComicBook(loader, file)
} else if (isFBZ(file)) {
const { makeFB2 } = await import('./foliate-js/fb2.js')
const { entries } = loader
const entry = entries.find(entry => entry.filename.endsWith('.fb2'))
const blob = await loader.loadBlob((entry ?? entries[0]).filename)
book = await makeFB2(blob)
} else {
const { EPUB } = await import('./foliate-js/epub.js')
book = await new EPUB(loader).init()
}
}
else if (await isPDF(file)) {
const { makePDF } = await import('./foliate-js/pdf.js')
book = await makePDF(file)
}
else {
const { isMOBI, MOBI } = await import('./foliate-js/mobi.js')
if (await isMOBI(file)) {
const fflate = await import('./foliate-js/vendor/fflate.js')
book = await new MOBI({ unzlib: fflate.unzlibSync }).open(file)
} else if (isFB2(file)) {
const { makeFB2 } = await import('./foliate-js/fb2.js')
book = await makeFB2(file)
}
}
if (!book) throw new Error('File type not supported');
console.log("epub book: ", book);
//const view = document.createElement('foliate-view')
//document.body.append(view)
//await view.open(book)
//return view
return book;
}
const getCSS = ({ spacing, justify, hyphenate }) => `
@namespace epub "http://www.idpf.org/2007/ops";
html {
color-scheme: light dark;
}
/* https://github.com/whatwg/html/issues/5426 */
@media (prefers-color-scheme: dark) {
a:link {
color: lightblue;
}
}
p, li, blockquote, dd {
line-height: ${spacing};
text-align: ${justify ? 'justify' : 'start'};
-webkit-hyphens: ${hyphenate ? 'auto' : 'manual'};
hyphens: ${hyphenate ? 'auto' : 'manual'};
-webkit-hyphenate-limit-before: 3;
-webkit-hyphenate-limit-after: 2;
-webkit-hyphenate-limit-lines: 2;
hanging-punctuation: allow-end last;
widows: 2;
}
/* prevent the above from overriding the align attribute */
[align="left"] { text-align: left; }
[align="right"] { text-align: right; }
[align="center"] { text-align: center; }
[align="justify"] { text-align: justify; }
pre {
white-space: pre-wrap !important;
}
aside[epub|type~="endnote"],
aside[epub|type~="footnote"],
aside[epub|type~="note"],
aside[epub|type~="rearnote"] {
display: none;
}
`
const $ = document.querySelector.bind(document)
const locales = 'en'
const percentFormat = new Intl.NumberFormat(locales, { style: 'percent' })
class Reader {
#tocView
style = {
spacing: 1.4,
justify: true,
hyphenate: true,
}
annotations = new Map()
annotationsByValue = new Map()
closeSideBar() {
$('#dimming-overlay').classList.remove('show')
$('#side-bar').classList.remove('show')
}
constructor() {
$('#side-bar-button').addEventListener('click', () => {
$('#dimming-overlay').classList.add('show')
$('#side-bar').classList.add('show')
})
$('#dimming-overlay').addEventListener('click', () => this.closeSideBar())
const menu = createMenu([
{
name: 'layout',
label: 'Layout',
type: 'radio',
items: [
['Paginated', 'paginated'],
['Scrolled', 'scrolled'],
],
onclick: value => {
this.view?.renderer.setAttribute('flow', value)
},
},
])
menu.element.classList.add('menu')
$('#menu-button').append(menu.element)
$('#menu-button > button').addEventListener('click', () =>
menu.element.classList.toggle('show'))
menu.groups.layout.select('paginated')
}
async open(file) {
this.view = await getView(file)
this.view.addEventListener('load', this.#onLoad.bind(this))
this.view.addEventListener('relocate', this.#onRelocate.bind(this))
const { book } = this.view
this.view.renderer.setStyles?.(getCSS(this.style))
this.view.renderer.next()
$('#header-bar').style.visibility = 'visible'
$('#nav-bar').style.visibility = 'visible'
$('#left-button').addEventListener('click', () => this.view.goLeft())
$('#right-button').addEventListener('click', () => this.view.goRight())
const slider = $('#progress-slider')
slider.dir = book.dir
slider.addEventListener('input', e =>
this.view.goToFraction(parseFloat(e.target.value)))
for (const fraction of this.view.getSectionFractions()) {
const option = document.createElement('option')
option.value = fraction
$('#tick-marks').append(option)
}
document.addEventListener('keydown', this.#handleKeydown.bind(this))
const title = book.metadata?.title ?? 'Untitled Book'
document.title = title
$('#side-bar-title').innerText = title
const author = book.metadata?.author
$('#side-bar-author').innerText = typeof author === 'string' ? author
: author
?.map(author => typeof author === 'string' ? author : author.name)
?.join(', ')
?? ''
Promise.resolve(book.getCover?.())?.then(blob =>
blob ? $('#side-bar-cover').src = URL.createObjectURL(blob) : null)
const toc = book.toc
if (toc) {
this.#tocView = createTOCView(toc, href => {
this.view.goTo(href).catch(e => console.error(e))
this.closeSideBar()
})
$('#toc-view').append(this.#tocView.element)
}
// load and show highlights embedded in the file by Calibre
const bookmarks = await book.getCalibreBookmarks?.()
if (bookmarks) {
const { fromCalibreHighlight } = await import('./foliate-js/epubcfi.js')
for (const obj of bookmarks) {
if (obj.type === 'highlight') {
const value = fromCalibreHighlight(obj)
const color = obj.style.which
const note = obj.notes
const annotation = { value, color, note }
const list = this.annotations.get(obj.spine_index)
if (list) list.push(annotation)
else this.annotations.set(obj.spine_index, [annotation])
this.annotationsByValue.set(value, annotation)
}
}
this.view.addEventListener('create-overlay', e => {
const { index } = e.detail
const list = this.annotations.get(index)
if (list) for (const annotation of list)
this.view.addAnnotation(annotation)
})
this.view.addEventListener('draw-annotation', e => {
const { draw, annotation } = e.detail
const { color } = annotation
draw(Overlayer.highlight, { color })
})
this.view.addEventListener('show-annotation', e => {
const annotation = this.annotationsByValue.get(e.detail.value)
if (annotation.note) alert(annotation.note)
})
}
}
#handleKeydown(event) {
const k = event.key
if (k === 'ArrowLeft' || k === 'h') this.view.goLeft()
else if(k === 'ArrowRight' || k === 'l') this.view.goRight()
}
#onLoad({ detail: { doc } }) {
doc.addEventListener('keydown', this.#handleKeydown.bind(this))
}
#onRelocate({ detail }) {
const { fraction, location, tocItem, pageItem } = detail
const percent = percentFormat.format(fraction)
const loc = pageItem
? `Page ${pageItem.label}`
: `Loc ${location.current}`
const slider = $('#progress-slider')
slider.style.visibility = 'visible'
slider.value = fraction
slider.title = `${percent} · ${loc}`
if (tocItem?.href) this.#tocView?.setCurrentHref?.(tocItem.href)
}
}
/*
const open = async file => {
// document.body.removeChild($('#drop-target'))
const reader = new Reader()
globalThis.reader = reader
await reader.open(file)
}
*/
/*
const dragOverHandler = e => e.preventDefault()
const dropHandler = e => {
e.preventDefault()
const item = Array.from(e.dataTransfer.items)
.find(item => item.kind === 'file')
if (item) {
const entry = item.webkitGetAsEntry()
open(entry.isFile ? item.getAsFile() : entry).catch(e => console.error(e))
}
}
const dropTarget = $('#drop-target')
dropTarget.addEventListener('drop', dropHandler)
dropTarget.addEventListener('dragover', dragOverHandler)
$('#file-input').addEventListener('change', e =>
open(e.target.files[0]).catch(e => console.error(e)))
$('#file-button').addEventListener('click', () => $('#file-input').click())
const params = new URLSearchParams(location.search)
const url = params.get('url')
if (url) fetch(url)
.then(res => res.blob())
.then(blob => open(new File([blob], new URL(url).pathname)))
.catch(e => console.error(e))
else dropTarget.style.visibility = 'visible'
*/
//import parser from './foliate-js/epub_parser/index.js'
//import EPUBJS from './foliate-js/js/epub.min.js';
/*
console.log('epub content:', parser(binaryData))
console.log('epub content:', parser('/path/to/file.epub', {
type: 'path'
}))
*/
//console.log("EPUBJS:", EPUBJS);
//window.epub_parser = EPUBJS;
/*
// create blob
const blob: any = new Blob([arrayBuffer], { type: 'application/epub+zip' });
// load the epub from arrayBuffer
this.instance = new Book(blob);
// wait until the book loaded
this.instance.ready.then(() => {
// create continuous scrolled options
const options: RenditionOptions = {
manager: 'continuous',
flow: 'scrolled',
};
// render to the div id "reader"
this.instance.renderTo(selector, options);
// display the content
this.instance.rendition.display();
});
*/
/*
import ePub from "epubjs";
import type Section from "epubjs/types/section";
export default async function getChaptersFromEpub(epub: string | ArrayBuffer): Promise<string[]> {
const book = ePub(epub);
await book.ready;
const sectionPromises: Promise<string>[] = [];
book.spine.each((section: Section) => {
const sectionPromise = (async () => {
const chapter = await book.load(section.href);
if (!(chapter instanceof Document) || !chapter.body?.textContent) {
return "";
}
return chapter.body.textContent.trim();
})();
sectionPromises.push(sectionPromise);
});
const content = await Promise.all(sectionPromises);
return content.filter(text => text);
}
*/