aksos-react-native-epub-reader 0.1.0 → 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.
@@ -18,7 +18,22 @@
18
18
  var RN = window.ReactNativeWebView;
19
19
  var XLINK = 'http://www.w3.org/1999/xlink';
20
20
  var XHTML = 'http://www.w3.org/1999/xhtml';
21
- var RTL_LANGS = ['ar', 'fa', 'ps', 'ur', 'he', 'yi', 'ckb', 'ug', 'sd', 'dv'];
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;
22
37
  var HL_COLORS = {
23
38
  yellow: ['rgba(255,214,10,.42)', '#e6b800'],
24
39
  green: ['rgba(52,199,89,.38)', '#2fb24f'],
@@ -31,13 +46,17 @@
31
46
  var ghost = document.getElementById('ghost');
32
47
  var hdr = document.getElementById('hdr');
33
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');
34
52
 
35
53
  var S = {
36
- zip: null, names: {}, spine: [], toc: [], rtl: false, meta: {},
54
+ zip: null, names: {}, spine: [], toc: [], rtl: false, bookRtl: false, ppd: '', contentRtl: false, meta: {},
55
+ obf: {}, identifier: '', obfKeys: {}, breaks: [],
37
56
  texts: [], cum: [], totalLen: 0, indexed: false,
38
57
  cur: -1, page: 0, pageCount: 1, token: 0,
39
58
  doc: null, win: null, segs: [], segMap: null, curText: '',
40
- pageStarts: {}, dataCache: {},
59
+ pageStarts: {}, dataCache: {}, fragCache: {},
41
60
  highlights: [], sel: null, searchId: 0, dragged: false,
42
61
  G: null, ghostDirty: true, labelsExternal: false,
43
62
  settings: {
@@ -84,16 +103,104 @@
84
103
  try { return decodeURIComponent(joined); } catch (e) { return joined; }
85
104
  }
86
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
+ }
87
112
  function getFile(path) {
88
113
  if (!path) return null;
89
114
  var f = S.zip.file(path);
90
115
  if (f) return f;
91
- var real = S.names[path.toLowerCase()];
116
+ var real = S.names[nameKey(path)];
92
117
  return real ? S.zip.file(real) : null;
93
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
+
94
142
  function readText(path) {
95
143
  var f = getFile(path);
96
- return f ? f.async('string') : Promise.resolve(null);
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);
97
204
  }
98
205
 
99
206
  var MIME = {
@@ -108,8 +215,12 @@
108
215
  function dataUri(path) {
109
216
  if (S.dataCache[path]) return Promise.resolve(S.dataCache[path]);
110
217
  var f = getFile(path);
111
- if (!f) return Promise.resolve(null);
112
- return f.async('base64').then(function (b64) {
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) {
113
224
  var uri = 'data:' + mimeOf(path) + ';base64,' + b64;
114
225
  S.dataCache[path] = uri;
115
226
  return uri;
@@ -118,8 +229,17 @@
118
229
 
119
230
  /* ---------------------------------------------------------------- xml */
120
231
 
121
- function parseXml(s) { return new DOMParser().parseFromString(s, 'application/xml'); }
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, '&amp;'), 'application/xml');
237
+ if (d.getElementsByTagName('parsererror').length) throw new Error('XML is malformed');
238
+ }
239
+ return d;
240
+ }
122
241
  function byLocal(root, name) {
242
+ if (!root) return [];
123
243
  return Array.prototype.slice.call(root.getElementsByTagNameNS('*', name));
124
244
  }
125
245
  function firstLocal(root, name) { return byLocal(root, name)[0] || null; }
@@ -140,13 +260,35 @@
140
260
  /* --------------------------------------------------------- book opening */
141
261
 
142
262
  async function openBook(b64) {
143
- S.zip = await JSZip.loadAsync(b64, { base64: true });
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).'); }
144
265
  S.names = {};
145
- Object.keys(S.zip.files).forEach(function (n) { S.names[n.toLowerCase()] = n; });
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.');
146
272
 
273
+ S.obf = {};
147
274
  var enc = await readText('META-INF/encryption.xml');
148
275
  if (enc) {
149
- var algos = byLocal(parseXml(enc), 'EncryptionMethod').map(function (e) { return e.getAttribute('Algorithm') || ''; });
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
+ }
150
292
  var drm = algos.some(function (a) {
151
293
  return a.indexOf('idpf.org/2008/embedding') < 0 && a.indexOf('ns.adobe.com/pdf/enc#RC') < 0;
152
294
  });
@@ -155,11 +297,15 @@
155
297
 
156
298
  var container = await readText('META-INF/container.xml');
157
299
  if (!container) throw new Error('Not a valid EPUB (container.xml is missing).');
158
- var rootfile = firstLocal(parseXml(container), 'rootfile');
300
+ var rootfile;
301
+ try { rootfile = firstLocal(parseXml(container), 'rootfile'); }
302
+ catch (e) { throw new Error('Not a valid EPUB (container.xml is malformed).'); }
159
303
  var opfPath = rootfile && rootfile.getAttribute('full-path');
160
304
  var opfText = opfPath && await readText(opfPath);
161
305
  if (!opfText) throw new Error('Not a valid EPUB (package document is missing).');
162
- var opf = parseXml(opfText);
306
+ var opf;
307
+ try { opf = parseXml(opfText); }
308
+ catch (e) { throw new Error('Not a valid EPUB (package document is malformed).'); }
163
309
 
164
310
  var manifest = {};
165
311
  byLocal(opf, 'item').forEach(function (it) {
@@ -173,12 +319,22 @@
173
319
  });
174
320
 
175
321
  var spineEl = firstLocal(opf, 'spine');
322
+ if (!spineEl) throw new Error('Not a valid EPUB (the package has no spine).');
176
323
  S.spine = byLocal(spineEl, 'itemref').map(function (r) {
177
324
  return manifest[r.getAttribute('idref')];
178
325
  }).filter(function (m) {
179
326
  return m && /html|xml/i.test(m.type) || (m && /\.x?html?$/i.test(m.path));
180
327
  });
181
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 = {};
182
338
 
183
339
  var title = firstLocal(opf, 'title');
184
340
  var lang = firstLocal(opf, 'language');
@@ -188,35 +344,52 @@
188
344
  language: lang ? lang.textContent.trim() : '',
189
345
  publisher: (firstLocal(opf, 'publisher') || { textContent: '' }).textContent.trim()
190
346
  };
191
- var ppd = spineEl.getAttribute('page-progression-direction');
192
- var langBase = S.meta.language.toLowerCase().split('-')[0];
193
- var autoRtl = ppd ? ppd === 'rtl' : RTL_LANGS.indexOf(langBase) >= 0;
194
- var dirSetting = S.settings.direction;
195
- S.rtl = dirSetting === 'rtl' ? true : dirSetting === 'ltr' ? false : autoRtl;
196
-
197
- if (dirSetting === 'auto' && !S.rtl) {
198
- var byContent = await contentIsRtl();
199
- if (byContent) S.rtl = true;
200
- }
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);
201
352
 
202
353
  S.toc = await parseToc(opf, manifest, spineEl, opfPath);
203
354
  post('metadata', S.meta);
204
- post('toc', { items: S.toc, rtl: S.rtl, spineCount: S.spine.length });
355
+ post('toc', { items: S.toc, rtl: effectiveRtl(S.bookRtl), spineCount: S.spine.length });
205
356
  sendCover(opf, manifest);
206
357
  }
207
358
 
208
- // true when the first chapters are mostly Arabic-script text (Pashto, Dari, Persian, Arabic, Urdu ...)
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 ...)
209
373
  async function contentIsRtl() {
210
- var arabic = 0, latin = 0;
211
- var AR = /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/g, LA = /[A-Za-z]/g;
212
- for (var i = 0; i < Math.min(S.spine.length, 6) && arabic + latin < 1500; i++) {
374
+ var rtl = 0, latin = 0;
375
+ for (var i = 0; i < Math.min(S.spine.length, 6) && rtl + latin < 1500; i++) {
213
376
  try {
214
- var text = (await parseChapter(i)).body.textContent || '';
215
- arabic += (text.match(AR) || []).length;
216
- latin += (text.match(LA) || []).length;
377
+ var c = scriptCounts((await parseChapter(i)).body.textContent || '');
378
+ rtl += c.rtl; latin += c.latin;
217
379
  } catch (e) { /* ignore unreadable chapters */ }
218
380
  }
219
- return arabic > 40 && arabic > latin * 1.5;
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;
220
393
  }
221
394
 
222
395
  function spineIndexOfPath(path) {
@@ -267,8 +440,10 @@
267
440
  Object.keys(manifest).map(function (k) { return manifest[k]; }).filter(function (m) { return /ncx/.test(m.type); })[0];
268
441
  if (ncx) {
269
442
  var ncxText = await readText(ncx.path);
270
- if (ncxText) {
271
- var map = firstLocal(parseXml(ncxText), 'navMap');
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');
272
447
  (function walk(parent, level) {
273
448
  Array.prototype.forEach.call(parent.children, function (np) {
274
449
  if (np.localName !== 'navPoint') return;
@@ -297,10 +472,27 @@
297
472
  }
298
473
  }
299
474
 
300
- function chapterTitle(i) {
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) {
301
487
  var best = '';
302
488
  for (var k = 0; k < S.toc.length; k++) {
303
- if (S.toc[k].spine <= i) best = S.toc[k].label; else break;
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;
304
496
  }
305
497
  return best || S.meta.title || '';
306
498
  }
@@ -320,9 +512,36 @@
320
512
  }
321
513
  function segsText(segs) { return segs.map(function (s) { return s.node.data; }).join(''); }
322
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
+
323
540
  async function parseChapter(i) {
324
541
  var it = S.spine[i];
325
- var raw = await readText(it.path);
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>'; }
326
545
  if (raw == null) raw = '<html><body><p></p></body></html>';
327
546
  var doc = parseMarkup(raw);
328
547
  var body = doc.body || doc.documentElement;
@@ -333,24 +552,29 @@
333
552
  else if (/stylesheet/i.test(el.getAttribute('rel') || '')) refs.push({ href: el.getAttribute('href'), base: it.path });
334
553
  el.parentNode.removeChild(el);
335
554
  });
336
- Array.prototype.slice.call(body.querySelectorAll('script,noscript,iframe,object,embed')).forEach(function (el) {
337
- el.parentNode.removeChild(el);
338
- });
339
- return { index: i, path: it.path, body: body, refs: refs, lang: doc.documentElement.getAttribute('xml:lang') || doc.documentElement.getAttribute('lang') || '', css: null };
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
+ };
340
562
  }
341
563
 
342
564
  async function rewriteCss(css, basePath) {
343
565
  css = css.replace(/@import[^;]*;/g, '');
344
566
  var re = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g, m, seen = {}, jobs = [];
345
567
  while ((m = re.exec(css))) {
346
- if (seen[m[0]] || /^[a-z][a-z0-9+.-]*:/i.test(m[2])) continue;
568
+ if (seen[m[0]]) continue;
347
569
  seen[m[0]] = 1;
348
- jobs.push({ full: m[0], rel: m[2] });
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]) });
349
573
  }
350
574
  for (var k = 0; k < jobs.length; k++) {
351
- var p = resolvePath(basePath, jobs[k].rel);
575
+ var p = jobs[k].remote ? null : resolvePath(basePath, jobs[k].rel);
352
576
  var uri = p && await dataUri(p);
353
- if (uri) css = css.split(jobs[k].full).join('url("' + uri + '")');
577
+ css = css.split(jobs[k].full).join('url("' + (uri || '') + '")');
354
578
  }
355
579
  return css;
356
580
  }
@@ -381,7 +605,7 @@
381
605
  function mountChapter(ch) {
382
606
  var d = frame.contentDocument;
383
607
  d.open();
384
- d.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
608
+ d.write(DOC_SHELL);
385
609
  d.close();
386
610
  d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
387
611
  d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
@@ -412,6 +636,7 @@
412
636
  S.root = holder;
413
637
  S.sections = scrollMode ? [{ index: ch.index, el: holder }] : [];
414
638
  S.cssSeen = {};
639
+ S.fragCache = {};
415
640
  ch.css.forEach(function (t) { S.cssSeen[t] = true; });
416
641
  S.ghostDirty = true;
417
642
  refreshSegs();
@@ -439,12 +664,13 @@
439
664
  var s = S.settings, W = window.innerWidth, H = window.innerHeight;
440
665
  var mx = s.marginX, ins = s.insets;
441
666
  var scroll = s.mode === 'scroll';
442
- var pageW = Math.max(120, W - 2 * mx), pageH = Math.max(120, H - ins.top - ins.bottom);
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);
443
669
  var cols = 1;
444
670
  if (!scroll) cols = s.columns === 'auto' ? (pageW >= 640 ? 2 : 1) : (+s.columns === 2 ? 2 : 1);
445
671
  var colW = pageW;
446
672
  if (cols === 2) { colW = Math.floor((pageW - s.gap) / 2); pageW = colW * 2 + s.gap; }
447
- return { W: W, H: H, mx: mx, top: ins.top, gap: s.gap, pageW: pageW, pageH: pageH, cols: cols, colW: colW, scroll: scroll, mode: s.mode };
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 };
448
674
  }
449
675
 
450
676
  function appCss(G) {
@@ -455,6 +681,8 @@
455
681
  'html{margin:0!important;padding:0!important;background:' + s.bg + '!important;-webkit-text-size-adjust:none;direction:' + dir + '!important;' +
456
682
  (G.scroll ? 'overflow-x:hidden!important;overflow-y:scroll!important;touch-action:pan-y;overflow-anchor:none;' : 'overflow:hidden!important;touch-action:none;') + '}',
457
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}',
458
686
  'body{margin:0!important;padding:0!important;border:0!important;width:' + G.pageW + 'px!important;max-width:none!important;min-width:0!important;' +
459
687
  (G.scroll ? 'height:auto!important;'
460
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;') +
@@ -462,7 +690,8 @@
462
690
  (ff ? 'font-family:' + ff + '!important;' : '') +
463
691
  (s.justify ? 'text-align:justify!important;hyphens:auto;-webkit-hyphens:auto;' : '') +
464
692
  (s.bold ? 'font-weight:600!important;' : '') +
465
- (s.letterSpacing ? 'letter-spacing:' + s.letterSpacing + 'em!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;' : '') +
466
695
  (s.wordSpacing ? 'word-spacing:' + s.wordSpacing + 'em!important;' : '') +
467
696
  '-webkit-touch-callout:none;-webkit-user-select:text;user-select:text;overflow-wrap:break-word;word-wrap:break-word}',
468
697
  'body *{color:inherit!important;background-color:transparent!important;' + (ff ? 'font-family:inherit!important;' : '') + (s.bold ? 'font-weight:inherit;' : '') + 'box-sizing:border-box}',
@@ -483,7 +712,7 @@
483
712
  }
484
713
 
485
714
  function place(el, G) {
486
- el.style.left = G.mx + 'px';
715
+ el.style.left = G.left + 'px';
487
716
  el.style.top = G.top + 'px';
488
717
  el.style.width = G.pageW + 'px';
489
718
  el.style.height = G.pageH + 'px';
@@ -521,7 +750,8 @@
521
750
 
522
751
  function autoLabels() {
523
752
  if (S.labelsExternal) return;
524
- hdr.textContent = chapterTitle(S.cur);
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);
525
755
  ftr.textContent = (S.page + 1) + ' / ' + S.pageCount;
526
756
  }
527
757
 
@@ -577,17 +807,18 @@
577
807
  function buildGhost() {
578
808
  if (S.ghostLock) return;
579
809
  buildInto(ghost);
580
- var g2 = document.getElementById("ghost2");
581
- if (g2) buildInto(g2);
810
+ // the second copy is only used by the page curl
811
+ if (S.G && S.G.mode === 'curl') buildInto(document.getElementById('ghost2'));
582
812
  S.ghostDirty = false;
583
813
  }
584
814
 
585
815
  function buildInto(frameEl) {
586
816
  var src = S.doc, g = frameEl.contentDocument;
587
817
  g.open();
588
- g.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
818
+ g.write(DOC_SHELL);
589
819
  g.close();
590
820
  g.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
821
+ g.documentElement.setAttribute('lang', src.documentElement.getAttribute('lang') || '');
591
822
  Array.prototype.forEach.call(src.head.querySelectorAll('style'), function (st) {
592
823
  var c = g.createElement('style');
593
824
  c.textContent = st.textContent;
@@ -704,7 +935,7 @@
704
935
  function syncLabels(c) {
705
936
  if (!c._lbl) {
706
937
  c._lbl = [document.createElement('div'), document.createElement('div')];
707
- c._lbl.forEach(function (e) { e.className = 'lbl'; c.appendChild(e); });
938
+ c._lbl.forEach(function (e) { e.className = 'lbl'; e.setAttribute('dir', 'auto'); c.appendChild(e); });
708
939
  }
709
940
  c._lbl[0].textContent = hdr.textContent;
710
941
  c._lbl[0].style.top = hdr.style.top || '20px';
@@ -881,9 +1112,10 @@
881
1112
  function mountInto(frameEl, ch) {
882
1113
  var d = frameEl.contentDocument;
883
1114
  d.open();
884
- d.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
1115
+ d.write(DOC_SHELL);
885
1116
  d.close();
886
1117
  d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
1118
+ d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
887
1119
  ch.css.forEach(function (t) {
888
1120
  var st = d.createElement('style');
889
1121
  st.textContent = t;
@@ -905,7 +1137,7 @@
905
1137
  var ch = await parseChapter(index);
906
1138
  await inlineChapter(ch);
907
1139
  var d1 = mountInto(ghost, ch);
908
- mountInto(ghost2, ch);
1140
+ if (S.G.mode === 'curl') mountInto(ghost2, ch);
909
1141
  var imgs = Array.prototype.slice.call(d1.images || []).filter(function (im) { return !im.complete; })
910
1142
  .map(function (im) { return new Promise(function (r) { im.onload = im.onerror = r; }); });
911
1143
  if (d1.fonts && d1.fonts.ready) imgs.push(d1.fonts.ready);
@@ -937,6 +1169,7 @@
937
1169
  curlHide();
938
1170
  }
939
1171
  } finally {
1172
+ curlHide(); // also on errors: never leave a half-turned page on screen
940
1173
  S.ghostLock = false;
941
1174
  S.ghostDirty = true;
942
1175
  scheduleGhost();
@@ -1061,6 +1294,7 @@
1061
1294
  slideHide();
1062
1295
  }
1063
1296
  } finally {
1297
+ slideHide(); // also on errors: never leave a half-turned page on screen
1064
1298
  S.ghostLock = false;
1065
1299
  S.ghostDirty = true;
1066
1300
  scheduleGhost();
@@ -1123,10 +1357,30 @@
1123
1357
  refreshSegs();
1124
1358
  }
1125
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
+
1126
1379
  async function ensureExtras() {
1127
1380
  if (!S.doc || !S.G || !S.G.scroll || S.extraBusy || !S.sections || !S.sections.length) return;
1128
1381
  S.extraBusy = true;
1129
1382
  try {
1383
+ evictFar();
1130
1384
  var last = S.sections[S.sections.length - 1].index;
1131
1385
  if (last < S.spine.length - 1 && last - S.cur < 2) await mountExtra(last + 1, 'tail');
1132
1386
  var first = S.sections[0].index;
@@ -1273,7 +1527,7 @@
1273
1527
  spine: S.cur, offset: start, end: end,
1274
1528
  page: S.page, pageCount: S.pageCount, spineCount: S.spine.length,
1275
1529
  textLength: S.segs.total,
1276
- progress: bookProgress(start), chapter: chapterTitle(S.cur),
1530
+ progress: bookProgress(start), chapter: chapterTitle(S.cur, start),
1277
1531
  excerpt: S.curText.slice(start, start + 120).replace(/\s+/g, ' ').trim(),
1278
1532
  indexed: S.indexed
1279
1533
  });
@@ -1291,6 +1545,8 @@
1291
1545
  if (token !== S.token) return;
1292
1546
  S.cur = i;
1293
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
1294
1550
  mountChapter(ch);
1295
1551
  await waitAssets();
1296
1552
  if (token !== S.token) return;
@@ -1360,12 +1616,16 @@
1360
1616
  // anchor is measured with the layout that is still on screen
1361
1617
  var anchor = S.doc ? pageStart(S.page) : 0;
1362
1618
  Object.keys(partial || {}).forEach(function (k) {
1363
- if (k === 'insets') s.insets = { top: partial.insets.top, bottom: partial.insets.bottom };
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
+ }
1364
1623
  else if (partial[k] != null) s[k] = partial[k];
1365
1624
  });
1366
1625
  if (s.direction !== dirBefore && S.spine.length) {
1367
- var lang = S.meta.language.toLowerCase().split('-')[0];
1368
- S.rtl = s.direction === 'rtl' ? true : s.direction === 'ltr' ? false : RTL_LANGS.indexOf(lang) >= 0;
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 });
1369
1629
  if (S.doc) { renderChapter(S.cur, { offset: anchor }); return; }
1370
1630
  }
1371
1631
  if (S.doc && S.G && S.G.scroll !== (s.mode === 'scroll')) {
@@ -1448,29 +1708,64 @@
1448
1708
 
1449
1709
  /* ------------------------------------------------------------- search */
1450
1710
 
1451
- var FOLD = { 'ي': 'ی', 'ك': 'ک', 'ة': 'ه', 'ى': 'ی', 'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ۀ': 'ه', 'ہ': 'ه', 'ە': 'ه' };
1452
- function fold(s) {
1453
- return s.toLowerCase().replace(/[يكةىأإآۀہە]/g, function (c) { return FOLD[c]; });
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 };
1454
1744
  }
1745
+ function fold(s) { return foldText(s.trim(), null).s; }
1455
1746
 
1456
1747
  async function search(query, id) {
1457
1748
  S.searchId = id;
1458
- var q = fold(query.trim());
1749
+ var q = fold(query);
1459
1750
  if (q.length < 2) { post('searchResults', { id: id, results: [], done: true }); return; }
1751
+ var waited = 0;
1460
1752
  while (!S.indexed) {
1461
1753
  if (S.searchId !== id) return;
1754
+ if (S.indexFailed || waited > 120000) { post('searchResults', { id: id, results: [], done: true }); return; }
1462
1755
  await sleep(80);
1756
+ waited += 80;
1463
1757
  }
1464
1758
  var total = 0;
1465
1759
  for (var i = 0; i < S.spine.length; i++) {
1466
1760
  if (S.searchId !== id) return;
1467
- var text = S.texts[i], folded = fold(text), from = 0, found = [], at;
1761
+ var text = S.texts[i], fd = foldText(text, S.breaks[i]), folded = fd.s, from = 0, found = [], at;
1468
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;
1469
1764
  found.push({
1470
- spine: i, offset: at, length: q.length, chapter: chapterTitle(i),
1471
- before: text.slice(Math.max(0, at - 40), at).replace(/\s+/g, ' '),
1472
- match: text.slice(at, at + q.length),
1473
- after: text.slice(at + q.length, at + q.length + 60).replace(/\s+/g, ' ')
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, ' ')
1474
1769
  });
1475
1770
  from = at + q.length;
1476
1771
  }
@@ -1481,18 +1776,36 @@
1481
1776
  }
1482
1777
  }
1483
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
+
1484
1787
  async function buildIndex() {
1485
1788
  var cum = 0, id = S.openId;
1486
- var texts = [], cums = [];
1789
+ var texts = [], cums = [], breaks = [];
1487
1790
  for (var i = 0; i < S.spine.length; i++) {
1488
- var ch = await parseChapter(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 */ }
1489
1803
  if (id !== S.openId) return;
1490
- var t = segsText(collectSegs(ch.body));
1491
- texts[i] = t; cums[i] = cum; cum += t.length;
1804
+ texts[i] = t; cums[i] = cum; breaks[i] = br; cum += t.length;
1492
1805
  if (i % 3 === 2) await sleep(0);
1493
1806
  }
1494
1807
  if (id !== S.openId) return;
1495
- S.texts = texts; S.cum = cums;
1808
+ S.texts = texts; S.cum = cums; S.breaks = breaks;
1496
1809
  S.totalLen = cum;
1497
1810
  S.indexed = true;
1498
1811
  post('indexed', { totalLength: cum, cum: S.cum });
@@ -1503,13 +1816,22 @@
1503
1816
 
1504
1817
  function handleLink(a) {
1505
1818
  var href = a.getAttribute('href') || '';
1506
- if (/^[a-z][a-z0-9+.-]*:/i.test(href)) { post('link', { href: href }); return; }
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
+ }
1507
1824
  var frag = href.indexOf('#') >= 0 ? href.split('#')[1] : '';
1825
+ try { frag = decodeURIComponent(frag); } catch (e) { /* keep as is */ }
1508
1826
  var host = a.closest && a.closest('.__ch');
1509
1827
  var path = resolvePath(S.spine[host ? +host.getAttribute('data-spine') : S.cur].path, href);
1510
1828
  var idx = path ? spineIndexOfPath(path) : -1;
1511
1829
  if (idx < 0) return;
1512
- queue = queue.then(function () { return gotoLocation({ spine: idx, fragment: frag, offset: 0 }); });
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
+ });
1513
1835
  }
1514
1836
 
1515
1837
  function attachListeners(d) {
@@ -1523,16 +1845,16 @@
1523
1845
  post('highlightTap', { id: m.getAttribute('data-hl'), rect: rectOf(m) });
1524
1846
  return;
1525
1847
  }
1526
- var x = (e.clientX + S.G.mx) / S.G.W;
1848
+ var x = (e.clientX + S.G.left) / S.G.W;
1527
1849
  var zone = S.G.scroll || (x >= 0.25 && x <= 0.75) ? 'center' : (x < 0.25 ? 'left' : 'right');
1528
1850
  if (zone === 'center') { clearHit(); post('tap', { zone: 'center' }); return; }
1529
1851
  var forward = (zone === 'right') !== S.rtl;
1530
- queue = queue.then(forward ? next : prev);
1852
+ enqueue(forward ? next : prev);
1531
1853
  }, true);
1532
1854
 
1533
1855
  var t0 = null;
1534
1856
  d.addEventListener('touchstart', function (e) {
1535
- if (e.touches.length !== 1) { t0 = null; return; }
1857
+ if (e.touches.length !== 1) { endTouch(true); return; }
1536
1858
  var t = e.touches[0], el = d.scrollingElement || d.documentElement;
1537
1859
  t0 = { x: t.clientX, y: t.clientY, time: Date.now(), drag: false, dx: 0, dy: 0, base: currentX(), top: el.scrollTop };
1538
1860
  }, { passive: true });
@@ -1550,32 +1872,35 @@
1550
1872
  if (S.G.mode === 'slide') slideDrag(t0, dx);
1551
1873
  else if (S.G.mode === 'curl') curlDrag(t0, dx);
1552
1874
  }, { passive: false });
1553
- d.addEventListener('touchend', function () {
1875
+ // cancelled: the system took the touch (edge-swipe gesture, notification shade, a second finger ...)
1876
+ function endTouch(cancelled) {
1554
1877
  var tt = t0;
1555
1878
  t0 = null;
1556
1879
  if (!tt) return;
1557
1880
  var G = S.G;
1558
1881
  if (G.scroll) {
1882
+ if (cancelled) return;
1559
1883
  // keep scrolling into the next/previous chapter when the edge is already reached
1560
1884
  var el = d.scrollingElement || d.documentElement;
1561
1885
  var still = Math.abs(el.scrollTop - tt.top) < 3;
1562
1886
  if (still && Math.abs(tt.dy) > 60) {
1563
- if (tt.dy < 0 && el.scrollTop + G.pageH >= el.scrollHeight - 2) queue = queue.then(next);
1564
- else if (tt.dy > 0 && el.scrollTop <= 1) queue = queue.then(prev);
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);
1565
1889
  }
1566
1890
  return;
1567
1891
  }
1568
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;
1569
1894
  if (tt.slide) {
1570
1895
  var ss = tt.slide;
1571
1896
  S.dragged = true;
1572
1897
  setTimeout(function () { S.dragged = false; }, 350);
1573
- var sfast = Math.abs(tt.dx) / Math.max(1, Date.now() - tt.time) > 0.5 && Math.abs(tt.dx) > 30;
1574
- var scommit = ss.p > 0.28 || sfast;
1898
+ var scommit = !cancelled && (ss.p > 0.28 || fastEnough);
1575
1899
  if (scommit) post('pageTurn', { mode: 'slide' });
1576
- queue = queue.then(async function () {
1577
- await slideAnimate(ss, ss.p, scommit ? 1 : 0, scommit ? 140 + 280 * (1 - ss.p) : 120 + 220 * ss.p);
1578
- slideEnd(ss, scommit);
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); }
1579
1904
  if (scommit) relocate();
1580
1905
  });
1581
1906
  return;
@@ -1584,24 +1909,26 @@
1584
1909
  var st = tt.curl;
1585
1910
  S.dragged = true;
1586
1911
  setTimeout(function () { S.dragged = false; }, 350);
1587
- var fast = Math.abs(tt.dx) / Math.max(1, Date.now() - tt.time) > 0.5 && Math.abs(tt.dx) > 30;
1588
- var commit = st.p > 0.3 || fast;
1912
+ var commit = !cancelled && (st.p > 0.3 || fastEnough);
1589
1913
  if (commit) post('pageTurn', { mode: 'curl' });
1590
- queue = queue.then(async function () {
1591
- await curlAnimate(st, st.p, commit ? 1 : 0, commit ? 260 + 560 * (1 - st.p) : 200 + 300 * st.p);
1592
- curlEnd(st, commit);
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); }
1593
1918
  if (commit) relocate();
1594
1919
  });
1595
1920
  return;
1596
1921
  }
1597
1922
  var dx = tt.dx, dt = Math.max(1, Date.now() - tt.time);
1598
- var go = Math.abs(dx) > G.W * 0.2 || (Math.abs(dx) / dt > 0.5 && Math.abs(dx) > 30);
1923
+ var go = !cancelled && (Math.abs(dx) > G.W * 0.2 || (Math.abs(dx) / dt > 0.5 && Math.abs(dx) > 30));
1599
1924
  S.dragged = true;
1600
1925
  setTimeout(function () { S.dragged = false; }, 350);
1601
1926
  if (!go) { if (G.mode === 'slide') showPage(S.page, true); return; }
1602
1927
  var forward = S.rtl ? dx > 0 : dx < 0;
1603
- queue = queue.then(forward ? next : prev);
1604
- }, { passive: true });
1928
+ enqueue(forward ? next : prev);
1929
+ }
1930
+ d.addEventListener('touchend', function () { endTouch(false); }, { passive: true });
1931
+ d.addEventListener('touchcancel', function () { endTouch(true); }, { passive: true });
1605
1932
 
1606
1933
  d.defaultView.addEventListener('scroll', debounce(function () {
1607
1934
  if (d !== S.doc || !S.G.scroll) return;
@@ -1631,11 +1958,24 @@
1631
1958
 
1632
1959
  var queue = Promise.resolve();
1633
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
+
1634
1969
  async function handle(c) {
1635
1970
  switch (c.cmd) {
1636
1971
  case 'open':
1637
1972
  S.openId = (S.openId || 0) + 1;
1638
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 = '';
1639
1979
  S.cur = -1;
1640
1980
  S.page = 0;
1641
1981
  S.pageCount = 1;
@@ -1652,10 +1992,16 @@
1652
1992
  S.searchId = -1;
1653
1993
  applySettings(c.settings);
1654
1994
  S.highlights = c.highlights || [];
1655
- await openBook(c.data);
1656
- buildIndex();
1657
- post('loaded', { spineCount: S.spine.length });
1658
- await gotoLocation(c.location);
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
+ }
1659
2005
  break;
1660
2006
  case 'settings': applySettings(c.settings); break;
1661
2007
  case 'labels':
@@ -1680,16 +2026,21 @@
1680
2026
  }
1681
2027
  }
1682
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
+
1683
2036
  window.__cmd = function (str) {
1684
2037
  var c;
1685
2038
  try { c = JSON.parse(str); } catch (e) { return; }
1686
- queue = queue.then(function () { return handle(c); }).catch(function (err) {
1687
- post('error', { message: String((err && err.message) || err) });
1688
- });
2039
+ enqueue(function () { return handle(c); });
1689
2040
  };
1690
2041
  window.addEventListener('message', function (e) { if (typeof e.data === 'string') window.__cmd(e.data); });
1691
2042
  document.addEventListener('message', function (e) { if (typeof e.data === 'string') window.__cmd(e.data); });
1692
- window.addEventListener('resize', debounce(function () { if (S.doc) relayout(); }, 150));
2043
+ window.addEventListener('resize', debounce(function () { if (S.doc) enqueue(function () { if (S.doc) relayout(); }); }, 150));
1693
2044
  window.__reader = S; // debugging aid
1694
2045
 
1695
2046
  post('ready');