aksos-react-native-epub-reader 0.1.1 → 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 (44) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +158 -13
  3. package/lib/EpubReader.d.ts +47 -9
  4. package/lib/EpubReader.js +69 -16
  5. package/lib/EpubReaderView.d.ts +27 -2
  6. package/lib/EpubReaderView.js +38 -32
  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 +1 -1
  11. package/lib/themes.d.ts +24 -6
  12. package/lib/themes.js +80 -20
  13. package/lib/types.d.ts +66 -1
  14. package/lib/ui/AppearanceSheet.d.ts +4 -2
  15. package/lib/ui/AppearanceSheet.js +20 -13
  16. package/lib/ui/ContentsSheet.d.ts +2 -0
  17. package/lib/ui/ContentsSheet.js +21 -13
  18. package/lib/ui/CustomizeSheet.d.ts +4 -2
  19. package/lib/ui/CustomizeSheet.js +20 -18
  20. package/lib/ui/HighlightMenu.d.ts +4 -2
  21. package/lib/ui/HighlightMenu.js +3 -3
  22. package/lib/ui/NoteEditor.js +6 -5
  23. package/lib/ui/SearchSheet.js +6 -5
  24. package/lib/ui/Sheet.js +5 -4
  25. package/lib/ui/Text.d.ts +9 -0
  26. package/lib/ui/Text.js +62 -0
  27. package/package.json +81 -76
  28. package/src/EpubReader.tsx +121 -25
  29. package/src/EpubReaderView.tsx +61 -17
  30. package/src/cfiOrder.ts +28 -0
  31. package/src/engine/epubcfi.js +527 -0
  32. package/src/engine/html.ts +1 -1
  33. package/src/engine/reader.js +830 -65
  34. package/src/index.ts +1 -1
  35. package/src/themes.ts +97 -21
  36. package/src/types.ts +71 -1
  37. package/src/ui/AppearanceSheet.tsx +19 -10
  38. package/src/ui/ContentsSheet.tsx +14 -4
  39. package/src/ui/CustomizeSheet.tsx +14 -10
  40. package/src/ui/HighlightMenu.tsx +6 -4
  41. package/src/ui/NoteEditor.tsx +2 -1
  42. package/src/ui/SearchSheet.tsx +2 -1
  43. package/src/ui/Sheet.tsx +4 -3
  44. package/src/ui/Text.tsx +27 -0
@@ -59,13 +59,15 @@
59
59
  pageStarts: {}, dataCache: {}, fragCache: {},
60
60
  highlights: [], sel: null, searchId: 0, dragged: false,
61
61
  G: null, ghostDirty: true, labelsExternal: false,
62
+ views: new Map(), viewJobs: {}, viewFailed: {}, cfiCache: new Map(), locs: null, locationChars: 150, repairZeroWidth: true, fontCss: '',
62
63
  settings: {
63
64
  bg: '#ffffff', fg: '#000000', link: '#0a60ff',
64
65
  fontFamily: 'original', fontSize: 18, lineHeight: 1.5,
65
66
  marginX: 28, gap: 48, justify: false, bold: false,
66
67
  columns: 'auto', letterSpacing: 0, wordSpacing: 0, mode: 'slide',
67
68
  insets: { top: 60, bottom: 52 }, direction: 'auto',
68
- showHeader: true, showFooter: true
69
+ showHeader: true, showFooter: true,
70
+ bookColors: 'theme', highlightColors: null, highlightOpacity: null, maxZoom: 3
69
71
  }
70
72
  };
71
73
 
@@ -320,8 +322,17 @@
320
322
 
321
323
  var spineEl = firstLocal(opf, 'spine');
322
324
  if (!spineEl) throw new Error('Not a valid EPUB (the package has no spine).');
323
- S.spine = byLocal(spineEl, 'itemref').map(function (r) {
324
- return manifest[r.getAttribute('idref')];
325
+ // 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
+ };
325
336
  }).filter(function (m) {
326
337
  return m && /html|xml/i.test(m.type) || (m && /\.x?html?$/i.test(m.path));
327
338
  });
@@ -350,9 +361,10 @@
350
361
  S.bookRtl = autoRtl();
351
362
  S.rtl = effectiveRtl(S.bookRtl);
352
363
 
353
- S.toc = await parseToc(opf, manifest, spineEl, opfPath);
364
+ var toc = await parseToc(opf, manifest, spineEl, opfPath);
365
+ S.toc = toc.items;
354
366
  post('metadata', S.meta);
355
- post('toc', { items: S.toc, rtl: effectiveRtl(S.bookRtl), spineCount: S.spine.length });
367
+ post('toc', { items: S.toc, all: toc.all, rtl: effectiveRtl(S.bookRtl), spineCount: S.spine.length });
356
368
  sendCover(opf, manifest);
357
369
  }
358
370
 
@@ -397,14 +409,25 @@
397
409
  return -1;
398
410
  }
399
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.
400
414
  async function parseToc(opf, manifest, spineEl, opfPath) {
401
- 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
+ }
402
420
  function add(label, href, level, base) {
403
421
  var path = resolvePath(base, href);
422
+ if (!path) return;
404
423
  var frag = href && href.indexOf('#') >= 0 ? href.split('#')[1] : '';
405
- var idx = path ? spineIndexOfPath(path) : -1;
406
- if (idx < 0) return;
407
- items.push({ label: (label || '').replace(/\s+/g, ' ').trim(), spine: idx, fragment: frag, level: level });
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);
408
431
  }
409
432
 
410
433
  var navItem = null;
@@ -433,7 +456,8 @@
433
456
  }
434
457
  }
435
458
  }
436
- if (items.length) return items;
459
+ if (items.length) return { items: items, all: all };
460
+ all = [];
437
461
 
438
462
  var ncxId = spineEl.getAttribute('toc');
439
463
  var ncx = (ncxId && manifest[ncxId]) ||
@@ -455,7 +479,7 @@
455
479
  })(map || { children: [] }, 0);
456
480
  }
457
481
  }
458
- return items;
482
+ return { items: items, all: all };
459
483
  }
460
484
 
461
485
  function sendCover(opf, manifest) {
@@ -484,7 +508,13 @@
484
508
  // Title of the TOC entry that applies to chapter i. When several entries point into the same file
485
509
  // (Calibre-style single-file books) `off`, a text offset in the chapter on screen, picks the right one.
486
510
  function chapterTitle(i, off) {
487
- var best = '';
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;
488
518
  for (var k = 0; k < S.toc.length; k++) {
489
519
  var t = S.toc[k];
490
520
  if (t.spine > i) break;
@@ -492,9 +522,9 @@
492
522
  var fo = fragOffset(t.fragment);
493
523
  if (fo != null && fo > off) continue;
494
524
  }
495
- best = t.label;
525
+ best = k;
496
526
  }
497
- return best || S.meta.title || '';
527
+ return best;
498
528
  }
499
529
 
500
530
  /* ------------------------------------------------------------- chapters */
@@ -537,13 +567,39 @@
537
567
  });
538
568
  }
539
569
 
540
- async function parseChapter(i) {
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) {
541
573
  var it = S.spine[i];
542
574
  var raw;
543
575
  try { raw = await readText(it.path); }
544
576
  catch (e) { raw = '<html><body><p>This chapter could not be read (the file is damaged).</p></body></html>'; }
545
577
  if (raw == null) raw = '<html><body><p></p></body></html>';
546
- 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];
547
603
  var body = doc.body || doc.documentElement;
548
604
  var refs = [];
549
605
  Array.prototype.slice.call(doc.querySelectorAll('link,style')).forEach(function (el) {
@@ -553,6 +609,7 @@
553
609
  el.parentNode.removeChild(el);
554
610
  });
555
611
  sanitize(body);
612
+ if (S.repairZeroWidth) repairZeroWidth(body);
556
613
  var root = doc.documentElement;
557
614
  var dir = (body.getAttribute('dir') || root.getAttribute('dir') || '').toLowerCase();
558
615
  return {
@@ -561,6 +618,216 @@
561
618
  };
562
619
  }
563
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;
634
+ });
635
+ }
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
+
564
831
  async function rewriteCss(css, basePath) {
565
832
  css = css.replace(/@import[^;]*;/g, '');
566
833
  var re = /url\(\s*(['"]?)([^)'"]+)\1\s*\)/g, m, seen = {}, jobs = [];
@@ -602,6 +869,15 @@
602
869
  }
603
870
  }
604
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
+
605
881
  function mountChapter(ch) {
606
882
  var d = frame.contentDocument;
607
883
  d.open();
@@ -614,6 +890,7 @@
614
890
  st.textContent = t;
615
891
  d.head.appendChild(st);
616
892
  });
893
+ addFontStyle(d);
617
894
  var app = d.createElement('style');
618
895
  app.id = 'app';
619
896
  d.head.appendChild(app);
@@ -693,9 +970,12 @@
693
970
  // letter-spacing would break the joins of cursive scripts (Arabic, Pashto, Persian, Urdu), so right-to-left books skip it
694
971
  (s.letterSpacing && !S.rtl ? 'letter-spacing:' + s.letterSpacing + 'em!important;' : '') +
695
972
  (s.wordSpacing ? 'word-spacing:' + s.wordSpacing + 'em!important;' : '') +
696
- '-webkit-touch-callout:none;-webkit-user-select:text;user-select:text;overflow-wrap:break-word;word-wrap:break-word}',
697
- 'body *{color:inherit!important;background-color:transparent!important;' + (ff ? 'font-family:inherit!important;' : '') + (s.bold ? 'font-weight:inherit;' : '') + 'box-sizing:border-box}',
698
- 'body a,body a *{color:' + s.link + '!important}',
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}',
699
979
  'body img,body svg,body video{max-width:100%!important;max-height:' + G.pageH + 'px!important;object-fit:contain;break-inside:avoid}',
700
980
  'body img{height:auto}',
701
981
  'body h1,body h2,body h3,body h4{break-after:avoid;-webkit-column-break-after:avoid}',
@@ -708,6 +988,7 @@
708
988
  css.push('body mark.ul-' + c + '{background-color:transparent!important;border-bottom:2px solid ' + HL_COLORS[c][1] + ';border-radius:0}');
709
989
  });
710
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}');
711
992
  return css.join('\n');
712
993
  }
713
994
 
@@ -744,6 +1025,7 @@
744
1025
  b.style.transform = prev;
745
1026
  S.pageStarts = {};
746
1027
  S.ghostDirty = true;
1028
+ applyBookColors(d);
747
1029
  scheduleGhost();
748
1030
  if (G.scroll) scheduleExtras(); else clearExtras();
749
1031
  }
@@ -756,6 +1038,7 @@
756
1038
  }
757
1039
 
758
1040
  function showPage(p, animate) {
1041
+ if (!Z.pinch) resetZoom();
759
1042
  p = clamp(p, 0, S.pageCount - 1);
760
1043
  S.page = p;
761
1044
  var G = S.G, b = S.doc.body;
@@ -1121,6 +1404,7 @@
1121
1404
  st.textContent = t;
1122
1405
  d.head.appendChild(st);
1123
1406
  });
1407
+ addFontStyle(d);
1124
1408
  var app = d.createElement('style');
1125
1409
  app.textContent = appCss(S.G);
1126
1410
  d.head.appendChild(app);
@@ -1142,6 +1426,8 @@
1142
1426
  .map(function (im) { return new Promise(function (r) { im.onload = im.onerror = r; }); });
1143
1427
  if (d1.fonts && d1.fonts.ready) imgs.push(d1.fonts.ready);
1144
1428
  if (imgs.length) await Promise.race([Promise.all(imgs), sleep(1500)]);
1429
+ applyBookColors(d1);
1430
+ if (S.G.mode === 'curl') applyBookColors(ghost2.contentDocument);
1145
1431
  var G = S.G, count = Math.max(1, Math.ceil((d1.body.scrollWidth + G.gap) / (G.pageW + G.gap) - 0.01));
1146
1432
  setGhostPages(first ? 0 : count - 1);
1147
1433
  }
@@ -1318,11 +1604,12 @@
1318
1604
  function applyHighlightsFor(el, index) {
1319
1605
  S.root = el;
1320
1606
  refreshSegs();
1321
- S.highlights.filter(function (h) { return h.spine === index; })
1322
- .sort(function (x, y) { return x.start - y.start; })
1323
- .forEach(function (h) {
1324
- var color = HL_COLORS[h.color] ? h.color : 'yellow';
1325
- wrapRange(h.start, h.end, (h.style === 'underline' ? 'ul-' : 'hl-') + color, h.id);
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);
1326
1613
  });
1327
1614
  }
1328
1615
 
@@ -1330,6 +1617,7 @@
1330
1617
  var token = S.token;
1331
1618
  var ch = await parseChapter(index);
1332
1619
  await inlineChapter(ch);
1620
+ await resolveHighlights(index);
1333
1621
  if (token !== S.token || !S.doc || !S.G.scroll) return;
1334
1622
  if (S.sections.some(function (x) { return x.index === index; })) return;
1335
1623
  var d = S.doc, el = d.createElement('div');
@@ -1355,6 +1643,7 @@
1355
1643
  applyHighlightsFor(el, index);
1356
1644
  S.root = cur;
1357
1645
  refreshSegs();
1646
+ applyBookColors(d);
1358
1647
  }
1359
1648
 
1360
1649
  // drop chapters that are far from the current one so a long reading session does not grow without bound
@@ -1523,16 +1812,44 @@
1523
1812
  function relocate() {
1524
1813
  var start = pageStart(S.page);
1525
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
+ }
1526
1830
  post('relocate', {
1527
1831
  spine: S.cur, offset: start, end: end,
1528
1832
  page: S.page, pageCount: S.pageCount, spineCount: S.spine.length,
1529
1833
  textLength: S.segs.total,
1530
1834
  progress: bookProgress(start), chapter: chapterTitle(S.cur, start),
1531
- excerpt: S.curText.slice(start, start + 120).replace(/\s+/g, ' ').trim(),
1532
- indexed: S.indexed
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
1533
1842
  });
1534
1843
  }
1535
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
+
1536
1853
  /* ----------------------------------------------------------- navigation */
1537
1854
 
1538
1855
  async function renderChapter(i, target) {
@@ -1557,6 +1874,16 @@
1557
1874
  else if (target && target.offset != null) p = pageForOffset(target.offset);
1558
1875
  else if (target && target.fragment) p = pageOfFragment(target.fragment);
1559
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
+ }
1560
1887
  relocate();
1561
1888
  }
1562
1889
 
@@ -1591,6 +1918,16 @@
1591
1918
 
1592
1919
  async function gotoLocation(loc) {
1593
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
+ }
1594
1931
  if (loc.progress != null && loc.spine == null) return gotoProgress(loc.progress);
1595
1932
  var spine = loc.spine != null ? clamp(loc.spine, 0, S.spine.length - 1) : 0;
1596
1933
  var target = loc.fragment ? { fragment: loc.fragment } : { offset: loc.offset || 0 };
@@ -1612,7 +1949,7 @@
1612
1949
  /* ---------------------------------------------------------- settings */
1613
1950
 
1614
1951
  function applySettings(partial) {
1615
- var s = S.settings, dirBefore = s.direction;
1952
+ var s = S.settings, dirBefore = s.direction, hlBefore = JSON.stringify(s.highlightColors) + s.highlightOpacity;
1616
1953
  // anchor is measured with the layout that is still on screen
1617
1954
  var anchor = S.doc ? pageStart(S.page) : 0;
1618
1955
  Object.keys(partial || {}).forEach(function (k) {
@@ -1634,6 +1971,7 @@
1634
1971
  }
1635
1972
  if (S.doc) {
1636
1973
  layout();
1974
+ if (JSON.stringify(s.highlightColors) + s.highlightOpacity !== hlBefore) applyHighlightsDom();
1637
1975
  showPage(pageForOffset(anchor), false);
1638
1976
  relocate();
1639
1977
  }
@@ -1661,7 +1999,30 @@
1661
1999
  return marks.length;
1662
2000
  }
1663
2001
 
1664
- 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) {
1665
2026
  var items = [];
1666
2027
  S.segs.forEach(function (seg) {
1667
2028
  if (seg.end <= a || seg.start >= b) return;
@@ -1680,6 +2041,7 @@
1680
2041
  var m = S.doc.createElement('mark');
1681
2042
  m.className = cls;
1682
2043
  m.setAttribute('data-hl', id);
2044
+ if (css) m.setAttribute('style', css);
1683
2045
  mid.parentNode.insertBefore(m, mid);
1684
2046
  m.appendChild(mid);
1685
2047
  });
@@ -1687,7 +2049,7 @@
1687
2049
  }
1688
2050
 
1689
2051
  function applyHighlightsDom() {
1690
- unwrapMarks('mark[data-hl]:not(.hit)');
2052
+ unwrapMarks('mark[data-hl]:not(.hit):not(.pick)');
1691
2053
  var cur = S.root;
1692
2054
  if (S.sections && S.sections.length) S.sections.forEach(function (sec) { applyHighlightsFor(sec.el, sec.index); });
1693
2055
  else applyHighlightsFor(S.doc.body, S.cur);
@@ -1718,7 +2080,7 @@
1718
2080
  'أ': 'ا', 'إ': 'ا', 'آ': 'ا', 'ٱ': 'ا', // alef
1719
2081
  'ؤ': 'و'
1720
2082
  };
1721
- var DROP = /[ً-ٰٟۖ-ۭـ​-‏‪-‮⁦-⁩­]/;
2083
+ var DROP = /[\u2060ً-ٰٟۖ-ۭـ​-‏‪-‮⁦-⁩­]/;
1722
2084
  function foldText(text, breaks) {
1723
2085
  var out = [], map = [], brk = breaks && breaks.length ? new Set(breaks) : null, lastSpace = true;
1724
2086
  for (var i = 0; i < text.length; i++) {
@@ -1763,9 +2125,9 @@
1763
2125
  var start = fd.map[at], end = fd.map[at + q.length - 1] + 1;
1764
2126
  found.push({
1765
2127
  spine: i, offset: start, length: end - start, chapter: chapterTitle(i),
1766
- before: text.slice(Math.max(0, start - 40), start).replace(/\s+/g, ' '),
1767
- match: text.slice(start, end),
1768
- after: text.slice(end, end + 60).replace(/\s+/g, ' ')
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, ' ')
1769
2131
  });
1770
2132
  from = at + q.length;
1771
2133
  }
@@ -1786,11 +2148,17 @@
1786
2148
 
1787
2149
  async function buildIndex() {
1788
2150
  var cum = 0, id = S.openId;
1789
- var texts = [], cums = [], breaks = [];
2151
+ var texts = [], cums = [], breaks = [], locs = [];
1790
2152
  for (var i = 0; i < S.spine.length; i++) {
1791
2153
  var t = '', br = [];
1792
2154
  try {
1793
- var ch = await parseChapter(i);
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);
1794
2162
  var segs = collectSegs(ch.body), prev = null;
1795
2163
  // positions where one block ends and the next begins: search must not match across them
1796
2164
  segs.forEach(function (sg) {
@@ -1808,10 +2176,368 @@
1808
2176
  S.texts = texts; S.cum = cums; S.breaks = breaks;
1809
2177
  S.totalLen = cum;
1810
2178
  S.indexed = true;
2179
+ if (S.locationChars > 0) S.locs = new EpubCompat.Locations(locs);
1811
2180
  post('indexed', { totalLength: cum, cum: S.cum });
2181
+ if (S.locs) post('locations', { count: locs.length });
1812
2182
  if (S.doc) relocate();
1813
2183
  }
1814
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
+
1815
2541
  /* ------------------------------------------------------------- events */
1816
2542
 
1817
2543
  function handleLink(a) {
@@ -1835,13 +2561,13 @@
1835
2561
  }
1836
2562
 
1837
2563
  function attachListeners(d) {
2564
+ attachZoom(d);
1838
2565
  d.addEventListener('click', function (e) {
1839
2566
  if (S.dragged) return;
1840
- var sel = d.getSelection();
1841
- if (sel && !sel.isCollapsed) return;
1842
- var t = e.target, a = t.closest && t.closest('a'), m = t.closest && t.closest('mark[data-hl]');
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)');
1843
2569
  if (a) { e.preventDefault(); handleLink(a); return; }
1844
- if (m && m.getAttribute('data-hl') !== '__hit') {
2570
+ if (m) {
1845
2571
  post('highlightTap', { id: m.getAttribute('data-hl'), rect: rectOf(m) });
1846
2572
  return;
1847
2573
  }
@@ -1853,15 +2579,20 @@
1853
2579
  }, true);
1854
2580
 
1855
2581
  var t0 = null;
2582
+ // a touch since the last scroll-mode 'end' (see the scroll listener below)
2583
+ var touchedSinceEnd = false;
1856
2584
  d.addEventListener('touchstart', function (e) {
1857
- if (e.touches.length !== 1) { endTouch(true); 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;
1858
2590
  var t = e.touches[0], el = d.scrollingElement || d.documentElement;
1859
2591
  t0 = { x: t.clientX, y: t.clientY, time: Date.now(), drag: false, dx: 0, dy: 0, base: currentX(), top: el.scrollTop };
1860
2592
  }, { passive: true });
1861
2593
  d.addEventListener('touchmove', function (e) {
2594
+ if (e.touches.length === 1 && pickMove(d, e)) { t0 = null; return; }
1862
2595
  if (!t0) return;
1863
- var sel = d.getSelection();
1864
- if (sel && !sel.isCollapsed) { t0 = null; return; }
1865
2596
  var t = e.touches[0], dx = t.clientX - t0.x, dy = t.clientY - t0.y;
1866
2597
  t0.dx = dx; t0.dy = dy;
1867
2598
  if (S.G.scroll) return;
@@ -1927,31 +2658,30 @@
1927
2658
  var forward = S.rtl ? dx > 0 : dx < 0;
1928
2659
  enqueue(forward ? next : prev);
1929
2660
  }
1930
- d.addEventListener('touchend', function () { endTouch(false); }, { passive: true });
1931
- d.addEventListener('touchcancel', function () { endTouch(true); }, { passive: true });
2661
+ d.addEventListener('touchend', function () {
2662
+ if (pickEnd()) { t0 = null; return; }
2663
+ endTouch(false);
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(); });
1932
2671
 
1933
2672
  d.defaultView.addEventListener('scroll', debounce(function () {
1934
2673
  if (d !== S.doc || !S.G.scroll) return;
1935
- if (checkSection()) return;
1936
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;
1937
2682
  var p = clamp(Math.round((el.scrollTop - bodyTop()) / S.G.pageH), 0, S.pageCount - 1);
1938
2683
  if (p !== S.page) { S.page = p; autoLabels(); relocate(); }
1939
2684
  }, 120));
1940
-
1941
- d.addEventListener('selectionchange', debounce(function () {
1942
- if (d !== S.doc) return;
1943
- var sel = d.getSelection();
1944
- if (!sel || sel.rangeCount === 0 || sel.isCollapsed) {
1945
- if (S.sel) { S.sel = null; post('selectionClear'); }
1946
- return;
1947
- }
1948
- var r = sel.getRangeAt(0);
1949
- if (!rootEl().contains(r.startContainer) || !rootEl().contains(r.endContainer)) return;
1950
- var a = boundaryOffset(r.startContainer, r.startOffset), b = boundaryOffset(r.endContainer, r.endOffset);
1951
- if (b <= a) return;
1952
- S.sel = { spine: S.cur, start: a, end: b, text: sel.toString() };
1953
- post('selection', { spine: S.cur, start: a, end: b, text: S.sel.text, rect: rectOf(r) });
1954
- }, 180));
1955
2685
  }
1956
2686
 
1957
2687
  /* ------------------------------------------------------------ commands */
@@ -1974,6 +2704,9 @@
1974
2704
  // nothing may leak from the previous book (cached images such as the cover, labels, direction)
1975
2705
  S.dataCache = {}; S.fragCache = {}; S.obf = {}; S.obfKeys = {}; S.identifier = '';
1976
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;
1977
2710
  S.bookRtl = false; S.rtl = false; S.ppd = ''; S.contentRtl = false; S.spine = []; S.toc = [];
1978
2711
  hdr.textContent = ''; ftr.textContent = '';
1979
2712
  S.cur = -1;
@@ -2004,6 +2737,19 @@
2004
2737
  }
2005
2738
  break;
2006
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;
2007
2753
  case 'labels':
2008
2754
  S.labelsExternal = true;
2009
2755
  hdr.textContent = c.header || '';
@@ -2011,21 +2757,40 @@
2011
2757
  break;
2012
2758
  case 'highlights':
2013
2759
  S.highlights = c.list || [];
2014
- 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
+ }
2015
2765
  break;
2016
2766
  case 'next': await next(); break;
2017
2767
  case 'prev': await prev(); break;
2018
2768
  case 'goto': await gotoLocation(c.location); break;
2019
2769
  case 'showHit': if (S.doc) showHit(c.offset, c.length); break;
2020
- case 'clearSelection':
2021
- if (S.doc) S.doc.getSelection().removeAllRanges();
2022
- S.sel = null;
2023
- break;
2770
+ case 'clearSelection': clearPick(); break;
2024
2771
  case 'search': search(c.query, c.id); break;
2025
2772
  case 'cancelSearch': S.searchId = c.id || -1; break;
2026
2773
  }
2027
2774
  }
2028
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
+
2029
2794
  // the book arrives in pieces (one injected call each) before the 'open' command
2030
2795
  var chunks = [];
2031
2796
  window.__chunk = function (reset, s) {