forked from johnfactotum/foliate-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.js
322 lines (298 loc) · 11.5 KB
/
reader.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
/* global zip: false, fflate: false */
import { View, getPosition } from './view.js'
import { createTOCView } from './ui/tree.js'
import { createMenu } from './ui/menu.js'
import { createPopover } from './ui/popover.js'
const { ZipReader, BlobReader, TextWriter, BlobWriter } = zip
zip.configure({ useWebWorkers: false })
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 makeZipLoader = async file => {
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')
const getView = async (file, emit) => {
let book
if (file.isDirectory) {
const loader = await makeDirectoryLoader(file)
const { EPUB } = await import('./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('./comic-book.js')
book = makeComicBook(loader, file)
} else if (isFBZ(file)) {
const { makeFB2 } = await import('./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('./epub.js')
book = await new EPUB(loader).init()
}
} else {
const { isMOBI, MOBI } = await import('./mobi.js')
if (await isMOBI(file))
book = await new MOBI({ unzlib: fflate.unzlibSync }).open(file)
else if (isFB2(file)) {
const { makeFB2 } = await import('./fb2.js')
book = await makeFB2(file)
}
}
if (!book) throw new Error('File type not supported')
const view = new View(book, emit)
const element = await view.display()
document.body.append(element)
return view
}
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,
}
layout = {
margin: 48,
gap: 48,
maxColumnWidth: 720,
}
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.layout.flow = value
this.setAppearance()
},
},
])
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.#handleEvent.bind(this))
const { book } = this.view
this.setAppearance()
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)))
const sizes = book.sections.filter(s => s.linear !== 'no').map(s => s.size)
if (sizes.length < 100) {
const total = sizes.reduce((a, b) => a + b, 0)
let sum = 0
for (const size of sizes.slice(0, -1)) {
sum += size
const option = document.createElement('option')
option.value = sum / total
$('#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)
}
}
setAppearance = () => {
this.view?.setAppearance({ css: getCSS(this.style), layout: this.layout })
const scrolled = this.layout.flow === 'scrolled'
document.documentElement.classList.toggle('scrolled', scrolled)
}
#handleEvent(obj) {
console.debug(obj)
switch (obj.type) {
case 'loaded': this.#onLoaded(obj); break
case 'relocated': this.#onRelocated(obj); break
case 'reference': this.#onReference(obj); break
case 'external-link': globalThis.open(obj.uri, '_blank'); break
}
}
#handleKeydown(event) {
const k = event.key
if (k === 'ArrowLeft' || k === 'h') this.view.goLeft()
else if(k === 'ArrowRight' || k === 'l') this.view.goRight()
}
#onLoaded({ doc }) {
doc.addEventListener('keydown', this.#handleKeydown.bind(this))
}
#onRelocated(obj) {
const { fraction, location, tocItem, pageItem } = obj
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)
}
#onReference(obj) {
const { content, element } = obj
const { point, dir } = getPosition(element)
const iframe = document.createElement('iframe')
iframe.sandbox = 'allow-same-origin'
iframe.srcdoc = content
iframe.onload = () => {
const doc = iframe.contentDocument
doc.documentElement.style.colorScheme = 'light dark'
doc.body.style.margin = '18px'
}
Object.assign(iframe.style, {
border: '0',
width: '100%',
height: '100%',
})
const { popover, arrow, overlay } = createPopover(300, 250, point, dir)
overlay.style.zIndex = 3
popover.style.zIndex = 3
arrow.style.zIndex = 3
popover.append(iframe)
document.body.append(overlay)
document.body.append(popover)
document.body.append(arrow)
}
}
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())