aksos-react-native-epub-reader 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +351 -2
- package/lib/EpubReader.d.ts +76 -0
- package/lib/EpubReader.js +284 -0
- package/lib/EpubReaderView.d.ts +31 -0
- package/lib/EpubReaderView.js +599 -0
- package/lib/assets/page-turn-1.wav +0 -0
- package/lib/assets/page-turn-2.wav +0 -0
- package/lib/assets/page-turn-3.wav +0 -0
- package/lib/assets/page-turn-4.wav +0 -0
- package/lib/engine/html.d.ts +1 -0
- package/lib/engine/html.js +5 -0
- package/lib/index.d.ts +9 -0
- package/lib/index.js +34 -0
- package/lib/sound.d.ts +1 -0
- package/lib/sound.js +71 -0
- package/lib/strings.d.ts +94 -0
- package/lib/strings.js +96 -0
- package/lib/themes.d.ts +60 -0
- package/lib/themes.js +166 -0
- package/lib/types.d.ts +149 -0
- package/lib/types.js +2 -0
- package/lib/ui/AppearanceSheet.d.ts +15 -0
- package/lib/ui/AppearanceSheet.js +134 -0
- package/lib/ui/ContentsSheet.d.ts +27 -0
- package/lib/ui/ContentsSheet.js +89 -0
- package/lib/ui/CustomizeSheet.d.ts +16 -0
- package/lib/ui/CustomizeSheet.js +141 -0
- package/lib/ui/Glass.d.ts +15 -0
- package/lib/ui/Glass.js +27 -0
- package/lib/ui/HighlightMenu.d.ts +25 -0
- package/lib/ui/HighlightMenu.js +45 -0
- package/lib/ui/Icons.d.ts +17 -0
- package/lib/ui/Icons.js +193 -0
- package/lib/ui/LineGuide.d.ts +21 -0
- package/lib/ui/LineGuide.js +92 -0
- package/lib/ui/NoteEditor.d.ts +12 -0
- package/lib/ui/NoteEditor.js +63 -0
- package/lib/ui/Scrubber.d.ts +15 -0
- package/lib/ui/Scrubber.js +86 -0
- package/lib/ui/SearchSheet.d.ts +14 -0
- package/lib/ui/SearchSheet.js +79 -0
- package/lib/ui/Sheet.d.ts +19 -0
- package/lib/ui/Sheet.js +40 -0
- package/lib/ui/Slider.d.ts +14 -0
- package/lib/ui/Slider.js +53 -0
- package/package.json +76 -6
- package/src/EpubReader.tsx +356 -0
- package/src/EpubReaderView.tsx +865 -0
- package/src/assets/page-turn-1.wav +0 -0
- package/src/assets/page-turn-2.wav +0 -0
- package/src/assets/page-turn-3.wav +0 -0
- package/src/assets/page-turn-4.wav +0 -0
- package/src/engine/html.ts +2 -0
- package/src/engine/reader.js +2047 -0
- package/src/index.ts +9 -0
- package/src/sound.ts +66 -0
- package/src/strings.ts +187 -0
- package/src/themes.ts +188 -0
- package/src/types.ts +154 -0
- package/src/ui/AppearanceSheet.tsx +176 -0
- package/src/ui/ContentsSheet.tsx +146 -0
- package/src/ui/CustomizeSheet.tsx +191 -0
- package/src/ui/Glass.tsx +37 -0
- package/src/ui/HighlightMenu.tsx +66 -0
- package/src/ui/Icons.tsx +246 -0
- package/src/ui/LineGuide.tsx +87 -0
- package/src/ui/NoteEditor.tsx +57 -0
- package/src/ui/Scrubber.tsx +78 -0
- package/src/ui/SearchSheet.tsx +95 -0
- package/src/ui/Sheet.tsx +71 -0
- package/src/ui/Slider.tsx +30 -0
|
@@ -0,0 +1,2047 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* EPUB reader engine. Runs inside the WebView (or any browser).
|
|
3
|
+
*
|
|
4
|
+
* native -> engine : window.__cmd(jsonString)
|
|
5
|
+
* engine -> native : ReactNativeWebView.postMessage(JSON {type, data})
|
|
6
|
+
*
|
|
7
|
+
* Offsets everywhere are character offsets into the concatenated text nodes of
|
|
8
|
+
* a chapter body (see collectSegs). They survive font/size/theme changes, which
|
|
9
|
+
* is why locations, highlights and bookmarks are stored as {spine, offset}.
|
|
10
|
+
*
|
|
11
|
+
* Page turn modes: 'slide' (finger-follow), 'curl' (hinged page flip),
|
|
12
|
+
* 'fade' (cross-fade) and 'scroll' (continuous vertical scroll per chapter).
|
|
13
|
+
* Curl and fade animate a "ghost" iframe that holds a copy of the chapter.
|
|
14
|
+
*/
|
|
15
|
+
(function () {
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
var RN = window.ReactNativeWebView;
|
|
19
|
+
var XLINK = 'http://www.w3.org/1999/xlink';
|
|
20
|
+
var XHTML = 'http://www.w3.org/1999/xhtml';
|
|
21
|
+
// ISO 639-1 and 639-2/3 codes: EPUBs in the wild use both ("ps" and "pus", "fa", "fas", "per" and "prs" ...)
|
|
22
|
+
var RTL_LANGS = ['ar', 'ara', 'arz', 'apc', 'fa', 'fas', 'per', 'prs', 'pes', 'ps', 'pus', 'pbu', 'pbt', 'ur', 'urd',
|
|
23
|
+
'he', 'heb', 'iw', 'yi', 'yid', 'ckb', 'ug', 'uig', 'sd', 'snd', 'dv', 'div', 'azb', 'glk', 'syr', 'ks', 'kas'];
|
|
24
|
+
function langIsRtl(l) {
|
|
25
|
+
l = String(l || '');
|
|
26
|
+
var base = l.toLowerCase().split(/[-_]/)[0];
|
|
27
|
+
return RTL_LANGS.indexOf(base) >= 0 || /[-_](arab|hebr|thaa|syrc|adlm|nkoo)(\b|$)/i.test(l);
|
|
28
|
+
}
|
|
29
|
+
// text scripts that run right to left: Hebrew, Arabic (+ supplements, presentation forms), Syriac, Thaana
|
|
30
|
+
var RTL_CHARS = /[-ࣿיִ-﷿ﹰ-]/g;
|
|
31
|
+
var LATIN_CHARS = /[A-Za-zÀ-ɏ]/g;
|
|
32
|
+
// a page of generated HTML never needs script or the network: block both for every book document
|
|
33
|
+
var DOC_SHELL = '<!doctype html><html><head><meta charset="utf-8">' +
|
|
34
|
+
'<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src data:; font-src data:; style-src \'unsafe-inline\'; media-src \'none\'">' +
|
|
35
|
+
'</head><body></body></html>';
|
|
36
|
+
var MAX_TEXT_BYTES = 40 * 1024 * 1024, MAX_ASSET_BYTES = 40 * 1024 * 1024, MAX_TOTAL_BYTES = 1024 * 1024 * 1024;
|
|
37
|
+
var HL_COLORS = {
|
|
38
|
+
yellow: ['rgba(255,214,10,.42)', '#e6b800'],
|
|
39
|
+
green: ['rgba(52,199,89,.38)', '#2fb24f'],
|
|
40
|
+
blue: ['rgba(10,132,255,.32)', '#0a84ff'],
|
|
41
|
+
pink: ['rgba(255,55,95,.32)', '#ff375f'],
|
|
42
|
+
purple: ['rgba(191,90,242,.34)', '#bf5af2']
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
var frame = document.getElementById('frame');
|
|
46
|
+
var ghost = document.getElementById('ghost');
|
|
47
|
+
var hdr = document.getElementById('hdr');
|
|
48
|
+
var ftr = document.getElementById('ftr');
|
|
49
|
+
// long titles in any script: the start of the text is what must stay visible
|
|
50
|
+
hdr.setAttribute('dir', 'auto');
|
|
51
|
+
ftr.setAttribute('dir', 'auto');
|
|
52
|
+
|
|
53
|
+
var S = {
|
|
54
|
+
zip: null, names: {}, spine: [], toc: [], rtl: false, bookRtl: false, ppd: '', contentRtl: false, meta: {},
|
|
55
|
+
obf: {}, identifier: '', obfKeys: {}, breaks: [],
|
|
56
|
+
texts: [], cum: [], totalLen: 0, indexed: false,
|
|
57
|
+
cur: -1, page: 0, pageCount: 1, token: 0,
|
|
58
|
+
doc: null, win: null, segs: [], segMap: null, curText: '',
|
|
59
|
+
pageStarts: {}, dataCache: {}, fragCache: {},
|
|
60
|
+
highlights: [], sel: null, searchId: 0, dragged: false,
|
|
61
|
+
G: null, ghostDirty: true, labelsExternal: false,
|
|
62
|
+
settings: {
|
|
63
|
+
bg: '#ffffff', fg: '#000000', link: '#0a60ff',
|
|
64
|
+
fontFamily: 'original', fontSize: 18, lineHeight: 1.5,
|
|
65
|
+
marginX: 28, gap: 48, justify: false, bold: false,
|
|
66
|
+
columns: 'auto', letterSpacing: 0, wordSpacing: 0, mode: 'slide',
|
|
67
|
+
insets: { top: 60, bottom: 52 }, direction: 'auto',
|
|
68
|
+
showHeader: true, showFooter: true
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
function post(type, data) {
|
|
73
|
+
var m = JSON.stringify({ type: type, data: data || {} });
|
|
74
|
+
if (RN) RN.postMessage(m);
|
|
75
|
+
else if (window.__harnessPost) window.__harnessPost(type, data || {});
|
|
76
|
+
}
|
|
77
|
+
function clamp(v, a, b) { return Math.max(a, Math.min(b, v)); }
|
|
78
|
+
function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
|
|
79
|
+
function debounce(fn, ms) {
|
|
80
|
+
var t;
|
|
81
|
+
return function () {
|
|
82
|
+
var a = arguments, self = this;
|
|
83
|
+
clearTimeout(t);
|
|
84
|
+
t = setTimeout(function () { fn.apply(self, a); }, ms);
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/* ------------------------------------------------------------ zip paths */
|
|
89
|
+
|
|
90
|
+
function dirOf(p) { var i = p.lastIndexOf('/'); return i < 0 ? '' : p.slice(0, i + 1); }
|
|
91
|
+
|
|
92
|
+
function resolvePath(base, rel) {
|
|
93
|
+
if (rel == null || /^[a-z][a-z0-9+.-]*:/i.test(rel)) return null;
|
|
94
|
+
var p = rel.split('#')[0].split('?')[0];
|
|
95
|
+
if (!p) return base;
|
|
96
|
+
var full = p.charAt(0) === '/' ? p.slice(1) : dirOf(base) + p;
|
|
97
|
+
var out = [];
|
|
98
|
+
full.split('/').forEach(function (s) {
|
|
99
|
+
if (s === '..') out.pop();
|
|
100
|
+
else if (s !== '.' && s !== '') out.push(s);
|
|
101
|
+
});
|
|
102
|
+
var joined = out.join('/');
|
|
103
|
+
try { return decodeURIComponent(joined); } catch (e) { return joined; }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// lookup key: forward slashes, NFC (macOS zips store NFD names), case-insensitive
|
|
107
|
+
function nameKey(n) {
|
|
108
|
+
n = String(n).replace(/\\/g, '/');
|
|
109
|
+
try { n = n.normalize('NFC'); } catch (e) { /* old engines */ }
|
|
110
|
+
return n.toLowerCase();
|
|
111
|
+
}
|
|
112
|
+
function getFile(path) {
|
|
113
|
+
if (!path) return null;
|
|
114
|
+
var f = S.zip.file(path);
|
|
115
|
+
if (f) return f;
|
|
116
|
+
var real = S.names[nameKey(path)];
|
|
117
|
+
return real ? S.zip.file(real) : null;
|
|
118
|
+
}
|
|
119
|
+
function entrySize(f) {
|
|
120
|
+
var d = f && f._data;
|
|
121
|
+
return d && typeof d.uncompressedSize === 'number' ? d.uncompressedSize : 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// decode bytes honouring a BOM or the declared encoding (XML declaration / <meta charset>)
|
|
125
|
+
function decodeBytes(u8) {
|
|
126
|
+
var enc = 'utf-8', start = 0;
|
|
127
|
+
if (u8.length >= 3 && u8[0] === 0xEF && u8[1] === 0xBB && u8[2] === 0xBF) start = 3;
|
|
128
|
+
else if (u8.length >= 2 && u8[0] === 0xFF && u8[1] === 0xFE) { enc = 'utf-16le'; start = 2; }
|
|
129
|
+
else if (u8.length >= 2 && u8[0] === 0xFE && u8[1] === 0xFF) { enc = 'utf-16be'; start = 2; }
|
|
130
|
+
else {
|
|
131
|
+
var head = '';
|
|
132
|
+
for (var i = 0; i < Math.min(u8.length, 400); i++) head += String.fromCharCode(u8[i]);
|
|
133
|
+
var m = /<\?xml[^>]*encoding\s*=\s*["']([\w.:-]+)["']/i.exec(head) || /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(head);
|
|
134
|
+
if (m && !/^utf-?8$/i.test(m[1])) enc = m[1].toLowerCase();
|
|
135
|
+
}
|
|
136
|
+
var text;
|
|
137
|
+
try { text = new TextDecoder(enc).decode(start ? u8.subarray(start) : u8); }
|
|
138
|
+
catch (e) { text = new TextDecoder('utf-8').decode(start ? u8.subarray(start) : u8); }
|
|
139
|
+
return text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function readText(path) {
|
|
143
|
+
var f = getFile(path);
|
|
144
|
+
if (!f) return Promise.resolve(null);
|
|
145
|
+
if (entrySize(f) > MAX_TEXT_BYTES) return Promise.resolve(null);
|
|
146
|
+
return f.async('uint8array').then(decodeBytes);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/* --------------------------------------------- font obfuscation (not DRM) */
|
|
150
|
+
|
|
151
|
+
function sha1(msg) {
|
|
152
|
+
var h0 = 0x67452301, h1 = 0xEFCDAB89 | 0, h2 = 0x98BADCFE | 0, h3 = 0x10325476, h4 = 0xC3D2E1F0 | 0;
|
|
153
|
+
var ml = msg.length, total = (((ml + 8) >> 6) + 1) * 64, buf = new Uint8Array(total);
|
|
154
|
+
buf.set(msg);
|
|
155
|
+
buf[ml] = 0x80;
|
|
156
|
+
var hi = Math.floor(ml / 0x20000000), lo = (ml << 3) >>> 0;
|
|
157
|
+
buf[total - 8] = hi >>> 24; buf[total - 7] = (hi >>> 16) & 255; buf[total - 6] = (hi >>> 8) & 255; buf[total - 5] = hi & 255;
|
|
158
|
+
buf[total - 4] = lo >>> 24; buf[total - 3] = (lo >>> 16) & 255; buf[total - 2] = (lo >>> 8) & 255; buf[total - 1] = lo & 255;
|
|
159
|
+
var w = new Array(80), i, off;
|
|
160
|
+
for (off = 0; off < total; off += 64) {
|
|
161
|
+
for (i = 0; i < 16; i++) w[i] = (buf[off + i * 4] << 24) | (buf[off + i * 4 + 1] << 16) | (buf[off + i * 4 + 2] << 8) | buf[off + i * 4 + 3];
|
|
162
|
+
for (i = 16; i < 80; i++) { var x = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; w[i] = (x << 1) | (x >>> 31); }
|
|
163
|
+
var a = h0, b = h1, c = h2, d = h3, e = h4;
|
|
164
|
+
for (i = 0; i < 80; i++) {
|
|
165
|
+
var f, k;
|
|
166
|
+
if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; }
|
|
167
|
+
else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
|
|
168
|
+
else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC | 0; }
|
|
169
|
+
else { f = b ^ c ^ d; k = 0xCA62C1D6 | 0; }
|
|
170
|
+
var t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0;
|
|
171
|
+
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
|
|
172
|
+
}
|
|
173
|
+
h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;
|
|
174
|
+
}
|
|
175
|
+
var out = new Uint8Array(20);
|
|
176
|
+
[h0, h1, h2, h3, h4].forEach(function (h, n) {
|
|
177
|
+
out[n * 4] = h >>> 24; out[n * 4 + 1] = (h >>> 16) & 255; out[n * 4 + 2] = (h >>> 8) & 255; out[n * 4 + 3] = h & 255;
|
|
178
|
+
});
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
S.sha1 = sha1; // exposed for the test harness
|
|
182
|
+
|
|
183
|
+
function obfuscationKey(kind) {
|
|
184
|
+
if (S.obfKeys[kind]) return S.obfKeys[kind];
|
|
185
|
+
var id = S.identifier || '', key;
|
|
186
|
+
if (kind === 'idpf') {
|
|
187
|
+
key = sha1(new TextEncoder().encode(id.replace(/[ \t\r\n]/g, '')));
|
|
188
|
+
} else {
|
|
189
|
+
var hex = id.replace(/^urn:uuid:/i, '').replace(/[^0-9a-f]/gi, '');
|
|
190
|
+
key = new Uint8Array(16);
|
|
191
|
+
for (var i = 0; i < 16; i++) key[i] = parseInt(hex.substr(i * 2, 2), 16) || 0;
|
|
192
|
+
}
|
|
193
|
+
return (S.obfKeys[kind] = key);
|
|
194
|
+
}
|
|
195
|
+
function deobfuscate(u8, kind) {
|
|
196
|
+
var key = obfuscationKey(kind), n = Math.min(u8.length, kind === 'idpf' ? 1040 : 1024);
|
|
197
|
+
for (var i = 0; i < n; i++) u8[i] ^= key[i % key.length];
|
|
198
|
+
return u8;
|
|
199
|
+
}
|
|
200
|
+
function bytesToBase64(u8) {
|
|
201
|
+
var s = '';
|
|
202
|
+
for (var i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
|
|
203
|
+
return btoa(s);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
var MIME = {
|
|
207
|
+
jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif',
|
|
208
|
+
svg: 'image/svg+xml', webp: 'image/webp', css: 'text/css',
|
|
209
|
+
ttf: 'font/ttf', otf: 'font/otf', woff: 'font/woff', woff2: 'font/woff2'
|
|
210
|
+
};
|
|
211
|
+
function mimeOf(path) {
|
|
212
|
+
var m = /\.([a-z0-9]+)$/i.exec(path);
|
|
213
|
+
return (m && MIME[m[1].toLowerCase()]) || 'application/octet-stream';
|
|
214
|
+
}
|
|
215
|
+
function dataUri(path) {
|
|
216
|
+
if (S.dataCache[path]) return Promise.resolve(S.dataCache[path]);
|
|
217
|
+
var f = getFile(path);
|
|
218
|
+
if (!f || entrySize(f) > MAX_ASSET_BYTES) return Promise.resolve(null);
|
|
219
|
+
var kind = S.obf[nameKey(f.name)];
|
|
220
|
+
var job = kind
|
|
221
|
+
? f.async('uint8array').then(function (u8) { return bytesToBase64(deobfuscate(u8, kind)); })
|
|
222
|
+
: f.async('base64');
|
|
223
|
+
return job.then(function (b64) {
|
|
224
|
+
var uri = 'data:' + mimeOf(path) + ';base64,' + b64;
|
|
225
|
+
S.dataCache[path] = uri;
|
|
226
|
+
return uri;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/* ---------------------------------------------------------------- xml */
|
|
231
|
+
|
|
232
|
+
// strict XML; one retry after escaping bare ampersands (a very common authoring error). Throws when unusable.
|
|
233
|
+
function parseXml(s) {
|
|
234
|
+
var d = new DOMParser().parseFromString(s, 'application/xml');
|
|
235
|
+
if (d.getElementsByTagName('parsererror').length) {
|
|
236
|
+
d = new DOMParser().parseFromString(s.replace(/&(?!(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);)/gi, '&'), 'application/xml');
|
|
237
|
+
if (d.getElementsByTagName('parsererror').length) throw new Error('XML is malformed');
|
|
238
|
+
}
|
|
239
|
+
return d;
|
|
240
|
+
}
|
|
241
|
+
function byLocal(root, name) {
|
|
242
|
+
if (!root) return [];
|
|
243
|
+
return Array.prototype.slice.call(root.getElementsByTagNameNS('*', name));
|
|
244
|
+
}
|
|
245
|
+
function firstLocal(root, name) { return byLocal(root, name)[0] || null; }
|
|
246
|
+
function attrLocal(el, name) {
|
|
247
|
+
for (var i = 0; i < el.attributes.length; i++) {
|
|
248
|
+
if (el.attributes[i].localName === name) return el.attributes[i].value;
|
|
249
|
+
}
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
function parseMarkup(raw) {
|
|
253
|
+
var d = new DOMParser().parseFromString(raw, 'application/xhtml+xml');
|
|
254
|
+
if (d.getElementsByTagName('parsererror').length || !d.body) {
|
|
255
|
+
d = new DOMParser().parseFromString(raw, 'text/html');
|
|
256
|
+
}
|
|
257
|
+
return d;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/* --------------------------------------------------------- book opening */
|
|
261
|
+
|
|
262
|
+
async function openBook(b64) {
|
|
263
|
+
try { S.zip = await JSZip.loadAsync(b64, { base64: true }); }
|
|
264
|
+
catch (e) { throw new Error('This file is not a valid EPUB (it could not be read as a zip archive).'); }
|
|
265
|
+
S.names = {};
|
|
266
|
+
var total = 0;
|
|
267
|
+
Object.keys(S.zip.files).forEach(function (n) {
|
|
268
|
+
S.names[nameKey(n)] = n;
|
|
269
|
+
total += entrySize(S.zip.files[n]);
|
|
270
|
+
});
|
|
271
|
+
if (total > MAX_TOTAL_BYTES) throw new Error('This EPUB is too large to open safely.');
|
|
272
|
+
|
|
273
|
+
S.obf = {};
|
|
274
|
+
var enc = await readText('META-INF/encryption.xml');
|
|
275
|
+
if (enc) {
|
|
276
|
+
var algos = [];
|
|
277
|
+
try {
|
|
278
|
+
byLocal(parseXml(enc), 'EncryptedData').forEach(function (ed) {
|
|
279
|
+
var m = firstLocal(ed, 'EncryptionMethod'), ref = firstLocal(ed, 'CipherReference');
|
|
280
|
+
var alg = (m && m.getAttribute('Algorithm')) || '', uri = ref && ref.getAttribute('URI');
|
|
281
|
+
algos.push(alg);
|
|
282
|
+
var kind = alg.indexOf('idpf.org/2008/embedding') >= 0 ? 'idpf' : alg.indexOf('ns.adobe.com/pdf/enc#RC') >= 0 ? 'adobe' : '';
|
|
283
|
+
var p = uri && resolvePath('', uri);
|
|
284
|
+
if (kind && p) S.obf[nameKey(p)] = kind;
|
|
285
|
+
});
|
|
286
|
+
} catch (e) {
|
|
287
|
+
// unreadable file: still look at the declared algorithms so a DRM book is never shown as garbage
|
|
288
|
+
var re = /Algorithm\s*=\s*["']([^"']+)["']/g, mm;
|
|
289
|
+
while ((mm = re.exec(enc))) algos.push(mm[1]);
|
|
290
|
+
if (!algos.length) throw new Error('This book has an unreadable encryption.xml and cannot be opened.');
|
|
291
|
+
}
|
|
292
|
+
var drm = algos.some(function (a) {
|
|
293
|
+
return a.indexOf('idpf.org/2008/embedding') < 0 && a.indexOf('ns.adobe.com/pdf/enc#RC') < 0;
|
|
294
|
+
});
|
|
295
|
+
if (drm) throw new Error('This book is protected by DRM and cannot be opened.');
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
var container = await readText('META-INF/container.xml');
|
|
299
|
+
if (!container) throw new Error('Not a valid EPUB (container.xml is missing).');
|
|
300
|
+
var rootfile;
|
|
301
|
+
try { rootfile = firstLocal(parseXml(container), 'rootfile'); }
|
|
302
|
+
catch (e) { throw new Error('Not a valid EPUB (container.xml is malformed).'); }
|
|
303
|
+
var opfPath = rootfile && rootfile.getAttribute('full-path');
|
|
304
|
+
var opfText = opfPath && await readText(opfPath);
|
|
305
|
+
if (!opfText) throw new Error('Not a valid EPUB (package document is missing).');
|
|
306
|
+
var opf;
|
|
307
|
+
try { opf = parseXml(opfText); }
|
|
308
|
+
catch (e) { throw new Error('Not a valid EPUB (package document is malformed).'); }
|
|
309
|
+
|
|
310
|
+
var manifest = {};
|
|
311
|
+
byLocal(opf, 'item').forEach(function (it) {
|
|
312
|
+
var href = it.getAttribute('href');
|
|
313
|
+
manifest[it.getAttribute('id')] = {
|
|
314
|
+
id: it.getAttribute('id'), href: href,
|
|
315
|
+
path: resolvePath(opfPath, href),
|
|
316
|
+
type: it.getAttribute('media-type') || '',
|
|
317
|
+
props: it.getAttribute('properties') || ''
|
|
318
|
+
};
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
var spineEl = firstLocal(opf, 'spine');
|
|
322
|
+
if (!spineEl) throw new Error('Not a valid EPUB (the package has no spine).');
|
|
323
|
+
S.spine = byLocal(spineEl, 'itemref').map(function (r) {
|
|
324
|
+
return manifest[r.getAttribute('idref')];
|
|
325
|
+
}).filter(function (m) {
|
|
326
|
+
return m && /html|xml/i.test(m.type) || (m && /\.x?html?$/i.test(m.path));
|
|
327
|
+
});
|
|
328
|
+
if (!S.spine.length) throw new Error('This EPUB has no readable content.');
|
|
329
|
+
if (!S.spine.some(function (m) { return getFile(m.path); })) {
|
|
330
|
+
throw new Error('This EPUB is damaged: none of its chapter files could be found.');
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// unique identifier: the key for obfuscated fonts
|
|
334
|
+
var uid = opf.documentElement.getAttribute('unique-identifier'), ids = byLocal(opf, 'identifier');
|
|
335
|
+
var idEl = ids.filter(function (e) { return uid && e.getAttribute('id') === uid; })[0] || ids[0];
|
|
336
|
+
S.identifier = idEl ? idEl.textContent : '';
|
|
337
|
+
S.obfKeys = {};
|
|
338
|
+
|
|
339
|
+
var title = firstLocal(opf, 'title');
|
|
340
|
+
var lang = firstLocal(opf, 'language');
|
|
341
|
+
S.meta = {
|
|
342
|
+
title: title && !/^(unknown|untitled|none|n\/a)$/i.test(title.textContent.trim()) ? title.textContent.trim() : '',
|
|
343
|
+
author: byLocal(opf, 'creator').map(function (c) { return c.textContent.trim(); }).join(', '),
|
|
344
|
+
language: lang ? lang.textContent.trim() : '',
|
|
345
|
+
publisher: (firstLocal(opf, 'publisher') || { textContent: '' }).textContent.trim()
|
|
346
|
+
};
|
|
347
|
+
S.ppd = spineEl.getAttribute('page-progression-direction') || '';
|
|
348
|
+
// content detection only matters when the metadata does not already say right-to-left
|
|
349
|
+
S.contentRtl = !S.ppd && !langIsRtl(S.meta.language) ? await contentIsRtl() : false;
|
|
350
|
+
S.bookRtl = autoRtl();
|
|
351
|
+
S.rtl = effectiveRtl(S.bookRtl);
|
|
352
|
+
|
|
353
|
+
S.toc = await parseToc(opf, manifest, spineEl, opfPath);
|
|
354
|
+
post('metadata', S.meta);
|
|
355
|
+
post('toc', { items: S.toc, rtl: effectiveRtl(S.bookRtl), spineCount: S.spine.length });
|
|
356
|
+
sendCover(opf, manifest);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// direction from the book itself: page-progression-direction, then dc:language, then the text
|
|
360
|
+
function autoRtl() { return S.ppd ? S.ppd === 'rtl' : (langIsRtl(S.meta.language) || S.contentRtl); }
|
|
361
|
+
// the user's override ('rtl' / 'ltr') wins over what the book says
|
|
362
|
+
function effectiveRtl(auto) {
|
|
363
|
+
var d = S.settings.direction;
|
|
364
|
+
return d === 'rtl' ? true : d === 'ltr' ? false : auto;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// counts right-to-left versus Latin letters in a piece of text
|
|
368
|
+
function scriptCounts(text) {
|
|
369
|
+
return { rtl: (text.match(RTL_CHARS) || []).length, latin: (text.match(LATIN_CHARS) || []).length };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// true when the first chapters are mostly right-to-left script (Pashto, Dari, Persian, Arabic, Urdu, Hebrew ...)
|
|
373
|
+
async function contentIsRtl() {
|
|
374
|
+
var rtl = 0, latin = 0;
|
|
375
|
+
for (var i = 0; i < Math.min(S.spine.length, 6) && rtl + latin < 1500; i++) {
|
|
376
|
+
try {
|
|
377
|
+
var c = scriptCounts((await parseChapter(i)).body.textContent || '');
|
|
378
|
+
rtl += c.rtl; latin += c.latin;
|
|
379
|
+
} catch (e) { /* ignore unreadable chapters */ }
|
|
380
|
+
}
|
|
381
|
+
return rtl > 40 && rtl > latin * 1.5;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// Direction of one chapter. Follows the book, except when the chapter says so itself (dir attribute) or is
|
|
385
|
+
// clearly written in the other script (an English chapter inside an Arabic-script book and the reverse).
|
|
386
|
+
function chapterRtl(ch) {
|
|
387
|
+
if (S.settings.direction !== 'auto') return effectiveRtl(S.bookRtl);
|
|
388
|
+
if (ch.dir === 'rtl' || ch.dir === 'ltr') return ch.dir === 'rtl';
|
|
389
|
+
var c = ch.counts || { rtl: 0, latin: 0 };
|
|
390
|
+
if (S.bookRtl && c.latin > 200 && c.latin > c.rtl * 3) return false;
|
|
391
|
+
if (!S.bookRtl && c.rtl > 200 && c.rtl > c.latin * 3) return true;
|
|
392
|
+
return S.bookRtl;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function spineIndexOfPath(path) {
|
|
396
|
+
for (var i = 0; i < S.spine.length; i++) if (S.spine[i].path === path) return i;
|
|
397
|
+
return -1;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function parseToc(opf, manifest, spineEl, opfPath) {
|
|
401
|
+
var items = [];
|
|
402
|
+
function add(label, href, level, base) {
|
|
403
|
+
var path = resolvePath(base, href);
|
|
404
|
+
var frag = href && href.indexOf('#') >= 0 ? href.split('#')[1] : '';
|
|
405
|
+
var idx = path ? spineIndexOfPath(path) : -1;
|
|
406
|
+
if (idx < 0) return;
|
|
407
|
+
items.push({ label: (label || '').replace(/\s+/g, ' ').trim(), spine: idx, fragment: frag, level: level });
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
var navItem = null;
|
|
411
|
+
Object.keys(manifest).forEach(function (k) {
|
|
412
|
+
if (/(^|\s)nav(\s|$)/.test(manifest[k].props)) navItem = manifest[k];
|
|
413
|
+
});
|
|
414
|
+
if (navItem) {
|
|
415
|
+
var navText = await readText(navItem.path);
|
|
416
|
+
if (navText) {
|
|
417
|
+
var nd = parseMarkup(navText);
|
|
418
|
+
var navs = Array.prototype.slice.call(nd.getElementsByTagName('nav'));
|
|
419
|
+
var navEl = navs.filter(function (n) { return /toc/.test(attrLocal(n, 'type') || ''); })[0] || navs[0];
|
|
420
|
+
if (navEl) {
|
|
421
|
+
(function walk(ol, level) {
|
|
422
|
+
Array.prototype.forEach.call(ol.children, function (li) {
|
|
423
|
+
if (li.localName !== 'li') return;
|
|
424
|
+
var a = null, sub = null;
|
|
425
|
+
Array.prototype.forEach.call(li.children, function (c) {
|
|
426
|
+
if (c.localName === 'a' || c.localName === 'span') a = a || c;
|
|
427
|
+
if (c.localName === 'ol') sub = c;
|
|
428
|
+
});
|
|
429
|
+
if (a) add(a.textContent, a.getAttribute('href'), level, navItem.path);
|
|
430
|
+
if (sub) walk(sub, level + 1);
|
|
431
|
+
});
|
|
432
|
+
})(navEl.getElementsByTagName('ol')[0] || navEl, 0);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
if (items.length) return items;
|
|
437
|
+
|
|
438
|
+
var ncxId = spineEl.getAttribute('toc');
|
|
439
|
+
var ncx = (ncxId && manifest[ncxId]) ||
|
|
440
|
+
Object.keys(manifest).map(function (k) { return manifest[k]; }).filter(function (m) { return /ncx/.test(m.type); })[0];
|
|
441
|
+
if (ncx) {
|
|
442
|
+
var ncxText = await readText(ncx.path);
|
|
443
|
+
var ncxDoc = null;
|
|
444
|
+
try { ncxDoc = ncxText && parseXml(ncxText); } catch (e) { /* a broken NCX only costs the table of contents */ }
|
|
445
|
+
if (ncxDoc) {
|
|
446
|
+
var map = firstLocal(ncxDoc, 'navMap');
|
|
447
|
+
(function walk(parent, level) {
|
|
448
|
+
Array.prototype.forEach.call(parent.children, function (np) {
|
|
449
|
+
if (np.localName !== 'navPoint') return;
|
|
450
|
+
var label = firstLocal(np, 'text');
|
|
451
|
+
var content = firstLocal(np, 'content');
|
|
452
|
+
if (content) add(label ? label.textContent : '', content.getAttribute('src'), level, ncx.path);
|
|
453
|
+
walk(np, level + 1);
|
|
454
|
+
});
|
|
455
|
+
})(map || { children: [] }, 0);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return items;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function sendCover(opf, manifest) {
|
|
462
|
+
var item = null;
|
|
463
|
+
Object.keys(manifest).forEach(function (k) {
|
|
464
|
+
if (/cover-image/.test(manifest[k].props)) item = manifest[k];
|
|
465
|
+
});
|
|
466
|
+
if (!item) {
|
|
467
|
+
var meta = byLocal(opf, 'meta').filter(function (m) { return m.getAttribute('name') === 'cover'; })[0];
|
|
468
|
+
if (meta) item = manifest[meta.getAttribute('content')];
|
|
469
|
+
}
|
|
470
|
+
if (item && /image/.test(item.type)) {
|
|
471
|
+
dataUri(item.path).then(function (uri) { if (uri) post('cover', { uri: uri }); });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// text offset of an element id in the chapter on screen (null when unknown)
|
|
476
|
+
function fragOffset(id) {
|
|
477
|
+
if (!S.doc || !S.segMap) return null;
|
|
478
|
+
var key = S.cur + ':' + id;
|
|
479
|
+
if (S.fragCache[key] !== undefined) return S.fragCache[key];
|
|
480
|
+
var el = S.doc.getElementById(id) || S.doc.getElementsByName(id)[0];
|
|
481
|
+
return (S.fragCache[key] = el && S.root && S.root.contains(el) ? boundaryOffset(el, 0) : null);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// Title of the TOC entry that applies to chapter i. When several entries point into the same file
|
|
485
|
+
// (Calibre-style single-file books) `off`, a text offset in the chapter on screen, picks the right one.
|
|
486
|
+
function chapterTitle(i, off) {
|
|
487
|
+
var best = '';
|
|
488
|
+
for (var k = 0; k < S.toc.length; k++) {
|
|
489
|
+
var t = S.toc[k];
|
|
490
|
+
if (t.spine > i) break;
|
|
491
|
+
if (t.spine === i && t.fragment && off != null && i === S.cur) {
|
|
492
|
+
var fo = fragOffset(t.fragment);
|
|
493
|
+
if (fo != null && fo > off) continue;
|
|
494
|
+
}
|
|
495
|
+
best = t.label;
|
|
496
|
+
}
|
|
497
|
+
return best || S.meta.title || '';
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/* ------------------------------------------------------------- chapters */
|
|
501
|
+
|
|
502
|
+
function collectSegs(root) {
|
|
503
|
+
var w = root.ownerDocument.createTreeWalker(root, 4, null);
|
|
504
|
+
var segs = [], pos = 0, n;
|
|
505
|
+
while ((n = w.nextNode())) {
|
|
506
|
+
var len = n.data.length;
|
|
507
|
+
segs.push({ node: n, start: pos, end: pos + len });
|
|
508
|
+
pos += len;
|
|
509
|
+
}
|
|
510
|
+
segs.total = pos;
|
|
511
|
+
return segs;
|
|
512
|
+
}
|
|
513
|
+
function segsText(segs) { return segs.map(function (s) { return s.node.data; }).join(''); }
|
|
514
|
+
|
|
515
|
+
var DROP_TAGS = 'script,noscript,iframe,frame,frameset,object,embed,applet,base,meta,form,input,button,select,textarea,' +
|
|
516
|
+
'audio,video,source,track,portal,foreignObject,set,animate';
|
|
517
|
+
var URL_ATTRS = ['href', 'src', 'xlink:href', 'action', 'formaction', 'data', 'poster', 'background', 'srcset', 'srcdoc'];
|
|
518
|
+
|
|
519
|
+
// Chapter markup is untrusted: remove everything that can run script or touch the network.
|
|
520
|
+
function sanitize(root) {
|
|
521
|
+
Array.prototype.slice.call(root.querySelectorAll(DROP_TAGS)).forEach(function (el) {
|
|
522
|
+
if (el.parentNode) el.parentNode.removeChild(el);
|
|
523
|
+
});
|
|
524
|
+
Array.prototype.slice.call(root.querySelectorAll('*')).forEach(function (el) {
|
|
525
|
+
var tag = el.localName;
|
|
526
|
+
Array.prototype.slice.call(el.attributes).forEach(function (a) {
|
|
527
|
+
var n = a.name.toLowerCase(), v = a.value;
|
|
528
|
+
if (n.indexOf('on') === 0 || n === 'srcdoc') { el.removeAttribute(a.name); return; }
|
|
529
|
+
if (URL_ATTRS.indexOf(n) >= 0) {
|
|
530
|
+
if (/^\s*(javascript|vbscript|data:text|data:application|file|content|intent):/i.test(v)) { el.removeAttribute(a.name); return; }
|
|
531
|
+
// pictures must come from inside the book: remote images only track the reader
|
|
532
|
+
if ((tag === 'img' || tag === 'image') && /^\s*(https?:)?\/\//i.test(v)) el.removeAttribute(a.name);
|
|
533
|
+
if (n === 'srcset') el.removeAttribute(a.name);
|
|
534
|
+
}
|
|
535
|
+
if (n === 'style' && /url\(\s*['"]?\s*(https?:|\/\/)/i.test(v)) el.removeAttribute(a.name);
|
|
536
|
+
});
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
async function parseChapter(i) {
|
|
541
|
+
var it = S.spine[i];
|
|
542
|
+
var raw;
|
|
543
|
+
try { raw = await readText(it.path); }
|
|
544
|
+
catch (e) { raw = '<html><body><p>This chapter could not be read (the file is damaged).</p></body></html>'; }
|
|
545
|
+
if (raw == null) raw = '<html><body><p></p></body></html>';
|
|
546
|
+
var doc = parseMarkup(raw);
|
|
547
|
+
var body = doc.body || doc.documentElement;
|
|
548
|
+
var refs = [];
|
|
549
|
+
Array.prototype.slice.call(doc.querySelectorAll('link,style')).forEach(function (el) {
|
|
550
|
+
if (el.namespaceURI !== XHTML) return;
|
|
551
|
+
if (el.localName === 'style') refs.push({ text: el.textContent, base: it.path });
|
|
552
|
+
else if (/stylesheet/i.test(el.getAttribute('rel') || '')) refs.push({ href: el.getAttribute('href'), base: it.path });
|
|
553
|
+
el.parentNode.removeChild(el);
|
|
554
|
+
});
|
|
555
|
+
sanitize(body);
|
|
556
|
+
var root = doc.documentElement;
|
|
557
|
+
var dir = (body.getAttribute('dir') || root.getAttribute('dir') || '').toLowerCase();
|
|
558
|
+
return {
|
|
559
|
+
index: i, path: it.path, body: body, refs: refs, css: null, dir: dir,
|
|
560
|
+
lang: root.getAttribute('xml:lang') || root.getAttribute('lang') || body.getAttribute('xml:lang') || body.getAttribute('lang') || ''
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
async function rewriteCss(css, basePath) {
|
|
565
|
+
css = css.replace(/@import[^;]*;/g, '');
|
|
566
|
+
var re = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g, m, seen = {}, jobs = [];
|
|
567
|
+
while ((m = re.exec(css))) {
|
|
568
|
+
if (seen[m[0]]) continue;
|
|
569
|
+
seen[m[0]] = 1;
|
|
570
|
+
if (/^data:/i.test(m[2])) continue;
|
|
571
|
+
// remote or odd-scheme resources never load (no network from a book)
|
|
572
|
+
jobs.push({ full: m[0], rel: m[2], remote: /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(m[2]) });
|
|
573
|
+
}
|
|
574
|
+
for (var k = 0; k < jobs.length; k++) {
|
|
575
|
+
var p = jobs[k].remote ? null : resolvePath(basePath, jobs[k].rel);
|
|
576
|
+
var uri = p && await dataUri(p);
|
|
577
|
+
css = css.split(jobs[k].full).join('url("' + (uri || '') + '")');
|
|
578
|
+
}
|
|
579
|
+
return css;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async function inlineChapter(ch) {
|
|
583
|
+
ch.css = [];
|
|
584
|
+
for (var r = 0; r < ch.refs.length; r++) {
|
|
585
|
+
var ref = ch.refs[r], text, base;
|
|
586
|
+
if (ref.href != null) {
|
|
587
|
+
base = resolvePath(ref.base, ref.href);
|
|
588
|
+
text = base && await readText(base);
|
|
589
|
+
} else { text = ref.text; base = ref.base; }
|
|
590
|
+
if (text) ch.css.push(await rewriteCss(text, base));
|
|
591
|
+
}
|
|
592
|
+
var imgs = Array.prototype.slice.call(ch.body.querySelectorAll('img,image'));
|
|
593
|
+
for (var k = 0; k < imgs.length; k++) {
|
|
594
|
+
var el = imgs[k];
|
|
595
|
+
var src = el.localName === 'img' ? el.getAttribute('src')
|
|
596
|
+
: (el.getAttributeNS(XLINK, 'href') || el.getAttribute('href'));
|
|
597
|
+
var path = src && resolvePath(ch.path, src);
|
|
598
|
+
var uri = path && await dataUri(path);
|
|
599
|
+
if (!uri) continue;
|
|
600
|
+
if (el.localName === 'img') { el.setAttribute('src', uri); el.removeAttribute('srcset'); }
|
|
601
|
+
else { el.setAttribute('href', uri); el.setAttributeNS(XLINK, 'xlink:href', uri); }
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function mountChapter(ch) {
|
|
606
|
+
var d = frame.contentDocument;
|
|
607
|
+
d.open();
|
|
608
|
+
d.write(DOC_SHELL);
|
|
609
|
+
d.close();
|
|
610
|
+
d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
|
|
611
|
+
d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
|
|
612
|
+
ch.css.forEach(function (t) {
|
|
613
|
+
var st = d.createElement('style');
|
|
614
|
+
st.textContent = t;
|
|
615
|
+
d.head.appendChild(st);
|
|
616
|
+
});
|
|
617
|
+
var app = d.createElement('style');
|
|
618
|
+
app.id = 'app';
|
|
619
|
+
d.head.appendChild(app);
|
|
620
|
+
Array.prototype.forEach.call(ch.body.attributes, function (a) {
|
|
621
|
+
if (a.name !== 'style' && a.name.indexOf('on') !== 0) d.body.setAttribute(a.name, a.value);
|
|
622
|
+
});
|
|
623
|
+
var holder = d.body;
|
|
624
|
+
var scrollMode = S.settings.mode === 'scroll';
|
|
625
|
+
if (scrollMode) {
|
|
626
|
+
holder = d.createElement('div');
|
|
627
|
+
holder.className = '__ch';
|
|
628
|
+
holder.setAttribute('data-spine', ch.index);
|
|
629
|
+
d.body.appendChild(holder);
|
|
630
|
+
}
|
|
631
|
+
Array.prototype.forEach.call(ch.body.childNodes, function (n) {
|
|
632
|
+
holder.appendChild(d.importNode(n, true));
|
|
633
|
+
});
|
|
634
|
+
S.doc = d;
|
|
635
|
+
S.win = frame.contentWindow;
|
|
636
|
+
S.root = holder;
|
|
637
|
+
S.sections = scrollMode ? [{ index: ch.index, el: holder }] : [];
|
|
638
|
+
S.cssSeen = {};
|
|
639
|
+
S.fragCache = {};
|
|
640
|
+
ch.css.forEach(function (t) { S.cssSeen[t] = true; });
|
|
641
|
+
S.ghostDirty = true;
|
|
642
|
+
refreshSegs();
|
|
643
|
+
S.curText = segsText(S.segs);
|
|
644
|
+
attachListeners(d);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function refreshSegs() {
|
|
648
|
+
S.segs = collectSegs(rootEl());
|
|
649
|
+
S.segMap = new Map();
|
|
650
|
+
S.segs.forEach(function (s) { S.segMap.set(s.node, s); });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function waitAssets() {
|
|
654
|
+
var d = S.doc;
|
|
655
|
+
var pending = Array.prototype.slice.call(d.images || []).filter(function (im) { return !im.complete; })
|
|
656
|
+
.map(function (im) { return new Promise(function (r) { im.onload = im.onerror = r; }); });
|
|
657
|
+
if (d.fonts && d.fonts.ready) pending.push(d.fonts.ready);
|
|
658
|
+
if (pending.length) await Promise.race([Promise.all(pending), sleep(1500)]);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/* --------------------------------------------------------------- layout */
|
|
662
|
+
|
|
663
|
+
function geometry() {
|
|
664
|
+
var s = S.settings, W = window.innerWidth, H = window.innerHeight;
|
|
665
|
+
var mx = s.marginX, ins = s.insets;
|
|
666
|
+
var scroll = s.mode === 'scroll';
|
|
667
|
+
var il = ins.left || 0, ir = ins.right || 0; // notch / rounded corners in landscape
|
|
668
|
+
var pageW = Math.max(120, W - 2 * mx - il - ir), pageH = Math.max(120, H - ins.top - ins.bottom);
|
|
669
|
+
var cols = 1;
|
|
670
|
+
if (!scroll) cols = s.columns === 'auto' ? (pageW >= 640 ? 2 : 1) : (+s.columns === 2 ? 2 : 1);
|
|
671
|
+
var colW = pageW;
|
|
672
|
+
if (cols === 2) { colW = Math.floor((pageW - s.gap) / 2); pageW = colW * 2 + s.gap; }
|
|
673
|
+
return { W: W, H: H, mx: mx, left: mx + il, top: ins.top, gap: s.gap, pageW: pageW, pageH: pageH, cols: cols, colW: colW, scroll: scroll, mode: s.mode };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function appCss(G) {
|
|
677
|
+
var s = S.settings;
|
|
678
|
+
var ff = s.fontFamily && s.fontFamily !== 'original' ? s.fontFamily : null;
|
|
679
|
+
var dir = S.rtl ? 'rtl' : 'ltr';
|
|
680
|
+
var css = [
|
|
681
|
+
'html{margin:0!important;padding:0!important;background:' + s.bg + '!important;-webkit-text-size-adjust:none;direction:' + dir + '!important;' +
|
|
682
|
+
(G.scroll ? 'overflow-x:hidden!important;overflow-y:scroll!important;touch-action:pan-y;overflow-anchor:none;' : 'overflow:hidden!important;touch-action:none;') + '}',
|
|
683
|
+
'html::-webkit-scrollbar{display:none}',
|
|
684
|
+
// vertical writing modes would break the column pagination: always lay text out horizontally
|
|
685
|
+
'html,body,body *{writing-mode:horizontal-tb!important;-webkit-writing-mode:horizontal-tb!important;text-orientation:mixed!important}',
|
|
686
|
+
'body{margin:0!important;padding:0!important;border:0!important;width:' + G.pageW + 'px!important;max-width:none!important;min-width:0!important;' +
|
|
687
|
+
(G.scroll ? 'height:auto!important;'
|
|
688
|
+
: 'height:' + G.pageH + 'px!important;column-width:' + G.colW + 'px!important;-webkit-column-width:' + G.colW + 'px!important;column-gap:' + G.gap + 'px!important;-webkit-column-gap:' + G.gap + 'px!important;column-fill:auto!important;overflow:hidden!important;') +
|
|
689
|
+
'color:' + s.fg + '!important;background:transparent!important;font-size:' + s.fontSize + 'px!important;line-height:' + s.lineHeight + '!important;direction:' + dir + '!important;' +
|
|
690
|
+
(ff ? 'font-family:' + ff + '!important;' : '') +
|
|
691
|
+
(s.justify ? 'text-align:justify!important;hyphens:auto;-webkit-hyphens:auto;' : '') +
|
|
692
|
+
(s.bold ? 'font-weight:600!important;' : '') +
|
|
693
|
+
// letter-spacing would break the joins of cursive scripts (Arabic, Pashto, Persian, Urdu), so right-to-left books skip it
|
|
694
|
+
(s.letterSpacing && !S.rtl ? 'letter-spacing:' + s.letterSpacing + 'em!important;' : '') +
|
|
695
|
+
(s.wordSpacing ? 'word-spacing:' + s.wordSpacing + 'em!important;' : '') +
|
|
696
|
+
'-webkit-touch-callout:none;-webkit-user-select:text;user-select:text;overflow-wrap:break-word;word-wrap:break-word}',
|
|
697
|
+
'body *{color:inherit!important;background-color:transparent!important;' + (ff ? 'font-family:inherit!important;' : '') + (s.bold ? 'font-weight:inherit;' : '') + 'box-sizing:border-box}',
|
|
698
|
+
'body a,body a *{color:' + s.link + '!important}',
|
|
699
|
+
'body img,body svg,body video{max-width:100%!important;max-height:' + G.pageH + 'px!important;object-fit:contain;break-inside:avoid}',
|
|
700
|
+
'body img{height:auto}',
|
|
701
|
+
'body h1,body h2,body h3,body h4{break-after:avoid;-webkit-column-break-after:avoid}',
|
|
702
|
+
'body table{max-width:100%}',
|
|
703
|
+
'::selection{background:rgba(10,132,255,.3)}',
|
|
704
|
+
'mark{color:inherit!important;border-radius:2px;padding:0!important}'
|
|
705
|
+
];
|
|
706
|
+
Object.keys(HL_COLORS).forEach(function (c) {
|
|
707
|
+
css.push('body mark.hl-' + c + '{background-color:' + HL_COLORS[c][0] + '!important}');
|
|
708
|
+
css.push('body mark.ul-' + c + '{background-color:transparent!important;border-bottom:2px solid ' + HL_COLORS[c][1] + ';border-radius:0}');
|
|
709
|
+
});
|
|
710
|
+
css.push('body mark.hit{background-color:rgba(255,149,0,.5)!important}');
|
|
711
|
+
return css.join('\n');
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function place(el, G) {
|
|
715
|
+
el.style.left = G.left + 'px';
|
|
716
|
+
el.style.top = G.top + 'px';
|
|
717
|
+
el.style.width = G.pageW + 'px';
|
|
718
|
+
el.style.height = G.pageH + 'px';
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function layout() {
|
|
722
|
+
var G = S.G = geometry(), s = S.settings, d = S.doc;
|
|
723
|
+
d.getElementById('app').textContent = appCss(G);
|
|
724
|
+
place(frame, G);
|
|
725
|
+
place(ghost, G);
|
|
726
|
+
placeCurl(G);
|
|
727
|
+
document.documentElement.style.setProperty('--bg', s.bg);
|
|
728
|
+
document.body.style.background = s.bg;
|
|
729
|
+
hdr.style.top = Math.max(10, G.top - 34) + 'px';
|
|
730
|
+
ftr.style.bottom = Math.max(10, s.insets.bottom - 34) + 'px';
|
|
731
|
+
hdr.style.color = ftr.style.color = s.fg;
|
|
732
|
+
hdr.style.display = s.showHeader ? '' : 'none';
|
|
733
|
+
ftr.style.display = s.showFooter ? '' : 'none';
|
|
734
|
+
var b = d.body;
|
|
735
|
+
var prev = b.style.transform;
|
|
736
|
+
b.style.transition = 'none';
|
|
737
|
+
b.style.transform = 'none';
|
|
738
|
+
if (G.scroll) {
|
|
739
|
+
S.pageCount = Math.max(1, Math.ceil(rootEl().offsetHeight / G.pageH - 0.02));
|
|
740
|
+
} else {
|
|
741
|
+
var step = G.pageW + G.gap;
|
|
742
|
+
S.pageCount = Math.max(1, Math.ceil((d.body.scrollWidth + G.gap) / step - 0.01));
|
|
743
|
+
}
|
|
744
|
+
b.style.transform = prev;
|
|
745
|
+
S.pageStarts = {};
|
|
746
|
+
S.ghostDirty = true;
|
|
747
|
+
scheduleGhost();
|
|
748
|
+
if (G.scroll) scheduleExtras(); else clearExtras();
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function autoLabels() {
|
|
752
|
+
if (S.labelsExternal) return;
|
|
753
|
+
var multi = S.doc && S.toc.some(function (t) { return t.spine === S.cur && t.fragment; });
|
|
754
|
+
hdr.textContent = chapterTitle(S.cur, multi ? pageStart(S.page) : null);
|
|
755
|
+
ftr.textContent = (S.page + 1) + ' / ' + S.pageCount;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function showPage(p, animate) {
|
|
759
|
+
p = clamp(p, 0, S.pageCount - 1);
|
|
760
|
+
S.page = p;
|
|
761
|
+
var G = S.G, b = S.doc.body;
|
|
762
|
+
if (G.scroll) {
|
|
763
|
+
b.style.transition = 'none';
|
|
764
|
+
b.style.transform = 'none';
|
|
765
|
+
S.win.scrollTo({ top: bodyTop() + p * G.pageH, behavior: animate ? 'smooth' : 'auto' });
|
|
766
|
+
} else {
|
|
767
|
+
scrollTo(S.doc.body, pageX(p), animate);
|
|
768
|
+
}
|
|
769
|
+
autoLabels();
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// horizontal scroll position of page p (negative in right-to-left documents)
|
|
773
|
+
function pageX(p) {
|
|
774
|
+
return (S.rtl ? -1 : 1) * p * (S.G.pageW + S.G.gap);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function currentX() {
|
|
778
|
+
return S.doc.body.scrollLeft;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
var scrollAnim = 0;
|
|
782
|
+
// scroll an element horizontally, optionally with a short ease-out animation
|
|
783
|
+
function scrollTo(el, x, animate) {
|
|
784
|
+
var id = ++scrollAnim;
|
|
785
|
+
if (!animate) { el.scrollLeft = x; return; }
|
|
786
|
+
var from = el.scrollLeft, t0 = null, dur = 240;
|
|
787
|
+
function step(ts) {
|
|
788
|
+
if (id !== scrollAnim) return;
|
|
789
|
+
if (t0 == null) t0 = ts;
|
|
790
|
+
var t = Math.min(1, (ts - t0) / dur);
|
|
791
|
+
el.scrollLeft = from + (x - from) * (1 - Math.pow(1 - t, 3));
|
|
792
|
+
if (t < 1) requestAnimationFrame(step);
|
|
793
|
+
}
|
|
794
|
+
requestAnimationFrame(step);
|
|
795
|
+
setTimeout(function () { if (id === scrollAnim) el.scrollLeft = x; }, dur + 80);
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/* ----------------------------------------- ghost iframe: curl and fade */
|
|
799
|
+
|
|
800
|
+
var ghostTimer;
|
|
801
|
+
function scheduleGhost() {
|
|
802
|
+
clearTimeout(ghostTimer);
|
|
803
|
+
if (!S.G || S.G.scroll) return;
|
|
804
|
+
ghostTimer = setTimeout(function () { if (S.ghostDirty && S.doc && !S.ghostLock) buildGhost(); }, 250);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function buildGhost() {
|
|
808
|
+
if (S.ghostLock) return;
|
|
809
|
+
buildInto(ghost);
|
|
810
|
+
// the second copy is only used by the page curl
|
|
811
|
+
if (S.G && S.G.mode === 'curl') buildInto(document.getElementById('ghost2'));
|
|
812
|
+
S.ghostDirty = false;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function buildInto(frameEl) {
|
|
816
|
+
var src = S.doc, g = frameEl.contentDocument;
|
|
817
|
+
g.open();
|
|
818
|
+
g.write(DOC_SHELL);
|
|
819
|
+
g.close();
|
|
820
|
+
g.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
|
|
821
|
+
g.documentElement.setAttribute('lang', src.documentElement.getAttribute('lang') || '');
|
|
822
|
+
Array.prototype.forEach.call(src.head.querySelectorAll('style'), function (st) {
|
|
823
|
+
var c = g.createElement('style');
|
|
824
|
+
c.textContent = st.textContent;
|
|
825
|
+
g.head.appendChild(c);
|
|
826
|
+
});
|
|
827
|
+
Array.prototype.forEach.call(src.body.attributes, function (a) {
|
|
828
|
+
if (a.name !== 'style') g.body.setAttribute(a.name, a.value);
|
|
829
|
+
});
|
|
830
|
+
Array.prototype.forEach.call(src.body.childNodes, function (n) {
|
|
831
|
+
g.body.appendChild(g.importNode(n, true));
|
|
832
|
+
});
|
|
833
|
+
S.ghostDirty = false;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
function setGhostPage(p) {
|
|
837
|
+
ghost.contentDocument.body.scrollLeft = pageX(p);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// Animate from the current page to `to` using the ghost. Resolves when finished.
|
|
841
|
+
function turn(to, forward) {
|
|
842
|
+
if (S.G.mode === 'curl') return curlTurn(to, forward);
|
|
843
|
+
var from = S.page, kind = S.G.mode;
|
|
844
|
+
return new Promise(function (resolve) {
|
|
845
|
+
if (S.ghostDirty) buildGhost();
|
|
846
|
+
syncLabels(oldPage);
|
|
847
|
+
var angle = (S.rtl ? 1 : -1) * 90, dur = kind === 'fade' ? 180 : 420;
|
|
848
|
+
oldPage.style.transition = 'none';
|
|
849
|
+
oldPage.style.transformOrigin = S.rtl ? 'right center' : 'left center';
|
|
850
|
+
oldPage.style.boxShadow = 'none';
|
|
851
|
+
oldPage.style.visibility = 'visible';
|
|
852
|
+
function finish() {
|
|
853
|
+
oldPage.style.visibility = 'hidden';
|
|
854
|
+
oldPage.style.transition = 'none';
|
|
855
|
+
oldPage.style.transform = 'none';
|
|
856
|
+
oldPage.style.opacity = '1';
|
|
857
|
+
oldPage.style.boxShadow = 'none';
|
|
858
|
+
resolve();
|
|
859
|
+
}
|
|
860
|
+
if (forward) {
|
|
861
|
+
// old page lifts away over the new one
|
|
862
|
+
setGhostPage(from);
|
|
863
|
+
showPage(to, false);
|
|
864
|
+
oldPage.style.opacity = '1';
|
|
865
|
+
oldPage.style.transform = 'perspective(1600px) rotateY(0deg)';
|
|
866
|
+
void oldPage.offsetWidth;
|
|
867
|
+
if (kind === 'fade') {
|
|
868
|
+
oldPage.style.transition = 'opacity ' + dur + 'ms ease';
|
|
869
|
+
oldPage.style.opacity = '0';
|
|
870
|
+
} else {
|
|
871
|
+
oldPage.style.transition = 'transform ' + dur + 'ms cubic-bezier(.45,.05,.55,.95), box-shadow ' + dur + 'ms';
|
|
872
|
+
oldPage.style.boxShadow = '0 0 38px rgba(0,0,0,.45)';
|
|
873
|
+
oldPage.style.transform = 'perspective(1600px) rotateY(' + angle + 'deg)';
|
|
874
|
+
}
|
|
875
|
+
setTimeout(finish, dur + 30);
|
|
876
|
+
} else {
|
|
877
|
+
// previous page falls back over the current one
|
|
878
|
+
setGhostPage(to);
|
|
879
|
+
if (kind === 'fade') {
|
|
880
|
+
oldPage.style.opacity = '0';
|
|
881
|
+
oldPage.style.transform = 'none';
|
|
882
|
+
} else {
|
|
883
|
+
oldPage.style.transform = 'perspective(1600px) rotateY(' + angle + 'deg)';
|
|
884
|
+
oldPage.style.boxShadow = '0 0 38px rgba(0,0,0,.45)';
|
|
885
|
+
}
|
|
886
|
+
void oldPage.offsetWidth;
|
|
887
|
+
if (kind === 'fade') {
|
|
888
|
+
oldPage.style.transition = 'opacity ' + dur + 'ms ease';
|
|
889
|
+
oldPage.style.opacity = '1';
|
|
890
|
+
} else {
|
|
891
|
+
oldPage.style.transition = 'transform ' + dur + 'ms cubic-bezier(.45,.05,.55,.95)';
|
|
892
|
+
oldPage.style.transform = 'perspective(1600px) rotateY(0deg)';
|
|
893
|
+
}
|
|
894
|
+
setTimeout(function () { showPage(to, false); finish(); }, dur + 30);
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
/* ---------------------------------------------------- page curl (corner fold) */
|
|
901
|
+
// The whole screen is the page. A corner A is dragged to F. The fold line is the perpendicular
|
|
902
|
+
// bisector of A-F:
|
|
903
|
+
// - the part of the old page on the far side stays flat (oldPage, clipped to a polygon),
|
|
904
|
+
// - the part on A's side is mirrored across the fold line and drawn as the back of the page (flap),
|
|
905
|
+
// - the next page shows underneath (the real frame).
|
|
906
|
+
// Page corners are rounded like the device screen.
|
|
907
|
+
var oldPage = document.getElementById('oldPage');
|
|
908
|
+
var curlBox = document.getElementById('curlBox');
|
|
909
|
+
var flap = document.getElementById('flap');
|
|
910
|
+
var flapClip = document.getElementById('flapClip');
|
|
911
|
+
var flapBack = document.getElementById('flapBack');
|
|
912
|
+
var foldShade = document.getElementById('foldShade');
|
|
913
|
+
var ghost2 = document.getElementById('ghost2');
|
|
914
|
+
var curlBusy = false;
|
|
915
|
+
|
|
916
|
+
function shade(hex, amt) {
|
|
917
|
+
var v = [1, 3, 5].map(function (i) { return parseInt(hex.slice(i, i + 2), 16); });
|
|
918
|
+
return 'rgb(' + v.map(function (c) { return Math.max(0, Math.min(255, Math.round(c + c * amt))); }).join(',') + ')';
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function placeCurl(G) {
|
|
922
|
+
var bg = S.settings.bg;
|
|
923
|
+
[oldPage, curlBox, flap, flapClip, flapBack].forEach(function (el) {
|
|
924
|
+
el.style.left = '0px';
|
|
925
|
+
el.style.top = '0px';
|
|
926
|
+
el.style.width = G.W + 'px';
|
|
927
|
+
el.style.height = G.H + 'px';
|
|
928
|
+
});
|
|
929
|
+
oldPage.style.backgroundColor = bg;
|
|
930
|
+
// the text iframes sit inside the page at the text position
|
|
931
|
+
place(ghost2, G);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
// running header / footer are part of the page, so they curl with it
|
|
935
|
+
function syncLabels(c) {
|
|
936
|
+
if (!c._lbl) {
|
|
937
|
+
c._lbl = [document.createElement('div'), document.createElement('div')];
|
|
938
|
+
c._lbl.forEach(function (e) { e.className = 'lbl'; e.setAttribute('dir', 'auto'); c.appendChild(e); });
|
|
939
|
+
}
|
|
940
|
+
c._lbl[0].textContent = hdr.textContent;
|
|
941
|
+
c._lbl[0].style.top = hdr.style.top || '20px';
|
|
942
|
+
c._lbl[0].style.color = hdr.style.color;
|
|
943
|
+
c._lbl[0].style.display = hdr.style.display;
|
|
944
|
+
c._lbl[1].textContent = ftr.textContent;
|
|
945
|
+
c._lbl[1].style.bottom = ftr.style.bottom || '20px';
|
|
946
|
+
c._lbl[1].style.color = ftr.style.color;
|
|
947
|
+
c._lbl[1].style.display = ftr.style.display;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// keep the part of a convex polygon on one side of the line through M with normal n
|
|
951
|
+
function clipPoly(poly, M, n, keepNegative) {
|
|
952
|
+
var out = [];
|
|
953
|
+
for (var i = 0; i < poly.length; i++) {
|
|
954
|
+
var p = poly[i], q = poly[(i + 1) % poly.length];
|
|
955
|
+
var sp = (p.x - M.x) * n.x + (p.y - M.y) * n.y, sq = (q.x - M.x) * n.x + (q.y - M.y) * n.y;
|
|
956
|
+
var inP = keepNegative ? sp <= 0 : sp >= 0, inQ = keepNegative ? sq <= 0 : sq >= 0;
|
|
957
|
+
if (inP) out.push(p);
|
|
958
|
+
if (inP !== inQ) {
|
|
959
|
+
var t = sp / (sp - sq);
|
|
960
|
+
out.push({ x: p.x + (q.x - p.x) * t, y: p.y + (q.y - p.y) * t });
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return out;
|
|
964
|
+
}
|
|
965
|
+
function polyCss(pts) {
|
|
966
|
+
if (pts.length < 3) return 'polygon(0px 0px,0px 0px,0px 0px)';
|
|
967
|
+
return 'polygon(' + pts.map(function (p) { return p.x.toFixed(1) + 'px ' + p.y.toFixed(1) + 'px'; }).join(',') + ')';
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function setGhostPages(p) {
|
|
971
|
+
setGhostPage(p);
|
|
972
|
+
ghost2.contentDocument.body.scrollLeft = pageX(p);
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// Where the dragged corner is for progress q (0 = flat page, 1 = page turned over).
|
|
976
|
+
// The corner first lifts up and across, then sweeps over the page: a diagonal fold that straightens out.
|
|
977
|
+
function curlCorner(st, q) {
|
|
978
|
+
var G = S.G, H = G.H;
|
|
979
|
+
var lift = 0.3 * H * Math.sin(Math.PI * Math.min(1, q));
|
|
980
|
+
return {
|
|
981
|
+
x: st.A.x + (st.E.x - st.A.x) * q,
|
|
982
|
+
y: st.A.y + (st.A.y > H / 2 ? -lift : lift)
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function curlBegin(to, forward, touchY, raw) {
|
|
987
|
+
var G = S.G, W = G.W, H = G.H, rtl = S.rtl, from = S.page;
|
|
988
|
+
if (!raw) {
|
|
989
|
+
if (S.ghostDirty) buildGhost();
|
|
990
|
+
if (forward) { setGhostPages(from); showPage(to, false); } else { setGhostPages(to); }
|
|
991
|
+
}
|
|
992
|
+
var bottom = touchY == null ? true : touchY > H / 2;
|
|
993
|
+
var st = {
|
|
994
|
+
from: from, to: to, forward: forward, p: 0,
|
|
995
|
+
A: { x: rtl ? 0 : W, y: bottom ? H : 0 },
|
|
996
|
+
E: { x: rtl ? 2 * W : -W, y: bottom ? H : 0 }
|
|
997
|
+
};
|
|
998
|
+
syncLabels(oldPage);
|
|
999
|
+
syncLabels(flapClip);
|
|
1000
|
+
oldPage.style.visibility = 'visible';
|
|
1001
|
+
oldPage.style.transition = 'none';
|
|
1002
|
+
oldPage.style.transform = 'none';
|
|
1003
|
+
oldPage.style.opacity = '1';
|
|
1004
|
+
oldPage.style.boxShadow = 'none';
|
|
1005
|
+
curlBox.style.visibility = 'visible';
|
|
1006
|
+
flapBack.style.backgroundColor = shade(S.settings.bg, -0.08);
|
|
1007
|
+
ghost2.style.opacity = '0.32';
|
|
1008
|
+
foldShade.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0) 0px, rgba(0,0,0,.16) 20px, rgba(0,0,0,.42) 25px, rgba(0,0,0,.14) 40px, rgba(0,0,0,0) 90px)';
|
|
1009
|
+
hdr.style.visibility = 'hidden';
|
|
1010
|
+
ftr.style.visibility = 'hidden';
|
|
1011
|
+
curlBusy = true;
|
|
1012
|
+
return st;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
// p: 0 = start of the turn, 1 = finished (for a backward turn the same curl is played in reverse)
|
|
1016
|
+
function curlApply(st, p) {
|
|
1017
|
+
var G = S.G, W = G.W, H = G.H;
|
|
1018
|
+
var q = st.forward ? p : 1 - p;
|
|
1019
|
+
var F = curlCorner(st, q), A = st.A;
|
|
1020
|
+
var dx = F.x - A.x, dy = F.y - A.y, dist = Math.sqrt(dx * dx + dy * dy);
|
|
1021
|
+
if (dist < 1.5) {
|
|
1022
|
+
oldPage.style.clipPath = 'none';
|
|
1023
|
+
oldPage.style.webkitClipPath = 'none';
|
|
1024
|
+
flapClip.style.clipPath = 'polygon(0px 0px,0px 0px,0px 0px)';
|
|
1025
|
+
foldShade.style.display = 'none';
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
var n = { x: dx / dist, y: dy / dist }, M = { x: (A.x + F.x) / 2, y: (A.y + F.y) / 2 };
|
|
1029
|
+
var rect = [{ x: 0, y: 0 }, { x: W, y: 0 }, { x: W, y: H }, { x: 0, y: H }];
|
|
1030
|
+
var flat = polyCss(clipPoly(rect, M, n, false));
|
|
1031
|
+
oldPage.style.clipPath = flat;
|
|
1032
|
+
oldPage.style.webkitClipPath = flat;
|
|
1033
|
+
var fold = polyCss(clipPoly(rect, M, n, true));
|
|
1034
|
+
flapClip.style.clipPath = fold;
|
|
1035
|
+
flapClip.style.webkitClipPath = fold;
|
|
1036
|
+
var mn = M.x * n.x + M.y * n.y;
|
|
1037
|
+
flap.style.transform = 'matrix(' + [1 - 2 * n.x * n.x, -2 * n.x * n.y, -2 * n.x * n.y, 1 - 2 * n.y * n.y, 2 * mn * n.x, 2 * mn * n.y].join(',') + ')';
|
|
1038
|
+
// shading strip centred on the fold line; local +y points towards the corner A
|
|
1039
|
+
var angle = Math.atan2(n.x, -n.y); // direction of the fold line (perpendicular to n)
|
|
1040
|
+
var L = 2 * (W + H);
|
|
1041
|
+
foldShade.style.display = 'block';
|
|
1042
|
+
foldShade.style.width = L + 'px';
|
|
1043
|
+
foldShade.style.height = '90px';
|
|
1044
|
+
foldShade.style.transform = 'translate(' + M.x + 'px,' + M.y + 'px) rotate(' + angle + 'rad) translate(' + (-L / 2) + 'px,-25px)';
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function curlHide() {
|
|
1048
|
+
oldPage.style.visibility = 'hidden';
|
|
1049
|
+
oldPage.style.clipPath = 'none';
|
|
1050
|
+
oldPage.style.webkitClipPath = 'none';
|
|
1051
|
+
curlBox.style.visibility = 'hidden';
|
|
1052
|
+
hdr.style.visibility = '';
|
|
1053
|
+
ftr.style.visibility = '';
|
|
1054
|
+
curlBusy = false;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
function curlEnd(st, commit) {
|
|
1058
|
+
curlHide();
|
|
1059
|
+
if (st.forward && !commit) showPage(st.from, false);
|
|
1060
|
+
if (!st.forward && commit) showPage(st.to, false);
|
|
1061
|
+
curlBusy = false;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function easeInOutCubic(t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; }
|
|
1065
|
+
|
|
1066
|
+
function curlAnimate(st, p0, p1, dur) {
|
|
1067
|
+
return new Promise(function (resolve) {
|
|
1068
|
+
var t0 = null, done = false;
|
|
1069
|
+
function finish() { if (!done) { done = true; resolve(); } }
|
|
1070
|
+
function step(ts) {
|
|
1071
|
+
if (done) return;
|
|
1072
|
+
if (t0 == null) t0 = ts;
|
|
1073
|
+
var t = Math.min(1, (ts - t0) / dur);
|
|
1074
|
+
st.p = p0 + (p1 - p0) * easeInOutCubic(t);
|
|
1075
|
+
curlApply(st, st.p);
|
|
1076
|
+
if (t < 1) requestAnimationFrame(step); else finish();
|
|
1077
|
+
}
|
|
1078
|
+
curlApply(st, p0);
|
|
1079
|
+
requestAnimationFrame(step);
|
|
1080
|
+
setTimeout(function () { if (done) return; st.p = p1; curlApply(st, p1); finish(); }, dur + 400);
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
async function curlTurn(to, forward) {
|
|
1085
|
+
post('pageTurn', { mode: 'curl' });
|
|
1086
|
+
if (S.ghostDirty) {
|
|
1087
|
+
buildGhost();
|
|
1088
|
+
var fonts = [ghost, ghost2].map(function (g) { return g.contentDocument.fonts && g.contentDocument.fonts.ready; }).filter(Boolean);
|
|
1089
|
+
if (fonts.length) await Promise.race([Promise.all(fonts), sleep(400)]);
|
|
1090
|
+
}
|
|
1091
|
+
var st = curlBegin(to, forward, null);
|
|
1092
|
+
await curlAnimate(st, 0, 1, 900);
|
|
1093
|
+
curlEnd(st, true);
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
// finger-follow: called from touchmove while dragging in curl mode
|
|
1097
|
+
function curlDrag(t0, dx) {
|
|
1098
|
+
if (t0.curl === undefined) {
|
|
1099
|
+
var forward = S.rtl ? dx > 0 : dx < 0;
|
|
1100
|
+
var to = S.page + (forward ? 1 : -1);
|
|
1101
|
+
t0.curl = to >= 0 && to < S.pageCount && !curlBusy ? curlBegin(to, forward, t0.y + S.G.top) : null;
|
|
1102
|
+
}
|
|
1103
|
+
if (t0.curl) {
|
|
1104
|
+
t0.curl.p = Math.min(1, Math.abs(dx) / (S.G.W * 0.95));
|
|
1105
|
+
curlApply(t0.curl, t0.curl.p);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/* ----------------------------------------- curl across chapter boundaries */
|
|
1110
|
+
|
|
1111
|
+
// write a chapter into one of the ghost iframes (used to show the previous chapter's last page)
|
|
1112
|
+
function mountInto(frameEl, ch) {
|
|
1113
|
+
var d = frameEl.contentDocument;
|
|
1114
|
+
d.open();
|
|
1115
|
+
d.write(DOC_SHELL);
|
|
1116
|
+
d.close();
|
|
1117
|
+
d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
|
|
1118
|
+
d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
|
|
1119
|
+
ch.css.forEach(function (t) {
|
|
1120
|
+
var st = d.createElement('style');
|
|
1121
|
+
st.textContent = t;
|
|
1122
|
+
d.head.appendChild(st);
|
|
1123
|
+
});
|
|
1124
|
+
var app = d.createElement('style');
|
|
1125
|
+
app.textContent = appCss(S.G);
|
|
1126
|
+
d.head.appendChild(app);
|
|
1127
|
+
Array.prototype.forEach.call(ch.body.attributes, function (a) {
|
|
1128
|
+
if (a.name !== 'style' && a.name.indexOf('on') !== 0) d.body.setAttribute(a.name, a.value);
|
|
1129
|
+
});
|
|
1130
|
+
Array.prototype.forEach.call(ch.body.childNodes, function (n) {
|
|
1131
|
+
d.body.appendChild(d.importNode(n, true));
|
|
1132
|
+
});
|
|
1133
|
+
return d;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
async function loadGhostChapter(index, first) {
|
|
1137
|
+
var ch = await parseChapter(index);
|
|
1138
|
+
await inlineChapter(ch);
|
|
1139
|
+
var d1 = mountInto(ghost, ch);
|
|
1140
|
+
if (S.G.mode === 'curl') mountInto(ghost2, ch);
|
|
1141
|
+
var imgs = Array.prototype.slice.call(d1.images || []).filter(function (im) { return !im.complete; })
|
|
1142
|
+
.map(function (im) { return new Promise(function (r) { im.onload = im.onerror = r; }); });
|
|
1143
|
+
if (d1.fonts && d1.fonts.ready) imgs.push(d1.fonts.ready);
|
|
1144
|
+
if (imgs.length) await Promise.race([Promise.all(imgs), sleep(1500)]);
|
|
1145
|
+
var G = S.G, count = Math.max(1, Math.ceil((d1.body.scrollWidth + G.gap) / (G.pageW + G.gap) - 0.01));
|
|
1146
|
+
setGhostPages(first ? 0 : count - 1);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
// Turn from the last page of a chapter to the first of the next (forward), or the reverse.
|
|
1150
|
+
async function curlChapter(index, forward) {
|
|
1151
|
+
post('pageTurn', { mode: 'curl' });
|
|
1152
|
+
S.ghostLock = true;
|
|
1153
|
+
try {
|
|
1154
|
+
var st;
|
|
1155
|
+
if (forward) {
|
|
1156
|
+
if (S.ghostDirty) { S.ghostLock = false; buildGhost(); S.ghostLock = true; }
|
|
1157
|
+
setGhostPages(S.page);
|
|
1158
|
+
st = curlBegin(index, true, null, true);
|
|
1159
|
+
curlApply(st, 0);
|
|
1160
|
+
await renderChapter(index, 'start'); // the new chapter loads underneath the old page
|
|
1161
|
+
await curlAnimate(st, 0, 1, 900);
|
|
1162
|
+
curlHide();
|
|
1163
|
+
} else {
|
|
1164
|
+
await loadGhostChapter(index); // previous chapter's last page goes into the ghosts
|
|
1165
|
+
st = curlBegin(index, false, null, true);
|
|
1166
|
+
curlApply(st, 0);
|
|
1167
|
+
await curlAnimate(st, 0, 1, 900);
|
|
1168
|
+
await renderChapter(index, 'end'); // load it underneath, then drop the cover
|
|
1169
|
+
curlHide();
|
|
1170
|
+
}
|
|
1171
|
+
} finally {
|
|
1172
|
+
curlHide(); // also on errors: never leave a half-turned page on screen
|
|
1173
|
+
S.ghostLock = false;
|
|
1174
|
+
S.ghostDirty = true;
|
|
1175
|
+
scheduleGhost();
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/* ----------------------------------------------- slide: a sheet laid over another */
|
|
1180
|
+
// Forward: the next page slides in over the current one (which moves back a little).
|
|
1181
|
+
// Backward: the current page slides off and reveals the previous one underneath.
|
|
1182
|
+
// The moving sheet is the ghost layer (a copy of the page); the real frame is the page underneath.
|
|
1183
|
+
var slideBusy = false;
|
|
1184
|
+
|
|
1185
|
+
function slideBegin(to, forward, raw) {
|
|
1186
|
+
var G = S.G, sign = S.rtl ? -1 : 1;
|
|
1187
|
+
var st = { from: S.page, to: to, forward: forward, sign: sign, p: 0 };
|
|
1188
|
+
if (!raw) {
|
|
1189
|
+
if (S.ghostDirty) buildGhost();
|
|
1190
|
+
if (forward) setGhostPage(to);
|
|
1191
|
+
else { setGhostPage(S.page); showPage(to, false); }
|
|
1192
|
+
}
|
|
1193
|
+
syncLabels(oldPage);
|
|
1194
|
+
oldPage.style.clipPath = 'none';
|
|
1195
|
+
oldPage.style.webkitClipPath = 'none';
|
|
1196
|
+
oldPage.style.transition = 'none';
|
|
1197
|
+
oldPage.style.opacity = '1';
|
|
1198
|
+
oldPage.style.boxShadow = (sign > 0 ? '-14px' : '14px') + ' 0 32px rgba(0,0,0,.38)';
|
|
1199
|
+
oldPage.style.visibility = 'visible';
|
|
1200
|
+
hdr.style.visibility = 'hidden';
|
|
1201
|
+
ftr.style.visibility = 'hidden';
|
|
1202
|
+
slideBusy = true;
|
|
1203
|
+
slideApply(st, 0);
|
|
1204
|
+
return st;
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// p: 0 = start of the turn, 1 = finished
|
|
1208
|
+
function slideApply(st, p) {
|
|
1209
|
+
var W = S.G.W;
|
|
1210
|
+
var sheet = st.forward ? st.sign * W * (1 - p) : st.sign * W * p;
|
|
1211
|
+
var under = st.forward ? -st.sign * W * 0.22 * p : -st.sign * W * 0.22 * (1 - p);
|
|
1212
|
+
oldPage.style.transform = 'translate3d(' + sheet.toFixed(1) + 'px,0,0)';
|
|
1213
|
+
frame.style.transform = 'translate3d(' + under.toFixed(1) + 'px,0,0)';
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function slideHide() {
|
|
1217
|
+
oldPage.style.visibility = 'hidden';
|
|
1218
|
+
oldPage.style.transform = 'none';
|
|
1219
|
+
oldPage.style.boxShadow = 'none';
|
|
1220
|
+
frame.style.transform = 'none';
|
|
1221
|
+
hdr.style.visibility = '';
|
|
1222
|
+
ftr.style.visibility = '';
|
|
1223
|
+
slideBusy = false;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
function slideEnd(st, commit) {
|
|
1227
|
+
slideHide();
|
|
1228
|
+
if (st.forward && commit) showPage(st.to, false);
|
|
1229
|
+
if (!st.forward && !commit) showPage(st.from, false);
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
function easeOutCubic(t) { return 1 - Math.pow(1 - t, 3); }
|
|
1233
|
+
|
|
1234
|
+
function slideAnimate(st, p0, p1, dur) {
|
|
1235
|
+
return new Promise(function (resolve) {
|
|
1236
|
+
var t0 = null, done = false;
|
|
1237
|
+
function finish() { if (!done) { done = true; resolve(); } }
|
|
1238
|
+
function step(ts) {
|
|
1239
|
+
if (done) return;
|
|
1240
|
+
if (t0 == null) t0 = ts;
|
|
1241
|
+
var t = Math.min(1, (ts - t0) / dur);
|
|
1242
|
+
st.p = p0 + (p1 - p0) * easeOutCubic(t);
|
|
1243
|
+
slideApply(st, st.p);
|
|
1244
|
+
if (t < 1) requestAnimationFrame(step); else finish();
|
|
1245
|
+
}
|
|
1246
|
+
requestAnimationFrame(step);
|
|
1247
|
+
setTimeout(function () { if (done) return; st.p = p1; slideApply(st, p1); finish(); }, dur + 300);
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
async function slideTurn(to, forward) {
|
|
1252
|
+
post('pageTurn', { mode: 'slide' });
|
|
1253
|
+
if (S.ghostDirty) {
|
|
1254
|
+
buildGhost();
|
|
1255
|
+
var fonts = [ghost].map(function (g) { return g.contentDocument.fonts && g.contentDocument.fonts.ready; }).filter(Boolean);
|
|
1256
|
+
if (fonts.length) await Promise.race([Promise.all(fonts), sleep(300)]);
|
|
1257
|
+
}
|
|
1258
|
+
var st = slideBegin(to, forward, false);
|
|
1259
|
+
await slideAnimate(st, 0, 1, 420);
|
|
1260
|
+
slideEnd(st, true);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// finger-follow: called from touchmove while dragging in slide mode
|
|
1264
|
+
function slideDrag(t0, dx) {
|
|
1265
|
+
if (t0.slide === undefined) {
|
|
1266
|
+
var forward = S.rtl ? dx > 0 : dx < 0;
|
|
1267
|
+
var to = S.page + (forward ? 1 : -1);
|
|
1268
|
+
t0.slide = to >= 0 && to < S.pageCount && !slideBusy && !curlBusy ? slideBegin(to, forward, false) : null;
|
|
1269
|
+
}
|
|
1270
|
+
if (t0.slide) {
|
|
1271
|
+
t0.slide.p = Math.min(1, Math.abs(dx) / (S.G.W * 0.9));
|
|
1272
|
+
slideApply(t0.slide, t0.slide.p);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// Slide across a chapter boundary
|
|
1277
|
+
async function slideChapter(index, forward) {
|
|
1278
|
+
post('pageTurn', { mode: 'slide' });
|
|
1279
|
+
S.ghostLock = true;
|
|
1280
|
+
try {
|
|
1281
|
+
var st;
|
|
1282
|
+
if (forward) {
|
|
1283
|
+
await loadGhostChapter(index, true); // first page of the next chapter is the sheet that slides in
|
|
1284
|
+
st = slideBegin(index, true, true);
|
|
1285
|
+
await slideAnimate(st, 0, 1, 420);
|
|
1286
|
+
await renderChapter(index, 'start');
|
|
1287
|
+
slideHide();
|
|
1288
|
+
} else {
|
|
1289
|
+
if (S.ghostDirty) { S.ghostLock = false; buildGhost(); S.ghostLock = true; }
|
|
1290
|
+
setGhostPages(S.page); // the current page is the sheet that slides off
|
|
1291
|
+
st = slideBegin(index, false, true);
|
|
1292
|
+
await renderChapter(index, 'end'); // previous chapter underneath
|
|
1293
|
+
await slideAnimate(st, 0, 1, 420);
|
|
1294
|
+
slideHide();
|
|
1295
|
+
}
|
|
1296
|
+
} finally {
|
|
1297
|
+
slideHide(); // also on errors: never leave a half-turned page on screen
|
|
1298
|
+
S.ghostLock = false;
|
|
1299
|
+
S.ghostDirty = true;
|
|
1300
|
+
scheduleGhost();
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/* --------------------------------------------- continuous scrolling (Scroll mode) */
|
|
1305
|
+
// Chapters are stacked as sections inside the body; the next ones are loaded below the current one and the
|
|
1306
|
+
// previous one above it. Nothing is moved or rewritten while the user scrolls: "current chapter" simply
|
|
1307
|
+
// follows the middle of the screen (the page offsets are measured against that chapter's own section).
|
|
1308
|
+
|
|
1309
|
+
function rootEl() { return S.root || S.doc.body; }
|
|
1310
|
+
|
|
1311
|
+
function bodyTop() {
|
|
1312
|
+
var d = S.doc, el = d.scrollingElement || d.documentElement;
|
|
1313
|
+
return rootEl().getBoundingClientRect().top + el.scrollTop;
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
function clearExtras() { /* switching mode re-renders the chapter, so there is nothing to remove */ }
|
|
1317
|
+
|
|
1318
|
+
function applyHighlightsFor(el, index) {
|
|
1319
|
+
S.root = el;
|
|
1320
|
+
refreshSegs();
|
|
1321
|
+
S.highlights.filter(function (h) { return h.spine === index; })
|
|
1322
|
+
.sort(function (x, y) { return x.start - y.start; })
|
|
1323
|
+
.forEach(function (h) {
|
|
1324
|
+
var color = HL_COLORS[h.color] ? h.color : 'yellow';
|
|
1325
|
+
wrapRange(h.start, h.end, (h.style === 'underline' ? 'ul-' : 'hl-') + color, h.id);
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
async function mountExtra(index, where) {
|
|
1330
|
+
var token = S.token;
|
|
1331
|
+
var ch = await parseChapter(index);
|
|
1332
|
+
await inlineChapter(ch);
|
|
1333
|
+
if (token !== S.token || !S.doc || !S.G.scroll) return;
|
|
1334
|
+
if (S.sections.some(function (x) { return x.index === index; })) return;
|
|
1335
|
+
var d = S.doc, el = d.createElement('div');
|
|
1336
|
+
el.className = '__ch';
|
|
1337
|
+
el.setAttribute('data-spine', index);
|
|
1338
|
+
Array.prototype.forEach.call(ch.body.childNodes, function (n) { el.appendChild(d.importNode(n, true)); });
|
|
1339
|
+
ch.css.forEach(function (t) {
|
|
1340
|
+
if (S.cssSeen[t]) return;
|
|
1341
|
+
S.cssSeen[t] = true;
|
|
1342
|
+
var st = d.createElement('style');
|
|
1343
|
+
st.textContent = t;
|
|
1344
|
+
d.head.insertBefore(st, d.getElementById('app')); // before the app style so the theme still wins
|
|
1345
|
+
});
|
|
1346
|
+
var sc = d.scrollingElement || d.documentElement, cur = S.root;
|
|
1347
|
+
if (where === 'tail') {
|
|
1348
|
+
d.body.appendChild(el);
|
|
1349
|
+
S.sections.push({ index: index, el: el });
|
|
1350
|
+
} else {
|
|
1351
|
+
d.body.insertBefore(el, S.sections[0].el);
|
|
1352
|
+
S.sections.unshift({ index: index, el: el });
|
|
1353
|
+
sc.scrollTop += el.offsetHeight; // keep what is on screen where it is
|
|
1354
|
+
}
|
|
1355
|
+
applyHighlightsFor(el, index);
|
|
1356
|
+
S.root = cur;
|
|
1357
|
+
refreshSegs();
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// drop chapters that are far from the current one so a long reading session does not grow without bound
|
|
1361
|
+
function evictFar() {
|
|
1362
|
+
var d = S.doc, secs = S.sections;
|
|
1363
|
+
if (!d || !secs || secs.length < 4) return;
|
|
1364
|
+
var sc = d.scrollingElement || d.documentElement;
|
|
1365
|
+
while (secs.length > 1) {
|
|
1366
|
+
var first = secs[0], last = secs[secs.length - 1];
|
|
1367
|
+
if (S.cur - first.index > 2) {
|
|
1368
|
+
var h = first.el.offsetHeight;
|
|
1369
|
+
first.el.parentNode.removeChild(first.el);
|
|
1370
|
+
secs.shift();
|
|
1371
|
+
sc.scrollTop -= h; // keep what is on screen where it is (no scroll anchoring here)
|
|
1372
|
+
} else if (last.index - S.cur > 2) {
|
|
1373
|
+
last.el.parentNode.removeChild(last.el);
|
|
1374
|
+
secs.pop();
|
|
1375
|
+
} else break;
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
async function ensureExtras() {
|
|
1380
|
+
if (!S.doc || !S.G || !S.G.scroll || S.extraBusy || !S.sections || !S.sections.length) return;
|
|
1381
|
+
S.extraBusy = true;
|
|
1382
|
+
try {
|
|
1383
|
+
evictFar();
|
|
1384
|
+
var last = S.sections[S.sections.length - 1].index;
|
|
1385
|
+
if (last < S.spine.length - 1 && last - S.cur < 2) await mountExtra(last + 1, 'tail');
|
|
1386
|
+
var first = S.sections[0].index;
|
|
1387
|
+
if (first > 0 && S.cur - first < 1) await mountExtra(first - 1, 'head');
|
|
1388
|
+
} catch (e) { /* neighbours are optional */ } finally { S.extraBusy = false; }
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
var extrasTimer;
|
|
1392
|
+
function scheduleExtras() {
|
|
1393
|
+
clearTimeout(extrasTimer);
|
|
1394
|
+
extrasTimer = setTimeout(ensureExtras, 350);
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
// follow the middle of the screen; true when the current chapter changed
|
|
1398
|
+
function checkSection() {
|
|
1399
|
+
var d = S.doc;
|
|
1400
|
+
if (!d || !S.G.scroll || !S.sections || !S.sections.length) return false;
|
|
1401
|
+
var sc = d.scrollingElement || d.documentElement, mid = sc.scrollTop + S.G.pageH / 2;
|
|
1402
|
+
for (var i = 0; i < S.sections.length; i++) {
|
|
1403
|
+
var sec = S.sections[i], r = sec.el.getBoundingClientRect(), top = r.top + sc.scrollTop;
|
|
1404
|
+
if (mid >= top && mid < top + r.height) {
|
|
1405
|
+
if (sec.index === S.cur) return false;
|
|
1406
|
+
setCurrentSection(sec);
|
|
1407
|
+
return true;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
return false;
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
function setCurrentSection(sec) {
|
|
1414
|
+
var d = S.doc, sc = d.scrollingElement || d.documentElement;
|
|
1415
|
+
S.cur = sec.index;
|
|
1416
|
+
S.root = sec.el;
|
|
1417
|
+
refreshSegs();
|
|
1418
|
+
S.curText = segsText(S.segs);
|
|
1419
|
+
S.pageStarts = {};
|
|
1420
|
+
S.pageCount = Math.max(1, Math.ceil(sec.el.offsetHeight / S.G.pageH - 0.02));
|
|
1421
|
+
S.page = clamp(Math.round((sc.scrollTop - bodyTop()) / S.G.pageH), 0, S.pageCount - 1);
|
|
1422
|
+
autoLabels();
|
|
1423
|
+
relocate();
|
|
1424
|
+
scheduleExtras();
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
async function goPage(to, forward) {
|
|
1428
|
+
var G = S.G;
|
|
1429
|
+
if (G.scroll) showPage(to, true);
|
|
1430
|
+
else if (G.mode === 'curl' || G.mode === 'fade') await turn(to, forward);
|
|
1431
|
+
else if (G.mode === 'slide') await slideTurn(to, forward);
|
|
1432
|
+
else showPage(to, true);
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
/* -------------------------------------------- offset <-> page geometry */
|
|
1436
|
+
|
|
1437
|
+
function segFor(o) {
|
|
1438
|
+
var lo = 0, hi = S.segs.length - 1;
|
|
1439
|
+
while (lo <= hi) {
|
|
1440
|
+
var mid = (lo + hi) >> 1, s = S.segs[mid];
|
|
1441
|
+
if (o < s.start) hi = mid - 1;
|
|
1442
|
+
else if (o >= s.end) lo = mid + 1;
|
|
1443
|
+
else return { node: s.node, pos: o - s.start };
|
|
1444
|
+
}
|
|
1445
|
+
return null;
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
function pageOfRect(r) {
|
|
1449
|
+
var G = S.G, b = (G.scroll ? rootEl() : S.doc.body).getBoundingClientRect();
|
|
1450
|
+
if (G.scroll) return Math.floor((r.top - b.top + 2) / G.pageH);
|
|
1451
|
+
var sl = S.doc.body.scrollLeft;
|
|
1452
|
+
var rel = S.rtl ? b.right - r.right - sl : r.left - b.left + sl;
|
|
1453
|
+
return Math.floor((rel + 2) / (G.pageW + G.gap));
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
// page of the first renderable character at or after offset o (Infinity if none nearby)
|
|
1457
|
+
function pageAt(o) {
|
|
1458
|
+
var total = S.segs.total, end = Math.min(o + 400, total);
|
|
1459
|
+
for (var k = Math.max(0, o); k < end; k++) {
|
|
1460
|
+
var loc = segFor(k);
|
|
1461
|
+
if (!loc) continue;
|
|
1462
|
+
var r = S.doc.createRange();
|
|
1463
|
+
r.setStart(loc.node, loc.pos);
|
|
1464
|
+
r.setEnd(loc.node, loc.pos + 1);
|
|
1465
|
+
var rects = r.getClientRects();
|
|
1466
|
+
if (rects.length && rects[0].width + rects[0].height > 0) return pageOfRect(rects[0]);
|
|
1467
|
+
}
|
|
1468
|
+
return Infinity;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
function pageStart(p) {
|
|
1472
|
+
var total = S.segs.total;
|
|
1473
|
+
if (p <= 0) return 0;
|
|
1474
|
+
if (p >= S.pageCount) return total;
|
|
1475
|
+
if (S.pageStarts[p] != null) return S.pageStarts[p];
|
|
1476
|
+
var lo = 0, hi = total;
|
|
1477
|
+
while (lo < hi) {
|
|
1478
|
+
var mid = (lo + hi) >> 1;
|
|
1479
|
+
if (pageAt(mid) >= p) hi = mid; else lo = mid + 1;
|
|
1480
|
+
}
|
|
1481
|
+
return (S.pageStarts[p] = lo);
|
|
1482
|
+
}
|
|
1483
|
+
|
|
1484
|
+
function pageForOffset(o) {
|
|
1485
|
+
var p = pageAt(o);
|
|
1486
|
+
return p === Infinity ? S.pageCount - 1 : clamp(p, 0, S.pageCount - 1);
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
function boundaryOffset(node, off) {
|
|
1490
|
+
if (node.nodeType === 3) {
|
|
1491
|
+
var s = S.segMap.get(node);
|
|
1492
|
+
return s ? s.start + off : 0;
|
|
1493
|
+
}
|
|
1494
|
+
var ref = node.childNodes[off], pred;
|
|
1495
|
+
if (ref) {
|
|
1496
|
+
pred = function (sn) { return sn === ref || (ref.compareDocumentPosition(sn) & 4) !== 0; };
|
|
1497
|
+
} else {
|
|
1498
|
+
pred = function (sn) {
|
|
1499
|
+
var c = node.compareDocumentPosition(sn);
|
|
1500
|
+
return (c & 4) !== 0 && (c & 16) === 0;
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
var lo = 0, hi = S.segs.length;
|
|
1504
|
+
while (lo < hi) {
|
|
1505
|
+
var mid = (lo + hi) >> 1;
|
|
1506
|
+
if (pred(S.segs[mid].node)) hi = mid; else lo = mid + 1;
|
|
1507
|
+
}
|
|
1508
|
+
return lo < S.segs.length ? S.segs[lo].start : S.segs.total;
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
function rectOf(x) {
|
|
1512
|
+
var r = x.getBoundingClientRect();
|
|
1513
|
+
return { x: r.left + frame.offsetLeft, y: r.top + frame.offsetTop, width: r.width, height: r.height };
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
/* ------------------------------------------------------------- progress */
|
|
1517
|
+
|
|
1518
|
+
function bookProgress(offset) {
|
|
1519
|
+
if (S.indexed && S.totalLen > 0) return clamp((S.cum[S.cur] + offset) / S.totalLen, 0, 1);
|
|
1520
|
+
return clamp((S.cur + S.page / S.pageCount) / S.spine.length, 0, 1);
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
function relocate() {
|
|
1524
|
+
var start = pageStart(S.page);
|
|
1525
|
+
var end = S.page + 1 >= S.pageCount ? S.segs.total : pageStart(S.page + 1);
|
|
1526
|
+
post('relocate', {
|
|
1527
|
+
spine: S.cur, offset: start, end: end,
|
|
1528
|
+
page: S.page, pageCount: S.pageCount, spineCount: S.spine.length,
|
|
1529
|
+
textLength: S.segs.total,
|
|
1530
|
+
progress: bookProgress(start), chapter: chapterTitle(S.cur, start),
|
|
1531
|
+
excerpt: S.curText.slice(start, start + 120).replace(/\s+/g, ' ').trim(),
|
|
1532
|
+
indexed: S.indexed
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
/* ----------------------------------------------------------- navigation */
|
|
1537
|
+
|
|
1538
|
+
async function renderChapter(i, target) {
|
|
1539
|
+
i = clamp(i, 0, S.spine.length - 1);
|
|
1540
|
+
var token = ++S.token;
|
|
1541
|
+
clearHit(true);
|
|
1542
|
+
S.dataCache = {};
|
|
1543
|
+
var ch = await parseChapter(i);
|
|
1544
|
+
await inlineChapter(ch);
|
|
1545
|
+
if (token !== S.token) return;
|
|
1546
|
+
S.cur = i;
|
|
1547
|
+
S.sel = null;
|
|
1548
|
+
ch.counts = scriptCounts((ch.body.textContent || '').slice(0, 30000));
|
|
1549
|
+
S.rtl = chapterRtl(ch); // text direction and swipe direction follow the chapter on screen
|
|
1550
|
+
mountChapter(ch);
|
|
1551
|
+
await waitAssets();
|
|
1552
|
+
if (token !== S.token) return;
|
|
1553
|
+
layout();
|
|
1554
|
+
applyHighlightsDom();
|
|
1555
|
+
var p = 0;
|
|
1556
|
+
if (target === 'end') p = S.pageCount - 1;
|
|
1557
|
+
else if (target && target.offset != null) p = pageForOffset(target.offset);
|
|
1558
|
+
else if (target && target.fragment) p = pageOfFragment(target.fragment);
|
|
1559
|
+
showPage(p, false);
|
|
1560
|
+
relocate();
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
function pageOfFragment(id) {
|
|
1564
|
+
var d = S.doc;
|
|
1565
|
+
var el = d.getElementById(id) || d.getElementsByName(id)[0];
|
|
1566
|
+
if (!el) return 0;
|
|
1567
|
+
var r = el.getBoundingClientRect();
|
|
1568
|
+
return clamp(pageOfRect(r), 0, S.pageCount - 1);
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
async function next() {
|
|
1572
|
+
clearHit();
|
|
1573
|
+
if (S.page < S.pageCount - 1) { await goPage(S.page + 1, true); relocate(); }
|
|
1574
|
+
else if (S.cur < S.spine.length - 1) {
|
|
1575
|
+
if (S.G.mode === 'curl') await curlChapter(S.cur + 1, true);
|
|
1576
|
+
else if (S.G.mode === 'slide') await slideChapter(S.cur + 1, true);
|
|
1577
|
+
else await renderChapter(S.cur + 1, 'start');
|
|
1578
|
+
}
|
|
1579
|
+
else { showPage(S.page, true); post('end', { edge: 'end' }); }
|
|
1580
|
+
}
|
|
1581
|
+
async function prev() {
|
|
1582
|
+
clearHit();
|
|
1583
|
+
if (S.page > 0) { await goPage(S.page - 1, false); relocate(); }
|
|
1584
|
+
else if (S.cur > 0) {
|
|
1585
|
+
if (S.G.mode === 'curl') await curlChapter(S.cur - 1, false);
|
|
1586
|
+
else if (S.G.mode === 'slide') await slideChapter(S.cur - 1, false);
|
|
1587
|
+
else await renderChapter(S.cur - 1, 'end');
|
|
1588
|
+
}
|
|
1589
|
+
else { showPage(S.page, true); post('end', { edge: 'start' }); }
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
async function gotoLocation(loc) {
|
|
1593
|
+
loc = loc || {};
|
|
1594
|
+
if (loc.progress != null && loc.spine == null) return gotoProgress(loc.progress);
|
|
1595
|
+
var spine = loc.spine != null ? clamp(loc.spine, 0, S.spine.length - 1) : 0;
|
|
1596
|
+
var target = loc.fragment ? { fragment: loc.fragment } : { offset: loc.offset || 0 };
|
|
1597
|
+
if (spine === S.cur && S.doc) {
|
|
1598
|
+
clearHit();
|
|
1599
|
+
showPage(target.fragment ? pageOfFragment(target.fragment) : pageForOffset(target.offset), false);
|
|
1600
|
+
relocate();
|
|
1601
|
+
} else await renderChapter(spine, target);
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
async function gotoProgress(p) {
|
|
1605
|
+
p = clamp(p, 0, 1);
|
|
1606
|
+
if (!S.indexed) { await renderChapter(Math.floor(p * (S.spine.length - 1)), 'start'); return; }
|
|
1607
|
+
var t = p * S.totalLen, i = 0;
|
|
1608
|
+
while (i < S.spine.length - 1 && S.cum[i + 1] <= t) i++;
|
|
1609
|
+
await renderChapter(i, { offset: Math.floor(t - S.cum[i]) });
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
/* ---------------------------------------------------------- settings */
|
|
1613
|
+
|
|
1614
|
+
function applySettings(partial) {
|
|
1615
|
+
var s = S.settings, dirBefore = s.direction;
|
|
1616
|
+
// anchor is measured with the layout that is still on screen
|
|
1617
|
+
var anchor = S.doc ? pageStart(S.page) : 0;
|
|
1618
|
+
Object.keys(partial || {}).forEach(function (k) {
|
|
1619
|
+
if (k === 'insets') {
|
|
1620
|
+
var pi = partial.insets || {};
|
|
1621
|
+
s.insets = { top: pi.top || 0, bottom: pi.bottom || 0, left: pi.left || 0, right: pi.right || 0 };
|
|
1622
|
+
}
|
|
1623
|
+
else if (partial[k] != null) s[k] = partial[k];
|
|
1624
|
+
});
|
|
1625
|
+
if (s.direction !== dirBefore && S.spine.length) {
|
|
1626
|
+
// same rules as when the book was opened: the override first, then page-progression-direction, language, text
|
|
1627
|
+
S.rtl = effectiveRtl(S.bookRtl);
|
|
1628
|
+
post('direction', { rtl: S.rtl });
|
|
1629
|
+
if (S.doc) { renderChapter(S.cur, { offset: anchor }); return; }
|
|
1630
|
+
}
|
|
1631
|
+
if (S.doc && S.G && S.G.scroll !== (s.mode === 'scroll')) {
|
|
1632
|
+
renderChapter(S.cur, { offset: anchor });
|
|
1633
|
+
return;
|
|
1634
|
+
}
|
|
1635
|
+
if (S.doc) {
|
|
1636
|
+
layout();
|
|
1637
|
+
showPage(pageForOffset(anchor), false);
|
|
1638
|
+
relocate();
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
function relayout() {
|
|
1643
|
+
var anchor = pageStart(S.page);
|
|
1644
|
+
layout();
|
|
1645
|
+
showPage(pageForOffset(anchor), false);
|
|
1646
|
+
relocate();
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
/* ----------------------------------------------------------- highlights */
|
|
1650
|
+
|
|
1651
|
+
function unwrapMarks(selector) {
|
|
1652
|
+
var marks = Array.prototype.slice.call(S.doc.querySelectorAll(selector));
|
|
1653
|
+
var parents = [];
|
|
1654
|
+
marks.forEach(function (m) {
|
|
1655
|
+
var p = m.parentNode;
|
|
1656
|
+
while (m.firstChild) p.insertBefore(m.firstChild, m);
|
|
1657
|
+
p.removeChild(m);
|
|
1658
|
+
parents.push(p);
|
|
1659
|
+
});
|
|
1660
|
+
parents.forEach(function (p) { if (p.parentNode) p.normalize(); });
|
|
1661
|
+
return marks.length;
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
function wrapRange(a, b, cls, id) {
|
|
1665
|
+
var items = [];
|
|
1666
|
+
S.segs.forEach(function (seg) {
|
|
1667
|
+
if (seg.end <= a || seg.start >= b) return;
|
|
1668
|
+
var la = Math.max(a, seg.start) - seg.start, lb = Math.min(b, seg.end) - seg.start;
|
|
1669
|
+
if (lb <= la) return;
|
|
1670
|
+
if (!seg.node.data.slice(la, lb).trim()) {
|
|
1671
|
+
var disp = seg.node.parentNode && S.win.getComputedStyle(seg.node.parentNode).display;
|
|
1672
|
+
if (!disp || disp.indexOf('inline') !== 0) return;
|
|
1673
|
+
}
|
|
1674
|
+
items.push({ node: seg.node, la: la, lb: lb });
|
|
1675
|
+
});
|
|
1676
|
+
items.forEach(function (it) {
|
|
1677
|
+
var mid = it.node;
|
|
1678
|
+
if (it.la > 0) mid = mid.splitText(it.la);
|
|
1679
|
+
if (it.lb - it.la < mid.data.length) mid.splitText(it.lb - it.la);
|
|
1680
|
+
var m = S.doc.createElement('mark');
|
|
1681
|
+
m.className = cls;
|
|
1682
|
+
m.setAttribute('data-hl', id);
|
|
1683
|
+
mid.parentNode.insertBefore(m, mid);
|
|
1684
|
+
m.appendChild(mid);
|
|
1685
|
+
});
|
|
1686
|
+
refreshSegs();
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
function applyHighlightsDom() {
|
|
1690
|
+
unwrapMarks('mark[data-hl]:not(.hit)');
|
|
1691
|
+
var cur = S.root;
|
|
1692
|
+
if (S.sections && S.sections.length) S.sections.forEach(function (sec) { applyHighlightsFor(sec.el, sec.index); });
|
|
1693
|
+
else applyHighlightsFor(S.doc.body, S.cur);
|
|
1694
|
+
S.root = cur;
|
|
1695
|
+
refreshSegs();
|
|
1696
|
+
S.ghostDirty = true;
|
|
1697
|
+
scheduleGhost();
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
function showHit(offset, length) {
|
|
1701
|
+
clearHit(true);
|
|
1702
|
+
wrapRange(offset, offset + length, 'hit', '__hit');
|
|
1703
|
+
}
|
|
1704
|
+
function clearHit(skipRefresh) {
|
|
1705
|
+
if (!S.doc) return;
|
|
1706
|
+
if (unwrapMarks('mark.hit') && !skipRefresh) refreshSegs();
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
/* ------------------------------------------------------------- search */
|
|
1710
|
+
|
|
1711
|
+
// Search folding: one output character per kept input character, so a hit in the folded text maps back to
|
|
1712
|
+
// exact offsets in the original (`map`). Dropped: diacritics (tashkeel, Quranic marks), tatweel, joiners and
|
|
1713
|
+
// bidi marks. Unified: Arabic/Persian/Pashto letter variants, all digit systems, case, runs of whitespace.
|
|
1714
|
+
var FOLD = {
|
|
1715
|
+
'ي': 'ی', 'ى': 'ی', 'ې': 'ی', 'ۍ': 'ی', 'ێ': 'ی', 'ئ': 'ی', // ye
|
|
1716
|
+
'ك': 'ک', 'ڪ': 'ک', // kaf
|
|
1717
|
+
'ة': 'ه', 'ۀ': 'ه', 'ہ': 'ه', 'ە': 'ه', 'ھ': 'ه', // heh
|
|
1718
|
+
'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ٱ': 'ا', // alef
|
|
1719
|
+
'ؤ': 'و'
|
|
1720
|
+
};
|
|
1721
|
+
var DROP = /[ً-ٰٟۖ-ۭـ---]/;
|
|
1722
|
+
function foldText(text, breaks) {
|
|
1723
|
+
var out = [], map = [], brk = breaks && breaks.length ? new Set(breaks) : null, lastSpace = true;
|
|
1724
|
+
for (var i = 0; i < text.length; i++) {
|
|
1725
|
+
var c = text.charAt(i), code = text.charCodeAt(i);
|
|
1726
|
+
if (brk && brk.has(i) && !lastSpace) { out.push(' '); map.push(i); lastSpace = true; }
|
|
1727
|
+
if (DROP.test(c)) continue;
|
|
1728
|
+
if (/\s/.test(c)) {
|
|
1729
|
+
if (!lastSpace) { out.push(' '); map.push(i); lastSpace = true; }
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1732
|
+
lastSpace = false;
|
|
1733
|
+
if (code >= 0x660 && code <= 0x669) c = String.fromCharCode(48 + code - 0x660);
|
|
1734
|
+
else if (code >= 0x6F0 && code <= 0x6F9) c = String.fromCharCode(48 + code - 0x6F0);
|
|
1735
|
+
else if (FOLD[c]) c = FOLD[c];
|
|
1736
|
+
else if (code < 0x3000) {
|
|
1737
|
+
var lc = c.toLowerCase();
|
|
1738
|
+
c = lc.charAt(0); // toLowerCase can change the length (e.g. U+0130); keep it one unit
|
|
1739
|
+
}
|
|
1740
|
+
out.push(c);
|
|
1741
|
+
map.push(i);
|
|
1742
|
+
}
|
|
1743
|
+
return { s: out.join(''), map: map };
|
|
1744
|
+
}
|
|
1745
|
+
function fold(s) { return foldText(s.trim(), null).s; }
|
|
1746
|
+
|
|
1747
|
+
async function search(query, id) {
|
|
1748
|
+
S.searchId = id;
|
|
1749
|
+
var q = fold(query);
|
|
1750
|
+
if (q.length < 2) { post('searchResults', { id: id, results: [], done: true }); return; }
|
|
1751
|
+
var waited = 0;
|
|
1752
|
+
while (!S.indexed) {
|
|
1753
|
+
if (S.searchId !== id) return;
|
|
1754
|
+
if (S.indexFailed || waited > 120000) { post('searchResults', { id: id, results: [], done: true }); return; }
|
|
1755
|
+
await sleep(80);
|
|
1756
|
+
waited += 80;
|
|
1757
|
+
}
|
|
1758
|
+
var total = 0;
|
|
1759
|
+
for (var i = 0; i < S.spine.length; i++) {
|
|
1760
|
+
if (S.searchId !== id) return;
|
|
1761
|
+
var text = S.texts[i], fd = foldText(text, S.breaks[i]), folded = fd.s, from = 0, found = [], at;
|
|
1762
|
+
while ((at = folded.indexOf(q, from)) >= 0 && total + found.length < 500) {
|
|
1763
|
+
var start = fd.map[at], end = fd.map[at + q.length - 1] + 1;
|
|
1764
|
+
found.push({
|
|
1765
|
+
spine: i, offset: start, length: end - start, chapter: chapterTitle(i),
|
|
1766
|
+
before: text.slice(Math.max(0, start - 40), start).replace(/\s+/g, ' '),
|
|
1767
|
+
match: text.slice(start, end),
|
|
1768
|
+
after: text.slice(end, end + 60).replace(/\s+/g, ' ')
|
|
1769
|
+
});
|
|
1770
|
+
from = at + q.length;
|
|
1771
|
+
}
|
|
1772
|
+
total += found.length;
|
|
1773
|
+
post('searchResults', { id: id, results: found, done: i === S.spine.length - 1 || total >= 500 });
|
|
1774
|
+
if (total >= 500) return;
|
|
1775
|
+
if (i % 4 === 3) await sleep(0);
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
var BLOCK = /^(p|div|li|ul|ol|dl|dt|dd|h[1-6]|table|tr|td|th|blockquote|section|article|aside|header|footer|pre|figure|figcaption|nav|body|main|address)$/i;
|
|
1780
|
+
function blockOf(node, stop) {
|
|
1781
|
+
for (var n = node.parentNode; n && n !== stop; n = n.parentNode) {
|
|
1782
|
+
if (n.localName && BLOCK.test(n.localName)) return n;
|
|
1783
|
+
}
|
|
1784
|
+
return stop;
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
async function buildIndex() {
|
|
1788
|
+
var cum = 0, id = S.openId;
|
|
1789
|
+
var texts = [], cums = [], breaks = [];
|
|
1790
|
+
for (var i = 0; i < S.spine.length; i++) {
|
|
1791
|
+
var t = '', br = [];
|
|
1792
|
+
try {
|
|
1793
|
+
var ch = await parseChapter(i);
|
|
1794
|
+
var segs = collectSegs(ch.body), prev = null;
|
|
1795
|
+
// positions where one block ends and the next begins: search must not match across them
|
|
1796
|
+
segs.forEach(function (sg) {
|
|
1797
|
+
var b = blockOf(sg.node, ch.body);
|
|
1798
|
+
if (prev && b !== prev && sg.start > 0) br.push(sg.start);
|
|
1799
|
+
prev = b;
|
|
1800
|
+
});
|
|
1801
|
+
t = segsText(segs);
|
|
1802
|
+
} catch (e) { /* an unreadable chapter is simply not searchable */ }
|
|
1803
|
+
if (id !== S.openId) return;
|
|
1804
|
+
texts[i] = t; cums[i] = cum; breaks[i] = br; cum += t.length;
|
|
1805
|
+
if (i % 3 === 2) await sleep(0);
|
|
1806
|
+
}
|
|
1807
|
+
if (id !== S.openId) return;
|
|
1808
|
+
S.texts = texts; S.cum = cums; S.breaks = breaks;
|
|
1809
|
+
S.totalLen = cum;
|
|
1810
|
+
S.indexed = true;
|
|
1811
|
+
post('indexed', { totalLength: cum, cum: S.cum });
|
|
1812
|
+
if (S.doc) relocate();
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/* ------------------------------------------------------------- events */
|
|
1816
|
+
|
|
1817
|
+
function handleLink(a) {
|
|
1818
|
+
var href = a.getAttribute('href') || '';
|
|
1819
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {
|
|
1820
|
+
// only web and mail links leave the book; intent:, file:, tel:, custom schemes ... are ignored
|
|
1821
|
+
if (/^(https?|mailto):/i.test(href)) post('link', { href: href });
|
|
1822
|
+
return;
|
|
1823
|
+
}
|
|
1824
|
+
var frag = href.indexOf('#') >= 0 ? href.split('#')[1] : '';
|
|
1825
|
+
try { frag = decodeURIComponent(frag); } catch (e) { /* keep as is */ }
|
|
1826
|
+
var host = a.closest && a.closest('.__ch');
|
|
1827
|
+
var path = resolvePath(S.spine[host ? +host.getAttribute('data-spine') : S.cur].path, href);
|
|
1828
|
+
var idx = path ? spineIndexOfPath(path) : -1;
|
|
1829
|
+
if (idx < 0) return;
|
|
1830
|
+
var from = { spine: S.cur, offset: S.doc ? pageStart(S.page) : 0 };
|
|
1831
|
+
enqueue(function () {
|
|
1832
|
+
post('linkJump', from); // lets the host offer a way back after a footnote or cross reference
|
|
1833
|
+
return gotoLocation({ spine: idx, fragment: frag, offset: 0 });
|
|
1834
|
+
});
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
function attachListeners(d) {
|
|
1838
|
+
d.addEventListener('click', function (e) {
|
|
1839
|
+
if (S.dragged) return;
|
|
1840
|
+
var sel = d.getSelection();
|
|
1841
|
+
if (sel && !sel.isCollapsed) return;
|
|
1842
|
+
var t = e.target, a = t.closest && t.closest('a'), m = t.closest && t.closest('mark[data-hl]');
|
|
1843
|
+
if (a) { e.preventDefault(); handleLink(a); return; }
|
|
1844
|
+
if (m && m.getAttribute('data-hl') !== '__hit') {
|
|
1845
|
+
post('highlightTap', { id: m.getAttribute('data-hl'), rect: rectOf(m) });
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
var x = (e.clientX + S.G.left) / S.G.W;
|
|
1849
|
+
var zone = S.G.scroll || (x >= 0.25 && x <= 0.75) ? 'center' : (x < 0.25 ? 'left' : 'right');
|
|
1850
|
+
if (zone === 'center') { clearHit(); post('tap', { zone: 'center' }); return; }
|
|
1851
|
+
var forward = (zone === 'right') !== S.rtl;
|
|
1852
|
+
enqueue(forward ? next : prev);
|
|
1853
|
+
}, true);
|
|
1854
|
+
|
|
1855
|
+
var t0 = null;
|
|
1856
|
+
d.addEventListener('touchstart', function (e) {
|
|
1857
|
+
if (e.touches.length !== 1) { endTouch(true); return; }
|
|
1858
|
+
var t = e.touches[0], el = d.scrollingElement || d.documentElement;
|
|
1859
|
+
t0 = { x: t.clientX, y: t.clientY, time: Date.now(), drag: false, dx: 0, dy: 0, base: currentX(), top: el.scrollTop };
|
|
1860
|
+
}, { passive: true });
|
|
1861
|
+
d.addEventListener('touchmove', function (e) {
|
|
1862
|
+
if (!t0) return;
|
|
1863
|
+
var sel = d.getSelection();
|
|
1864
|
+
if (sel && !sel.isCollapsed) { t0 = null; return; }
|
|
1865
|
+
var t = e.touches[0], dx = t.clientX - t0.x, dy = t.clientY - t0.y;
|
|
1866
|
+
t0.dx = dx; t0.dy = dy;
|
|
1867
|
+
if (S.G.scroll) return;
|
|
1868
|
+
if (!t0.drag) {
|
|
1869
|
+
if (Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy) * 1.5) t0.drag = true; else return;
|
|
1870
|
+
}
|
|
1871
|
+
e.preventDefault();
|
|
1872
|
+
if (S.G.mode === 'slide') slideDrag(t0, dx);
|
|
1873
|
+
else if (S.G.mode === 'curl') curlDrag(t0, dx);
|
|
1874
|
+
}, { passive: false });
|
|
1875
|
+
// cancelled: the system took the touch (edge-swipe gesture, notification shade, a second finger ...)
|
|
1876
|
+
function endTouch(cancelled) {
|
|
1877
|
+
var tt = t0;
|
|
1878
|
+
t0 = null;
|
|
1879
|
+
if (!tt) return;
|
|
1880
|
+
var G = S.G;
|
|
1881
|
+
if (G.scroll) {
|
|
1882
|
+
if (cancelled) return;
|
|
1883
|
+
// keep scrolling into the next/previous chapter when the edge is already reached
|
|
1884
|
+
var el = d.scrollingElement || d.documentElement;
|
|
1885
|
+
var still = Math.abs(el.scrollTop - tt.top) < 3;
|
|
1886
|
+
if (still && Math.abs(tt.dy) > 60) {
|
|
1887
|
+
if (tt.dy < 0 && el.scrollTop + G.pageH >= el.scrollHeight - 2) enqueue(next);
|
|
1888
|
+
else if (tt.dy > 0 && el.scrollTop <= 1) enqueue(prev);
|
|
1889
|
+
}
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
if (!tt.drag) return;
|
|
1893
|
+
var fastEnough = Math.abs(tt.dx) / Math.max(1, Date.now() - tt.time) > 0.5 && Math.abs(tt.dx) > 30;
|
|
1894
|
+
if (tt.slide) {
|
|
1895
|
+
var ss = tt.slide;
|
|
1896
|
+
S.dragged = true;
|
|
1897
|
+
setTimeout(function () { S.dragged = false; }, 350);
|
|
1898
|
+
var scommit = !cancelled && (ss.p > 0.28 || fastEnough);
|
|
1899
|
+
if (scommit) post('pageTurn', { mode: 'slide' });
|
|
1900
|
+
enqueue(async function () {
|
|
1901
|
+
try {
|
|
1902
|
+
await slideAnimate(ss, ss.p, scommit ? 1 : 0, scommit ? 140 + 280 * (1 - ss.p) : 120 + 220 * ss.p);
|
|
1903
|
+
} finally { slideEnd(ss, scommit); }
|
|
1904
|
+
if (scommit) relocate();
|
|
1905
|
+
});
|
|
1906
|
+
return;
|
|
1907
|
+
}
|
|
1908
|
+
if (tt.curl) {
|
|
1909
|
+
var st = tt.curl;
|
|
1910
|
+
S.dragged = true;
|
|
1911
|
+
setTimeout(function () { S.dragged = false; }, 350);
|
|
1912
|
+
var commit = !cancelled && (st.p > 0.3 || fastEnough);
|
|
1913
|
+
if (commit) post('pageTurn', { mode: 'curl' });
|
|
1914
|
+
enqueue(async function () {
|
|
1915
|
+
try {
|
|
1916
|
+
await curlAnimate(st, st.p, commit ? 1 : 0, commit ? 260 + 560 * (1 - st.p) : 200 + 300 * st.p);
|
|
1917
|
+
} finally { curlEnd(st, commit); }
|
|
1918
|
+
if (commit) relocate();
|
|
1919
|
+
});
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
var dx = tt.dx, dt = Math.max(1, Date.now() - tt.time);
|
|
1923
|
+
var go = !cancelled && (Math.abs(dx) > G.W * 0.2 || (Math.abs(dx) / dt > 0.5 && Math.abs(dx) > 30));
|
|
1924
|
+
S.dragged = true;
|
|
1925
|
+
setTimeout(function () { S.dragged = false; }, 350);
|
|
1926
|
+
if (!go) { if (G.mode === 'slide') showPage(S.page, true); return; }
|
|
1927
|
+
var forward = S.rtl ? dx > 0 : dx < 0;
|
|
1928
|
+
enqueue(forward ? next : prev);
|
|
1929
|
+
}
|
|
1930
|
+
d.addEventListener('touchend', function () { endTouch(false); }, { passive: true });
|
|
1931
|
+
d.addEventListener('touchcancel', function () { endTouch(true); }, { passive: true });
|
|
1932
|
+
|
|
1933
|
+
d.defaultView.addEventListener('scroll', debounce(function () {
|
|
1934
|
+
if (d !== S.doc || !S.G.scroll) return;
|
|
1935
|
+
if (checkSection()) return;
|
|
1936
|
+
var el = d.scrollingElement || d.documentElement;
|
|
1937
|
+
var p = clamp(Math.round((el.scrollTop - bodyTop()) / S.G.pageH), 0, S.pageCount - 1);
|
|
1938
|
+
if (p !== S.page) { S.page = p; autoLabels(); relocate(); }
|
|
1939
|
+
}, 120));
|
|
1940
|
+
|
|
1941
|
+
d.addEventListener('selectionchange', debounce(function () {
|
|
1942
|
+
if (d !== S.doc) return;
|
|
1943
|
+
var sel = d.getSelection();
|
|
1944
|
+
if (!sel || sel.rangeCount === 0 || sel.isCollapsed) {
|
|
1945
|
+
if (S.sel) { S.sel = null; post('selectionClear'); }
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
var r = sel.getRangeAt(0);
|
|
1949
|
+
if (!rootEl().contains(r.startContainer) || !rootEl().contains(r.endContainer)) return;
|
|
1950
|
+
var a = boundaryOffset(r.startContainer, r.startOffset), b = boundaryOffset(r.endContainer, r.endOffset);
|
|
1951
|
+
if (b <= a) return;
|
|
1952
|
+
S.sel = { spine: S.cur, start: a, end: b, text: sel.toString() };
|
|
1953
|
+
post('selection', { spine: S.cur, start: a, end: b, text: S.sel.text, rect: rectOf(r) });
|
|
1954
|
+
}, 180));
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
/* ------------------------------------------------------------ commands */
|
|
1958
|
+
|
|
1959
|
+
var queue = Promise.resolve();
|
|
1960
|
+
|
|
1961
|
+
// Every piece of work (commands, taps, swipes) runs one after another. A failure is reported and never
|
|
1962
|
+
// breaks the chain, so the reader keeps responding after an error.
|
|
1963
|
+
function enqueue(fn) {
|
|
1964
|
+
queue = queue.then(fn).catch(function (err) {
|
|
1965
|
+
post('error', { message: String((err && err.message) || err) });
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
async function handle(c) {
|
|
1970
|
+
switch (c.cmd) {
|
|
1971
|
+
case 'open':
|
|
1972
|
+
S.openId = (S.openId || 0) + 1;
|
|
1973
|
+
S.token++;
|
|
1974
|
+
// nothing may leak from the previous book (cached images such as the cover, labels, direction)
|
|
1975
|
+
S.dataCache = {}; S.fragCache = {}; S.obf = {}; S.obfKeys = {}; S.identifier = '';
|
|
1976
|
+
S.breaks = []; S.indexFailed = false; S.labelsExternal = false;
|
|
1977
|
+
S.bookRtl = false; S.rtl = false; S.ppd = ''; S.contentRtl = false; S.spine = []; S.toc = [];
|
|
1978
|
+
hdr.textContent = ''; ftr.textContent = '';
|
|
1979
|
+
S.cur = -1;
|
|
1980
|
+
S.page = 0;
|
|
1981
|
+
S.pageCount = 1;
|
|
1982
|
+
S.doc = null;
|
|
1983
|
+
S.win = null;
|
|
1984
|
+
S.segs = [];
|
|
1985
|
+
S.curText = '';
|
|
1986
|
+
S.pageStarts = {};
|
|
1987
|
+
S.texts = [];
|
|
1988
|
+
S.cum = [];
|
|
1989
|
+
S.totalLen = 0;
|
|
1990
|
+
S.indexed = false;
|
|
1991
|
+
S.sel = null;
|
|
1992
|
+
S.searchId = -1;
|
|
1993
|
+
applySettings(c.settings);
|
|
1994
|
+
S.highlights = c.highlights || [];
|
|
1995
|
+
var data = c.data != null ? c.data : chunks.join('');
|
|
1996
|
+
chunks = [];
|
|
1997
|
+
try {
|
|
1998
|
+
await openBook(data);
|
|
1999
|
+
buildIndex().catch(function () { S.indexFailed = true; }); // search and exact progress are optional
|
|
2000
|
+
post('loaded', { spineCount: S.spine.length });
|
|
2001
|
+
await gotoLocation(c.location);
|
|
2002
|
+
} catch (err) {
|
|
2003
|
+
post('error', { message: String((err && err.message) || err), fatal: true });
|
|
2004
|
+
}
|
|
2005
|
+
break;
|
|
2006
|
+
case 'settings': applySettings(c.settings); break;
|
|
2007
|
+
case 'labels':
|
|
2008
|
+
S.labelsExternal = true;
|
|
2009
|
+
hdr.textContent = c.header || '';
|
|
2010
|
+
ftr.textContent = c.footer || '';
|
|
2011
|
+
break;
|
|
2012
|
+
case 'highlights':
|
|
2013
|
+
S.highlights = c.list || [];
|
|
2014
|
+
if (S.doc) { applyHighlightsDom(); }
|
|
2015
|
+
break;
|
|
2016
|
+
case 'next': await next(); break;
|
|
2017
|
+
case 'prev': await prev(); break;
|
|
2018
|
+
case 'goto': await gotoLocation(c.location); break;
|
|
2019
|
+
case 'showHit': if (S.doc) showHit(c.offset, c.length); break;
|
|
2020
|
+
case 'clearSelection':
|
|
2021
|
+
if (S.doc) S.doc.getSelection().removeAllRanges();
|
|
2022
|
+
S.sel = null;
|
|
2023
|
+
break;
|
|
2024
|
+
case 'search': search(c.query, c.id); break;
|
|
2025
|
+
case 'cancelSearch': S.searchId = c.id || -1; break;
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
// the book arrives in pieces (one injected call each) before the 'open' command
|
|
2030
|
+
var chunks = [];
|
|
2031
|
+
window.__chunk = function (reset, s) {
|
|
2032
|
+
if (reset) chunks = [];
|
|
2033
|
+
chunks.push(s);
|
|
2034
|
+
};
|
|
2035
|
+
|
|
2036
|
+
window.__cmd = function (str) {
|
|
2037
|
+
var c;
|
|
2038
|
+
try { c = JSON.parse(str); } catch (e) { return; }
|
|
2039
|
+
enqueue(function () { return handle(c); });
|
|
2040
|
+
};
|
|
2041
|
+
window.addEventListener('message', function (e) { if (typeof e.data === 'string') window.__cmd(e.data); });
|
|
2042
|
+
document.addEventListener('message', function (e) { if (typeof e.data === 'string') window.__cmd(e.data); });
|
|
2043
|
+
window.addEventListener('resize', debounce(function () { if (S.doc) enqueue(function () { if (S.doc) relayout(); }); }, 150));
|
|
2044
|
+
window.__reader = S; // debugging aid
|
|
2045
|
+
|
|
2046
|
+
post('ready');
|
|
2047
|
+
})();
|