aksos-react-native-epub-reader 0.1.0 → 0.2.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +178 -20
  3. package/lib/EpubReader.d.ts +66 -15
  4. package/lib/EpubReader.js +168 -30
  5. package/lib/EpubReaderView.d.ts +37 -5
  6. package/lib/EpubReaderView.js +194 -93
  7. package/lib/cfiOrder.d.ts +2 -0
  8. package/lib/cfiOrder.js +34 -0
  9. package/lib/engine/html.js +1 -1
  10. package/lib/index.d.ts +5 -2
  11. package/lib/index.js +5 -1
  12. package/lib/strings.d.ts +94 -0
  13. package/lib/strings.js +96 -0
  14. package/lib/themes.d.ts +28 -6
  15. package/lib/themes.js +80 -20
  16. package/lib/types.d.ts +82 -1
  17. package/lib/ui/AppearanceSheet.d.ts +4 -2
  18. package/lib/ui/AppearanceSheet.js +40 -26
  19. package/lib/ui/ContentsSheet.d.ts +2 -0
  20. package/lib/ui/ContentsSheet.js +32 -22
  21. package/lib/ui/CustomizeSheet.d.ts +4 -2
  22. package/lib/ui/CustomizeSheet.js +31 -27
  23. package/lib/ui/HighlightMenu.d.ts +4 -2
  24. package/lib/ui/HighlightMenu.js +13 -11
  25. package/lib/ui/NoteEditor.js +12 -9
  26. package/lib/ui/SearchSheet.js +19 -6
  27. package/lib/ui/Sheet.js +7 -4
  28. package/lib/ui/Text.d.ts +9 -0
  29. package/lib/ui/Text.js +62 -0
  30. package/package.json +81 -76
  31. package/src/EpubReader.tsx +239 -43
  32. package/src/EpubReaderView.tsx +287 -99
  33. package/src/cfiOrder.ts +28 -0
  34. package/src/engine/epubcfi.js +527 -0
  35. package/src/engine/html.ts +1 -1
  36. package/src/engine/reader.js +1273 -157
  37. package/src/index.ts +5 -2
  38. package/src/strings.ts +187 -0
  39. package/src/themes.ts +97 -21
  40. package/src/types.ts +88 -2
  41. package/src/ui/AppearanceSheet.tsx +47 -29
  42. package/src/ui/ContentsSheet.tsx +34 -22
  43. package/src/ui/CustomizeSheet.tsx +27 -21
  44. package/src/ui/HighlightMenu.tsx +17 -13
  45. package/src/ui/NoteEditor.tsx +12 -9
  46. package/src/ui/SearchSheet.tsx +22 -5
  47. package/src/ui/Sheet.tsx +8 -5
  48. package/src/ui/Text.tsx +27 -0
@@ -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,22 +46,28 @@
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,
62
+ views: new Map(), viewJobs: {}, viewFailed: {}, cfiCache: new Map(), locs: null, locationChars: 150, repairZeroWidth: true, fontCss: '',
43
63
  settings: {
44
64
  bg: '#ffffff', fg: '#000000', link: '#0a60ff',
45
65
  fontFamily: 'original', fontSize: 18, lineHeight: 1.5,
46
66
  marginX: 28, gap: 48, justify: false, bold: false,
47
67
  columns: 'auto', letterSpacing: 0, wordSpacing: 0, mode: 'slide',
48
68
  insets: { top: 60, bottom: 52 }, direction: 'auto',
49
- showHeader: true, showFooter: true
69
+ showHeader: true, showFooter: true,
70
+ bookColors: 'theme', highlightColors: null, highlightOpacity: null, maxZoom: 3
50
71
  }
51
72
  };
52
73
 
@@ -84,16 +105,104 @@
84
105
  try { return decodeURIComponent(joined); } catch (e) { return joined; }
85
106
  }
86
107
 
108
+ // lookup key: forward slashes, NFC (macOS zips store NFD names), case-insensitive
109
+ function nameKey(n) {
110
+ n = String(n).replace(/\\/g, '/');
111
+ try { n = n.normalize('NFC'); } catch (e) { /* old engines */ }
112
+ return n.toLowerCase();
113
+ }
87
114
  function getFile(path) {
88
115
  if (!path) return null;
89
116
  var f = S.zip.file(path);
90
117
  if (f) return f;
91
- var real = S.names[path.toLowerCase()];
118
+ var real = S.names[nameKey(path)];
92
119
  return real ? S.zip.file(real) : null;
93
120
  }
121
+ function entrySize(f) {
122
+ var d = f && f._data;
123
+ return d && typeof d.uncompressedSize === 'number' ? d.uncompressedSize : 0;
124
+ }
125
+
126
+ // decode bytes honouring a BOM or the declared encoding (XML declaration / <meta charset>)
127
+ function decodeBytes(u8) {
128
+ var enc = 'utf-8', start = 0;
129
+ if (u8.length >= 3 && u8[0] === 0xEF && u8[1] === 0xBB && u8[2] === 0xBF) start = 3;
130
+ else if (u8.length >= 2 && u8[0] === 0xFF && u8[1] === 0xFE) { enc = 'utf-16le'; start = 2; }
131
+ else if (u8.length >= 2 && u8[0] === 0xFE && u8[1] === 0xFF) { enc = 'utf-16be'; start = 2; }
132
+ else {
133
+ var head = '';
134
+ for (var i = 0; i < Math.min(u8.length, 400); i++) head += String.fromCharCode(u8[i]);
135
+ var m = /<\?xml[^>]*encoding\s*=\s*["']([\w.:-]+)["']/i.exec(head) || /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(head);
136
+ if (m && !/^utf-?8$/i.test(m[1])) enc = m[1].toLowerCase();
137
+ }
138
+ var text;
139
+ try { text = new TextDecoder(enc).decode(start ? u8.subarray(start) : u8); }
140
+ catch (e) { text = new TextDecoder('utf-8').decode(start ? u8.subarray(start) : u8); }
141
+ return text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text;
142
+ }
143
+
94
144
  function readText(path) {
95
145
  var f = getFile(path);
96
- return f ? f.async('string') : Promise.resolve(null);
146
+ if (!f) return Promise.resolve(null);
147
+ if (entrySize(f) > MAX_TEXT_BYTES) return Promise.resolve(null);
148
+ return f.async('uint8array').then(decodeBytes);
149
+ }
150
+
151
+ /* --------------------------------------------- font obfuscation (not DRM) */
152
+
153
+ function sha1(msg) {
154
+ var h0 = 0x67452301, h1 = 0xEFCDAB89 | 0, h2 = 0x98BADCFE | 0, h3 = 0x10325476, h4 = 0xC3D2E1F0 | 0;
155
+ var ml = msg.length, total = (((ml + 8) >> 6) + 1) * 64, buf = new Uint8Array(total);
156
+ buf.set(msg);
157
+ buf[ml] = 0x80;
158
+ var hi = Math.floor(ml / 0x20000000), lo = (ml << 3) >>> 0;
159
+ buf[total - 8] = hi >>> 24; buf[total - 7] = (hi >>> 16) & 255; buf[total - 6] = (hi >>> 8) & 255; buf[total - 5] = hi & 255;
160
+ buf[total - 4] = lo >>> 24; buf[total - 3] = (lo >>> 16) & 255; buf[total - 2] = (lo >>> 8) & 255; buf[total - 1] = lo & 255;
161
+ var w = new Array(80), i, off;
162
+ for (off = 0; off < total; off += 64) {
163
+ 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];
164
+ 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); }
165
+ var a = h0, b = h1, c = h2, d = h3, e = h4;
166
+ for (i = 0; i < 80; i++) {
167
+ var f, k;
168
+ if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; }
169
+ else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
170
+ else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC | 0; }
171
+ else { f = b ^ c ^ d; k = 0xCA62C1D6 | 0; }
172
+ var t = (((a << 5) | (a >>> 27)) + f + e + k + w[i]) | 0;
173
+ e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
174
+ }
175
+ h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;
176
+ }
177
+ var out = new Uint8Array(20);
178
+ [h0, h1, h2, h3, h4].forEach(function (h, n) {
179
+ 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;
180
+ });
181
+ return out;
182
+ }
183
+ S.sha1 = sha1; // exposed for the test harness
184
+
185
+ function obfuscationKey(kind) {
186
+ if (S.obfKeys[kind]) return S.obfKeys[kind];
187
+ var id = S.identifier || '', key;
188
+ if (kind === 'idpf') {
189
+ key = sha1(new TextEncoder().encode(id.replace(/[ \t\r\n]/g, '')));
190
+ } else {
191
+ var hex = id.replace(/^urn:uuid:/i, '').replace(/[^0-9a-f]/gi, '');
192
+ key = new Uint8Array(16);
193
+ for (var i = 0; i < 16; i++) key[i] = parseInt(hex.substr(i * 2, 2), 16) || 0;
194
+ }
195
+ return (S.obfKeys[kind] = key);
196
+ }
197
+ function deobfuscate(u8, kind) {
198
+ var key = obfuscationKey(kind), n = Math.min(u8.length, kind === 'idpf' ? 1040 : 1024);
199
+ for (var i = 0; i < n; i++) u8[i] ^= key[i % key.length];
200
+ return u8;
201
+ }
202
+ function bytesToBase64(u8) {
203
+ var s = '';
204
+ for (var i = 0; i < u8.length; i += 0x8000) s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000));
205
+ return btoa(s);
97
206
  }
98
207
 
99
208
  var MIME = {
@@ -108,8 +217,12 @@
108
217
  function dataUri(path) {
109
218
  if (S.dataCache[path]) return Promise.resolve(S.dataCache[path]);
110
219
  var f = getFile(path);
111
- if (!f) return Promise.resolve(null);
112
- return f.async('base64').then(function (b64) {
220
+ if (!f || entrySize(f) > MAX_ASSET_BYTES) return Promise.resolve(null);
221
+ var kind = S.obf[nameKey(f.name)];
222
+ var job = kind
223
+ ? f.async('uint8array').then(function (u8) { return bytesToBase64(deobfuscate(u8, kind)); })
224
+ : f.async('base64');
225
+ return job.then(function (b64) {
113
226
  var uri = 'data:' + mimeOf(path) + ';base64,' + b64;
114
227
  S.dataCache[path] = uri;
115
228
  return uri;
@@ -118,8 +231,17 @@
118
231
 
119
232
  /* ---------------------------------------------------------------- xml */
120
233
 
121
- function parseXml(s) { return new DOMParser().parseFromString(s, 'application/xml'); }
234
+ // strict XML; one retry after escaping bare ampersands (a very common authoring error). Throws when unusable.
235
+ function parseXml(s) {
236
+ var d = new DOMParser().parseFromString(s, 'application/xml');
237
+ if (d.getElementsByTagName('parsererror').length) {
238
+ d = new DOMParser().parseFromString(s.replace(/&(?!(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);)/gi, '&amp;'), 'application/xml');
239
+ if (d.getElementsByTagName('parsererror').length) throw new Error('XML is malformed');
240
+ }
241
+ return d;
242
+ }
122
243
  function byLocal(root, name) {
244
+ if (!root) return [];
123
245
  return Array.prototype.slice.call(root.getElementsByTagNameNS('*', name));
124
246
  }
125
247
  function firstLocal(root, name) { return byLocal(root, name)[0] || null; }
@@ -140,13 +262,35 @@
140
262
  /* --------------------------------------------------------- book opening */
141
263
 
142
264
  async function openBook(b64) {
143
- S.zip = await JSZip.loadAsync(b64, { base64: true });
265
+ try { S.zip = await JSZip.loadAsync(b64, { base64: true }); }
266
+ catch (e) { throw new Error('This file is not a valid EPUB (it could not be read as a zip archive).'); }
144
267
  S.names = {};
145
- Object.keys(S.zip.files).forEach(function (n) { S.names[n.toLowerCase()] = n; });
268
+ var total = 0;
269
+ Object.keys(S.zip.files).forEach(function (n) {
270
+ S.names[nameKey(n)] = n;
271
+ total += entrySize(S.zip.files[n]);
272
+ });
273
+ if (total > MAX_TOTAL_BYTES) throw new Error('This EPUB is too large to open safely.');
146
274
 
275
+ S.obf = {};
147
276
  var enc = await readText('META-INF/encryption.xml');
148
277
  if (enc) {
149
- var algos = byLocal(parseXml(enc), 'EncryptionMethod').map(function (e) { return e.getAttribute('Algorithm') || ''; });
278
+ var algos = [];
279
+ try {
280
+ byLocal(parseXml(enc), 'EncryptedData').forEach(function (ed) {
281
+ var m = firstLocal(ed, 'EncryptionMethod'), ref = firstLocal(ed, 'CipherReference');
282
+ var alg = (m && m.getAttribute('Algorithm')) || '', uri = ref && ref.getAttribute('URI');
283
+ algos.push(alg);
284
+ var kind = alg.indexOf('idpf.org/2008/embedding') >= 0 ? 'idpf' : alg.indexOf('ns.adobe.com/pdf/enc#RC') >= 0 ? 'adobe' : '';
285
+ var p = uri && resolvePath('', uri);
286
+ if (kind && p) S.obf[nameKey(p)] = kind;
287
+ });
288
+ } catch (e) {
289
+ // unreadable file: still look at the declared algorithms so a DRM book is never shown as garbage
290
+ var re = /Algorithm\s*=\s*["']([^"']+)["']/g, mm;
291
+ while ((mm = re.exec(enc))) algos.push(mm[1]);
292
+ if (!algos.length) throw new Error('This book has an unreadable encryption.xml and cannot be opened.');
293
+ }
150
294
  var drm = algos.some(function (a) {
151
295
  return a.indexOf('idpf.org/2008/embedding') < 0 && a.indexOf('ns.adobe.com/pdf/enc#RC') < 0;
152
296
  });
@@ -155,11 +299,15 @@
155
299
 
156
300
  var container = await readText('META-INF/container.xml');
157
301
  if (!container) throw new Error('Not a valid EPUB (container.xml is missing).');
158
- var rootfile = firstLocal(parseXml(container), 'rootfile');
302
+ var rootfile;
303
+ try { rootfile = firstLocal(parseXml(container), 'rootfile'); }
304
+ catch (e) { throw new Error('Not a valid EPUB (container.xml is malformed).'); }
159
305
  var opfPath = rootfile && rootfile.getAttribute('full-path');
160
306
  var opfText = opfPath && await readText(opfPath);
161
307
  if (!opfText) throw new Error('Not a valid EPUB (package document is missing).');
162
- var opf = parseXml(opfText);
308
+ var opf;
309
+ try { opf = parseXml(opfText); }
310
+ catch (e) { throw new Error('Not a valid EPUB (package document is malformed).'); }
163
311
 
164
312
  var manifest = {};
165
313
  byLocal(opf, 'item').forEach(function (it) {
@@ -173,12 +321,31 @@
173
321
  });
174
322
 
175
323
  var spineEl = firstLocal(opf, 'spine');
176
- S.spine = byLocal(spineEl, 'itemref').map(function (r) {
177
- return manifest[r.getAttribute('idref')];
324
+ if (!spineEl) throw new Error('Not a valid EPUB (the package has no spine).');
325
+ // epub.js numbers every itemref (also ones we cannot show), so each item keeps its epub.js number and CFI base
326
+ var spineNodeIndex = EpubCompat.indexOfElementNode(spineEl);
327
+ S.spine = byLocal(spineEl, 'itemref').map(function (r, n) {
328
+ var m = manifest[r.getAttribute('idref')];
329
+ if (!m) return null;
330
+ return {
331
+ id: m.id, href: m.href, path: m.path, type: m.type, props: m.props,
332
+ epubIndex: n,
333
+ linear: (r.getAttribute('linear') || 'yes') === 'yes',
334
+ cfiBase: EpubCompat.EpubCFI.prototype.generateChapterComponent(spineNodeIndex, n, r.getAttribute('id'))
335
+ };
178
336
  }).filter(function (m) {
179
337
  return m && /html|xml/i.test(m.type) || (m && /\.x?html?$/i.test(m.path));
180
338
  });
181
339
  if (!S.spine.length) throw new Error('This EPUB has no readable content.');
340
+ if (!S.spine.some(function (m) { return getFile(m.path); })) {
341
+ throw new Error('This EPUB is damaged: none of its chapter files could be found.');
342
+ }
343
+
344
+ // unique identifier: the key for obfuscated fonts
345
+ var uid = opf.documentElement.getAttribute('unique-identifier'), ids = byLocal(opf, 'identifier');
346
+ var idEl = ids.filter(function (e) { return uid && e.getAttribute('id') === uid; })[0] || ids[0];
347
+ S.identifier = idEl ? idEl.textContent : '';
348
+ S.obfKeys = {};
182
349
 
183
350
  var title = firstLocal(opf, 'title');
184
351
  var lang = firstLocal(opf, 'language');
@@ -188,35 +355,53 @@
188
355
  language: lang ? lang.textContent.trim() : '',
189
356
  publisher: (firstLocal(opf, 'publisher') || { textContent: '' }).textContent.trim()
190
357
  };
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
- }
201
-
202
- S.toc = await parseToc(opf, manifest, spineEl, opfPath);
358
+ S.ppd = spineEl.getAttribute('page-progression-direction') || '';
359
+ // content detection only matters when the metadata does not already say right-to-left
360
+ S.contentRtl = !S.ppd && !langIsRtl(S.meta.language) ? await contentIsRtl() : false;
361
+ S.bookRtl = autoRtl();
362
+ S.rtl = effectiveRtl(S.bookRtl);
363
+
364
+ var toc = await parseToc(opf, manifest, spineEl, opfPath);
365
+ S.toc = toc.items;
203
366
  post('metadata', S.meta);
204
- post('toc', { items: S.toc, rtl: S.rtl, spineCount: S.spine.length });
367
+ post('toc', { items: S.toc, all: toc.all, rtl: effectiveRtl(S.bookRtl), spineCount: S.spine.length });
205
368
  sendCover(opf, manifest);
206
369
  }
207
370
 
208
- // true when the first chapters are mostly Arabic-script text (Pashto, Dari, Persian, Arabic, Urdu ...)
371
+ // direction from the book itself: page-progression-direction, then dc:language, then the text
372
+ function autoRtl() { return S.ppd ? S.ppd === 'rtl' : (langIsRtl(S.meta.language) || S.contentRtl); }
373
+ // the user's override ('rtl' / 'ltr') wins over what the book says
374
+ function effectiveRtl(auto) {
375
+ var d = S.settings.direction;
376
+ return d === 'rtl' ? true : d === 'ltr' ? false : auto;
377
+ }
378
+
379
+ // counts right-to-left versus Latin letters in a piece of text
380
+ function scriptCounts(text) {
381
+ return { rtl: (text.match(RTL_CHARS) || []).length, latin: (text.match(LATIN_CHARS) || []).length };
382
+ }
383
+
384
+ // true when the first chapters are mostly right-to-left script (Pashto, Dari, Persian, Arabic, Urdu, Hebrew ...)
209
385
  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++) {
386
+ var rtl = 0, latin = 0;
387
+ for (var i = 0; i < Math.min(S.spine.length, 6) && rtl + latin < 1500; i++) {
213
388
  try {
214
- var text = (await parseChapter(i)).body.textContent || '';
215
- arabic += (text.match(AR) || []).length;
216
- latin += (text.match(LA) || []).length;
389
+ var c = scriptCounts((await parseChapter(i)).body.textContent || '');
390
+ rtl += c.rtl; latin += c.latin;
217
391
  } catch (e) { /* ignore unreadable chapters */ }
218
392
  }
219
- return arabic > 40 && arabic > latin * 1.5;
393
+ return rtl > 40 && rtl > latin * 1.5;
394
+ }
395
+
396
+ // Direction of one chapter. Follows the book, except when the chapter says so itself (dir attribute) or is
397
+ // clearly written in the other script (an English chapter inside an Arabic-script book and the reverse).
398
+ function chapterRtl(ch) {
399
+ if (S.settings.direction !== 'auto') return effectiveRtl(S.bookRtl);
400
+ if (ch.dir === 'rtl' || ch.dir === 'ltr') return ch.dir === 'rtl';
401
+ var c = ch.counts || { rtl: 0, latin: 0 };
402
+ if (S.bookRtl && c.latin > 200 && c.latin > c.rtl * 3) return false;
403
+ if (!S.bookRtl && c.rtl > 200 && c.rtl > c.latin * 3) return true;
404
+ return S.bookRtl;
220
405
  }
221
406
 
222
407
  function spineIndexOfPath(path) {
@@ -224,14 +409,25 @@
224
409
  return -1;
225
410
  }
226
411
 
412
+ // items: entries whose file is in the book. all: every entry, spine -1 when its file is missing
413
+ // (a preview drops the later chapters). Only items is used inside the engine.
227
414
  async function parseToc(opf, manifest, spineEl, opfPath) {
228
- var items = [];
415
+ var items = [], all = [];
416
+ function manifestHrefOf(path) {
417
+ for (var k in manifest) if (manifest[k].path === path) return manifest[k].href.split('#')[0];
418
+ return null;
419
+ }
229
420
  function add(label, href, level, base) {
230
421
  var path = resolvePath(base, href);
422
+ if (!path) return;
231
423
  var frag = href && href.indexOf('#') >= 0 ? href.split('#')[1] : '';
232
- var idx = path ? spineIndexOfPath(path) : -1;
233
- if (idx < 0) return;
234
- items.push({ label: (label || '').replace(/\s+/g, ' ').trim(), spine: idx, fragment: frag, level: level });
424
+ var idx = spineIndexOfPath(path);
425
+ // the manifest href as written (not URL-decoded), so it equals relocate.href, like epub.js
426
+ var file = idx >= 0 ? S.spine[idx].href : manifestHrefOf(path);
427
+ if (file == null) { var dir = dirOf(opfPath); file = path.indexOf(dir) === 0 ? path.slice(dir.length) : path; }
428
+ var entry = { label: cleanText(label).replace(/\s+/g, ' ').trim(), spine: idx, fragment: frag, level: level, href: file + (frag ? '#' + frag : '') };
429
+ all.push(entry);
430
+ if (idx >= 0) items.push(entry);
235
431
  }
236
432
 
237
433
  var navItem = null;
@@ -260,15 +456,18 @@
260
456
  }
261
457
  }
262
458
  }
263
- if (items.length) return items;
459
+ if (items.length) return { items: items, all: all };
460
+ all = [];
264
461
 
265
462
  var ncxId = spineEl.getAttribute('toc');
266
463
  var ncx = (ncxId && manifest[ncxId]) ||
267
464
  Object.keys(manifest).map(function (k) { return manifest[k]; }).filter(function (m) { return /ncx/.test(m.type); })[0];
268
465
  if (ncx) {
269
466
  var ncxText = await readText(ncx.path);
270
- if (ncxText) {
271
- var map = firstLocal(parseXml(ncxText), 'navMap');
467
+ var ncxDoc = null;
468
+ try { ncxDoc = ncxText && parseXml(ncxText); } catch (e) { /* a broken NCX only costs the table of contents */ }
469
+ if (ncxDoc) {
470
+ var map = firstLocal(ncxDoc, 'navMap');
272
471
  (function walk(parent, level) {
273
472
  Array.prototype.forEach.call(parent.children, function (np) {
274
473
  if (np.localName !== 'navPoint') return;
@@ -280,7 +479,7 @@
280
479
  })(map || { children: [] }, 0);
281
480
  }
282
481
  }
283
- return items;
482
+ return { items: items, all: all };
284
483
  }
285
484
 
286
485
  function sendCover(opf, manifest) {
@@ -297,12 +496,35 @@
297
496
  }
298
497
  }
299
498
 
300
- function chapterTitle(i) {
301
- var best = '';
499
+ // text offset of an element id in the chapter on screen (null when unknown)
500
+ function fragOffset(id) {
501
+ if (!S.doc || !S.segMap) return null;
502
+ var key = S.cur + ':' + id;
503
+ if (S.fragCache[key] !== undefined) return S.fragCache[key];
504
+ var el = S.doc.getElementById(id) || S.doc.getElementsByName(id)[0];
505
+ return (S.fragCache[key] = el && S.root && S.root.contains(el) ? boundaryOffset(el, 0) : null);
506
+ }
507
+
508
+ // Title of the TOC entry that applies to chapter i. When several entries point into the same file
509
+ // (Calibre-style single-file books) `off`, a text offset in the chapter on screen, picks the right one.
510
+ function chapterTitle(i, off) {
511
+ var k = tocIndex(i, off);
512
+ return (k >= 0 && S.toc[k].label) || S.meta.title || '';
513
+ }
514
+
515
+ // index in S.toc of the entry that applies to chapter i (-1 before the first entry)
516
+ function tocIndex(i, off) {
517
+ var best = -1;
302
518
  for (var k = 0; k < S.toc.length; k++) {
303
- if (S.toc[k].spine <= i) best = S.toc[k].label; else break;
519
+ var t = S.toc[k];
520
+ if (t.spine > i) break;
521
+ if (t.spine === i && t.fragment && off != null && i === S.cur) {
522
+ var fo = fragOffset(t.fragment);
523
+ if (fo != null && fo > off) continue;
524
+ }
525
+ best = k;
304
526
  }
305
- return best || S.meta.title || '';
527
+ return best;
306
528
  }
307
529
 
308
530
  /* ------------------------------------------------------------- chapters */
@@ -320,11 +542,64 @@
320
542
  }
321
543
  function segsText(segs) { return segs.map(function (s) { return s.node.data; }).join(''); }
322
544
 
323
- async function parseChapter(i) {
545
+ var DROP_TAGS = 'script,noscript,iframe,frame,frameset,object,embed,applet,base,meta,form,input,button,select,textarea,' +
546
+ 'audio,video,source,track,portal,foreignObject,set,animate';
547
+ var URL_ATTRS = ['href', 'src', 'xlink:href', 'action', 'formaction', 'data', 'poster', 'background', 'srcset', 'srcdoc'];
548
+
549
+ // Chapter markup is untrusted: remove everything that can run script or touch the network.
550
+ function sanitize(root) {
551
+ Array.prototype.slice.call(root.querySelectorAll(DROP_TAGS)).forEach(function (el) {
552
+ if (el.parentNode) el.parentNode.removeChild(el);
553
+ });
554
+ Array.prototype.slice.call(root.querySelectorAll('*')).forEach(function (el) {
555
+ var tag = el.localName;
556
+ Array.prototype.slice.call(el.attributes).forEach(function (a) {
557
+ var n = a.name.toLowerCase(), v = a.value;
558
+ if (n.indexOf('on') === 0 || n === 'srcdoc') { el.removeAttribute(a.name); return; }
559
+ if (URL_ATTRS.indexOf(n) >= 0) {
560
+ if (/^\s*(javascript|vbscript|data:text|data:application|file|content|intent):/i.test(v)) { el.removeAttribute(a.name); return; }
561
+ // pictures must come from inside the book: remote images only track the reader
562
+ if ((tag === 'img' || tag === 'image') && /^\s*(https?:)?\/\//i.test(v)) el.removeAttribute(a.name);
563
+ if (n === 'srcset') el.removeAttribute(a.name);
564
+ }
565
+ if (n === 'style' && /url\(\s*['"]?\s*(https?:|\/\/)/i.test(v)) el.removeAttribute(a.name);
566
+ });
567
+ });
568
+ }
569
+
570
+ // The chapter document as epub.js loads it: .html/.htm as HTML, everything else as XHTML.
571
+ // Same parser means the same DOM tree, and so the same CFIs.
572
+ async function readSection(i) {
324
573
  var it = S.spine[i];
325
- var raw = await readText(it.path);
574
+ var raw;
575
+ try { raw = await readText(it.path); }
576
+ catch (e) { raw = '<html><body><p>This chapter could not be read (the file is damaged).</p></body></html>'; }
326
577
  if (raw == null) raw = '<html><body><p></p></body></html>';
327
- var doc = parseMarkup(raw);
578
+ var ext = (/\.([^./]+)$/.exec(it.path) || [])[1] || '';
579
+ if (/^html?$/i.test(ext)) {
580
+ var hd = new DOMParser().parseFromString(raw, 'text/html');
581
+ if (hasContent(hd)) return hd;
582
+ // XHTML saved as .html: a self-closed <title/> or <script/> swallows the whole page when read as HTML
583
+ var xd = parseMarkup(raw);
584
+ if (!hasContent(xd)) return hd;
585
+ xd.asEpubjs = hd; // epub.js sees the blank HTML version: locations are counted on that one
586
+ return xd;
587
+ }
588
+ return parseMarkup(raw);
589
+ }
590
+ function hasContent(d) {
591
+ var b = d && d.body;
592
+ return !!b && (!!b.textContent.trim() || !!b.querySelector('img,svg,image,video,audio,object,iframe'));
593
+ }
594
+
595
+ async function parseChapter(i) {
596
+ return prepareChapter(i, await readSection(i));
597
+ }
598
+
599
+ // Cleans a chapter document for display. Text inside the removed elements is gone from our offsets
600
+ // (see cleanedAway, which must stay in step with this).
601
+ function prepareChapter(i, doc) {
602
+ var it = S.spine[i];
328
603
  var body = doc.body || doc.documentElement;
329
604
  var refs = [];
330
605
  Array.prototype.slice.call(doc.querySelectorAll('link,style')).forEach(function (el) {
@@ -333,24 +608,240 @@
333
608
  else if (/stylesheet/i.test(el.getAttribute('rel') || '')) refs.push({ href: el.getAttribute('href'), base: it.path });
334
609
  el.parentNode.removeChild(el);
335
610
  });
336
- Array.prototype.slice.call(body.querySelectorAll('script,noscript,iframe,object,embed')).forEach(function (el) {
337
- el.parentNode.removeChild(el);
611
+ sanitize(body);
612
+ if (S.repairZeroWidth) repairZeroWidth(body);
613
+ var root = doc.documentElement;
614
+ var dir = (body.getAttribute('dir') || root.getAttribute('dir') || '').toLowerCase();
615
+ return {
616
+ index: i, path: it.path, body: body, refs: refs, css: null, dir: dir,
617
+ lang: root.getAttribute('xml:lang') || root.getAttribute('lang') || body.getAttribute('xml:lang') || body.getAttribute('lang') || ''
618
+ };
619
+ }
620
+
621
+ /* ------------------------------------------------ hidden zero-width runs */
622
+ // A run of 3+ zero-width characters is a hidden mark (a watermark), not spelling: a single U+200C is real
623
+ // Pashto / Persian spelling and is kept. The run breaks the joins of Arabic-script letters and gives line
624
+ // breaks inside words, so it is shown as U+2060 WORD JOINER instead. One for one: offsets and CFIs do not move.
625
+ var ZW_RUN = /[\u200B\u200C\u200D\uFEFF]{3,}/g;
626
+ var ZW_ANY_RUN = /[\u200B-\u200D\u2060\uFEFF]{3,}/g;
627
+
628
+ function repairZeroWidth(root) {
629
+ textNodesOf(root).forEach(function (n) {
630
+ var d = n.data;
631
+ if (d.length < 3) return;
632
+ var fixed = d.replace(ZW_RUN, function (run) { return new Array(run.length + 1).join('\u2060'); });
633
+ if (fixed !== d) n.data = fixed;
338
634
  });
339
- return { index: i, path: it.path, body: body, refs: refs, lang: doc.documentElement.getAttribute('xml:lang') || doc.documentElement.getAttribute('lang') || '', css: null };
340
635
  }
341
636
 
637
+ // text for the app's own UI (labels, excerpts, selection): the runs are left out
638
+ function cleanText(t) { return String(t || '').replace(ZW_ANY_RUN, ''); }
639
+
640
+ /* ------------------------------------------- epub.js view of a chapter (CFIs) */
641
+ // epub.js makes CFIs on the page it shows. That page is the chapter document written out as text and read
642
+ // back as HTML (iframe srcdoc), which can differ from the parsed file (a <tbody> is added, for example).
643
+ // A view is that same DOM, with each of its text nodes linked to an offset in our text.
644
+
645
+ var EpubCFI = EpubCompat.EpubCFI;
646
+ var VIEW_CACHE = 4;
647
+
648
+ function textNodesOf(root) {
649
+ var w = root.ownerDocument.createTreeWalker(root, 4, null), out = [], n;
650
+ while ((n = w.nextNode())) out.push(n);
651
+ return out;
652
+ }
653
+
654
+ // true when prepareChapter removes this text node (so it has no offset in our text)
655
+ function cleanedAway(node, body) {
656
+ for (var p = node.parentNode; p && p !== body; p = p.parentNode) {
657
+ if (p.nodeType !== 1) continue;
658
+ if (p.matches(DROP_TAGS)) return true;
659
+ if (p.namespaceURI === XHTML && (p.localName === 'style' || p.localName === 'link')) return true;
660
+ }
661
+ return false;
662
+ }
663
+
664
+ // Cached, least recently used first out. Callers asking for the same chapter at once share one build.
665
+ async function chapterView(i) {
666
+ if (S.views.has(i)) {
667
+ var hit = S.views.get(i);
668
+ S.views.delete(i);
669
+ S.views.set(i, hit);
670
+ return hit;
671
+ }
672
+ if (S.viewJobs[i]) return S.viewJobs[i];
673
+ var jobs = S.viewJobs, job = buildView(i);
674
+ jobs[i] = job;
675
+ try { return await job; } finally { if (jobs[i] === job) delete jobs[i]; }
676
+ }
677
+
678
+ async function buildView(i) {
679
+ var openId = S.openId;
680
+ var doc = await readSection(i);
681
+ var body = doc.body || doc.documentElement;
682
+ // our offsets: text nodes that survive cleaning, counted in order
683
+ var src = textNodesOf(body), ours = [], pos = 0;
684
+ src.forEach(function (n) {
685
+ if (cleanedAway(n, body)) ours.push(-1);
686
+ else { ours.push(pos); pos += n.length; }
687
+ });
688
+ var vdoc = new DOMParser().parseFromString(new XMLSerializer().serializeToString(doc.documentElement), 'text/html');
689
+ var nodes = vdoc.body ? textNodesOf(vdoc.body) : [];
690
+ var vOurs = [], shift = [], olen = [], k = 0;
691
+ // Match view text nodes to source text nodes in order. They are nearly always the same list. The HTML
692
+ // parser only: drops a newline right after <pre> (shift), adds the whitespace after </body> to the last
693
+ // text node (extra text at the end), and turns CDATA into comments.
694
+ nodes.forEach(function (vn, j) {
695
+ var d = vn.data, found = -1;
696
+ shift[j] = 0;
697
+ for (var a = k; a < Math.min(src.length, k + 8); a++) {
698
+ var s = src[a].data;
699
+ if (s === d || (d.length > s.length && d.slice(0, s.length) === s)) { found = a; break; }
700
+ if (s.length === d.length + 1 && s.charAt(0) === '\n' && s.slice(1) === d) { found = a; shift[j] = 1; break; }
701
+ }
702
+ vOurs[j] = found >= 0 ? ours[found] : -1;
703
+ olen[j] = found >= 0 ? src[found].length : 0;
704
+ if (found >= 0) k = found + 1;
705
+ });
706
+ var kept = [], index = new Map();
707
+ nodes.forEach(function (n, j) {
708
+ index.set(n, j);
709
+ if (vOurs[j] >= 0) kept.push(j);
710
+ });
711
+ var v = { doc: vdoc, nodes: nodes, ours: vOurs, shift: shift, olen: olen, kept: kept, index: index, total: pos, base: S.spine[i].cfiBase };
712
+ if (openId !== S.openId) return v;
713
+ if (S.views.size >= VIEW_CACHE) {
714
+ // never drop the chapter on screen: relocate and selections need its view
715
+ var old = Array.from(S.views.keys()).filter(function (k) { return k !== S.cur; })[0];
716
+ if (old !== undefined) S.views.delete(old);
717
+ }
718
+ S.views.set(i, v);
719
+ return v;
720
+ }
721
+
722
+ // Text node and offset in the view for our offset o. A spot between two nodes has two answers: like epub.js,
723
+ // a start goes to the start of the next node, an end (asEnd) to the end of the previous one.
724
+ function viewPoint(v, o, asEnd) {
725
+ var K = v.kept, lo = 0, hi = K.length - 1, best = -1;
726
+ while (lo <= hi) {
727
+ var mid = (lo + hi) >> 1, st = v.ours[K[mid]];
728
+ if (asEnd ? st < o : st <= o) { best = mid; lo = mid + 1; } else hi = mid - 1;
729
+ }
730
+ if (best < 0) {
731
+ if (!K.length) return { node: v.doc.body || v.doc.documentElement, offset: 0 };
732
+ best = 0;
733
+ }
734
+ var j = K[best], n = v.nodes[j];
735
+ return { node: n, offset: clamp(o - v.ours[j] - v.shift[j], 0, n.length) };
736
+ }
737
+
738
+ // our offset for a boundary point in the view
739
+ function viewOffset(v, node, off) {
740
+ var j = v.index.get(node);
741
+ if (j != null && v.ours[j] >= 0) return v.ours[j] + v.shift[j] + clamp(off, 0, v.olen[j] - v.shift[j]);
742
+ // an element, or text we do not show: the first shown text at or after that point
743
+ var r = v.doc.createRange();
744
+ try { r.setStart(node, off); } catch (e) { r.setStart(node, 0); }
745
+ var K = v.kept, lo = 0, hi = K.length;
746
+ while (lo < hi) {
747
+ var mid = (lo + hi) >> 1;
748
+ if (r.comparePoint(v.nodes[K[mid]], 0) >= 0) hi = mid; else lo = mid + 1;
749
+ }
750
+ return lo < K.length ? v.ours[K[lo]] : v.total;
751
+ }
752
+
753
+ function pointCfi(v, o, asEnd) {
754
+ var p = viewPoint(v, o, asEnd);
755
+ return new EpubCFI({ startContainer: p.node, startOffset: p.offset, endContainer: p.node, endOffset: p.offset, collapsed: true }, v.base).toString();
756
+ }
757
+
758
+ function rangeCfi(v, a, b) {
759
+ if (b <= a) return pointCfi(v, a, false);
760
+ var s = viewPoint(v, a, false), e = viewPoint(v, b, true);
761
+ return new EpubCFI({ startContainer: s.node, startOffset: s.offset, endContainer: e.node, endOffset: e.offset, collapsed: false }, v.base).toString();
762
+ }
763
+
764
+ function spineOfEpubIndex(n) {
765
+ for (var i = 0; i < S.spine.length; i++) if (S.spine[i].epubIndex === n) return i;
766
+ return -1;
767
+ }
768
+
769
+ // first spine item at or after the CFI's itemref (a filtered-out or removed item), -1 when there is none
770
+ function nearSpineOfCfi(str) {
771
+ try {
772
+ var n = new EpubCFI(str).spinePos;
773
+ if (!(n >= 0)) return -1;
774
+ for (var i = 0; i < S.spine.length; i++) if (S.spine[i].epubIndex >= n) return i;
775
+ } catch (e) { /* unreadable CFI */ }
776
+ return -1;
777
+ }
778
+
779
+ // our spine index of a CFI, without loading anything (-1 when unknown)
780
+ function cfiSpine(str) {
781
+ try {
782
+ var c = new EpubCFI(str);
783
+ return c.spinePos >= 0 ? spineOfEpubIndex(c.spinePos) : -1;
784
+ } catch (e) { return -1; }
785
+ }
786
+
787
+ // CFI string -> { spine, start, end } in our offsets (end === start for a point), or null
788
+ async function resolveCfi(str) {
789
+ if (S.cfiCache.has(str)) return S.cfiCache.get(str);
790
+ var out = null, openId = S.openId, cache = S.cfiCache;
791
+ try {
792
+ var c = new EpubCFI(str), spine = c.spinePos >= 0 ? spineOfEpubIndex(c.spinePos) : -1;
793
+ if (spine >= 0) {
794
+ var v = await chapterView(spine), r = c.toRange(v.doc);
795
+ if (r) {
796
+ var a = viewOffset(v, r.startContainer, r.startOffset);
797
+ var b = c.range ? viewOffset(v, r.endContainer, r.endOffset) : a;
798
+ out = { spine: spine, start: a, end: Math.max(a, b) };
799
+ } else {
800
+ out = { spine: spine, start: 0, end: 0 };
801
+ }
802
+ }
803
+ } catch (e) { out = null; }
804
+ if (openId !== S.openId) return null; // another book was opened meanwhile: this result is not for it
805
+ cache.set(str, out);
806
+ return out;
807
+ }
808
+
809
+ // fills in offsets for highlights given as CFIs, for one chapter
810
+ async function resolveHighlights(i) {
811
+ for (var k = 0; k < S.highlights.length; k++) {
812
+ var h = S.highlights[k];
813
+ if (h.cfi && cfiSpine(h.cfi) === i) await resolveCfi(h.cfi);
814
+ }
815
+ }
816
+
817
+ // spine / start / end of a highlight: from its CFI when it has one, else its own offsets.
818
+ // A CFI that was tried and did not resolve falls back to the offsets, so the highlight is not lost.
819
+ function hlRange(h) {
820
+ var own = { spine: h.spine, start: h.start, end: h.end };
821
+ if (!h.cfi) return own;
822
+ var r = S.cfiCache.get(h.cfi);
823
+ if (r && r.end > r.start) return r;
824
+ var tried = S.cfiCache.has(h.cfi) || cfiSpine(h.cfi) < 0; // an unreadable CFI is never sent to resolveCfi
825
+ if (tried && typeof h.spine === 'number' && typeof h.start === 'number' && typeof h.end === 'number') return own;
826
+ return { spine: r ? r.spine : cfiSpine(h.cfi), start: -1, end: -1 };
827
+ }
828
+
829
+ S.compat = { chapterView: chapterView, pointCfi: pointCfi, rangeCfi: rangeCfi, resolveCfi: resolveCfi }; // exposed for the tests
830
+
342
831
  async function rewriteCss(css, basePath) {
343
832
  css = css.replace(/@import[^;]*;/g, '');
344
833
  var re = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g, m, seen = {}, jobs = [];
345
834
  while ((m = re.exec(css))) {
346
- if (seen[m[0]] || /^[a-z][a-z0-9+.-]*:/i.test(m[2])) continue;
835
+ if (seen[m[0]]) continue;
347
836
  seen[m[0]] = 1;
348
- jobs.push({ full: m[0], rel: m[2] });
837
+ if (/^data:/i.test(m[2])) continue;
838
+ // remote or odd-scheme resources never load (no network from a book)
839
+ jobs.push({ full: m[0], rel: m[2], remote: /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(m[2]) });
349
840
  }
350
841
  for (var k = 0; k < jobs.length; k++) {
351
- var p = resolvePath(basePath, jobs[k].rel);
842
+ var p = jobs[k].remote ? null : resolvePath(basePath, jobs[k].rel);
352
843
  var uri = p && await dataUri(p);
353
- if (uri) css = css.split(jobs[k].full).join('url("' + uri + '")');
844
+ css = css.split(jobs[k].full).join('url("' + (uri || '') + '")');
354
845
  }
355
846
  return css;
356
847
  }
@@ -378,10 +869,19 @@
378
869
  }
379
870
  }
380
871
 
872
+ // @font-face rules of the host's fonts (see the 'fonts' command), added to every chapter document
873
+ function addFontStyle(d) {
874
+ if (!S.fontCss) return;
875
+ var st = d.createElement('style');
876
+ st.id = 'fonts';
877
+ st.textContent = S.fontCss;
878
+ d.head.appendChild(st);
879
+ }
880
+
381
881
  function mountChapter(ch) {
382
882
  var d = frame.contentDocument;
383
883
  d.open();
384
- d.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
884
+ d.write(DOC_SHELL);
385
885
  d.close();
386
886
  d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
387
887
  d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
@@ -390,6 +890,7 @@
390
890
  st.textContent = t;
391
891
  d.head.appendChild(st);
392
892
  });
893
+ addFontStyle(d);
393
894
  var app = d.createElement('style');
394
895
  app.id = 'app';
395
896
  d.head.appendChild(app);
@@ -412,6 +913,7 @@
412
913
  S.root = holder;
413
914
  S.sections = scrollMode ? [{ index: ch.index, el: holder }] : [];
414
915
  S.cssSeen = {};
916
+ S.fragCache = {};
415
917
  ch.css.forEach(function (t) { S.cssSeen[t] = true; });
416
918
  S.ghostDirty = true;
417
919
  refreshSegs();
@@ -439,12 +941,13 @@
439
941
  var s = S.settings, W = window.innerWidth, H = window.innerHeight;
440
942
  var mx = s.marginX, ins = s.insets;
441
943
  var scroll = s.mode === 'scroll';
442
- var pageW = Math.max(120, W - 2 * mx), pageH = Math.max(120, H - ins.top - ins.bottom);
944
+ var il = ins.left || 0, ir = ins.right || 0; // notch / rounded corners in landscape
945
+ var pageW = Math.max(120, W - 2 * mx - il - ir), pageH = Math.max(120, H - ins.top - ins.bottom);
443
946
  var cols = 1;
444
947
  if (!scroll) cols = s.columns === 'auto' ? (pageW >= 640 ? 2 : 1) : (+s.columns === 2 ? 2 : 1);
445
948
  var colW = pageW;
446
949
  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 };
950
+ 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
951
  }
449
952
 
450
953
  function appCss(G) {
@@ -455,6 +958,8 @@
455
958
  'html{margin:0!important;padding:0!important;background:' + s.bg + '!important;-webkit-text-size-adjust:none;direction:' + dir + '!important;' +
456
959
  (G.scroll ? 'overflow-x:hidden!important;overflow-y:scroll!important;touch-action:pan-y;overflow-anchor:none;' : 'overflow:hidden!important;touch-action:none;') + '}',
457
960
  'html::-webkit-scrollbar{display:none}',
961
+ // vertical writing modes would break the column pagination: always lay text out horizontally
962
+ 'html,body,body *{writing-mode:horizontal-tb!important;-webkit-writing-mode:horizontal-tb!important;text-orientation:mixed!important}',
458
963
  'body{margin:0!important;padding:0!important;border:0!important;width:' + G.pageW + 'px!important;max-width:none!important;min-width:0!important;' +
459
964
  (G.scroll ? 'height:auto!important;'
460
965
  : '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,11 +967,15 @@
462
967
  (ff ? 'font-family:' + ff + '!important;' : '') +
463
968
  (s.justify ? 'text-align:justify!important;hyphens:auto;-webkit-hyphens:auto;' : '') +
464
969
  (s.bold ? 'font-weight:600!important;' : '') +
465
- (s.letterSpacing ? 'letter-spacing:' + s.letterSpacing + 'em!important;' : '') +
970
+ // letter-spacing would break the joins of cursive scripts (Arabic, Pashto, Persian, Urdu), so right-to-left books skip it
971
+ (s.letterSpacing && !S.rtl ? 'letter-spacing:' + s.letterSpacing + 'em!important;' : '') +
466
972
  (s.wordSpacing ? 'word-spacing:' + s.wordSpacing + 'em!important;' : '') +
467
- '-webkit-touch-callout:none;-webkit-user-select:text;user-select:text;overflow-wrap:break-word;word-wrap:break-word}',
468
- 'body *{color:inherit!important;background-color:transparent!important;' + (ff ? 'font-family:inherit!important;' : '') + (s.bold ? 'font-weight:inherit;' : '') + 'box-sizing:border-box}',
469
- 'body a,body a *{color:' + s.link + '!important}',
973
+ // no browser selection: text is picked by hand (see "selection" below)
974
+ '-webkit-touch-callout:none;-webkit-user-select:none;user-select:none;overflow-wrap:break-word;word-wrap:break-word}',
975
+ // 'keep' leaves the book's own colours to applyBookColors; 'theme' paints every element in the theme colours
976
+ 'body *{' + (s.bookColors === 'keep' ? '' : 'color:inherit!important;background-color:transparent!important;') +
977
+ (ff ? 'font-family:inherit!important;' : '') + (s.bold ? 'font-weight:inherit;' : '') + 'box-sizing:border-box}',
978
+ s.bookColors === 'keep' ? 'body a{color:' + s.link + '}' : 'body a,body a *{color:' + s.link + '!important}',
470
979
  'body img,body svg,body video{max-width:100%!important;max-height:' + G.pageH + 'px!important;object-fit:contain;break-inside:avoid}',
471
980
  'body img{height:auto}',
472
981
  'body h1,body h2,body h3,body h4{break-after:avoid;-webkit-column-break-after:avoid}',
@@ -479,11 +988,12 @@
479
988
  css.push('body mark.ul-' + c + '{background-color:transparent!important;border-bottom:2px solid ' + HL_COLORS[c][1] + ';border-radius:0}');
480
989
  });
481
990
  css.push('body mark.hit{background-color:rgba(255,149,0,.5)!important}');
991
+ css.push('body mark.pick{background-color:rgba(10,132,255,.3)!important}');
482
992
  return css.join('\n');
483
993
  }
484
994
 
485
995
  function place(el, G) {
486
- el.style.left = G.mx + 'px';
996
+ el.style.left = G.left + 'px';
487
997
  el.style.top = G.top + 'px';
488
998
  el.style.width = G.pageW + 'px';
489
999
  el.style.height = G.pageH + 'px';
@@ -515,17 +1025,20 @@
515
1025
  b.style.transform = prev;
516
1026
  S.pageStarts = {};
517
1027
  S.ghostDirty = true;
1028
+ applyBookColors(d);
518
1029
  scheduleGhost();
519
1030
  if (G.scroll) scheduleExtras(); else clearExtras();
520
1031
  }
521
1032
 
522
1033
  function autoLabels() {
523
1034
  if (S.labelsExternal) return;
524
- hdr.textContent = chapterTitle(S.cur);
1035
+ var multi = S.doc && S.toc.some(function (t) { return t.spine === S.cur && t.fragment; });
1036
+ hdr.textContent = chapterTitle(S.cur, multi ? pageStart(S.page) : null);
525
1037
  ftr.textContent = (S.page + 1) + ' / ' + S.pageCount;
526
1038
  }
527
1039
 
528
1040
  function showPage(p, animate) {
1041
+ if (!Z.pinch) resetZoom();
529
1042
  p = clamp(p, 0, S.pageCount - 1);
530
1043
  S.page = p;
531
1044
  var G = S.G, b = S.doc.body;
@@ -577,17 +1090,18 @@
577
1090
  function buildGhost() {
578
1091
  if (S.ghostLock) return;
579
1092
  buildInto(ghost);
580
- var g2 = document.getElementById("ghost2");
581
- if (g2) buildInto(g2);
1093
+ // the second copy is only used by the page curl
1094
+ if (S.G && S.G.mode === 'curl') buildInto(document.getElementById('ghost2'));
582
1095
  S.ghostDirty = false;
583
1096
  }
584
1097
 
585
1098
  function buildInto(frameEl) {
586
1099
  var src = S.doc, g = frameEl.contentDocument;
587
1100
  g.open();
588
- g.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
1101
+ g.write(DOC_SHELL);
589
1102
  g.close();
590
1103
  g.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
1104
+ g.documentElement.setAttribute('lang', src.documentElement.getAttribute('lang') || '');
591
1105
  Array.prototype.forEach.call(src.head.querySelectorAll('style'), function (st) {
592
1106
  var c = g.createElement('style');
593
1107
  c.textContent = st.textContent;
@@ -704,7 +1218,7 @@
704
1218
  function syncLabels(c) {
705
1219
  if (!c._lbl) {
706
1220
  c._lbl = [document.createElement('div'), document.createElement('div')];
707
- c._lbl.forEach(function (e) { e.className = 'lbl'; c.appendChild(e); });
1221
+ c._lbl.forEach(function (e) { e.className = 'lbl'; e.setAttribute('dir', 'auto'); c.appendChild(e); });
708
1222
  }
709
1223
  c._lbl[0].textContent = hdr.textContent;
710
1224
  c._lbl[0].style.top = hdr.style.top || '20px';
@@ -881,14 +1395,16 @@
881
1395
  function mountInto(frameEl, ch) {
882
1396
  var d = frameEl.contentDocument;
883
1397
  d.open();
884
- d.write('<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>');
1398
+ d.write(DOC_SHELL);
885
1399
  d.close();
886
1400
  d.documentElement.setAttribute('dir', S.rtl ? 'rtl' : 'ltr');
1401
+ d.documentElement.setAttribute('lang', ch.lang || S.meta.language || '');
887
1402
  ch.css.forEach(function (t) {
888
1403
  var st = d.createElement('style');
889
1404
  st.textContent = t;
890
1405
  d.head.appendChild(st);
891
1406
  });
1407
+ addFontStyle(d);
892
1408
  var app = d.createElement('style');
893
1409
  app.textContent = appCss(S.G);
894
1410
  d.head.appendChild(app);
@@ -905,11 +1421,13 @@
905
1421
  var ch = await parseChapter(index);
906
1422
  await inlineChapter(ch);
907
1423
  var d1 = mountInto(ghost, ch);
908
- mountInto(ghost2, ch);
1424
+ if (S.G.mode === 'curl') mountInto(ghost2, ch);
909
1425
  var imgs = Array.prototype.slice.call(d1.images || []).filter(function (im) { return !im.complete; })
910
1426
  .map(function (im) { return new Promise(function (r) { im.onload = im.onerror = r; }); });
911
1427
  if (d1.fonts && d1.fonts.ready) imgs.push(d1.fonts.ready);
912
1428
  if (imgs.length) await Promise.race([Promise.all(imgs), sleep(1500)]);
1429
+ applyBookColors(d1);
1430
+ if (S.G.mode === 'curl') applyBookColors(ghost2.contentDocument);
913
1431
  var G = S.G, count = Math.max(1, Math.ceil((d1.body.scrollWidth + G.gap) / (G.pageW + G.gap) - 0.01));
914
1432
  setGhostPages(first ? 0 : count - 1);
915
1433
  }
@@ -937,6 +1455,7 @@
937
1455
  curlHide();
938
1456
  }
939
1457
  } finally {
1458
+ curlHide(); // also on errors: never leave a half-turned page on screen
940
1459
  S.ghostLock = false;
941
1460
  S.ghostDirty = true;
942
1461
  scheduleGhost();
@@ -1061,6 +1580,7 @@
1061
1580
  slideHide();
1062
1581
  }
1063
1582
  } finally {
1583
+ slideHide(); // also on errors: never leave a half-turned page on screen
1064
1584
  S.ghostLock = false;
1065
1585
  S.ghostDirty = true;
1066
1586
  scheduleGhost();
@@ -1084,11 +1604,12 @@
1084
1604
  function applyHighlightsFor(el, index) {
1085
1605
  S.root = el;
1086
1606
  refreshSegs();
1087
- S.highlights.filter(function (h) { return h.spine === index; })
1088
- .sort(function (x, y) { return x.start - y.start; })
1089
- .forEach(function (h) {
1090
- var color = HL_COLORS[h.color] ? h.color : 'yellow';
1091
- wrapRange(h.start, h.end, (h.style === 'underline' ? 'ul-' : 'hl-') + color, h.id);
1607
+ S.highlights.map(function (h) { return { h: h, r: hlRange(h) }; })
1608
+ .filter(function (x) { return x.r.spine === index && x.r.start >= 0 && x.r.end > x.r.start; })
1609
+ .sort(function (x, y) { return x.r.start - y.r.start; })
1610
+ .forEach(function (x) {
1611
+ var paint = hlPaint(x.h.color, x.h.style);
1612
+ wrapRange(x.r.start, x.r.end, paint.cls, x.h.id, paint.css);
1092
1613
  });
1093
1614
  }
1094
1615
 
@@ -1096,6 +1617,7 @@
1096
1617
  var token = S.token;
1097
1618
  var ch = await parseChapter(index);
1098
1619
  await inlineChapter(ch);
1620
+ await resolveHighlights(index);
1099
1621
  if (token !== S.token || !S.doc || !S.G.scroll) return;
1100
1622
  if (S.sections.some(function (x) { return x.index === index; })) return;
1101
1623
  var d = S.doc, el = d.createElement('div');
@@ -1121,12 +1643,33 @@
1121
1643
  applyHighlightsFor(el, index);
1122
1644
  S.root = cur;
1123
1645
  refreshSegs();
1646
+ applyBookColors(d);
1647
+ }
1648
+
1649
+ // drop chapters that are far from the current one so a long reading session does not grow without bound
1650
+ function evictFar() {
1651
+ var d = S.doc, secs = S.sections;
1652
+ if (!d || !secs || secs.length < 4) return;
1653
+ var sc = d.scrollingElement || d.documentElement;
1654
+ while (secs.length > 1) {
1655
+ var first = secs[0], last = secs[secs.length - 1];
1656
+ if (S.cur - first.index > 2) {
1657
+ var h = first.el.offsetHeight;
1658
+ first.el.parentNode.removeChild(first.el);
1659
+ secs.shift();
1660
+ sc.scrollTop -= h; // keep what is on screen where it is (no scroll anchoring here)
1661
+ } else if (last.index - S.cur > 2) {
1662
+ last.el.parentNode.removeChild(last.el);
1663
+ secs.pop();
1664
+ } else break;
1665
+ }
1124
1666
  }
1125
1667
 
1126
1668
  async function ensureExtras() {
1127
1669
  if (!S.doc || !S.G || !S.G.scroll || S.extraBusy || !S.sections || !S.sections.length) return;
1128
1670
  S.extraBusy = true;
1129
1671
  try {
1672
+ evictFar();
1130
1673
  var last = S.sections[S.sections.length - 1].index;
1131
1674
  if (last < S.spine.length - 1 && last - S.cur < 2) await mountExtra(last + 1, 'tail');
1132
1675
  var first = S.sections[0].index;
@@ -1269,16 +1812,44 @@
1269
1812
  function relocate() {
1270
1813
  var start = pageStart(S.page);
1271
1814
  var end = S.page + 1 >= S.pageCount ? S.segs.total : pageStart(S.page + 1);
1815
+ var cur = S.cur, v = S.views.get(cur), compat = {};
1816
+ if (!v && !S.viewFailed[cur]) {
1817
+ // scroll mode can reach a chapter without renderChapter: build its view, then report once
1818
+ if (S.relocWait === cur) return;
1819
+ S.relocWait = cur;
1820
+ chapterView(cur).then(function () { S.relocWait = -1; if (S.cur === cur) relocate(); },
1821
+ function () { S.relocWait = -1; S.viewFailed[cur] = true; if (S.cur === cur) relocate(); });
1822
+ return;
1823
+ }
1824
+ if (v) {
1825
+ compat.startCfi = pointCfi(v, start, false);
1826
+ // a page with no text (a full-page picture, only whitespace): one spot, so end never comes before start
1827
+ compat.endCfi = S.curText.slice(start, end).trim() ? pointCfi(v, end, true) : compat.startCfi;
1828
+ if (S.locs) compat.locations = locationsInfo(compat.startCfi, compat.endCfi);
1829
+ }
1272
1830
  post('relocate', {
1273
1831
  spine: S.cur, offset: start, end: end,
1274
1832
  page: S.page, pageCount: S.pageCount, spineCount: S.spine.length,
1275
1833
  textLength: S.segs.total,
1276
- progress: bookProgress(start), chapter: chapterTitle(S.cur),
1277
- excerpt: S.curText.slice(start, start + 120).replace(/\s+/g, ' ').trim(),
1278
- indexed: S.indexed
1834
+ progress: bookProgress(start), chapter: chapterTitle(S.cur, start),
1835
+ excerpt: cleanText(S.curText.slice(start, start + 320)).slice(0, 120).replace(/\s+/g, ' ').trim(),
1836
+ href: S.spine[cur].href,
1837
+ tocIndex: tocIndex(cur, start),
1838
+ indexed: S.indexed,
1839
+ startCfi: compat.startCfi,
1840
+ endCfi: compat.endCfi,
1841
+ locations: compat.locations
1279
1842
  });
1280
1843
  }
1281
1844
 
1845
+ // chunk numbers of a page, as epub.js reports them in rendition.currentLocation()
1846
+ // no chunks (an image-only book): epub.js has no locations either, so none are reported
1847
+ function locationsInfo(startCfi, endCfi) {
1848
+ if (!S.locs._locations.length) return undefined;
1849
+ var L = S.locs, start = L.locationFromCfi(startCfi), end = L.locationFromCfi(endCfi);
1850
+ return { start: start, end: end, count: L._locations.length, progress: L.percentageFromLocation(start) };
1851
+ }
1852
+
1282
1853
  /* ----------------------------------------------------------- navigation */
1283
1854
 
1284
1855
  async function renderChapter(i, target) {
@@ -1291,6 +1862,8 @@
1291
1862
  if (token !== S.token) return;
1292
1863
  S.cur = i;
1293
1864
  S.sel = null;
1865
+ ch.counts = scriptCounts((ch.body.textContent || '').slice(0, 30000));
1866
+ S.rtl = chapterRtl(ch); // text direction and swipe direction follow the chapter on screen
1294
1867
  mountChapter(ch);
1295
1868
  await waitAssets();
1296
1869
  if (token !== S.token) return;
@@ -1301,6 +1874,16 @@
1301
1874
  else if (target && target.offset != null) p = pageForOffset(target.offset);
1302
1875
  else if (target && target.fragment) p = pageOfFragment(target.fragment);
1303
1876
  showPage(p, false);
1877
+ // The page is on screen. Now the CFI view (a second parse of the chapter), then the highlights that only have a
1878
+ // CFI, then relocate (it needs the view for startCfi / endCfi).
1879
+ try { await chapterView(i); } catch (e) { S.viewFailed[i] = true; }
1880
+ if (token !== S.token) return;
1881
+ var hasCfi = S.highlights.some(function (h) { return h.cfi && cfiSpine(h.cfi) === i; });
1882
+ if (hasCfi) {
1883
+ await resolveHighlights(i);
1884
+ if (token !== S.token) return;
1885
+ applyHighlightsDom();
1886
+ }
1304
1887
  relocate();
1305
1888
  }
1306
1889
 
@@ -1335,6 +1918,16 @@
1335
1918
 
1336
1919
  async function gotoLocation(loc) {
1337
1920
  loc = loc || {};
1921
+ if (loc.cfi) {
1922
+ var r = await resolveCfi(loc.cfi);
1923
+ if (r) loc = { spine: r.spine, offset: r.start };
1924
+ else if (loc.spine != null) loc = { spine: loc.spine, offset: loc.offset }; // the caller's fallback
1925
+ else {
1926
+ var near = nearSpineOfCfi(loc.cfi);
1927
+ if (near < 0 && S.doc) { post('error', { message: 'This place could not be found in the book.', fatal: false }); return; }
1928
+ loc = { spine: Math.max(0, near), offset: 0 };
1929
+ }
1930
+ }
1338
1931
  if (loc.progress != null && loc.spine == null) return gotoProgress(loc.progress);
1339
1932
  var spine = loc.spine != null ? clamp(loc.spine, 0, S.spine.length - 1) : 0;
1340
1933
  var target = loc.fragment ? { fragment: loc.fragment } : { offset: loc.offset || 0 };
@@ -1356,16 +1949,20 @@
1356
1949
  /* ---------------------------------------------------------- settings */
1357
1950
 
1358
1951
  function applySettings(partial) {
1359
- var s = S.settings, dirBefore = s.direction;
1952
+ var s = S.settings, dirBefore = s.direction, hlBefore = JSON.stringify(s.highlightColors) + s.highlightOpacity;
1360
1953
  // anchor is measured with the layout that is still on screen
1361
1954
  var anchor = S.doc ? pageStart(S.page) : 0;
1362
1955
  Object.keys(partial || {}).forEach(function (k) {
1363
- if (k === 'insets') s.insets = { top: partial.insets.top, bottom: partial.insets.bottom };
1956
+ if (k === 'insets') {
1957
+ var pi = partial.insets || {};
1958
+ s.insets = { top: pi.top || 0, bottom: pi.bottom || 0, left: pi.left || 0, right: pi.right || 0 };
1959
+ }
1364
1960
  else if (partial[k] != null) s[k] = partial[k];
1365
1961
  });
1366
1962
  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;
1963
+ // same rules as when the book was opened: the override first, then page-progression-direction, language, text
1964
+ S.rtl = effectiveRtl(S.bookRtl);
1965
+ post('direction', { rtl: S.rtl });
1369
1966
  if (S.doc) { renderChapter(S.cur, { offset: anchor }); return; }
1370
1967
  }
1371
1968
  if (S.doc && S.G && S.G.scroll !== (s.mode === 'scroll')) {
@@ -1374,6 +1971,7 @@
1374
1971
  }
1375
1972
  if (S.doc) {
1376
1973
  layout();
1974
+ if (JSON.stringify(s.highlightColors) + s.highlightOpacity !== hlBefore) applyHighlightsDom();
1377
1975
  showPage(pageForOffset(anchor), false);
1378
1976
  relocate();
1379
1977
  }
@@ -1401,7 +1999,30 @@
1401
1999
  return marks.length;
1402
2000
  }
1403
2001
 
1404
- function wrapRange(a, b, cls, id) {
2002
+ // Class (built-in colours) or inline style (host colours, see settings.highlightColors) of a highlight.
2003
+ // Host colours are filled at settings.highlightOpacity (default 0.3, like epub.js).
2004
+ var SAFE_COLOR = /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%\/]+\)|hsla?\([\d\s.,%deg\/]+\)|[a-z]{3,20})$/i;
2005
+ function hlPaint(color, style) {
2006
+ var custom = S.settings.highlightColors || {}, c = custom[color] || (HL_COLORS[color] ? null : color);
2007
+ var underline = style === 'underline';
2008
+ if (!c || !SAFE_COLOR.test(String(c).trim())) {
2009
+ return { cls: (underline ? 'ul-' : 'hl-') + (HL_COLORS[color] ? color : 'yellow') };
2010
+ }
2011
+ c = String(c).trim();
2012
+ var op = S.settings.highlightOpacity == null ? 0.3 : S.settings.highlightOpacity;
2013
+ return underline
2014
+ ? { cls: 'ul', css: 'background-color:transparent!important;border-bottom:2px solid ' + c + '!important;border-radius:0' }
2015
+ : { cls: 'hl', css: 'background-color:' + withAlpha(c, op) + '!important' };
2016
+ }
2017
+
2018
+ // plain rgba(), so older WebViews (no color-mix before iOS 16.2) can draw it. The colour's own alpha is kept.
2019
+ function withAlpha(c, a) {
2020
+ var v = cssRgb(c);
2021
+ if (!v) return 'rgba(255,214,10,' + a + ')'; // built-in yellow
2022
+ return 'rgba(' + Math.round(v.r) + ',' + Math.round(v.g) + ',' + Math.round(v.b) + ',' + +(a * v.a).toFixed(3) + ')';
2023
+ }
2024
+
2025
+ function wrapRange(a, b, cls, id, css) {
1405
2026
  var items = [];
1406
2027
  S.segs.forEach(function (seg) {
1407
2028
  if (seg.end <= a || seg.start >= b) return;
@@ -1420,6 +2041,7 @@
1420
2041
  var m = S.doc.createElement('mark');
1421
2042
  m.className = cls;
1422
2043
  m.setAttribute('data-hl', id);
2044
+ if (css) m.setAttribute('style', css);
1423
2045
  mid.parentNode.insertBefore(m, mid);
1424
2046
  m.appendChild(mid);
1425
2047
  });
@@ -1427,7 +2049,7 @@
1427
2049
  }
1428
2050
 
1429
2051
  function applyHighlightsDom() {
1430
- unwrapMarks('mark[data-hl]:not(.hit)');
2052
+ unwrapMarks('mark[data-hl]:not(.hit):not(.pick)');
1431
2053
  var cur = S.root;
1432
2054
  if (S.sections && S.sections.length) S.sections.forEach(function (sec) { applyHighlightsFor(sec.el, sec.index); });
1433
2055
  else applyHighlightsFor(S.doc.body, S.cur);
@@ -1448,29 +2070,64 @@
1448
2070
 
1449
2071
  /* ------------------------------------------------------------- search */
1450
2072
 
1451
- var FOLD = { 'ي': 'ی', 'ك': 'ک', 'ة': 'ه', 'ى': 'ی', 'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ۀ': 'ه', 'ہ': 'ه', 'ە': 'ه' };
1452
- function fold(s) {
1453
- return s.toLowerCase().replace(/[يكةىأإآۀہە]/g, function (c) { return FOLD[c]; });
2073
+ // Search folding: one output character per kept input character, so a hit in the folded text maps back to
2074
+ // exact offsets in the original (`map`). Dropped: diacritics (tashkeel, Quranic marks), tatweel, joiners and
2075
+ // bidi marks. Unified: Arabic/Persian/Pashto letter variants, all digit systems, case, runs of whitespace.
2076
+ var FOLD = {
2077
+ 'ي': 'ی', 'ى': 'ی', 'ې': 'ی', 'ۍ': 'ی', 'ێ': 'ی', 'ئ': 'ی', // ye
2078
+ 'ك': 'ک', 'ڪ': 'ک', // kaf
2079
+ 'ة': 'ه', 'ۀ': 'ه', 'ہ': 'ه', 'ە': 'ه', 'ھ': 'ه', // heh
2080
+ 'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ٱ': 'ا', // alef
2081
+ 'ؤ': 'و'
2082
+ };
2083
+ var DROP = /[\u2060ً-ٰٟۖ-ۭـ​-‏‪-‮⁦-⁩­]/;
2084
+ function foldText(text, breaks) {
2085
+ var out = [], map = [], brk = breaks && breaks.length ? new Set(breaks) : null, lastSpace = true;
2086
+ for (var i = 0; i < text.length; i++) {
2087
+ var c = text.charAt(i), code = text.charCodeAt(i);
2088
+ if (brk && brk.has(i) && !lastSpace) { out.push(' '); map.push(i); lastSpace = true; }
2089
+ if (DROP.test(c)) continue;
2090
+ if (/\s/.test(c)) {
2091
+ if (!lastSpace) { out.push(' '); map.push(i); lastSpace = true; }
2092
+ continue;
2093
+ }
2094
+ lastSpace = false;
2095
+ if (code >= 0x660 && code <= 0x669) c = String.fromCharCode(48 + code - 0x660);
2096
+ else if (code >= 0x6F0 && code <= 0x6F9) c = String.fromCharCode(48 + code - 0x6F0);
2097
+ else if (FOLD[c]) c = FOLD[c];
2098
+ else if (code < 0x3000) {
2099
+ var lc = c.toLowerCase();
2100
+ c = lc.charAt(0); // toLowerCase can change the length (e.g. U+0130); keep it one unit
2101
+ }
2102
+ out.push(c);
2103
+ map.push(i);
2104
+ }
2105
+ return { s: out.join(''), map: map };
1454
2106
  }
2107
+ function fold(s) { return foldText(s.trim(), null).s; }
1455
2108
 
1456
2109
  async function search(query, id) {
1457
2110
  S.searchId = id;
1458
- var q = fold(query.trim());
2111
+ var q = fold(query);
1459
2112
  if (q.length < 2) { post('searchResults', { id: id, results: [], done: true }); return; }
2113
+ var waited = 0;
1460
2114
  while (!S.indexed) {
1461
2115
  if (S.searchId !== id) return;
2116
+ if (S.indexFailed || waited > 120000) { post('searchResults', { id: id, results: [], done: true }); return; }
1462
2117
  await sleep(80);
2118
+ waited += 80;
1463
2119
  }
1464
2120
  var total = 0;
1465
2121
  for (var i = 0; i < S.spine.length; i++) {
1466
2122
  if (S.searchId !== id) return;
1467
- var text = S.texts[i], folded = fold(text), from = 0, found = [], at;
2123
+ var text = S.texts[i], fd = foldText(text, S.breaks[i]), folded = fd.s, from = 0, found = [], at;
1468
2124
  while ((at = folded.indexOf(q, from)) >= 0 && total + found.length < 500) {
2125
+ var start = fd.map[at], end = fd.map[at + q.length - 1] + 1;
1469
2126
  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, ' ')
2127
+ spine: i, offset: start, length: end - start, chapter: chapterTitle(i),
2128
+ before: cleanText(text.slice(Math.max(0, start - 300), start)).slice(-40).replace(/\s+/g, ' '),
2129
+ match: cleanText(text.slice(start, end)),
2130
+ after: cleanText(text.slice(end, end + 300)).slice(0, 60).replace(/\s+/g, ' ')
1474
2131
  });
1475
2132
  from = at + q.length;
1476
2133
  }
@@ -1481,65 +2138,461 @@
1481
2138
  }
1482
2139
  }
1483
2140
 
2141
+ 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;
2142
+ function blockOf(node, stop) {
2143
+ for (var n = node.parentNode; n && n !== stop; n = n.parentNode) {
2144
+ if (n.localName && BLOCK.test(n.localName)) return n;
2145
+ }
2146
+ return stop;
2147
+ }
2148
+
1484
2149
  async function buildIndex() {
1485
2150
  var cum = 0, id = S.openId;
1486
- var texts = [], cums = [];
2151
+ var texts = [], cums = [], breaks = [], locs = [];
1487
2152
  for (var i = 0; i < S.spine.length; i++) {
1488
- var ch = await parseChapter(i);
2153
+ var t = '', br = [];
2154
+ try {
2155
+ var doc = await readSection(i), it = S.spine[i];
2156
+ // epub.js locations: only linear items, counted on the document as loaded (before cleaning)
2157
+ if (S.locationChars > 0 && it.linear) {
2158
+ var part = EpubCompat.parseLocations((doc.asEpubjs || doc).documentElement, it.cfiBase, S.locationChars);
2159
+ for (var q = 0; q < part.length; q++) locs.push(part[q]); // concat would copy the whole list each chapter
2160
+ }
2161
+ var ch = prepareChapter(i, doc);
2162
+ var segs = collectSegs(ch.body), prev = null;
2163
+ // positions where one block ends and the next begins: search must not match across them
2164
+ segs.forEach(function (sg) {
2165
+ var b = blockOf(sg.node, ch.body);
2166
+ if (prev && b !== prev && sg.start > 0) br.push(sg.start);
2167
+ prev = b;
2168
+ });
2169
+ t = segsText(segs);
2170
+ } catch (e) { /* an unreadable chapter is simply not searchable */ }
1489
2171
  if (id !== S.openId) return;
1490
- var t = segsText(collectSegs(ch.body));
1491
- texts[i] = t; cums[i] = cum; cum += t.length;
2172
+ texts[i] = t; cums[i] = cum; breaks[i] = br; cum += t.length;
1492
2173
  if (i % 3 === 2) await sleep(0);
1493
2174
  }
1494
2175
  if (id !== S.openId) return;
1495
- S.texts = texts; S.cum = cums;
2176
+ S.texts = texts; S.cum = cums; S.breaks = breaks;
1496
2177
  S.totalLen = cum;
1497
2178
  S.indexed = true;
2179
+ if (S.locationChars > 0) S.locs = new EpubCompat.Locations(locs);
1498
2180
  post('indexed', { totalLength: cum, cum: S.cum });
2181
+ if (S.locs) post('locations', { count: locs.length });
1499
2182
  if (S.doc) relocate();
1500
2183
  }
1501
2184
 
2185
+ /* --------------------------------------------------------- book colours */
2186
+ // settings.bookColors 'keep': the book's own text colours stay (coloured headings, links). Grey, black and white
2187
+ // stand for "normal text" and get the theme colour (this fixes books that hardcode black text). A real colour
2188
+ // that is hard to read on the page is made lighter (dark page) or darker (light page). Text on a box the book
2189
+ // painted itself is left alone. Ported from the Aklantis app (readerColors.ts).
2190
+ var SRC_COLOR = 'data-src-color', SRC_PAPER = 'data-src-paper';
2191
+ var GREY_SPREAD = 24, MIN_L_ON_DARK = 0.62, MAX_L_ON_LIGHT = 0.52;
2192
+
2193
+ function parseRgb(v) {
2194
+ var m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s\/]+([\d.]+))?/.exec(v || '');
2195
+ return m ? { r: +m[1], g: +m[2], b: +m[3], a: m[4] === undefined ? 1 : +m[4] } : null;
2196
+ }
2197
+ // any CSS colour (hex, names, hsl ...) as { r, g, b, a }: the browser converts it. null when it is not a colour.
2198
+ var colorProbe = null;
2199
+ function cssRgb(c) {
2200
+ if (!c) return null;
2201
+ var direct = parseRgb(c);
2202
+ if (direct) return direct;
2203
+ if (!colorProbe) {
2204
+ colorProbe = document.createElement('i');
2205
+ colorProbe.style.display = 'none';
2206
+ document.documentElement.appendChild(colorProbe);
2207
+ }
2208
+ colorProbe.style.color = '';
2209
+ colorProbe.style.color = c;
2210
+ if (!colorProbe.style.color) return null;
2211
+ return parseRgb(getComputedStyle(colorProbe).color);
2212
+ }
2213
+ function toHsl(c) {
2214
+ var r = c.r / 255, g = c.g / 255, b = c.b / 255, max = Math.max(r, g, b), min = Math.min(r, g, b);
2215
+ var l = (max + min) / 2, h = 0, s = 0;
2216
+ if (max !== min) {
2217
+ var dd = max - min;
2218
+ s = l > 0.5 ? dd / (2 - max - min) : dd / (max + min);
2219
+ if (max === r) h = (g - b) / dd + (g < b ? 6 : 0);
2220
+ else if (max === g) h = (b - r) / dd + 2;
2221
+ else h = (r - g) / dd + 4;
2222
+ h /= 6;
2223
+ }
2224
+ return { h: h, s: s, l: l };
2225
+ }
2226
+ function hueToChannel(p, q, t) {
2227
+ if (t < 0) t += 1;
2228
+ if (t > 1) t -= 1;
2229
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
2230
+ if (t < 1 / 2) return q;
2231
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
2232
+ return p;
2233
+ }
2234
+ function fromHsl(c) {
2235
+ if (c.s === 0) { var v = Math.round(c.l * 255); return 'rgb(' + v + ',' + v + ',' + v + ')'; }
2236
+ var q = c.l < 0.5 ? c.l * (1 + c.s) : c.l + c.s - c.l * c.s, p = 2 * c.l - q;
2237
+ return 'rgb(' + Math.round(hueToChannel(p, q, c.h + 1 / 3) * 255) + ',' + Math.round(hueToChannel(p, q, c.h) * 255) + ',' +
2238
+ Math.round(hueToChannel(p, q, c.h - 1 / 3) * 255) + ')';
2239
+ }
2240
+ function pageIsDark() {
2241
+ var c = cssRgb(S.settings.bg);
2242
+ if (!c) return false;
2243
+ return (0.299 * c.r + 0.587 * c.g + 0.114 * c.b) / 255 < 0.5;
2244
+ }
2245
+ // null = keep the book's colour as it is
2246
+ function resolveBookColor(original, dark) {
2247
+ var c = parseRgb(original);
2248
+ if (!c || c.a === 0) return null; // fully transparent text is deliberate
2249
+ if (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b) <= GREY_SPREAD) return S.settings.fg;
2250
+ var hsl = toHsl(c);
2251
+ if (dark) { if (hsl.l >= MIN_L_ON_DARK) return null; hsl.l = MIN_L_ON_DARK; }
2252
+ else { if (hsl.l <= MAX_L_ON_LIGHT) return null; hsl.l = MAX_L_ON_LIGHT; }
2253
+ return fromHsl(hsl);
2254
+ }
2255
+
2256
+ function applyBookColors(d) {
2257
+ if (!d || !d.body || !d.defaultView) return;
2258
+ var els = d.body.querySelectorAll('*'), i, el;
2259
+ if (S.settings.bookColors !== 'keep') {
2260
+ // undo an earlier 'keep' pass
2261
+ for (i = 0; i < els.length; i++) if (els[i].hasAttribute(SRC_COLOR)) els[i].style.removeProperty('color');
2262
+ return;
2263
+ }
2264
+ var win = d.defaultView, dark = pageIsDark(), lc = cssRgb(S.settings.link);
2265
+ var linkRgb = lc ? 'rgb(' + lc.r + ', ' + lc.g + ', ' + lc.b + ')' : '';
2266
+ // pass 1 records what the book asked for, before pass 2 writes anything (a parent's new colour changes its children)
2267
+ for (i = 0; i < els.length; i++) {
2268
+ el = els[i];
2269
+ if (el.hasAttribute(SRC_COLOR) || el.localName === 'mark') continue;
2270
+ var st = win.getComputedStyle(el), parent = el.parentElement;
2271
+ var onPaper = !!parent && parent !== d.body && parent.getAttribute(SRC_PAPER) === '1';
2272
+ if (!onPaper) { var bg = parseRgb(st.backgroundColor); onPaper = !!bg && bg.a > 0; }
2273
+ el.setAttribute(SRC_PAPER, onPaper ? '1' : '0');
2274
+ var own = st.color, inherited = parent ? win.getComputedStyle(parent).color : '';
2275
+ // a link in our own theme link colour is not a book colour: it must follow the theme when it changes
2276
+ var themeLink = own === linkRgb && !!el.closest('a');
2277
+ el.setAttribute(SRC_COLOR, onPaper || themeLink || own === inherited ? '' : (own || ''));
2278
+ }
2279
+ for (i = 0; i < els.length; i++) {
2280
+ el = els[i];
2281
+ var original = el.getAttribute(SRC_COLOR);
2282
+ if (!original) continue;
2283
+ var resolved = resolveBookColor(original, dark);
2284
+ if (resolved) el.style.setProperty('color', resolved, 'important');
2285
+ else el.style.removeProperty('color');
2286
+ }
2287
+ }
2288
+
2289
+ /* ----------------------------------------------------------- pinch zoom */
2290
+ // Two fingers scale the page like a picture (the text does not reflow). While zoomed, one finger moves the
2291
+ // page, taps and swipes never turn it, and text cannot be selected. A double tap or pinching back resets it.
2292
+ // Paged modes only: in scroll mode the browser owns vertical drags.
2293
+ var Z = { s: 1, x: 0, y: 0, pinch: null, pan: null, lastTap: 0 };
2294
+
2295
+ function zoomed() { return Z.s > 1.01; }
2296
+
2297
+ function applyZoom() {
2298
+ var G = S.G;
2299
+ Z.x = clamp(Z.x, G.pageW - G.pageW * Z.s, 0);
2300
+ Z.y = clamp(Z.y, G.pageH - G.pageH * Z.s, 0);
2301
+ frame.style.transformOrigin = '0 0';
2302
+ frame.style.transform = Z.s === 1 ? 'none' : 'translate(' + Z.x + 'px,' + Z.y + 'px) scale(' + Z.s + ')';
2303
+ if (S.doc) S.doc.body.style.webkitUserSelect = S.doc.body.style.userSelect = zoomed() ? 'none' : '';
2304
+ }
2305
+
2306
+ function resetZoom() {
2307
+ if (Z.s === 1 && !Z.pinch) return;
2308
+ Z.s = 1; Z.x = 0; Z.y = 0; Z.pinch = null; Z.pan = null;
2309
+ applyZoom();
2310
+ post('zoom', { scale: 1 });
2311
+ }
2312
+
2313
+ function zoomTap() {
2314
+ var now = Date.now();
2315
+ if (now - Z.lastTap < 320) { resetZoom(); Z.lastTap = 0; } else Z.lastTap = now;
2316
+ }
2317
+
2318
+ function attachZoom(d) {
2319
+ // screen position of the outer page's (0,0): touches are reported in the chapter's own, scaled coordinates
2320
+ function outer(t) { return { x: t.screenX - Z.off.x, y: t.screenY - Z.off.y }; }
2321
+ function mid(a, b) { return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }; }
2322
+ function dist(a, b) { return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); }
2323
+
2324
+ d.addEventListener('touchstart', function (e) {
2325
+ var G = S.G;
2326
+ if (!G || G.scroll || !(S.settings.maxZoom > 1) || curlBusy || slideBusy) return;
2327
+ var t = e.touches[0];
2328
+ Z.off = { x: t.screenX - (G.left + Z.x + t.clientX * Z.s), y: t.screenY - (G.top + Z.y + t.clientY * Z.s) };
2329
+ if (e.touches.length === 2) {
2330
+ var a = outer(e.touches[0]), b = outer(e.touches[1]), m = mid(a, b);
2331
+ var sel = d.getSelection();
2332
+ if (sel) sel.removeAllRanges();
2333
+ // the page point under the fingers stays under them
2334
+ Z.pinch = { d0: Math.max(1, dist(a, b)), s0: Z.s, px: (m.x - G.left - Z.x) / Z.s, py: (m.y - G.top - Z.y) / Z.s };
2335
+ Z.pan = null;
2336
+ d.body.style.webkitUserSelect = d.body.style.userSelect = 'none';
2337
+ } else if (e.touches.length === 1 && zoomed()) {
2338
+ var o = outer(t);
2339
+ Z.pan = { x: o.x, y: o.y, x0: Z.x, y0: Z.y, moved: false };
2340
+ }
2341
+ }, { passive: true, capture: true });
2342
+
2343
+ d.addEventListener('touchmove', function (e) {
2344
+ if (Z.pinch && e.touches.length >= 2) {
2345
+ e.preventDefault();
2346
+ var a = outer(e.touches[0]), b = outer(e.touches[1]), m = mid(a, b), G = S.G;
2347
+ Z.s = clamp(Z.pinch.s0 * dist(a, b) / Z.pinch.d0, 1, S.settings.maxZoom);
2348
+ Z.x = m.x - G.left - Z.pinch.px * Z.s;
2349
+ Z.y = m.y - G.top - Z.pinch.py * Z.s;
2350
+ applyZoom();
2351
+ } else if (Z.pan && e.touches.length === 1) {
2352
+ e.preventDefault();
2353
+ var o = outer(e.touches[0]);
2354
+ if (Math.abs(o.x - Z.pan.x) + Math.abs(o.y - Z.pan.y) > 6) Z.pan.moved = true;
2355
+ Z.x = Z.pan.x0 + o.x - Z.pan.x;
2356
+ Z.y = Z.pan.y0 + o.y - Z.pan.y;
2357
+ applyZoom();
2358
+ }
2359
+ }, { passive: false, capture: true });
2360
+
2361
+ function end(e) {
2362
+ if (Z.pinch && (!e || e.touches.length < 2)) {
2363
+ Z.pinch = null;
2364
+ // the lifted finger must not become a tap, a swipe or a selection
2365
+ S.dragged = true;
2366
+ setTimeout(function () { S.dragged = false; }, 350);
2367
+ if (Z.s < 1.05) resetZoom();
2368
+ else { applyZoom(); post('zoom', { scale: Z.s }); }
2369
+ // a finger still down continues as a pan
2370
+ if (e && e.touches.length === 1 && zoomed()) {
2371
+ var o = outer(e.touches[0]);
2372
+ Z.pan = { x: o.x, y: o.y, x0: Z.x, y0: Z.y, moved: true };
2373
+ }
2374
+ } else if (Z.pan && (!e || e.touches.length === 0)) {
2375
+ if (Z.pan.moved) { S.dragged = true; setTimeout(function () { S.dragged = false; }, 350); }
2376
+ Z.pan = null;
2377
+ }
2378
+ }
2379
+ d.addEventListener('touchend', end, { passive: true, capture: true });
2380
+ d.addEventListener('touchcancel', end, { passive: true, capture: true });
2381
+ }
2382
+
2383
+ /* ------------------------------------------------------------ selection */
2384
+
2385
+ // Text is picked by hand, not by the browser. iOS always shows its own menu (Copy, Speak ...) for a browser
2386
+ // selection. It cannot be hidden, and it races the host's popup. So: a long press picks a word, dragging
2387
+ // extends the pick word by word, and the pick is drawn as marks, like a highlight. Moving more than
2388
+ // PICK_MOVE_PX before the long press fires makes the touch a swipe instead (like Apple Books and Kindle).
2389
+ // Picks are kept as chapter offsets, not DOM Ranges: drawing marks splits text nodes, which moves Ranges.
2390
+ var PICK_HOLD_MS = 400, PICK_MOVE_PX = 10, PICK_NEAR_PX = 28;
2391
+ // \p{M}: tashkeel and other marks. ZWNJ / ZWJ / U+2060 sit inside Persian and Pashto words (U+2060 also
2392
+ // replaces watermark runs, see repairZeroWidth).
2393
+ var WORD_CHAR = /[\p{L}\p{N}\p{M}'‘’‌‍⁠-]/u;
2394
+ var P = { timer: 0, x: 0, y: 0, armed: false, anchor: null, a: 0, b: 0 };
2395
+
2396
+ // Character at chapter offset o, or '' when it is in another block (a word never runs across paragraphs).
2397
+ function pickChar(o, block) {
2398
+ var s = o >= 0 ? segFor(o) : null;
2399
+ if (!s || blockOf(s.node, rootEl()) !== block) return '';
2400
+ return s.node.data[s.pos];
2401
+ }
2402
+
2403
+ function wordAt(d, x, y, inBlockOnly) {
2404
+ var r = d.caretRangeFromPoint && d.caretRangeFromPoint(x, y);
2405
+ if (!r || r.startContainer.nodeType !== 3 || !rootEl().contains(r.startContainer)) return null;
2406
+ var seg = S.segMap.get(r.startContainer);
2407
+ if (!seg) return null;
2408
+ var block = blockOf(seg.node, rootEl()), a = seg.start + r.startOffset, b = a;
2409
+ // In the gap between paragraphs the browser snaps to the next one's first word. While dragging, only take a
2410
+ // word when the finger is over its paragraph, so ending on a full stop does not pull in the next paragraph.
2411
+ if (inBlockOnly && block !== rootEl()) {
2412
+ var box = block.getBoundingClientRect();
2413
+ if (y < box.top || y > box.bottom) return null;
2414
+ }
2415
+ // A dragging finger on a full stop (or just after one) means the word before it. widenPick then adds the stop.
2416
+ if (inBlockOnly && !WORD_CHAR.test(pickChar(a, block)) && !WORD_CHAR.test(pickChar(a - 1, block))) {
2417
+ var m = TRAIL_MARK.test(pickChar(a, block)) ? a + 1 : a, e = m;
2418
+ while (e > 0 && TRAIL_MARK.test(pickChar(e - 1, block))) e--;
2419
+ if (e === m) return null;
2420
+ a = b = e;
2421
+ }
2422
+ while (a > 0 && WORD_CHAR.test(pickChar(a - 1, block))) a--;
2423
+ while (b < S.segs.total && WORD_CHAR.test(pickChar(b, block))) b++;
2424
+ return b > a ? { a: a, b: b } : null;
2425
+ }
2426
+
2427
+ // A dragged pick takes the punctuation touching its ends, so a sentence can end on its full stop (the stop is
2428
+ // small and sits at the paragraph's edge). Same marks as the Aklantis app's epub.js reader. Never past a block.
2429
+ var LEAD_MARK = /[«“‘"'(\[]/, TRAIL_MARK = /[.,;:!?،؛؟۔…»”’"')\]]/;
2430
+ function widenPick(a, b) {
2431
+ var sa = segFor(a), sb = segFor(b - 1);
2432
+ var ba = sa && blockOf(sa.node, rootEl()), bb = sb && blockOf(sb.node, rootEl());
2433
+ while (ba && a > 0 && LEAD_MARK.test(pickChar(a - 1, ba))) a--;
2434
+ while (bb && b < S.segs.total && TRAIL_MARK.test(pickChar(b, bb))) b++;
2435
+ return { a: a, b: b };
2436
+ }
2437
+
2438
+ function drawPick(a, b) {
2439
+ if (unwrapMarks('mark.pick')) refreshSegs();
2440
+ wrapRange(a, b, 'pick', '__pick');
2441
+ P.a = a; P.b = b;
2442
+ }
2443
+
2444
+ // caretRangeFromPoint snaps to the nearest text even from a blank margin, so check the finger is on the word.
2445
+ function nearPick(x, y) {
2446
+ var marks = S.doc.querySelectorAll('mark.pick');
2447
+ for (var i = 0; i < marks.length; i++) {
2448
+ var r = marks[i].getBoundingClientRect();
2449
+ if (x >= r.left - PICK_NEAR_PX && x <= r.right + PICK_NEAR_PX && y >= r.top - PICK_NEAR_PX && y <= r.bottom + PICK_NEAR_PX) return true;
2450
+ }
2451
+ return false;
2452
+ }
2453
+
2454
+ // One rect around all marks of the pick, in the same coordinates as rectOf.
2455
+ function pickRect() {
2456
+ var box = null;
2457
+ S.doc.querySelectorAll('mark.pick').forEach(function (m) {
2458
+ var r = rectOf(m);
2459
+ if (!r.width && !r.height) return;
2460
+ if (!box) { box = { x1: r.x, y1: r.y, x2: r.x + r.width, y2: r.y + r.height }; return; }
2461
+ box.x1 = Math.min(box.x1, r.x); box.y1 = Math.min(box.y1, r.y);
2462
+ box.x2 = Math.max(box.x2, r.x + r.width); box.y2 = Math.max(box.y2, r.y + r.height);
2463
+ });
2464
+ return box ? { x: box.x1, y: box.y1, width: box.x2 - box.x1, height: box.y2 - box.y1 } : { x: 0, y: 0, width: 0, height: 0 };
2465
+ }
2466
+
2467
+ function pickText(a, b) {
2468
+ return S.segs.filter(function (s) { return s.end > a && s.start < b; })
2469
+ .map(function (s) { return s.node.data.slice(Math.max(a, s.start) - s.start, Math.min(b, s.end) - s.start); })
2470
+ .join('');
2471
+ }
2472
+
2473
+ function clearPick() {
2474
+ if (P.timer) clearTimeout(P.timer);
2475
+ P.timer = 0; P.armed = false; P.anchor = null;
2476
+ if (S.doc && unwrapMarks('mark.pick')) refreshSegs();
2477
+ if (S.sel) { S.sel = null; post('selectionClear'); }
2478
+ }
2479
+
2480
+ function armPick(d) {
2481
+ P.timer = 0;
2482
+ if (d !== S.doc || zoomed() || Z.pinch) return;
2483
+ var w = wordAt(d, P.x, P.y);
2484
+ if (!w) return;
2485
+ drawPick(w.a, w.b);
2486
+ if (!nearPick(P.x, P.y)) { clearPick(); return; }
2487
+ P.armed = true;
2488
+ P.anchor = w;
2489
+ }
2490
+
2491
+ // touchstart with one finger. A tap while a pick is shown only dismisses it.
2492
+ function pickStart(d, t) {
2493
+ if (S.sel || P.armed) {
2494
+ clearPick();
2495
+ S.dragged = true;
2496
+ setTimeout(function () { S.dragged = false; }, 350);
2497
+ }
2498
+ if (P.timer) clearTimeout(P.timer);
2499
+ P.x = t.clientX; P.y = t.clientY;
2500
+ P.timer = zoomed() ? 0 : setTimeout(function () { armPick(d); }, PICK_HOLD_MS);
2501
+ }
2502
+
2503
+ // touchmove. True when the move belongs to the pick (then it is not a swipe or a scroll).
2504
+ function pickMove(d, e) {
2505
+ var t = e.touches[0];
2506
+ if (!P.armed) {
2507
+ if (P.timer && (Math.abs(t.clientX - P.x) > PICK_MOVE_PX || Math.abs(t.clientY - P.y) > PICK_MOVE_PX)) {
2508
+ clearTimeout(P.timer);
2509
+ P.timer = 0;
2510
+ }
2511
+ return false;
2512
+ }
2513
+ e.preventDefault();
2514
+ var w = wordAt(d, t.clientX, t.clientY, true);
2515
+ if (w) {
2516
+ var span = widenPick(Math.min(P.anchor.a, w.a), Math.max(P.anchor.b, w.b));
2517
+ if (span.a !== P.a || span.b !== P.b) drawPick(span.a, span.b);
2518
+ }
2519
+ return true;
2520
+ }
2521
+
2522
+ // touchend. True when it finished a pick: then the host gets the selection, and the touch is not a tap.
2523
+ function pickEnd() {
2524
+ if (P.timer) clearTimeout(P.timer);
2525
+ P.timer = 0;
2526
+ if (!P.armed) return false;
2527
+ P.armed = false;
2528
+ S.dragged = true;
2529
+ setTimeout(function () { S.dragged = false; }, 350);
2530
+ var a = P.a, b = P.b, cur = S.cur, v = S.views.get(cur);
2531
+ var sel = S.sel = { spine: cur, start: a, end: b, text: cleanText(pickText(a, b)) }, rect = pickRect();
2532
+ var send = function (view) {
2533
+ if (S.sel !== sel) return; // cleared or replaced while the view was built
2534
+ post('selection', { spine: cur, start: a, end: b, text: sel.text, rect: rect, cfi: view ? rangeCfi(view, a, b) : undefined });
2535
+ };
2536
+ if (v) send(v);
2537
+ else chapterView(cur).then(send, function () { send(null); });
2538
+ return true;
2539
+ }
2540
+
1502
2541
  /* ------------------------------------------------------------- events */
1503
2542
 
1504
2543
  function handleLink(a) {
1505
2544
  var href = a.getAttribute('href') || '';
1506
- if (/^[a-z][a-z0-9+.-]*:/i.test(href)) { post('link', { href: href }); return; }
2545
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {
2546
+ // only web and mail links leave the book; intent:, file:, tel:, custom schemes ... are ignored
2547
+ if (/^(https?|mailto):/i.test(href)) post('link', { href: href });
2548
+ return;
2549
+ }
1507
2550
  var frag = href.indexOf('#') >= 0 ? href.split('#')[1] : '';
2551
+ try { frag = decodeURIComponent(frag); } catch (e) { /* keep as is */ }
1508
2552
  var host = a.closest && a.closest('.__ch');
1509
2553
  var path = resolvePath(S.spine[host ? +host.getAttribute('data-spine') : S.cur].path, href);
1510
2554
  var idx = path ? spineIndexOfPath(path) : -1;
1511
2555
  if (idx < 0) return;
1512
- queue = queue.then(function () { return gotoLocation({ spine: idx, fragment: frag, offset: 0 }); });
2556
+ var from = { spine: S.cur, offset: S.doc ? pageStart(S.page) : 0 };
2557
+ enqueue(function () {
2558
+ post('linkJump', from); // lets the host offer a way back after a footnote or cross reference
2559
+ return gotoLocation({ spine: idx, fragment: frag, offset: 0 });
2560
+ });
1513
2561
  }
1514
2562
 
1515
2563
  function attachListeners(d) {
2564
+ attachZoom(d);
1516
2565
  d.addEventListener('click', function (e) {
1517
2566
  if (S.dragged) return;
1518
- var sel = d.getSelection();
1519
- if (sel && !sel.isCollapsed) return;
1520
- var t = e.target, a = t.closest && t.closest('a'), m = t.closest && t.closest('mark[data-hl]');
2567
+ if (zoomed()) { zoomTap(); return; }
2568
+ var t = e.target, a = t.closest && t.closest('a'), m = t.closest && t.closest('mark[data-hl]:not(.hit):not(.pick)');
1521
2569
  if (a) { e.preventDefault(); handleLink(a); return; }
1522
- if (m && m.getAttribute('data-hl') !== '__hit') {
2570
+ if (m) {
1523
2571
  post('highlightTap', { id: m.getAttribute('data-hl'), rect: rectOf(m) });
1524
2572
  return;
1525
2573
  }
1526
- var x = (e.clientX + S.G.mx) / S.G.W;
2574
+ var x = (e.clientX + S.G.left) / S.G.W;
1527
2575
  var zone = S.G.scroll || (x >= 0.25 && x <= 0.75) ? 'center' : (x < 0.25 ? 'left' : 'right');
1528
2576
  if (zone === 'center') { clearHit(); post('tap', { zone: 'center' }); return; }
1529
2577
  var forward = (zone === 'right') !== S.rtl;
1530
- queue = queue.then(forward ? next : prev);
2578
+ enqueue(forward ? next : prev);
1531
2579
  }, true);
1532
2580
 
1533
2581
  var t0 = null;
2582
+ // a touch since the last scroll-mode 'end' (see the scroll listener below)
2583
+ var touchedSinceEnd = false;
1534
2584
  d.addEventListener('touchstart', function (e) {
1535
- if (e.touches.length !== 1) { t0 = null; return; }
2585
+ touchedSinceEnd = true;
2586
+ // a second finger (pinch) ends a pick in progress
2587
+ if (e.touches.length !== 1) { if (P.armed || P.timer) clearPick(); endTouch(true); return; }
2588
+ pickStart(d, e.touches[0]);
2589
+ if (zoomed() || Z.pinch) return;
1536
2590
  var t = e.touches[0], el = d.scrollingElement || d.documentElement;
1537
2591
  t0 = { x: t.clientX, y: t.clientY, time: Date.now(), drag: false, dx: 0, dy: 0, base: currentX(), top: el.scrollTop };
1538
2592
  }, { passive: true });
1539
2593
  d.addEventListener('touchmove', function (e) {
2594
+ if (e.touches.length === 1 && pickMove(d, e)) { t0 = null; return; }
1540
2595
  if (!t0) return;
1541
- var sel = d.getSelection();
1542
- if (sel && !sel.isCollapsed) { t0 = null; return; }
1543
2596
  var t = e.touches[0], dx = t.clientX - t0.x, dy = t.clientY - t0.y;
1544
2597
  t0.dx = dx; t0.dy = dy;
1545
2598
  if (S.G.scroll) return;
@@ -1550,32 +2603,35 @@
1550
2603
  if (S.G.mode === 'slide') slideDrag(t0, dx);
1551
2604
  else if (S.G.mode === 'curl') curlDrag(t0, dx);
1552
2605
  }, { passive: false });
1553
- d.addEventListener('touchend', function () {
2606
+ // cancelled: the system took the touch (edge-swipe gesture, notification shade, a second finger ...)
2607
+ function endTouch(cancelled) {
1554
2608
  var tt = t0;
1555
2609
  t0 = null;
1556
2610
  if (!tt) return;
1557
2611
  var G = S.G;
1558
2612
  if (G.scroll) {
2613
+ if (cancelled) return;
1559
2614
  // keep scrolling into the next/previous chapter when the edge is already reached
1560
2615
  var el = d.scrollingElement || d.documentElement;
1561
2616
  var still = Math.abs(el.scrollTop - tt.top) < 3;
1562
2617
  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);
2618
+ if (tt.dy < 0 && el.scrollTop + G.pageH >= el.scrollHeight - 2) enqueue(next);
2619
+ else if (tt.dy > 0 && el.scrollTop <= 1) enqueue(prev);
1565
2620
  }
1566
2621
  return;
1567
2622
  }
1568
2623
  if (!tt.drag) return;
2624
+ var fastEnough = Math.abs(tt.dx) / Math.max(1, Date.now() - tt.time) > 0.5 && Math.abs(tt.dx) > 30;
1569
2625
  if (tt.slide) {
1570
2626
  var ss = tt.slide;
1571
2627
  S.dragged = true;
1572
2628
  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;
2629
+ var scommit = !cancelled && (ss.p > 0.28 || fastEnough);
1575
2630
  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);
2631
+ enqueue(async function () {
2632
+ try {
2633
+ await slideAnimate(ss, ss.p, scommit ? 1 : 0, scommit ? 140 + 280 * (1 - ss.p) : 120 + 220 * ss.p);
2634
+ } finally { slideEnd(ss, scommit); }
1579
2635
  if (scommit) relocate();
1580
2636
  });
1581
2637
  return;
@@ -1584,58 +2640,75 @@
1584
2640
  var st = tt.curl;
1585
2641
  S.dragged = true;
1586
2642
  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;
2643
+ var commit = !cancelled && (st.p > 0.3 || fastEnough);
1589
2644
  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);
2645
+ enqueue(async function () {
2646
+ try {
2647
+ await curlAnimate(st, st.p, commit ? 1 : 0, commit ? 260 + 560 * (1 - st.p) : 200 + 300 * st.p);
2648
+ } finally { curlEnd(st, commit); }
1593
2649
  if (commit) relocate();
1594
2650
  });
1595
2651
  return;
1596
2652
  }
1597
2653
  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);
2654
+ var go = !cancelled && (Math.abs(dx) > G.W * 0.2 || (Math.abs(dx) / dt > 0.5 && Math.abs(dx) > 30));
1599
2655
  S.dragged = true;
1600
2656
  setTimeout(function () { S.dragged = false; }, 350);
1601
2657
  if (!go) { if (G.mode === 'slide') showPage(S.page, true); return; }
1602
2658
  var forward = S.rtl ? dx > 0 : dx < 0;
1603
- queue = queue.then(forward ? next : prev);
2659
+ enqueue(forward ? next : prev);
2660
+ }
2661
+ d.addEventListener('touchend', function () {
2662
+ if (pickEnd()) { t0 = null; return; }
2663
+ endTouch(false);
1604
2664
  }, { passive: true });
2665
+ d.addEventListener('touchcancel', function () {
2666
+ if (P.armed || P.timer) clearPick();
2667
+ endTouch(true);
2668
+ }, { passive: true });
2669
+ // a long press belongs to the pick, never to a system menu
2670
+ d.addEventListener('contextmenu', function (e) { e.preventDefault(); });
1605
2671
 
1606
2672
  d.defaultView.addEventListener('scroll', debounce(function () {
1607
2673
  if (d !== S.doc || !S.G.scroll) return;
1608
- if (checkSection()) return;
1609
2674
  var el = d.scrollingElement || d.documentElement;
2675
+ // A finger scroll that ends at the bottom of the last chapter. Every time, so it works again after the
2676
+ // host closes its end page. The pull in endTouch is not enough: the iOS bounce cancels it.
2677
+ // Only after a touch: a re-layout (font, theme) that moves the page must not fire it.
2678
+ var lastSec = S.sections && S.sections[S.sections.length - 1];
2679
+ var bottom = !!lastSec && lastSec.index === S.spine.length - 1 && el.scrollTop + S.G.pageH >= el.scrollHeight - 2;
2680
+ if (bottom && touchedSinceEnd) { touchedSinceEnd = false; post('end', { edge: 'end' }); }
2681
+ if (checkSection()) return;
1610
2682
  var p = clamp(Math.round((el.scrollTop - bodyTop()) / S.G.pageH), 0, S.pageCount - 1);
1611
2683
  if (p !== S.page) { S.page = p; autoLabels(); relocate(); }
1612
2684
  }, 120));
1613
-
1614
- d.addEventListener('selectionchange', debounce(function () {
1615
- if (d !== S.doc) return;
1616
- var sel = d.getSelection();
1617
- if (!sel || sel.rangeCount === 0 || sel.isCollapsed) {
1618
- if (S.sel) { S.sel = null; post('selectionClear'); }
1619
- return;
1620
- }
1621
- var r = sel.getRangeAt(0);
1622
- if (!rootEl().contains(r.startContainer) || !rootEl().contains(r.endContainer)) return;
1623
- var a = boundaryOffset(r.startContainer, r.startOffset), b = boundaryOffset(r.endContainer, r.endOffset);
1624
- if (b <= a) return;
1625
- S.sel = { spine: S.cur, start: a, end: b, text: sel.toString() };
1626
- post('selection', { spine: S.cur, start: a, end: b, text: S.sel.text, rect: rectOf(r) });
1627
- }, 180));
1628
2685
  }
1629
2686
 
1630
2687
  /* ------------------------------------------------------------ commands */
1631
2688
 
1632
2689
  var queue = Promise.resolve();
1633
2690
 
2691
+ // Every piece of work (commands, taps, swipes) runs one after another. A failure is reported and never
2692
+ // breaks the chain, so the reader keeps responding after an error.
2693
+ function enqueue(fn) {
2694
+ queue = queue.then(fn).catch(function (err) {
2695
+ post('error', { message: String((err && err.message) || err) });
2696
+ });
2697
+ }
2698
+
1634
2699
  async function handle(c) {
1635
2700
  switch (c.cmd) {
1636
2701
  case 'open':
1637
2702
  S.openId = (S.openId || 0) + 1;
1638
2703
  S.token++;
2704
+ // nothing may leak from the previous book (cached images such as the cover, labels, direction)
2705
+ S.dataCache = {}; S.fragCache = {}; S.obf = {}; S.obfKeys = {}; S.identifier = '';
2706
+ S.breaks = []; S.indexFailed = false; S.labelsExternal = false;
2707
+ S.views = new Map(); S.viewJobs = {}; S.viewFailed = {}; S.cfiCache = new Map(); S.locs = null;
2708
+ S.locationChars = c.locationChars == null ? 150 : c.locationChars;
2709
+ S.repairZeroWidth = c.repairZeroWidth !== false;
2710
+ S.bookRtl = false; S.rtl = false; S.ppd = ''; S.contentRtl = false; S.spine = []; S.toc = [];
2711
+ hdr.textContent = ''; ftr.textContent = '';
1639
2712
  S.cur = -1;
1640
2713
  S.page = 0;
1641
2714
  S.pageCount = 1;
@@ -1652,12 +2725,31 @@
1652
2725
  S.searchId = -1;
1653
2726
  applySettings(c.settings);
1654
2727
  S.highlights = c.highlights || [];
1655
- await openBook(c.data);
1656
- buildIndex();
1657
- post('loaded', { spineCount: S.spine.length });
1658
- await gotoLocation(c.location);
2728
+ var data = c.data != null ? c.data : chunks.join('');
2729
+ chunks = [];
2730
+ try {
2731
+ await openBook(data);
2732
+ buildIndex().catch(function () { S.indexFailed = true; }); // search and exact progress are optional
2733
+ post('loaded', { spineCount: S.spine.length });
2734
+ await gotoLocation(c.location);
2735
+ } catch (err) {
2736
+ post('error', { message: String((err && err.message) || err), fatal: true });
2737
+ }
1659
2738
  break;
1660
2739
  case 'settings': applySettings(c.settings); break;
2740
+ case 'fonts':
2741
+ S.fontCss = (c.list || []).map(fontFace).join('\n');
2742
+ (c.list || []).forEach(function (f) { if (f) delete blobs[f.key]; }); // later updates use other keys
2743
+ if (S.doc) {
2744
+ var old = S.doc.getElementById('fonts');
2745
+ if (old) old.parentNode.removeChild(old);
2746
+ addFontStyle(S.doc);
2747
+ if (S.doc.getElementById('app')) S.doc.head.appendChild(S.doc.getElementById('app')); // theme rules stay last
2748
+ S.ghostDirty = true;
2749
+ if (S.doc.fonts && S.doc.fonts.ready) await Promise.race([S.doc.fonts.ready, sleep(1500)]);
2750
+ relayout();
2751
+ }
2752
+ break;
1661
2753
  case 'labels':
1662
2754
  S.labelsExternal = true;
1663
2755
  hdr.textContent = c.header || '';
@@ -1665,31 +2757,55 @@
1665
2757
  break;
1666
2758
  case 'highlights':
1667
2759
  S.highlights = c.list || [];
1668
- if (S.doc) { applyHighlightsDom(); }
2760
+ if (S.doc) {
2761
+ var shown = S.sections && S.sections.length ? S.sections.map(function (x) { return x.index; }) : [S.cur];
2762
+ for (var k = 0; k < shown.length; k++) await resolveHighlights(shown[k]);
2763
+ applyHighlightsDom();
2764
+ }
1669
2765
  break;
1670
2766
  case 'next': await next(); break;
1671
2767
  case 'prev': await prev(); break;
1672
2768
  case 'goto': await gotoLocation(c.location); break;
1673
2769
  case 'showHit': if (S.doc) showHit(c.offset, c.length); break;
1674
- case 'clearSelection':
1675
- if (S.doc) S.doc.getSelection().removeAllRanges();
1676
- S.sel = null;
1677
- break;
2770
+ case 'clearSelection': clearPick(); break;
1678
2771
  case 'search': search(c.query, c.id); break;
1679
2772
  case 'cancelSearch': S.searchId = c.id || -1; break;
1680
2773
  }
1681
2774
  }
1682
2775
 
2776
+ // Host fonts arrive like the book, in pieces (window.__blob), before the 'fonts' command that names them.
2777
+ var blobs = {};
2778
+ window.__blob = function (key, reset, s) {
2779
+ if (reset || !blobs[key]) blobs[key] = [];
2780
+ blobs[key].push(s);
2781
+ };
2782
+ function fontFace(f) {
2783
+ var data = (blobs[f && f.key] || []).join('').replace(/[^A-Za-z0-9+\/=]/g, '');
2784
+ if (!data || !f.family) return '';
2785
+ var family = String(f.family).replace(/["\\<>{};]/g, '');
2786
+ var mime = /^[a-z0-9.+\/-]+$/i.test(f.mime || '') ? f.mime : 'font/ttf';
2787
+ var format = /woff2/.test(mime) ? 'woff2' : /woff/.test(mime) ? 'woff' : /otf|opentype/.test(mime) ? 'opentype' : 'truetype';
2788
+ var weight = /^(\d{3}|normal|bold)$/.test(String(f.weight || '')) ? f.weight : 'normal';
2789
+ var style = /^(normal|italic|oblique)$/.test(f.style || '') ? f.style : 'normal';
2790
+ return '@font-face{font-family:"' + family + '";src:url(data:' + mime + ';base64,' + data + ') format("' + format + '");' +
2791
+ 'font-weight:' + weight + ';font-style:' + style + ';font-display:block}';
2792
+ }
2793
+
2794
+ // the book arrives in pieces (one injected call each) before the 'open' command
2795
+ var chunks = [];
2796
+ window.__chunk = function (reset, s) {
2797
+ if (reset) chunks = [];
2798
+ chunks.push(s);
2799
+ };
2800
+
1683
2801
  window.__cmd = function (str) {
1684
2802
  var c;
1685
2803
  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
- });
2804
+ enqueue(function () { return handle(c); });
1689
2805
  };
1690
2806
  window.addEventListener('message', function (e) { if (typeof e.data === 'string') window.__cmd(e.data); });
1691
2807
  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));
2808
+ window.addEventListener('resize', debounce(function () { if (S.doc) enqueue(function () { if (S.doc) relayout(); }); }, 150));
1693
2809
  window.__reader = S; // debugging aid
1694
2810
 
1695
2811
  post('ready');